using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Teamcenter.Services.Strong.Core; using Teamcenter.Soa.Client.Model; using Teamcenter.Soa.Client.Model.Strong; using Session = Teamcenter.ClientX.Session; using KPlan.Forms; using Teamcenter.Services.Strong.Query; using Teamcenter.Services.Strong.Query._2006_03.SavedQuery; using Teamcenter.Services.Strong.Query._2007_06.SavedQuery; using Teamcenter.Services.Strong.Administration; using Teamcenter.Services.Strong.Administration._2012_09.PreferenceManagement; using System.IO; using Teamcenter.Soa.Client; using Teamcenter.Soa.Internal.Client; using System.Windows.Media.Imaging; using Teamcenter.Services.Strong.Core._2008_06.DataManagement; using ModelType = Teamcenter.Schemas.Soa._2011_06.Metamodel.ModelType; using PropertyDescriptor = Teamcenter.Schemas.Soa._2011_06.Metamodel.PropertyDescriptor; using KPlan.Forms.Bean; using VecStruct = Teamcenter.Services.Strong.Core._2007_01.DataManagement.VecStruct; using Teamcenter.Services.Strong.Classification; using Teamcenter.Services.Strong.Classification._2007_01.Classification; using Teamcenter.Services.Loose.Core._2006_03.FileManagement; using Teamcenter.Services.Strong.Core._2007_06.DataManagement; using Teamcenter.Services.Strong.Workflow; using CreateInput = Teamcenter.Services.Strong.Core._2008_06.DataManagement.CreateInput; using System.Collections; using Teamcenter.Services.Strong.Core._2007_01.DataManagement; using Oracle.ManagedDataAccess.Client; namespace KPlan.Util { class TCUtil { public const string ITEM = "ITEM"; public const string REV = "REV"; public const string ITEMMASTER = "ITEM_MASTER"; public const string REVMASTER = "REV_MASTER"; public const string PREF_ADMIN = "Eplan_Administrator_UserID"; public static User user; public static string userName = ""; public static DataManagementService dmService; public static SavedQueryService queryService; public static PreferenceManagementService prefService; public static SessionService sessionService; public static ClassificationService csService; public static ImanQuery query_LatestRev; public static Dictionary usedQueries = new Dictionary(); public const string REL_REV_EPLAN = "IMAN_specification"; public const string TYPE_EPLAN = "Text"; public static CallBackArgs forAddin = new CallBackArgs(); public static com.teamcenter.fms.ticket.ticketinternal.FMSTicketConstants fms = new com.teamcenter.fms.ticket.ticketinternal.FMSTicketConstants(); public static com.teamcenter.fms.servercache.proxy.FSCConstants fsc = new com.teamcenter.fms.servercache.proxy.FSCConstants(); public static Teamcenter.Schemas.Classification._2016_09.Classification.AttributeValue cls = new Teamcenter.Schemas.Classification._2016_09.Classification.AttributeValue(); //public static Teamcenter.FMS.FCCProxy.ClientCache.NetFileCacheProxy fcc = new Teamcenter.FMS.FCCProxy.ClientCache.NetFileCacheProxy(); public static ICSharpCode.SharpZipLib.Zip.ZipOutputStream zip = null; public static Teamcenter.Services.Strong.Workflow._2007_06.Workflow.ReleaseStatusInput wf = null; public static Teamcenter.Schemas.Workflow._2007_06.Workflow.ReleaseStatusInput wfType = null; public static System.IO.Compression.ZipArchiveMode mode = System.IO.Compression.ZipArchiveMode.Read; public static Teamcenter.Services.Strong.Cad._2008_06.DataManagement.DatasetFileInfo cadCore = null; public static Teamcenter.Schemas.Cad._2008_06.Datamanagement.AttributeInfo cadType = null; public static Oracle.ManagedDataAccess.Client.OracleCommand oraCmd = null; public static void PreLogin() { if (user != null) { return; } string pwd = KUtil.GetConfigValue(KConfigure.LOGIN_SECTION, KConfigure.LOGIN_PWD); if (!KUtil.IsEmpty(pwd)) { string userName = KUtil.GetConfigValue(KConfigure.LOGIN_SECTION, KConfigure.LOGIN_USER); string role = KUtil.GetConfigValue(KConfigure.LOGIN_SECTION, KConfigure.LOGIN_ROLE); string host = KUtil.GetConfigValue(KConfigure.LOGIN_SECTION, KConfigure.HOST); try { Login(host, userName, pwd, role, true); if (user != null) { KUtil.Log("自动登录成功"); } } catch (System.Exception ex) { KUtil.Log("自动登录失败"); KUtil.LogErr(ex); } } } public static void Test() { CreateInput revInput = new CreateInput(); revInput.BoName = "SF6_DocumentRevision"; Hashtable revPropMap = new Hashtable(); revPropMap.Add("item_revision_id", "000"); revPropMap.Add("sf6_DOCType", "AB"); revInput.StringProps = revPropMap; //create rev CreateInput itemInput = new CreateInput(); itemInput.BoName = "SF6_Document"; Hashtable itemPropMap = new Hashtable(); itemPropMap.Add("item_id", "C2F00000166"); itemPropMap.Add("object_name", "kk"); itemPropMap.Add("object_desc", "k2"); itemInput.StringProps = itemPropMap; Hashtable revInfoMap = new Hashtable(); revInfoMap.Add("revision", new CreateInput[] { revInput }); itemInput.CompoundCreateInput = revInfoMap; //create info CreateIn cI = new CreateIn(); cI.ClientId = "CreateItem"; cI.Data = itemInput; //service DataManagementService service = DataManagementService.getService(Session.getConnection()); //create CreateResponse resp = service.CreateObjects(new CreateIn[] { cI }); ThrowServiceDataError(resp.ServiceData); } public static bool ItemExist(string item_id) { if (KUtil.IsEmpty(item_id)) { return false; } //DateTime time= DateTime.Now; //GetItemFromIdPref Pref = new GetItemFromIdPref(); //GetItemFromIdInfo OneInfo = new GetItemFromIdInfo(); //OneInfo.ItemId = item_id; //GetItemFromIdResponse InfoResp = dmService.GetItemFromId(new GetItemFromIdInfo[] { OneInfo }, 1, Pref); // 1,个数,是最新版本*/ //KUtil.Log("查询" + item_id + ",耗时:" + (DateTime.Now - time)); //return InfoResp.Output.Length > 0; GetItemAndRelatedObjectsInfo info = new GetItemAndRelatedObjectsInfo(); AttrInfo attrInfo = new AttrInfo(); attrInfo.Name = "item_id"; attrInfo.Value = item_id; ItemInfo itemInfo = new ItemInfo(); itemInfo.Ids = new AttrInfo[] { attrInfo }; itemInfo.UseIdFirst = true; itemInfo.ClientId = "itemInfo1"; RevInfo revInfo = new RevInfo(); revInfo.Processing = "None";// "Ids"; revInfo.UseIdFirst = true; revInfo.NRevs = 1; revInfo.ClientId = "revInfo1"; DatasetInfo dsInfo = new DatasetInfo(); dsInfo.ClientId = "dsInfo1"; dsInfo.Filter = new DatasetFilter(); dsInfo.Filter.Processing = "None"; info.ItemInfo = itemInfo; info.RevInfo = revInfo; info.DatasetInfo = dsInfo; GetItemAndRelatedObjectsResponse resp = dmService.GetItemAndRelatedObjects(new GetItemAndRelatedObjectsInfo[] { info }); //ThrowServiceDataError(resp.ServiceData); //KUtil.Log("查询" + item_id + ",耗时:" + (DateTime.Now - time)); return resp.Output.Length > 0; } public static bool CheckAuthorityFromPref(string prefName) { if (user == null) { return false; } GetProperties(false, new ModelObject[] { user }, "userid"); string userId = user.Userid; string[] prefVals = TCUtil.GetPrefVals(prefName); if (prefVals == null || prefVals.Length == 0) { return false; } foreach(string val in prefVals) { if (userId.Equals(val)) { return true; } } return false; } public static void UploadFile(Dataset dataset,string filePath,string refName) { KUtil.Log("上传文件:"+filePath+",引用:"+refName); //if ("SF6_ZW1".Equals(refName)) { // filePath = @"C:\test1\KKKK33.zw1"; //} List oldfiles = GetDatasetFile(dataset, ""); Teamcenter.Services.Strong.Core._2007_09.DataManagement.NamedReferenceInfo[] nrInfos = new Teamcenter.Services.Strong.Core._2007_09.DataManagement.NamedReferenceInfo[oldfiles.Count]; for (int i=0;i 0) { Teamcenter.Services.Strong.Core._2007_09.DataManagement.RemoveNamedReferenceFromDatasetInfo inputInfo = new Teamcenter.Services.Strong.Core._2007_09.DataManagement.RemoveNamedReferenceFromDatasetInfo(); inputInfo.Dataset = dataset; inputInfo.ClientId = "KPlan"; inputInfo.NrInfo = nrInfos; ServiceData delResp = dmService.RemoveNamedReferenceFromDataset(new Teamcenter.Services.Strong.Core._2007_09.DataManagement.RemoveNamedReferenceFromDatasetInfo[] { inputInfo }); ThrowServiceDataError(delResp); KUtil.Log("旧文件引用已移除"); } 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); DatasetFileInfo fileInfo = new DatasetFileInfo(); fileInfo.FileName = filePath; fileInfo.AllowReplace = true; fileInfo.NamedReferencedName = refName; GetDatasetWriteTicketsInputData input = new GetDatasetWriteTicketsInputData(); input.Dataset = dataset; input.CreateNewVersion = false; input.DatasetFileInfos = new DatasetFileInfo[] { fileInfo }; ServiceData resp = fmsFileManagement.PutFiles(new GetDatasetWriteTicketsInputData[] { input }); fmsFileManagement.Term(); ThrowServiceDataError(resp); } public static ModelObject StringToComponent(string uid) { if (KUtil.IsEmpty(uid)) { return null; } ServiceData resp = dmService.LoadObjects(new string[] { uid }); //ThrowServiceDataError(resp); if (resp.sizeOfPlainObjects()> 0) { return resp.GetPlainObject(0); } return null; } public static string[] GetClassId(ItemRevision rev) { ModelObject[] mos = Refresh(rev); GetProperties(false, mos, "fnd0IcsClassNames", "ics_classified", "object_string"); string[] classes = rev.Fnd0IcsClassNames; return classes; } public static void SendToClassification(string classId, ModelObject mo) { if (KUtil.IsEmpty(classId) || mo == null) { return; } ModelObject[] mos = Refresh(mo); GetProperties(false, mos, "fnd0IcsClassNames", "ics_classified","object_string"); string[] classes = ((WorkspaceObject)mo).Fnd0IcsClassNames; //if (classes != null && classes.Length > 0) { // KUtil.Log("对象已存在于分类“" + string.Join(",",classes) + "”:" + mo.GetPropertyDisplayableValue("object_string")); // //return; //} if (classes != null && classes.Length > 0) { string name = ""; GetClassDescriptionsResponse descResps = csService.GetClassDescriptions(new string[] { classId }); ThrowServiceDataError(descResps.Data); ClassDef desc = descResps.Descriptions[classId] as ClassDef; if (desc != null) { name = desc.Name; } KUtil.Log("分类名称:"+classId+" -> " + name); foreach (string className in classes) { if (name.Equals(className)) { KUtil.Log("对象已存在于分类“" + classId + "”:" + mo.GetPropertyDisplayableValue("object_string")); return; } } } ClassificationObject co = new ClassificationObject(); //ClassificationProperty ico_props = new ClassificationProperty(); //ClassificationPropertyValue ico_prop_values = new ClassificationPropertyValue(); //ico_prop_values.DbValue = "Acceleration"; //ico_props.AttributeId = -60006; // this value can be obtained with //ico_props.Values = new ClassificationPropertyValue[] {ico_prop_values }; co.ClassId = classId; //co.InstanceId = "AngularVelocity_nm_degrees"; //co.Properties = new ClassificationProperty[] { ico_props }; co.UnitBase = "METRIC"; co.WsoId = mo as WorkspaceObject; //ClassificationObject co = new ClassificationObject(); //co.ClassId = classId; //co.ClsObjTag = mo; CreateClassificationObjectsResponse resp = csService.CreateClassificationObjects(new ClassificationObject[] { co }); ThrowServiceDataError(resp.Data); } public static ModelType GetTCType(string typeName) { if (KUtil.IsEmpty(typeName)) { return null; } Teamcenter.Schemas.Soa._2011_06.Metamodel.TypeSchema typeScheme = sessionService.GetTypeDescriptions(new string[] { typeName }); ModelType[] types = typeScheme.Types; if (types != null && types.Length > 0) { return types[0]; } return null; } public static bool IsType(ModelType type,string name) { ModelType pType = type; while (pType != null) { string tName = pType.Name; if (name.Equals(tName)){ return true; } pType = GetTCType(pType.ParentTypeName); } return false; } public static List GetAllPropDescs(ModelType type,string location,string typeName) { List res = new List(); //while(type!=null) { System.Collections.ArrayList descs = type.getPropertyDescriptors(); foreach(PropertyDescriptor desc in descs) { TCPropBean bean = new TCPropBean() { location = location,realName = desc.Name,disName = desc.DisplayName,typeName = typeName }; res.Add(bean); } //type = GetTCType(type.ParentTypeName); // } return res; } public static Dictionary> GetDefinedProperties(string itemTypeName) { Dictionary> res = new Dictionary>(); if (KUtil.IsEmpty(itemTypeName)) { return res; } //对象属性 ModelType itemType = GetTCType(itemTypeName); if (itemType == null) { throw new Exception("对象类型不存在:"+itemTypeName); } if (!IsType(itemType, "Item")) { throw new Exception("对象类型不是Item类型:"+itemTypeName); } res.Add(itemTypeName, GetAllPropDescs(itemType,ITEM,itemTypeName)); //版本属性 string revTypeName = itemTypeName + "Revision"; ModelType revType = GetTCType(revTypeName); if (revType == null) { throw new Exception("未找到对象对应版本类型"); } res.Add(revTypeName, GetAllPropDescs(revType,REV,revTypeName)); //对象表单属性 string itemMasterTypeName = itemTypeName + "Master"; ModelType itemMasterType = GetTCType(itemMasterTypeName); if (itemMasterType == null) { itemMasterTypeName = itemTypeName + " Master"; itemMasterType = GetTCType(itemMasterTypeName); } if (itemMasterType == null) { throw new Exception("未找到对象表单类型:"+itemMasterTypeName); } res.Add(itemMasterTypeName, GetAllPropDescs(itemMasterType,ITEMMASTER,itemMasterTypeName)); //版本表单熟悉 string revMasterTypeName = revTypeName + "Master"; ModelType revMasterType = GetTCType(revMasterTypeName); if (revMasterType == null) { revMasterTypeName = revTypeName + " Master"; revMasterType = GetTCType(revMasterTypeName); } if (revMasterType == null) { throw new Exception("未找到版本表单类型:" + revMasterTypeName); } res.Add(revMasterTypeName, GetAllPropDescs(revMasterType,REVMASTER,revMasterTypeName)); return res; } public static ModelObject[] Query_LatestRevByOrderNr(string partNr) { Dictionary fields = new Dictionary(); string queryName = KUtil.GetConfigValue(KConfigure.PART_QUERY_SECTION, KConfigure.PART_QUERY_NAME); string partField = KUtil.GetConfigValue(KConfigure.PART_QUERY_SECTION, KConfigure.PART_QUERY_ORDERNR); if (!KUtil.IsEmpty(partNr)) { fields.Add(partField, partNr); } if (fields.Count == 0) { return null; } KUtil.Log("查询TC中的部件:OrderNR = " + partNr); ModelObject[] unsyncItems = TCUtil.query(queryName, fields); int len = unsyncItems == null ? 0 : unsyncItems.Length; KUtil.Log("查询结果数量:" + len); return unsyncItems; } public static ItemRevision createItem(String objectType, String itemID) { CreateInput revInput = new CreateInput(); revInput.BoName = objectType + "Revision"; Hashtable revPropMap = new Hashtable(); revInput.StringProps = revPropMap; //create rev CreateInput itemInput = new CreateInput(); itemInput.BoName = objectType; Hashtable itemPropMap = new Hashtable(); itemPropMap.Add("item_id", itemID); itemInput.StringProps = itemPropMap; Hashtable revInfoMap = new Hashtable(); revInfoMap.Add("revision", new CreateInput[] { revInput }); itemInput.CompoundCreateInput = revInfoMap; //create info CreateIn cI = new CreateIn(); cI.ClientId = "CreateItem"; cI.Data = itemInput; //service DataManagementService service = DataManagementService.getService(Session.getConnection()); //create CreateResponse resp = service.CreateObjects(new CreateIn[] { cI }); ThrowServiceDataError(resp.ServiceData); for (int i = 0; i < resp.ServiceData.sizeOfCreatedObjects(); i++) { if (resp.ServiceData.GetCreatedObject(i) is ItemRevision) { return (ItemRevision)resp.ServiceData.GetCreatedObject(i); } } return null; } public static ItemRevision Query_LatestRevByOrderNr_single(string partNr) { Dictionary fields = new Dictionary(); string queryName = KUtil.GetConfigValue(KConfigure.PART_QUERY_SECTION, KConfigure.PART_QUERY_NAME); string partField = KUtil.GetConfigValue(KConfigure.PART_QUERY_SECTION, KConfigure.PART_QUERY_ORDERNR); if (!KUtil.IsEmpty(partNr)) { fields.Add(partField, partNr); } if (fields.Count == 0) { return null; } KUtil.Log("查询TC中的部件:OrderNR = " + partNr); ModelObject[] unsyncItems = TCUtil.query(queryName, fields); int len = unsyncItems == null ? 0 : unsyncItems.Length; KUtil.Log("查询结果数量:" + len); if (len == 1) { return unsyncItems[0] as ItemRevision; } if (len == 0) { return null; } KUtil.Log("==ERROR==通过订单号 = " + partNr + " 查询到多个对象"); return null; //throw new Exception("通过订单号 = "+partNr+" 查询到多个对象"); } public static ItemRevision Query_LatestRevByItemUid1(string uid,OracleConnection conn) { if (KUtil.IsEmpty(uid)) { return null; } string revUid=null; using (OracleCommand cmd = new OracleCommand()) { //DateTime time = DateTime.Now; cmd.Connection = conn; cmd.CommandText = "select puid from pitemrevision where ritems_tagu='"+uid+"' order by pitem_revision_id desc, psequence_id desc"; using (OracleDataReader dr = cmd.ExecuteReader()) { if (dr.Read()) { revUid = dr.GetString(0); //KUtil.Log(uid+ " -> 最新版本UID = "+ revUid); } //int res = dr.GetInt32(0); //KUtil.Log("查询结果数量:" + res); //itemExist = res > 0; } //KUtil.Log("查询最新版本耗时:"+(DateTime.Now-time)); } if (KUtil.IsEmpty(revUid)) { return null; } ServiceData resp = dmService.LoadObjects(new string[] { revUid }); ThrowServiceDataError(resp); if (resp.sizeOfPlainObjects() > 0) { return resp.GetPlainObject(0) as ItemRevision; } return null; } public static ItemRevision Query_LatestRev(string itemID, OracleConnection conn) { if (KUtil.IsEmpty(itemID)) { return null; } string puid = null; using (OracleCommand cmd = new OracleCommand()) { cmd.Connection = conn; cmd.CommandText = "select puid from pitemrevision t1" + " where ritems_tagu = (select puid from PITEM where pitem_id = '"+itemID+"')" + " order by pitem_revision_id desc, psequence_id desc"; using (OracleDataReader dr = cmd.ExecuteReader()) { if (dr.Read()) { puid = dr.GetString(0); } } } KUtil.Log("查询最新版本:" + itemID + " -> " + puid); if (string.IsNullOrEmpty(puid)) { return null; } ServiceData resp = dmService.LoadObjects(new string[] { puid }); if (resp.sizeOfPlainObjects() == 0) { return null; } return resp.GetPlainObject(0) as ItemRevision; } public static ItemRevision Query_LatestRev(string itemID) { if (KUtil.IsEmpty(itemID)) { return null; } if (query_LatestRev == null) { KUtil.Log("未找到查询Latest Item Revision..."); return null; } SavedQueryInput savedQueryInput = new SavedQueryInput(); savedQueryInput.Query = query_LatestRev; savedQueryInput.Entries = new string[] { "Item ID" }; savedQueryInput.Values = new string[] { itemID }; ExecuteSavedQueriesResponse res = queryService.ExecuteSavedQueries(new SavedQueryInput[] { savedQueryInput }); ThrowServiceDataError(res.ServiceData); SavedQueryResults found = res.ArrayOfResults[0]; if (found.NumOfObjects > 0) { return found.Objects[0] as ItemRevision; } return null; } public static ItemRevision Revise(ItemRevision oldRev) { if (oldRev == null) { return null; } ReviseInfo ri = new ReviseInfo(); ri.BaseItemRevision = oldRev; // ri. ReviseResponse2 resp = dmService.Revise2(new ReviseInfo[] { ri }); //ThrowServiceDataError(resp.ServiceData); KUtil.Log(""+resp.ServiceData.sizeOfPlainObjects()+"|"+resp.ServiceData.sizeOfCreatedObjects()+"|"+resp.ServiceData.sizeOfUpdatedObjects()); for(int i = 0; i < resp.ServiceData.sizeOfCreatedObjects(); i++) { ModelObject mo = resp.ServiceData.GetCreatedObject(i); if (mo.GetType() == typeof(ItemRevision)) { return mo as ItemRevision; } } return null; } public static void DO_NOTHING() { } public static ModelObject[] Refresh(params ModelObject[] mo){ dmService.RefreshObjects(mo); return mo; } public static void GetProperties(bool checkErr,ModelObject[] mo, params string[] props){ ServiceData sd = dmService.GetProperties(mo, props); if (checkErr) { ThrowServiceDataError(sd); } } public static ModelObject CreateNewRow(string rowType,Dictionary props) { Teamcenter.Services.Strong.Core._2008_06.DataManagement.CreateInput input = new Teamcenter.Services.Strong.Core._2008_06.DataManagement.CreateInput(); input.BoName = rowType; CreateIn ci = new CreateIn(); ci.Data = input; CreateResponse resp = dmService.CreateObjects(new CreateIn[] { ci }); ThrowServiceDataError(resp.ServiceData); for (int i = 0; i < resp.ServiceData.sizeOfCreatedObjects(); i++) { ModelObject mo = resp.ServiceData.GetCreatedObject(i); TCUtil.SetProperties(mo, props); return mo; } return null; } public static Dataset CreateNewDataset(string dsType,string name) { DatasetProperties2 input = new DatasetProperties2(); input.ClientId = "kplan"; input.Type = dsType; input.Name = name; Teamcenter.Services.Strong.Core._2006_03.DataManagement.CreateDatasetsResponse resp = dmService.CreateDatasets2(new DatasetProperties2[] { input }); ThrowServiceDataError(resp.ServiceData); if (resp.Output.Length > 0) { return resp.Output[0].Dataset; } return null; } public static ItemRevision CreateNewRev(string itemType) { Teamcenter.Services.Strong.Core._2008_06.DataManagement.CreateInput input = new Teamcenter.Services.Strong.Core._2008_06.DataManagement.CreateInput(); //System.Collections.Hashtable itemProps = new System.Collections.Hashtable() ; //itemProps.Add("object_name", name); input.BoName = itemType; //input.StringProps = itemProps; CreateIn ci = new CreateIn(); ci.Data = input; CreateResponse resp = dmService.CreateObjects(new CreateIn[] { ci }); ThrowServiceDataError(resp.ServiceData); for(int i = 0; i < resp.ServiceData.sizeOfCreatedObjects(); i++) { ModelObject mo = resp.ServiceData.GetCreatedObject(i); if (mo.GetType() == typeof(ItemRevision)) { return mo as ItemRevision; } } return null; } public static ItemRevision CreateNewRev(string itemType,string name) { Teamcenter.Services.Strong.Core._2008_06.DataManagement.CreateInput input = new Teamcenter.Services.Strong.Core._2008_06.DataManagement.CreateInput(); System.Collections.Hashtable itemProps = new System.Collections.Hashtable() ; itemProps.Add("object_name", name); input.BoName = itemType; input.StringProps = itemProps; CreateIn ci = new CreateIn(); ci.Data = input; CreateResponse resp = dmService.CreateObjects(new CreateIn[] { ci }); ThrowServiceDataError(resp.ServiceData); for (int i = 0; i < resp.ServiceData.sizeOfCreatedObjects(); i++) { ModelObject mo = resp.ServiceData.GetCreatedObject(i); if (mo.GetType() == typeof(ItemRevision)) { return mo as ItemRevision; } } return null; } public static ItemRevision CreateNewDocument(string itemType, string name) { Teamcenter.Services.Strong.Core._2008_06.DataManagement.CreateInput input = new Teamcenter.Services.Strong.Core._2008_06.DataManagement.CreateInput(); System.Collections.Hashtable itemProps = new System.Collections.Hashtable(); itemProps.Add("object_name", name); input.BoName = itemType; input.StringProps = itemProps; CreateIn ci = new CreateIn(); ci.Data = input; CreateResponse resp = dmService.CreateObjects(new CreateIn[] { ci }); ThrowServiceDataError(resp.ServiceData); for (int i = 0; i < resp.ServiceData.sizeOfCreatedObjects(); i++) { ModelObject mo = resp.ServiceData.GetCreatedObject(i); if (mo.GetType() == typeof(DocumentRevision)) { return mo as DocumentRevision; } if (mo.GetType() == typeof(ItemRevision)) { return mo as ItemRevision; } } return null; } public static void CreateNewRelation(ModelObject parent,ModelObject child,string rel) { if (parent == null || child == null || KUtil.IsEmpty(rel)) { return; } Teamcenter.Services.Strong.Core._2006_03.DataManagement.Relationship relInput = new Teamcenter.Services.Strong.Core._2006_03.DataManagement.Relationship(); relInput.PrimaryObject = parent; relInput.SecondaryObject = child; relInput.RelationType = rel; Teamcenter.Services.Strong.Core._2006_03.DataManagement.CreateRelationsResponse resp = dmService.CreateRelations(new Teamcenter.Services.Strong.Core._2006_03.DataManagement.Relationship[] { relInput }); ThrowServiceDataError(resp.ServiceData); } public static void CreateNewProcess(string templateName, ModelObject target, int relation) { WorkflowService wfService = WorkflowService.getService(Session.getConnection()); Teamcenter.Services.Strong.Workflow._2008_06.Workflow.ContextData contextData = new Teamcenter.Services.Strong.Workflow._2008_06.Workflow.ContextData(); contextData.ProcessTemplate = templateName; contextData.SubscribeToEvents = false; contextData.SubscriptionEventCount=0; contextData.AttachmentCount = 1; contextData.Attachments = new string[] { target.Uid }; contextData.AttachmentTypes = new int[] { 1 }; Teamcenter.Services.Strong.Workflow._2008_06.Workflow.InstanceInfo inst = wfService.CreateInstance(true, "", templateName, "createInstance", "EPLAN编码申请流程", contextData); ThrowServiceDataError(inst.ServiceData); } public static void CheckDatasetForUpdate(Dataset ds) { if (ds == null) { return; } TCUtil.GetProperties(false, TCUtil.Refresh(ds), "object_string","is_modifiable", "checked_out", "checked_out_user"); string name = ds.Object_string; if (!ds.Is_modifiable) { throw new Exception("数据集“"+name+"”为只读格式,无法保存"); } User check = ds.Checked_out_user as User; if (check != null && check.Uid != TCUtil.user?.Uid) { throw new Exception("数据集“"+name+"”由其他用户签出,无法保存"); } } public static ModelObject[] GetChild(ModelObject mo,string rel,string type) { List res = new List(); if (mo == null || KUtil.IsEmpty(type)) { return null; } ExpandGRMRelationsPref myPref = new ExpandGRMRelationsPref(); RelationAndTypesFilter2 myFilter = new RelationAndTypesFilter2(); myFilter.RelationName = rel; myFilter.ObjectTypeNames = new string[] { type}; myPref.ExpItemRev = false; myPref.Info = new RelationAndTypesFilter2[] { myFilter }; ModelObject[] primaryObjects = { mo }; ExpandGRMRelationsResponse myResp = dmService.ExpandGRMRelationsForPrimary(primaryObjects, myPref); ThrowServiceDataError(myResp.ServiceData); for (int k = 0; k < myResp.Output.Length; k++) { ExpandGRMRelationsOutput grmOutput = myResp.Output[k]; for (int l = 0; l < grmOutput.OtherSideObjData.Length; l++) { ExpandGRMRelationsData otherSideData = grmOutput.OtherSideObjData[l]; if (otherSideData.OtherSideObjects.Length > 0) { res.AddRange(otherSideData.OtherSideObjects); } } } return res.ToArray(); ; } public static void RemoveChildren(ModelObject parent, ModelObject[] children, string rel) { if (parent == null || children == null || children.Length == 0) { return; } Teamcenter.Services.Strong.Core._2014_10.DataManagement.ChildrenInputData input = new Teamcenter.Services.Strong.Core._2014_10.DataManagement.ChildrenInputData(); input.ChildrenObj = children; input.ParentObj = parent; input.PropertyName = rel; input.ClientId = "KPLAN"; ServiceData resp = dmService.RemoveChildren(new Teamcenter.Services.Strong.Core._2014_10.DataManagement.ChildrenInputData[] { input }); ThrowServiceDataError(resp); } public static ModelObject[] GetChildFromPref(ModelObject mo) { string[] prefVals = null; if (TCUtil.IsType(mo.SoaType, "Item")) { prefVals = new string[] { "revision_list",TCUtil.REL_REV_EPLAN}; } else { prefVals = new string[] { TCUtil.REL_REV_EPLAN }; } //SoaType st = mo.SoaType; //while (st != null && prefVals == null) { // string prefName = st.Name + "_DefaultChildProperties"; // prefVals = GetPrefVals(prefName); // st = st.Parent; //} if (prefVals == null || prefVals.Length == 0) { return null; } ModelObject[] mos = TCUtil.Refresh(mo); TCUtil.GetProperties(true, mos, prefVals); List modelObjects = new List(); for(int i = 0; i < prefVals.Length; i++) { try { modelObjects.AddRange(mo.GetProperty(prefVals[i]).ModelObjectArrayValue); } catch (System.Exception) { } } return modelObjects.ToArray(); } public static void SetRefProperty(ModelObject mo, string propName, List propVal) { if (mo == null ||KUtil.IsEmpty(propName)) { return; } System.Collections.Hashtable tcProps = new System.Collections.Hashtable(); VecStruct formVal = new VecStruct(); formVal.StringVec = new string[propVal.Count]; for(int i = 0; i < propVal.Count; i++) { formVal.StringVec[i] = propVal[i].Uid; } tcProps.Add(propName, formVal); ServiceData sd = dmService.SetProperties(new ModelObject[] { mo }, tcProps); ThrowServiceDataError(sd); } public static void SetProperties(ModelObject mo, Dictionary props) { if (mo == null || props == null || props.Count == 0) { return; } System.Collections.Hashtable tcProps = new System.Collections.Hashtable(); foreach (string key in props.Keys) { string val = props[key]; VecStruct formVal = new VecStruct(); formVal.StringVec = new string[] { val }; tcProps.Add(key, formVal); } ServiceData sd = dmService.SetProperties(new ModelObject[] { mo }, tcProps); ThrowServiceDataError(sd); } public static void SetArrayProperty(ModelObject mo, string propName, string[] propVal) { if (mo == null || string.IsNullOrWhiteSpace(propName)) { return; } System.Collections.Hashtable tcProps = new System.Collections.Hashtable(); VecStruct formVal = new VecStruct(); formVal.StringVec = propVal; tcProps.Add(propName, formVal); ServiceData sd = dmService.SetProperties(new ModelObject[] { mo }, tcProps); ThrowServiceDataError(sd); } public static void SetProperties(ItemRevision rev, Dictionary configProps) { if (rev == null || configProps == null || configProps.Count == 0) { return; } System.Collections.Hashtable itemProps = new System.Collections.Hashtable(); System.Collections.Hashtable revProps = new System.Collections.Hashtable(); System.Collections.Hashtable itemMasterProps = new System.Collections.Hashtable(); System.Collections.Hashtable revMasterProps = new System.Collections.Hashtable(); foreach(string key in configProps.Keys) { string[] split = key.Split('.'); string val = configProps[key]; VecStruct formVal = new VecStruct(); formVal.StringVec = new string[] { val }; if (split.Length == 2) { string loc = split[0].Trim(); string prop = split[1].Trim(); KUtil.Log(">> 添加属性:"+loc+"."+prop+" = "+val); switch (loc) { case ITEM: itemProps.Add(prop, formVal); break; case REV: revProps.Add(prop, formVal); break; case ITEMMASTER: itemMasterProps.Add(prop, formVal); break; case REVMASTER: revMasterProps.Add(prop, formVal); break; default: KUtil.Log("未知属性位置:"+loc); break; } } } ModelObject[] revs = TCUtil.Refresh(rev); TCUtil.GetProperties(false, revs, "items_tag", "IMAN_master_form_rev","object_string"); Item item = rev.Items_tag; if (item == null) { throw new Exception("获取对象失败:"+rev.Object_string); } ModelObject[] revMaster = rev.IMAN_master_form_rev; ModelObject[] items = TCUtil.Refresh(item); TCUtil.GetProperties(false, items, "IMAN_master_form"); ModelObject[] itemMaster = item.IMAN_master_form; if (itemMasterProps.Count > 0) { ServiceData sd = dmService.SetProperties(itemMaster, itemMasterProps); ThrowServiceDataError(sd); } if (revMasterProps.Count > 0) { ServiceData sd = dmService.SetProperties(revMaster, revMasterProps); ThrowServiceDataError(sd); } if (itemProps.Count > 0) { ServiceData sd = dmService.SetProperties(items, itemProps); ThrowServiceDataError(sd); } if (revProps.Count > 0) { ServiceData sd = dmService.SetProperties(revs, revProps); ThrowServiceDataError(sd); } } public static string GetRevConfigProp(ItemRevision rev,string config) { if (rev == null || KUtil.IsEmpty(config)) { return ""; } string[] split = config.Split('.'); if (split.Length != 2) { return ""; } ModelObject[] mo = Refresh(rev); GetProperties(false,mo, "object_string"); string loc = split[0].Trim(); string propName = split[1].Trim(); ModelObject target = null; switch (loc) { case ITEM: GetProperties(false, mo, "items_tag"); target = ((ItemRevision)rev).Items_tag; break; case REV: target = rev; break; case ITEMMASTER: GetProperties(false, mo, "items_tag"); Item item = ((ItemRevision)rev).Items_tag; GetProperties(false, new ModelObject[] { item }, "IMAN_master_form"); ModelObject[] forms1 = item.IMAN_master_form; target = (forms1 != null && forms1.Length > 0) ? forms1[0] : null; break; case REVMASTER: GetProperties(false, mo, "IMAN_master_form_rev"); ModelObject[] forms2 = ((ItemRevision)rev).IMAN_master_form_rev; target = (forms2 != null && forms2.Length > 0) ? forms2[0] : null; break; default: throw new Exception("获取配置属性失败,未知属性位置“"+loc+"”:" + rev.GetPropertyDisplayableValue("object_string")); } if (target == null) { throw new Exception("获取配置属性失败,获取目标位置对象失败“" + loc + "”:" + rev.GetPropertyDisplayableValue("object_string")); } ModelObject[] ts = TCUtil.Refresh(target); GetProperties(true, ts, propName); return target.GetPropertyDisplayableValue(propName); } public static string[] GetPrefVals(string prefName) { GetPreferencesResponse resp = prefService.GetPreferences(new string[] { prefName }, false); if (resp.Response.Length == 1) { return resp.Response[0].Values.Values; } return null; } public static String GetOriginalFileName(ImanFile file) { dmService.GetProperties(new ModelObject[] { file }, new string[] { "original_file_name" }); string name = file.Original_file_name; return name; } public static FileInfo GetFileInfo(ImanFile file) { if (file == null) { return null; } string cacheDir = KUtil.GetConfigValue(KConfigure.FMS_SECTION, KConfigure.FMS_PATH)+"\\"+Guid.NewGuid(); if (!Directory.Exists(cacheDir)) { Directory.CreateDirectory(cacheDir); } String[] FMS_Bootstrap_Urls = new String[] {KUtil.GetConfigValue(KConfigure.FMS_SECTION,KConfigure.FMS_URL) }; //KUtil.Log(cacheDir); // KUtil.Log(FMS_Bootstrap_Urls[0]); //if (1 == 1) {//test // return new FileInfo[] { new FileInfo("C:\\model.xml") }; //} //FileManagementService.getService(Session.getConnection()); //KUtil.Log(cacheDir); //KUtil.Log(FMS_Bootstrap_Urls[0]); //KUtil.Log("1"); FileManagementUtility fmsFileManagement = new FileManagementUtility(Session.getConnection(), null, null, FMS_Bootstrap_Urls, cacheDir); //KUtil.Log("2"); //FileManagementUtility fmsFileManagement = new FileManagementUtility(Session.getConnection()); GetFileResponse resp = fmsFileManagement.GetFiles(new ModelObject[] { file }); fmsFileManagement.Term(); ThrowServiceDataError(resp); dmService.GetProperties(new ModelObject[] { file }, new string[] { "original_file_name" }); string fileName = file.Original_file_name; FileInfo[] files = resp.GetFiles(); if (files.Length > 0) { FileInfo fileInfo = new FileInfo(files[0].DirectoryName+"\\" + fileName); files[0].MoveTo(fileInfo.FullName); return fileInfo; } return null; } public static List GetDatasetFile(ModelObject ds, string fileExt) { if (ds == null) { return null; } if (!(ds is Dataset)) { throw new Exception("对象不是数据集"); } Dataset dataset = (Dataset)ds; dmService.RefreshObjects(new ModelObject[] { dataset }); dmService.GetProperties(new ModelObject[] { dataset }, new string[] { "ref_list", "object_name" }); //KMain.Log("开始获取数据集文件:"+dataset.Object_name+",后缀名:"+fileExt); ModelObject[] refs = dataset.Ref_list; List files = new List(); foreach (ModelObject f in refs) { if (f is ImanFile) { ImanFile file = (ImanFile)f; dmService.RefreshObjects(new ModelObject[] { file }); dmService.GetProperties(new ModelObject[] { file }, new string[] { "original_file_name", "file_ext" }); //KMain.Log("找到文件:"+file.Original_file_name); string ext = file.File_ext; if (fileExt == null || "".Equals(fileExt)) { files.Add(file); } else if (ext != null && ext.ToLower().Equals(fileExt.ToLower())) { //KMain.Log("文件后缀符合要求"); files.Add(file); } } } return files; } public static bool IsType(SoaType soaType,string className) { while (soaType != null) { if (soaType.Name.Equals(className)) { return true; } soaType = soaType.Parent; } return false; } public static string GetIconNameFromClass(string className) { string res = ""; switch (className) { case "Item": res = "item"; break; case "ItemRevision": res = "itemrevision"; break; case "Dataset": res = "dataset"; break; case "Form": res = "form"; break; case "Folder": res = "folder"; break; case "Mail Folder": res = "mailboxfolder"; break; case "Newstuff Folder": res = "newstufffolder"; break; case "Fnd0HomeFolder": res = "homefolder"; break; default: break; } return res; } public static string GetIconName(ModelObject mo) { //KUtil.Log(mo.SoaType.ClassName); SoaType soaType = mo.SoaType; string iconName = ""; while(KUtil.IsEmpty(iconName) &&soaType!=null){ iconName = GetIconNameFromClass(soaType.Name); soaType = soaType.Parent; } if (KUtil.IsEmpty(iconName)) { return "logo_16.ico"; } return iconName + "_16.png"; } public static BitmapImage GetIcon(string partGroupName) { BitmapImage img; try { img = new BitmapImage(new Uri("pack://application:,,,/EPLAN.EplAddin.KPlan;component/Resources_EPLAN/" + partGroupName + ".png")); } catch(System.Exception ex) { img = new BitmapImage(new Uri("pack://application:,,,/EPLAN.EplAddin.KPlan;component/Resources/logo_16.ico")); } return img; } public static void Logout() { if (user == null) { return; } SessionService ss = SessionService.getService(Session.getConnection()); ServiceData sd = ss.Logout(); TCUtil.ThrowServiceDataError(sd); user = null; userName = ""; KPlanModule.RemoveSpMenu(); KUtil.Log("用户已注销"); } public static bool CheckLogin() { if (user != null) { return true; } string pwd = KUtil.GetConfigValue(KConfigure.LOGIN_SECTION,KConfigure.LOGIN_PWD); if (!KUtil.IsEmpty(pwd)) { string userName = KUtil.GetConfigValue(KConfigure.LOGIN_SECTION, KConfigure.LOGIN_USER); string role = KUtil.GetConfigValue(KConfigure.LOGIN_SECTION, KConfigure.LOGIN_ROLE); string host = KUtil.GetConfigValue(KConfigure.LOGIN_SECTION, KConfigure.HOST); Eplan.EplApi.Base.Progress progress = new Eplan.EplApi.Base.Progress("SimpleProgress"); try { progress.SetTitle("Teamcenter"); progress.SetAllowCancel(false); progress.BeginPart(100.0, "LOGIN"); progress.ShowImmediately(); progress.SetActionText("正在登录..."); Login(host, userName, pwd, role, true); if (user != null) { KUtil.Log("自动登录成功"); return true; } } catch (System.Exception ex) { KUtil.Log("自动登录失败"); KUtil.LogErr(ex); } finally { progress.EndPart(true); } } new Login().ShowDialog(); return user!=null; } public static void Login(string host, string userName, string password, string character, bool autoLogin) { KUtil.Log("开始登录..."); if (KUtil.IsEmpty(userName) || KUtil.IsEmpty(password)) { throw new Exception("用户名和密码不能为空"); } if (KUtil.IsEmpty(host)) { throw new Exception("获取TC服务地址失败"); } Session session = new Session(host); user = session.Login2(userName, password, "", character); dmService = DataManagementService.getService(Session.getConnection()); queryService = SavedQueryService.getService(Session.getConnection()); prefService = PreferenceManagementService.getService(Session.getConnection()); sessionService = SessionService.getService(Session.getConnection()); csService = ClassificationService.getService(Session.getConnection()); dmService.GetProperties(new ModelObject[] { user }, new string[] { "user_name" }); InitQuery(); TCUtil.userName = user.User_name; if (CheckAuthorityFromPref(PREF_ADMIN)) { KPlanModule.AddSpMenu(); } KUtil.Log("登录成功,登录用户:" + userName); KUtil.SetConfigValue(KConfigure.LOGIN_SECTION, KConfigure.LOGIN_USER, userName); KUtil.SetConfigValue(KConfigure.LOGIN_SECTION, KConfigure.LOGIN_PWD, autoLogin ? password : ""); KUtil.SetConfigValue(KConfigure.LOGIN_SECTION, KConfigure.LOGIN_ROLE, character); } public static void InitQuery() { GetSavedQueriesResponse savedQueries = queryService.GetSavedQueries(); if (savedQueries.Queries.Length == 0) { throw new Exception("系统中没有保存的查询"); } foreach (SavedQueryObject queryObj in savedQueries.Queries) { if (queryObj.Name.Equals("Latest Item Revision...")) { query_LatestRev = queryObj.Query; } } } //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; //} public static void ThrowServiceDataError(ServiceData data) { if (data.sizeOfPartialErrors() > 0) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < data.sizeOfPartialErrors(); i++) { foreach (string msg in data.GetPartialError(i).Messages) { sb.Append(msg + "\n"); } } if (sb.Length > 0) { throw new System.Exception(sb.ToString()); } } } public static void ThrowServiceDataError(GetFileResponse data) { if (data.SizeOfPartialErrors() > 0) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < data.SizeOfPartialErrors(); i++) { foreach (string msg in data.GetPartialError(i).Messages) { sb.Append(msg + "\n"); } } if (sb.Length > 0) { throw new System.Exception(sb.ToString()); } } } public static ModelObject[] query(string queryName, Dictionary fields) { KUtil.Log("开始执行查询:" + queryName + ",查询条件:"); foreach (string key in fields.Keys) { KUtil.Log(key + " = " + fields[key]); } SavedQueryObject query = null; if (!usedQueries.ContainsKey(queryName)) { GetSavedQueriesResponse savedQueries = queryService.GetSavedQueries(); if (savedQueries.Queries.Length == 0) { throw new Exception("没有从TC中找到保存的查询"); } for (int i = 0; i < savedQueries.Queries.Length; i++) { if (queryName.Equals(savedQueries.Queries[i].Name)) { query = savedQueries.Queries[i]; break; } } if (query == null) { throw new Exception("没有找到查询:" + queryName); } usedQueries.Add(queryName, query); } else { query = usedQueries[queryName]; } SavedQueryInput savedQueryInput = new SavedQueryInput(); savedQueryInput.Query = query.Query; savedQueryInput.Entries = fields.Keys.ToArray(); savedQueryInput.Values = fields.Values.ToArray(); ExecuteSavedQueriesResponse res = queryService.ExecuteSavedQueries(new SavedQueryInput[] { savedQueryInput }); ThrowServiceDataError(res.ServiceData); SavedQueryResults found = res.ArrayOfResults[0]; return found.Objects; } public static string GetPropValue(ModelObject mo, string propName) { if (mo == null || KUtil.IsEmpty(propName)) { return ""; } ServiceData resp = dmService.GetProperties(Refresh(mo), new string[] { propName }); ThrowServiceDataError(resp); return mo.GetPropertyDisplayableValue(propName); } public static string[] GetPropArrayValue(ModelObject mo, string propName) { if (mo == null || KUtil.IsEmpty(propName)) { return null; } ServiceData resp = dmService.GetProperties(Refresh(mo), new string[] { propName }); ThrowServiceDataError(resp); Teamcenter.Soa.Client.Model.Property prop = mo.GetProperty(propName); if (prop == null) { return null; } return prop.StringArrayValue;// GetPropertyDisplayableValue(propName); } } }