public static bool saveAs(SldWorks swApp, Component2 swComp0, Component2 swComp1, ModelDocExtension swModelDocExt) { // Initiate variables string stComp0; int Error = 0; int Warnings = 0; bool bRet = false; // Get component name stComp0 = swComp0.GetPathName(); stComp0 = stComp0.Replace(Path.GetExtension(stComp0), ".stl"); // Set file preferences swApp.SetUserPreferenceDoubleValue(2, 0.00002); swApp.SetUserPreferenceDoubleValue(3, 0.174532925199433); swApp.SetUserPreferenceIntegerValue(78, 433); swApp.SetUserPreferenceToggle(69, false); swApp.SetUserPreferenceToggle(70, false); swApp.SetUserPreferenceToggle(191, false); // Save as .stl bRet = swModelDocExt.SaveAs(stComp0, 0, 1, null, ref Error, ref Warnings); // Check for errors if (Error != 0) { return(false); } if (Warnings != 0) { return(false); } // Return status bool return(bRet); }
private void traverse(Component2 comp) { object[] childrens = comp.GetChildren(); foreach (Component2 child in childrens) { traverse(child); } ModelDoc2 mdocChild = comp.GetModelDoc2(); if (mdocChild.GetType() == 1) { // Bezeichnung kann über 2 Möglichkeiten erfolgen // Dateiname (mit GetFileName wird nur der Dateiname aus einem Dateipfad extrahiert string entry = System.IO.Path.GetFileName(comp.GetPathName()); // oder string entry2 = comp.Name2; //entfernen der 2 hinteren Zeichen im String entry2 = entry2.Remove(entry2.Length - 2); int Row = 0; // überprüfen, ob aktueller Eintrag bereits vorhanden ist, wenn ja Zeilen-Index speichern for (int i = 2; i < index; i++) { if ((string)exlSheet.Cells[i, 3].Value2 == entry) { Row = i; } } // wenn Zeilen Index gesetzt wurde, Wert für Anzahl aus Zeile lesen und um 1 erhöhen // erhöhten Wert in Zelle schreiben if (Row > 0) { double newCount = (double)exlSheet.Cells[Row, 1].Value2 + 1; exlSheet.Cells[Row, 1] = newCount; } else { // Wenn ZeilenIndex nicht gesetzt wurde, neuen Dateipfad exlSheet.Cells[index, 1] = 1; exlSheet.Cells[index, 2] = "Stück"; exlSheet.Cells[index, 3] = entry; lb_output.Items.Add(entry); index++; } } }
private void Rechercher_Composants(Component2 compBase) { Bdd = new BDD(); _Mdl.eRecParcourirComposants( c => { if (!c.IsSuppressed() && (c.GetPathName() == compBase.GetPathName())) { Bdd.AjouterComposant(c); } return(false); } ); }
/// <summary> /// 获取组件的类型 /// </summary> /// <param name="comp"></param> /// <returns></returns> public static swDocTemplateTypes_e GetCompType(this Component2 comp) { string extension = Path.GetExtension(comp.GetPathName()); switch (extension.ToLower()) { case ".sldprt": return(swDocTemplateTypes_e.swDocTemplateTypePART); case ".sldasm": return(swDocTemplateTypes_e.swDocTemplateTypeASSEMBLY); default: throw new FileFormatException(string.Format("不能判断组件:{0} 的类型", comp.Name2)); } }
/// <summary> /// Creer un percage ou ajouter /// </summary> /// <param name="comp"></param> private void AjouterPercage(Component2 comp = null) { Component2 Comp = comp; if (comp.IsNull()) { Comp = _AssBase.AddComponent5(CompPercage.GetPathName(), (int)swAddComponentConfigOptions_e.swAddComponentConfigOptions_CurrentSelectedConfig, "", true, CompPercage.eNomConfiguration(), 0, 0, 0); } _MdlBase.eSelectByIdComp(Comp.GetSelectByIDString()); _AssBase.eModifierEtatComposant(swComponentSuppressionState_e.swComponentResolved); _MdlBase.eEffacerSelection(); _ListePercage.Add(Comp.Name2, Comp.GetSelectByIDString()); }
// Converts the PIDs to actual references to the components public static List <Component2> LoadSWComponents(ModelDoc2 model, List <byte[]> PIDs) { List <Component2> components = new List <Component2>(); foreach (byte[] PID in PIDs) { string byteAsString = PIDToString(PID); logger.Info("Loading component with PID " + byteAsString); Component2 comp = LoadSWComponent(model, PID); if (comp == null) { logger.Warn("Component with PID " + byteAsString + " failed to load"); } else { components.Add(comp); logger.Info("Successfully loaded component " + comp.GetPathName()); } } return(components); }
private void Appliquer(List <Param> ListeParam, action_e action) { if (!FichierCharger) { return; } Dictionary <String, Component2> DicCp = new Dictionary <String, Component2>(); Func <Component2, String> Cle = delegate(Component2 cp) { String cle = cp.GetPathName(); if (radioMdl.Checked) { return(cle); } return(cle + "_" + cp.eNomConfiguration()); }; Action <Component2, Param> AppliquerProp = delegate(Component2 cp, Param p) { ModelDoc2 mdl = cp.eModelDoc2(); String cle = p.Nom, val = p.Resultat; String cfg = ""; if (radioCfg.Checked) { cfg = cp.eNomConfiguration(); } if (mdl.ePropExiste(cle, cfg)) { mdl.eGestProp(cfg).ePropSet(cle, val); return; } if (action == action_e.Importer) { mdl.eGestProp(cfg).ePropAdd(cle, val); } }; Component2 CpCourant = MdlActif.eComposantRacine(false); Component2 CpEdited = null; if (MdlActif.TypeDoc() == eTypeDoc.Assemblage) { CpEdited = MdlActif.eAssemblyDoc().GetEditTargetComponent(); } if (CpEdited.IsRef() && (CpCourant.GetPathName() != CpEdited.GetPathName())) { DicCp.Add(Cle(CpEdited), CpEdited); } else { DicCp.Add("Courant", CpCourant); } // Si c'est un assemblage, on liste les composants if (radioTtModeles.Checked && (MdlActif.TypeDoc() == eTypeDoc.Assemblage)) { MdlActif.eRecParcourirComposants( c => { String cle = Cle(c); if (!DicCp.ContainsKey(cle) && c.eEstDansLeDossier(MdlActif) && !c.IsHidden(true)) { DicCp.Add(cle, c); } return(false); }, null ); } try { foreach (Component2 cp in DicCp.Values) { foreach (Param k in ListeParam) { AppliquerProp(cp, k); } } } catch (Exception ex) { this.LogMethode(new Object[] { ex }); } }
//k - ���������� ����������� ��� ������������ private void SaveAsComponent(ModelDoc2 swModel, Component2 inComp, bool isFirstLevel, LinkedList<CopiedFileNames> filesNames, int k) { string offset = string.Empty; //for (int i = 0; i < k; i++) // offset += " "; try { string strSubCompOldFileNameFromComponent = inComp.GetPathName(); if (strSubCompOldFileNameFromComponent == "") { var swCompModel = (ModelDoc2)inComp.GetModelDoc(); if (swCompModel != null) strSubCompOldFileNameFromComponent = swCompModel.GetPathName(); else return; } bool isModelAlreadyReplaced = filesNames.Any(oldfile => oldfile.OldName == strSubCompOldFileNameFromComponent); if (!isModelAlreadyReplaced) { ModelDoc2 swCompModel; string strSubCompOldFileNameFromModel; if (GetComponentModel(swModel, inComp, out swCompModel, out strSubCompOldFileNameFromModel)) { bool isAuxiliary = (swCompModel.get_CustomInfo2("", "Auxiliary") == "Yes"); bool isAccessory = (swCompModel.get_CustomInfo2("", "Accessories") == "Yes"); string strSubCompNewFileName; if (GetComponentNewFileName(swModel, isAuxiliary, isAccessory, isFirstLevel, strSubCompOldFileNameFromModel, out strSubCompNewFileName)) { bool isCopyError = false; try { if (!File.Exists(strSubCompNewFileName)) //��������� { File.Copy(strSubCompOldFileNameFromModel, strSubCompNewFileName, true); } } catch (Exception) { MessageBox.Show(@"�� ������� ��������� ���� " + strSubCompNewFileName, MyTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); isCopyError = true; } if (!isCopyError) { filesNames.AddLast(new CopiedFileNames(strSubCompOldFileNameFromComponent, strSubCompNewFileName)); File.SetAttributes(strSubCompNewFileName, FileAttributes.Normal); var subComps = new LinkedList<Component2>(); if (GetComponents(inComp, subComps, false, false)) { foreach (Component2 subcmp in subComps) { SaveAsComponent(swModel, subcmp, false, filesNames, k + 1); } } SwDmDocumentOpenError oe; SwDMApplication swDocMgr = GetSwDmApp(); var swDoc = (SwDMDocument8)swDocMgr.GetDocument(strSubCompNewFileName, SwDmDocumentType.swDmDocumentAssembly, false, out oe); if (swDoc != null) { SwDMSearchOption src = swDocMgr.GetSearchOptionObject(); src.SearchFilters = 255; object brokenRefVar; var varRef = (object[])swDoc.GetAllExternalReferences2(src, out brokenRefVar); if (varRef != null) { foreach (object t in varRef) { var strRef = (string)t; string strRefFileName = Path.GetFileName(strRef); string strNewRef = ""; foreach (CopiedFileNames oldfile in filesNames) { if (Path.GetFileName(oldfile.OldName).ToLower() == strRefFileName.ToLower()) { strNewRef = oldfile.NewName; break; } } if (strNewRef != "") swDoc.ReplaceReference(strRef, strNewRef); } } swDoc.Save(); swDoc.CloseDoc(); } if (isFirstLevel) { var outList1 = new LinkedList<Component2>(); if (inComp.Select(false)) ((AssemblyDoc)swModel).ReplaceComponents(strSubCompNewFileName, "", false, true); if (inComp.Select(false)) ((AssemblyDoc)swModel).ComponentReload(); if (GetComponents(inComp, outList1, true, false)) { foreach (var component in outList1) { var model = component.IGetModelDoc(); if (model != null && model.GetConfigurationCount() > 1) { int err = 0, wrn = 0; var mod = SwApp.OpenDoc6(model.GetPathName(), (int)swDocumentTypes_e.swDocPART, 0, "", ref err, ref wrn); if (mod != null) { mod.ShowConfiguration2(component.ReferencedConfiguration); mod.Save(); SwApp.CloseDoc(mod.GetPathName()); } } } } } } } } } } catch (Exception e) { Logging.Log.Instance.Fatal(e.Message + "SaveAsComponent()"); MessageBox.Show(e.Message, MyTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } return; }
protected override void Command() { Ass = MdlBase.eAssemblyDoc(); try { CurveDrivenPatternFeatureData def = FonctionRepetition.GetDefinition(); Object[] tabB = def.PatternBodyArray; Body2 b = (Body2)tabB[0]; MathTransform compRepetTrans = ComposantRepetition.Transform2; MathTransform baseMarcheTrans = Marche.Transform2; Vertex v = (Vertex)Point; Edge e = (Edge)Arrete; List <Face2> ListeFace = FonctionRepetition.eListeDesFaces(); Sketch sk = PointMarche.GetSketch(); Feature fPointMarche = (Feature)sk; List <Component2> ListeComposants = new List <Component2>() { Marche }; Double arr = 0.0001; for (int i = 1; i <= (def.D1InstanceCount + def.D2InstanceCount); i++) { MathTransform bodyTrans = def.GetTransform(i); if (bodyTrans.IsNull()) { break; } MathTransform Transform = compRepetTrans.Inverse(); Transform = Transform.Multiply(bodyTrans); Transform = Transform.Multiply(compRepetTrans); Transform = baseMarcheTrans.Multiply(Transform); gPoint pt = new gPoint(v); gSegment sg = new gSegment(e); pt.MultiplyTransfom(bodyTrans); sg.MultiplyTransfom(bodyTrans); Vertex vertex = null; Edge edge = null; foreach (Face2 face in ListeFace) { foreach (Edge ed in face.eListeDesArretes()) { gSegment s = new gSegment(ed); if (sg.Compare(s, arr)) { edge = ed; } if (s.Start.Comparer(pt, arr)) { vertex = ed.GetStartVertex(); } if (s.End.Comparer(pt, arr)) { vertex = ed.GetEndVertex(); } if (edge.IsRef() && vertex.IsRef()) { break; } } if (edge.IsRef() && vertex.IsRef()) { break; } } Entity eVertex = (Entity)vertex; Entity eEdge = (Entity)edge; Component2 cp = Ass.AddComponent5(Marche.GetPathName(), (int)swAddComponentConfigOptions_e.swAddComponentConfigOptions_CurrentSelectedConfig, "", false, "", 0, 0, 0); if (cp.IsNull()) { continue; } // Quand on réinsere un composant, les précédentes contraintes sont recrées. // On les supprime pour eviter des conflits Object[] Mates = cp.GetMates(); if (Mates.IsRef()) { foreach (Feature mate in Mates) { mate.eSelect(); MdlBase.Extension.DeleteSelection2((int)swDeleteSelectionOptions_e.swDelete_Absorbed); } } WindowLog.Ecrire(cp.Name2); cp.Transform2 = Transform; ListeComposants.Add(cp); int longstatus = 0; MdlBase.eEffacerSelection(); eVertex.eSelectEntite(false); Feature f = cp.FeatureByName(fPointMarche.Name); Sketch sketchOrigine = f.GetSpecificFeature2(); Object[] tabPt = sketchOrigine.GetSketchPoints2(); SketchPoint origine = (SketchPoint)tabPt[0]; origine.Select4(true, null); Mate2 mPoint = Ass.AddMate5((int)swMateType_e.swMateCOINCIDENT, (int)swMateAlign_e.swMateAlignCLOSEST, false, 0, 0, 0, 0, 0, 0, 0, 0, false, false, 0, out longstatus); MdlBase.eEffacerSelection(); MdlBase.eEffacerSelection(); eEdge.eSelectEntite(false); cp.FeatureByName(AxeMarche.Name).eSelect(true); Mate2 mAxe = Ass.AddMate5((int)swMateType_e.swMateANGLE, (int)swMateAlign_e.swAlignNONE, false, 0, 0, 0, 0, 0, 0, 0, 0, false, false, 0, out longstatus); MdlBase.eEffacerSelection(); MdlBase.eEffacerSelection(); Plan.eSelect(false); cp.FeatureByName(PlanMarche.Name).eSelect(true); Mate2 mPlan = Ass.AddMate5((int)swMateType_e.swMatePARALLEL, (int)swMateAlign_e.swAlignNONE, false, 0, 0, 0, 0, 0, 0, 0, 0, false, false, 0, out longstatus); MdlBase.eEffacerSelection(); Feature m = (Feature)mPoint; WindowLog.Ecrire(" " + m.Name); m = (Feature)mAxe; WindowLog.Ecrire(" " + m.Name); m = (Feature)mPlan; WindowLog.Ecrire(" " + m.Name); } MdlBase.eEffacerSelection(); foreach (var cp in ListeComposants) { cp.eSelectById(MdlBase, -1, true); } Feature Dossier = MdlBase.FeatureManager.InsertFeatureTreeFolder2((int)swFeatureTreeFolderType_e.swFeatureTreeFolder_Containing); Dossier.eRenommerFonction(String.Format("Marches ({0} {1}) ", ComposantRepetition.Name2, FonctionRepetition.Name)); } catch (Exception e) { this.LogErreur(new Object[] { e }); } }
public void Main() { swSuccess = false; errors = 0; warnings = 0; string swSourcePath = swApp.GetCurrentWorkingDirectory(); string swExportPath = Path.Combine(swSourcePath, "IGS"); string[] tmp = Directory.GetFiles(swSourcePath, "*.SLDPRT", SearchOption.TopDirectoryOnly); if (Directory.Exists(swExportPath)) { Directory.Delete(swExportPath, true); } Directory.CreateDirectory(swExportPath); ModelDoc2 swModel = swApp.ActiveDoc as ModelDoc2; AssemblyDoc swAssem = (AssemblyDoc)swModel; #region TopLevel string igsFileName = MakeFileName(swModel.Extension.Document.GetTitle()); swModel.Extension.SaveAs(Path.Combine(swExportPath, igsFileName), (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Copy, null, ref errors, ref warnings); //PrintSaveResults(); #endregion TopLevel #region Subassemblies string swExportSubPath = Path.Combine(swExportPath, "Subassemblies"); Directory.CreateDirectory(swExportSubPath); object[] objComps = (object[])swAssem.GetComponents(true); ModelDoc2 igsModel; foreach (object obj in objComps) { swComponent = obj as Component2; Debug.WriteLine(String.Format("Working on {0}.. \n\t {1}", swComponent.Name2, swComponent.GetPathName())); igsModel = swApp.OpenDoc6(swComponent.GetPathName(), (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_ReadOnly, null, ref errors, ref warnings); swApp.ActivateDoc2(igsModel.GetTitle(), true, ref errors); igsFileName = MakeFileName(igsModel.Extension.Document.GetTitle()); igsModel.Extension.SaveAs(Path.Combine(swExportSubPath, igsFileName), (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Copy, null, ref errors, ref warnings); swApp.CloseDoc(igsModel.GetTitle()); } #endregion Subassemblies #region Parts string swExportPartPath = Path.Combine(swExportPath, "Parts"); Directory.CreateDirectory(swExportPartPath); string[] swPartFiles = Directory.GetFiles(swSourcePath, "*.SLDPRT", SearchOption.TopDirectoryOnly); foreach (string partFile in swPartFiles) { try { igsModel = swApp.OpenDoc6(partFile, (int)swDocumentTypes_e.swDocPART, (int)swOpenDocOptions_e.swOpenDocOptions_ReadOnly, null, ref errors, ref warnings); swApp.ActivateDoc2(igsModel.GetTitle(), true, ref errors); string[] swConfigs = (string[])igsModel.GetConfigurationNames(); int swConfigCount = igsModel.GetConfigurationCount(); string swConfigFilename; for (int i = 0; i < swConfigCount; i++) { igsModel.ShowConfiguration2(swConfigs[i]); swConfigFilename = igsModel.Extension.Document.GetTitle(); if (swConfigCount > 1) { swConfigFilename += String.Format("-CFG{0}", (i + 1).ToString()); } igsFileName = MakeFileName(swConfigFilename); igsModel.Extension.SaveAs(Path.Combine(swExportPartPath, igsFileName), (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Copy, null, ref errors, ref warnings); } swApp.CloseDoc(igsModel.GetTitle()); } catch (NullReferenceException e) { Debug.WriteLine(e.Message); } } #endregion Parts string timeFilename = Path.Combine(swExportPath, "Timestamp.txt"); using (StreamWriter swTimeStamper = new StreamWriter(timeFilename)) { swTimeStamper.WriteLine("Exported on {0} at {1}", System.DateTime.Now.ToShortDateString(), System.DateTime.Now.ToShortTimeString()); swTimeStamper.Flush(); } }
/// <summary> /// Returns Lists of Custom_parts and Standard_Parts /// </summary> /// <param name="swModel"></param> /// <param name="swTableAnn"></param> /// <param name="ConfigName"></param> /// <param name="Standard_Parts"></param> /// <param name="Custom_Parts"></param> public static void Get_Sorted_Part_Data(ModelDoc2 swModel, BomFeature swBomFeat, List <BOM_Part_Informations> Standard_Parts, List <BOM_Part_Informations> Custom_Parts, string projectpath) { try { int nNumRow = 0; int J = 0; int I = 0; int numStandard_Part = 1; int numCustom_Part = 1; int quantity = 0; int index_description = 0; int index_article_number = 0; int index_supplier = 0; BOM_Part_Informations part_informations; string ItemNumber = null; string PartNumber = null; // Debug.Print(" Table Title " + swTableAnn.Title); Feature swFeat = default(Feature); object[] vTableArr = null; object vTable = null; string[] vConfigArray = null; object vConfig = null; string ConfigName = null; string partconfig = null; TableAnnotation swTable = default(TableAnnotation); Annotation swAnnotation = default(Annotation); object visibility = null; swFeat = swBomFeat.GetFeature(); vTableArr = (object[])swBomFeat.GetTableAnnotations(); foreach (TableAnnotation vTable_loopVariable in vTableArr) { vTable = vTable_loopVariable; swTable = (TableAnnotation)vTable; vConfigArray = (string[])swBomFeat.GetConfigurations(true, ref visibility); foreach (object vConfig_loopVariable in vConfigArray) { vConfig = vConfig_loopVariable; ConfigName = (string)vConfig; // MessageBox.Show(ConfigName); // swTable.SaveAsPDF(@"C:\Users\alex\Desktop\test.pdf"); nNumRow = swTable.RowCount; BomTableAnnotation swBOMTableAnn = default(BomTableAnnotation); swBOMTableAnn = (BomTableAnnotation)swTable; //swTable.GetColumnTitle for (int h = 0; h < swTable.ColumnCount; h++) { switch (swTable.GetColumnTitle(h)) { case "Benennung": index_description = h; break; case "Artikelnummer": index_article_number = h; break; case "Lieferant": index_supplier = h; break; default: break; } } if (index_supplier != 0 || index_supplier != 0 || index_article_number != 0) //Standard BOM Template { for (int n = 0; n <= nNumRow - 1; n++) { // Debug.Print(" Row Number " + J + " Component Count : " + swBOMTableAnn.GetComponentsCount2(J, ConfigName, out ItemNumber, out PartNumber)); // Debug.Print(" Item Number : " + ItemNumber); // Debug.Print(" Part Number : " + PartNumber); // MessageBox.Show("bubu"); object[] vPtArr = null; Component2 swComp = null; object pt = null; quantity = swBOMTableAnn.GetComponentsCount2(n, ConfigName, out ItemNumber, out PartNumber); vPtArr = (object[])swBOMTableAnn.GetComponents2(n, ConfigName); if (((vPtArr != null))) { for (I = 0; I <= vPtArr.GetUpperBound(0); I++) { pt = vPtArr[I]; swComp = (Component2)pt; if ((swComp != null)) { part_informations = new BOM_Part_Informations(); part_informations.manufacturer = swTable.get_Text(n, index_supplier); part_informations.order_number = swTable.get_Text(n, index_article_number); part_informations.IsAssembly = false; part_informations.part_number = PartNumber.TrimStart(); part_informations.quantity = quantity.ToString(); //Custom part if (swComp.GetPathName().Contains(projectpath)) { if (swComp.GetPathName().Contains(".sldasm") || swComp.GetPathName().Contains(".SLDASM")) { // MessageBox.Show(swComp.GetPathName()); part_informations.IsAssembly = true; } part_informations.description = swComp.ReferencedConfiguration; part_informations.item_number = numCustom_Part.ToString(); numCustom_Part++; Custom_Parts.Add(part_informations); break; } part_informations.description = swTable.get_Text(n, index_description); part_informations.item_number = numStandard_Part.ToString(); numStandard_Part++; Standard_Parts.Add(part_informations); break; } else { Debug.Print(" Could not get component."); } } } } } else //No Standard BOM Template { for (J = 0; J <= nNumRow - 1; J++) { // Debug.Print(" Row Number " + J + " Component Count : " + swBOMTableAnn.GetComponentsCount2(J, ConfigName, out ItemNumber, out PartNumber)); // Debug.Print(" Item Number : " + ItemNumber); // Debug.Print(" Part Number : " + PartNumber); object[] vPtArr = null; Component2 swComp = null; object pt = null; quantity = swBOMTableAnn.GetComponentsCount2(J, ConfigName, out ItemNumber, out PartNumber); vPtArr = (object[])swBOMTableAnn.GetComponents2(J, ConfigName); if (((vPtArr != null))) { for (I = 0; I <= vPtArr.GetUpperBound(0); I++) { pt = vPtArr[I]; swComp = (Component2)pt; if ((swComp != null)) { part_informations = new BOM_Part_Informations(); part_informations.description = swComp.ReferencedConfiguration; part_informations.part_number = PartNumber; part_informations.quantity = quantity.ToString(); //Custom part if (swComp.GetPathName().Contains(projectpath)) { if (swComp.GetPathName().Contains(".sldasm") || swComp.GetPathName().Contains(".SLDASM")) { break; } else { part_informations.item_number = numCustom_Part.ToString(); numCustom_Part++; Custom_Parts.Add(part_informations); break; } } part_informations.item_number = numStandard_Part.ToString(); numStandard_Part++; Standard_Parts.Add(part_informations); break; } else { Debug.Print(" Could not get component."); } } } } } break; } } swAnnotation = swTable.GetAnnotation(); swAnnotation.Select3(false, null); swModel.EditDelete(); } catch (Exception ex) { MessageBox.Show(ex.Message + ex.StackTrace); } }
public void ProcessTableAnn(IEdmVault5 poVault, BomTableAnnotation swBOMTableAnn, string ConfigName, SldAsm asmPrd) { int nNumRow = 0; string ItemNumber = null; string PartNumber = null; TableAnnotation swTableAnn = (TableAnnotation)swBOMTableAnn; nNumRow = swTableAnn.RowCount; swBOMTableAnn = (BomTableAnnotation)swTableAnn; for (int j = 0; j < swTableAnn.RowCount; j++) { // //for (int i = 0; i < swTableAnn.ColumnCount;i++ ) // Console.WriteLine(swTableAnn.get_Text(j, i)); //获取类别和特有信息 if (j == swTableAnn.RowCount - 1)//最后一行为标题栏,跳过 { continue; } string filePath = ""; string compName = ""; string compConfig = ""; int compCount = swBOMTableAnn.GetComponentsCount2(j, ConfigName, out ItemNumber, out PartNumber); object[] vPtArr = swBOMTableAnn.GetComponents2(j, ConfigName); if (vPtArr != null) { for (int prIndex = 0; prIndex <= vPtArr.GetUpperBound(0); prIndex++) { Component2 swComp = (Component2)vPtArr[prIndex]; if ((swComp != null)) { //Debug.Print(" Component Name :" + swComp.Name2 + " Configuration Name : " + swComp.ReferencedConfiguration); //Debug.Print(" Component Path :" + swComp.GetPathName()); filePath = swComp.GetPathName(); compName = swComp.Name2; compConfig = swComp.ReferencedConfiguration; break; } else { continue; } } //Component2 comp2 = null; //comp2 = swBOMTableAnn.IGetComponents2(j, ConfigName, 0); //if (comp2 != null) //{ // filePath = comp2.GetPathName(); // compName = comp2.Name2; // compConfig = comp2.ReferencedConfiguration; //} } SldBsp bsp = null; if (filePath == "") { errors++; errorStr += "明细表第" + (j + 1) + "行" + swTableAnn.get_Text(j, 1) + " 未找到关联文件\n"; bsp = new SldBsp(); bsp.type = 5; } else { bsp = GetSldPrdInfoFromFile(poVault, filePath); if (bsp == null) { errors++; errorStr += "明细表第" + (j + 1) + "行" + swTableAnn.get_Text(j, 1) + " 文件:" + filePath + " 在PDM中未找到\n"; bsp = new SldBsp(); bsp.type = 5; } } bsp.path = filePath; //SldBsp bsp = new SldBsp(); swTableAnn.get_Text(j, 0); //序号 bsp.number = swTableAnn.get_Text(j, 1); //代号 bsp.name = swTableAnn.get_Text(j, 2); //名称 string amout = swTableAnn.get_Text(j, 3); int parseInt = 0; try { parseInt = int.Parse(amout); }catch (Exception) { parseInt = 0; } bsp.amout = parseInt; //数量 bsp.material = swTableAnn.get_Text(j, 4); //材料 string weight = swTableAnn.get_Text(j, 5); double parseDouble = 0.0; try { parseDouble = double.Parse(weight); } catch (Exception) { parseDouble = 0.0; } bsp.weight = parseDouble; //单重 bsp.totalWeight = bsp.weight * bsp.amout; // swTableAnn.get_Text(j, 6);//总重 bsp.remark = swTableAnn.get_Text(j, 7); //备注 //string number = swTableAnn.get_Text(j, 8);//测试 //if (bsp.number == "") bsp.number = number; if (bsp is SldPrt) { bsp.materialNumber = bsp.number == ""?"":("03." + bsp.number); asmPrd.sldPrtList.Add((SldPrt)bsp); } else if (bsp is SldStd) { asmPrd.sldStdList.Add((SldStd)bsp); } else if (bsp is SldBuy) { asmPrd.sldBuyList.Add((SldBuy)bsp); } else if (bsp is SldBsp) { asmPrd.sldBspList.Add(bsp); } } return; }
public int OnNewSelection() { //var swSelMgr = document.SelectionManager; //var f = swSelMgr.GetSelectedObject6(1, 0); ModelDoc2 swDoc = null; Feature swFeature; swDoc = iSwApp.ActiveDoc; SelectionMgr swSelMgr; swSelMgr = (SelectionMgr)swDoc.SelectionManager; Feature swFeat = default(Feature); ModelDocExtension swModDocExt = default(ModelDocExtension); Component2 swComp = default(Component2); object vModelPathName = null; int selObjType = 0; int nRefCount = 0; selObjType = swSelMgr.GetSelectedObjectType3(1, -1);; if (selObjType == (int)swSelectType_e.swSelBODYFEATURES) { swFeature = swSelMgr.GetSelectedObject6(1, 1); } else if (selObjType == (int)swSelectType_e.swSelCOMPONENTS) { swComp = (Component2)swSelMgr.GetSelectedObjectsComponent3(1, -1); if (swComp == null) { return(0); } //MessageBox.Show(swComp.GetPathName()); swFeat = swComp.FirstFeature(); EventHelper eh = EventHelper.GetInstance(); SelectedEventArgs arg = new SelectedEventArgs(); arg.ComponentName = swComp.GetPathName(); eh.RasieTesting(arg); //display feature's sensor //MessageBox.Show(swFeat.Name); } else if (selObjType == (int)swSelectType_e.swSelSKETCHES) { swFeat = (Feature)swSelMgr.GetSelectedObject6(1, -1); nRefCount = swFeat.ListExternalFileReferencesCount(); } //Component2 swComp = null; //swComp = (Component2)swDwgComp.Component; //ModelDoc2 swCompModDoc = null; //swCompModDoc = (ModelDoc2)swComp.GetModelDoc2(); //Debug.Print("dsfasdf"); //var swSelMgr = modelDoc2.SelectionManager; //var swCompEnt = swSelMgr.GetSelectedObject6(1, 0); #region 递归输出Feature.Name //StringBuilder sb = new StringBuilder(); //Feature feature = modelDoc2.FirstFeature(); //Feature nextFeature = null; //sb.Append("名称:" + feature.Name + "----类型:" + feature.GetTypeName()); //while (feature != null) //{ // nextFeature = (Feature)feature.GetNextFeature(); // if (nextFeature == null) { break; } // sb.Append("名称:" + nextFeature.Name + "----类型:" + feature.GetTypeName()); // feature = null; // feature = nextFeature; // nextFeature = null; //} #endregion #region 类型转换出错 //ModelDocExtension swModelDocExt = default(ModelDocExtension); //SelectionMgr swSelMgr = default(SelectionMgr); //Feature swFeat = default(Feature); //string featName = null; //string featType = null; //swSelMgr = (SelectionMgr)document.SelectionManager; //swModelDocExt = (ModelDocExtension)document.Extension; //// Get the selected feature //swFeat = (Feature)swSelMgr.GetSelectedObject6(1, -1); //document.ClearSelection2(true); //// Get the feature's type and name //featName = swFeat.GetNameForSelection(out featType); //swModelDocExt.SelectByID2(featName, featType, 0, 0, 0, true, 0, null, 0); //MessageBox.Show(featName + "" + featType); #endregion return(0); }
public void TableTopProcess(Component2 swAddedComp) { var mates = swAddedComp.GetMates(); Component2 firstComponent = null; var swAddedCompModel = (ModelDoc2)swAddedComp.GetModelDoc(); bool? isLeft = null; if (swAddedCompModel.GetCustomInfoValue("", "KitchenType").Contains("левая")) isLeft = true; else if (swAddedCompModel.GetCustomInfoValue("", "KitchenType").Contains("правая")) isLeft = false; if (isLeft == null) return; if (mates != null) { foreach (var mate in mates) { if (mate is Mate2) { var spec = (Mate2)mate; int mec = spec.GetMateEntityCount(); if (mec > 1) { for (int ik = 0; ik < mec; ik++) { MateEntity2 me = spec.MateEntity(ik); if (me.ReferenceComponent.Name.Contains(swAddedComp.Name)) { string firstComp = spec.MateEntity(0).ReferenceComponent.Name.Split('/')[0]; swAddin.GetComponentByName(RootModel, firstComp, false, out firstComponent); break; } } } } } } if (firstComponent != null) { //привязать... swAddin.AddMate(RootModel, firstComponent.FeatureByName("#swrfЗадняя"), swAddedComp.FeatureByName("#swrfЗадняя"), true); } bool status; var swComponents = new LinkedList<Component2>(); if (swAddin.GetComponents(swRootComponent, swComponents, false, false)) { double[] origBox = swAddedComp.GetBox(true, true); double origaverx = Math.Min(origBox[3], origBox[0]) + Math.Abs(origBox[3] - origBox[0]) / 2; double origaverz = Math.Min(origBox[5], origBox[2]) + Math.Abs(origBox[5] - origBox[2]) / 2; var swCompModel = (ModelDoc2)firstComponent.GetModelDoc(); bool isAnglePartFirst = false, isUpPartfirst = false, isTabletopFirst = false; if (swCompModel != null) GetTypeProperty(swCompModel.GetCustomInfoValue("", "KitchenType"), out isAnglePartFirst, out isUpPartfirst, out isTabletopFirst); if (isTabletopFirst || isUpPartfirst) return; string tmp = (bool)isLeft ? "#swrfЛевая" : "#swrfПравая"; if (isAnglePartFirst) swAddin.AddMate(RootModel, firstComponent.FeatureByName("#swrfЗадняя2"), swAddedComp.FeatureByName(tmp), true); else swAddin.AddMate(RootModel, firstComponent.FeatureByName(tmp), swAddedComp.FeatureByName(tmp), true); InfoForMate maxDistance = FindMinTopTable(swComponents, swAddedComp, isLeft); InfoForMate maxDistance3 = FindMaxPlate(swComponents, swAddedComp, firstComponent, origaverx, origaverz, isAnglePartFirst, isLeft); if (maxDistance.planeDist != null && maxDistance.planeSource != null && maxDistance3.distance > maxDistance.distance)//&& maxDistance3.planeSource.Name == maxDistance.planeSource.Name) { swModel.ClearSelection(); InfoForMate maxDistance2 = new InfoForMate(double.MinValue, null, null); string tt = isAnglePartFirst ? "#swrfЗадняя2" : plateleft; status = RootModel.Extension.SelectByID2(string.Format("{0}@{1}@{2}", tt, firstComponent.Name, rootName), "PLANE", 0, 0, 0, false, 0, null, 0); maxDistance.planeDist.Select(true); measure.Calculate(null); if (measure.IsParallel && maxDistance2.distance < measure.Distance) maxDistance2 = new InfoForMate(measure.Distance, firstComponent.FeatureByName(tt), null); swModel.ClearSelection(); status = RootModel.Extension.SelectByID2(string.Format("{0}@{1}@{2}", plateright, firstComponent.Name, rootName), "PLANE", 0, 0, 0, false, 0, null, 0); maxDistance.planeDist.Select(true); measure.Calculate(null); if (measure.IsParallel && maxDistance2.distance < measure.Distance) maxDistance2 = new InfoForMate(measure.Distance, firstComponent.FeatureByName(plateright), null); //if (maxDistance2.planeDist!=null) // swAddin.AddMate(swModel, maxDistance2.planeDist, maxDistance.planeSource, true);//distToTopTable = new InfoForMate(maxDistance.distance, maxDistance2.planeDist, maxDistance.planeSource);// swModel.ClearSelection(); maxDistance.planeDist.Select(false); maxDistance2.planeDist.Select(true); measure.Calculate(null); maxDistance.distance = measure.Distance; } else { maxDistance = maxDistance3;//maxDistance = FindMaxPlate(swComponents, swAddedComp, firstComponent, origaverx, origaverz,isAnglePartFirst); //if (maxDistance.planeDist != null && maxDistance.planeSource != null) //{ // if (maxDistance.planeSource.Name != "#swrfЗадняя2") // swAddin.AddMate(swModel, maxDistance.planeSource, swAddedComp.FeatureByName(maxDistance.planeSource.Name), true); // else // { // maxDistance.planeSource.Select(false); // swAddedComp.FeatureByName(plateleft).Select(true); // measure.Calculate(null); // double distanceleft = measure.Distance; // maxDistance.planeSource.Select(false); // swAddedComp.FeatureByName(plateright).Select(true); // measure.Calculate(null); // double distanceright = measure.Distance; // if (distanceleft<distanceright) // swAddin.AddMate(swModel, maxDistance.planeSource, swAddedComp.FeatureByName(plateleft), true); // else // swAddin.AddMate(swModel, maxDistance.planeSource, swAddedComp.FeatureByName(plateright), true); // } //} } double distance2; swModel.ClearSelection(); if (!isAnglePartFirst) status = RootModel.Extension.SelectByID2(string.Format("{0}@{1}@{2}", "Передняя", firstComponent.Name, rootName), "PLANE", 0, 0, 0, false, 0, null, 0); else status = RootModel.Extension.SelectByID2(string.Format("{0}@{1}@{2}", plateleft, firstComponent.Name, rootName), "PLANE", 0, 0, 0, false, 0, null, 0); status = RootModel.Extension.SelectByID2(string.Format("{0}@{1}@{2}", "#swrfЗадняя", firstComponent.Name, rootName), "PLANE", 0, 0, 0, true, 0, null, 0); measure.Calculate(null); distance2 = measure.Distance * 1000; //поменять размер.. var curModel = swAddedComp.GetModelDoc2(); bool isNumber = false; OleDbConnection oleDb; OleDbDataReader rd; List<string> strObjNames = new List<string>(); string filePath = swAddedComp.GetPathName(); if (swAddin.OpenModelDatabase(curModel, out oleDb)) { using (oleDb) { OleDbCommand cm; cm = isNumber ? new OleDbCommand( "SELECT * FROM objects WHERE number>0 ORDER BY number", oleDb) : new OleDbCommand("SELECT * FROM objects ORDER BY id", oleDb); rd = cm.ExecuteReader(); while (rd.Read()) { if (rd["caption"].ToString() == null || rd["caption"].ToString() == "" || rd["caption"].ToString().Trim() == "") continue; string strObjName = rd["name"].ToString(); if (filePath.Contains("_SWLIB_BACKUP")) { string pn = Path.GetFileNameWithoutExtension(filePath); string last3 = pn.Substring(pn.Length - 4, 4); string[] arr = strObjName.Split('@'); if (arr.Length != 3) throw new Exception("что-то не так"); arr[2] = Path.GetFileNameWithoutExtension(arr[2]) + last3 + Path.GetExtension(arr[2]); strObjName = string.Format("{0}@{1}@{2}", arr[0], arr[1], arr[2]); } strObjNames.Add(strObjName); } } } swAddin.SetObjectValue(curModel, strObjNames[0], 14, maxDistance.distance * 1000); swAddin.SetObjectValue(curModel, strObjNames[1], 14, distance2); } }
/// <summary> /// 对于一个视图进行重排序,返回序号已经排到哪了 /// </summary> private int ReSortOneView(int abc, SolidWorks.Interop.sldworks.View swView, ModelDoc2 swModel) { //先得到视图的对角线的三点坐标和比例//初始化视图 this.GetViewThreePointAndScale(swView); //排序用 ArrayList arSort = new ArrayList(); //保存数据 Hashtable ht = new Hashtable(); //保存数据 Hashtable ht2 = new Hashtable(); //是否有在右上方的//如果没有则为0,否则保在最上方的最大值,如果最大值<0.15,说明虽然有在上方的,但可以忽略,因为离左上角很进. double dAtTopMaxValue = 0; //遍历注释 Note not = (Note)swView.GetFirstNote(); while (not != null) { if (not.IsBomBalloon()) //只有符号这个条件才可以 { Annotation ann = (Annotation)not.GetAnnotation(); //必须要有Annotation if (ann == null) { goto ABC; } object[] obArr = (object[])ann.GetAttachedEntities2();//必须要有Entities if (obArr == null || obArr.Length == 0) { goto ABC; } Entity ent = (Entity)obArr[0]; Component2 comp = (Component2)ent.GetComponent(); //看看是否有重复的,一个配置只允许标注一次,如果需要多次标注,只能用不同的配置。 string FullPath = comp.GetPathName() + comp.ReferencedConfiguration; if (arCheckRepect.Contains(FullPath)) { goto ABC; } else { arCheckRepect.Add(FullPath); } //string txt = not.GetText(); double[] dbArr = (double[])not.GetTextPoint2(); //计算角度 double dAngle = GetAngelByNotePoint(dbArr[0], dbArr[1]); if (CheckUnderOrUpTheLine(dbArr[0], dbArr[1]) == true)//在上方//升序 { if (dAtTopMaxValue < dAngle) { dAtTopMaxValue = dAngle; //保存这个角度//这个角度是上方角度的最大值 } } else//下方的//降序 { dAngle = 15 - dAngle;//dAngle一般不会大于二 } arSort.Add(dAngle); //排序 ht.Add(dAngle, not); //保存数据 ht2.Add(dAngle, comp); //防止再算一遍 } ABC: not = (Note)not.GetNext(); } /////////////////////////////////////////////////////////////////////////////////////////////// arSort.Sort();//排序 if (dAtTopMaxValue < 0.15) { arSort.Reverse(); //如果上方没有,或靠近左上角的地方有一两个(Angle<0.15),下方的也不会按DESC排序 } ///////////////////////////////////////////////////////////////////////////////////////////////// //序号为项目号,还是零件属性,还是文本 int iTextContent = -1; string strText = ""; if (this.rdoTemp1.Checked) { iTextContent = (int)swDetailingNoteTextContent_e.swDetailingNoteTextItemNumber; strText = ""; } else if (this.rdoTemp2.Checked) { iTextContent = (int)swDetailingNoteTextContent_e.swDetailingNoteTextCustomProperty; strText = "$PRPMODEL:\"序号\""; } else if (this.rdoTemp3.Checked) { iTextContent = (int)swDetailingNoteTextContent_e.swDetailingNoteTextCustom; strText = ""; } else if (this.rdoTemp4.Checked) { iTextContent = (int)swBalloonTextContent_e.swBalloonTextQuantity; strText = "0"; } //开始修改 for (int i = 0; i < arSort.Count; i++) { Note notsub = (Note)ht[arSort[i]]; Component2 comp = (Component2)ht2[arSort[i]]; //选中这个注释 swModel.Extension.SelectByID2(notsub.GetName() + "@" + swView.Name, "NOTE", 0, 0, 0, true, 0, null, 0); if (this.rdoTemp2.Checked) { this.swm.SetAtrByCompAndAtrName(comp, "序号", abc);//设置属性,并保存到零件 } else { strText = abc.ToString();//序号 } //notsub.PropertyLinkedText = "$PRPMODEL:\"序号\"";//这样可能也可以 notsub.SetBomBalloonText(iTextContent, strText, iTextContent, strText); ////////////////////////////////////////////////////////////////////// //检查看看是否正确,如果不正确,再设置,这里没起到任何作用 string txt = notsub.GetText(); if (txt != abc.ToString()) { notsub.SetText(abc.ToString()); } /////////////////////////////////////////////////////////////////////// abc++; } return(abc); }
/// <summary> /// 如果不是数字冲排序,而是重新指定文字,特别是一些复杂的组合,如【项目数X代号】 /// </summary> private void SaidiResortOneView(SolidWorks.Interop.sldworks.View swView, ModelDoc2 swModel) { //101,$数量×$图号 ,$数量($属性名)等等各种格式 string strText = this.cmbStartIndex.Text; //是否需要进行赛迪处理-页码-页数的时候,如果页数=1不显示,否则显示页码 bool bSaidiCheck = false; char[] carr = new char[] { '(', ')', '×', 'x', 'X', '-', '_', '=', '(', ')', '[', ']', ' ', '/', '"' }; string[] strArr = strText.Split(carr); //执行完切割后,要去掉引号,因为下面还要加引号 strText = strText.Replace("\"", ""); foreach (string s in strArr) { if (s != "$项目数" && s != "$项目号" && s.Length > 1) { strText = strText.Replace(s, "$PRPMODEL:\"" + s.Trim(new char[] { '$' }) + "\"");//如"$项目数×$PRPMODEL:\"名称\""; } } bool bXMS = (strText.IndexOf("$项目数") != -1); bool bXMH = (strText.IndexOf("$项目号") != -1); int iTextQuantity = (int)swDetailingNoteTextContent_e.swDetailingNoteTextQuantity; //数量 int iTextNumber = (int)swDetailingNoteTextContent_e.swDetailingNoteTextItemNumber; //项目号 int iTextProperty = (int)swDetailingNoteTextContent_e.swDetailingNoteTextCustomProperty; //属性 //遍历注释 Note not = (Note)swView.GetFirstNote(); while (not != null) { if (not.IsBomBalloon()) //只有符号这个条件才可以 { Annotation ann = (Annotation)not.GetAnnotation(); //必须要有Annotation if (ann == null) { goto ABC; } object[] obArr = (object[])ann.GetAttachedEntities2();//必须要有Entities if (obArr == null || obArr.Length == 0) { goto ABC; } Entity ent = (Entity)obArr[0]; Component2 comp = (Component2)ent.GetComponent(); //看看是否有重复的,一个配置只允许标注一次,如果需要多次标注,只能用不同的配置。 string FullPath = comp.GetPathName() + comp.ReferencedConfiguration; //先复制一份值 string thisTxt = strText; //如果有项目数,读取项目数 if (bXMS) { //选中这个注释,然后设为项目数 swModel.Extension.SelectByID2(not.GetName() + "@" + swView.Name, "NOTE", 0, 0, 0, true, 0, null, 0); not.SetBomBalloonText(iTextQuantity, "", iTextQuantity, ""); string txt = not.GetText(); if (txt.Length > 0) { thisTxt = thisTxt.Replace("$项目数", txt); } } //如果有项目号,读取项目号 if (bXMH) { //选中这个注释,然后设为项目号 swModel.Extension.SelectByID2(not.GetName() + "@" + swView.Name, "NOTE", 0, 0, 0, true, 0, null, 0); not.SetBomBalloonText(iTextNumber, "", iTextNumber, ""); string txt = not.GetText(); if (txt.Length > 0) { thisTxt = thisTxt.Replace("$项目号", txt); } } //如果是赛迪,当页数>1时,加上-页码,否侧不加-页码 //先列出-页数-页码来,然后再去掉-1-1 if (bSaidiCheck) { //先设置页数属性链接 not.SetBomBalloonText(iTextProperty, "$PRPMODEL:\"页数\"", iTextProperty, "$PRPMODEL:\"页数\""); string s = not.GetText(); if (s.Length > 0 && s.Length < 4 && s != "1" && s != "0") { thisTxt = thisTxt.Replace("-$PRPMODEL:\"页数\"", ""); } else { thisTxt = thisTxt.Replace("-$PRPMODEL:\"页码\"-$PRPMODEL:\"页数\"", ""); } } //最后设置新的文本 not.SetBomBalloonText(iTextProperty, thisTxt, iTextProperty, thisTxt); } ABC: not = (Note)not.GetNext(); } }
private void CheckBoxIntersectionWithCavities(List<Component2> cutList, Component2 key) { //����� ��� ���� ������������� ���� �� key var swFeat = key.FirstFeature(); while (swFeat != null) { if (swFeat.GetTypeName2() == "ICE") { foreach (var cut in cutList) { if (CheckComponentsIntersection2(cut, swFeat, key)) { //cut.Select(false); swFeat.Select(true); MessageBox.Show("�����������! ������: " + key.GetPathName() + " ����:" + swFeat.Name, "�����������!", MessageBoxButtons.OK); return; } } } swFeat = swFeat.IGetNextFeature(); } }
public void ProcessTableAnn(BomTableAnnotation swBOMTableAnn, string ConfigName, SldAsm asmPrd) { int nNumRow = 0; string ItemNumber = null; string PartNumber = null; TableAnnotation swTableAnn = (TableAnnotation)swBOMTableAnn; Console.WriteLine(" Table Title " + swTableAnn.Title); IEdmVault5 vault = new EdmVault5(); vault.LoginAuto("科德研发部", 0); if (!vault.IsLoggedIn) { Console.WriteLine("登录PDM失败"); return; } nNumRow = swTableAnn.RowCount; swBOMTableAnn = (BomTableAnnotation)swTableAnn; for (int j = 0; j < swTableAnn.RowCount; j++) { // //for (int i = 0; i < swTableAnn.ColumnCount;i++ ) // Console.WriteLine(swTableAnn.get_Text(j, i)); //获取类别和特有信息 //if (j == swTableAnn.RowCount - 1)//最后一行为标题栏,跳过 // continue; string filePath = ""; string compName = ""; string compConfig = ""; int compCount = swBOMTableAnn.GetComponentsCount2(j, ConfigName, out ItemNumber, out PartNumber); for (int i = 0; i < compCount; i++) { Component2 comp2 = swBOMTableAnn.IGetComponents2(j, ConfigName, i); if (comp2 != null) { filePath = comp2.GetPathName(); compName = comp2.Name2; compConfig = comp2.ReferencedConfiguration; Console.WriteLine(" Component Name :" + comp2.Name2 + " Configuration Name : " + comp2.ReferencedConfiguration); Console.WriteLine(" Component Path :" + comp2.GetPathName()); } } if (filePath == "") { continue; } SldBsp bsp = GetSldPrdInfoFromFile(vault, filePath); if (bsp == null) { continue; } bsp.path = filePath; //SldBsp bsp = new SldBsp(); swTableAnn.get_Text(j, 0); //序号 bsp.number = swTableAnn.get_Text(j, 1); //代号 bsp.name = swTableAnn.get_Text(j, 2); //名称 string amout = swTableAnn.get_Text(j, 3); bsp.amout = amout == ""?0:int.Parse(amout); //数量 bsp.material = swTableAnn.get_Text(j, 4); //材料 string weight = swTableAnn.get_Text(j, 5); bsp.weight = weight == "" ? 0 : int.Parse(weight); //单重 bsp.totalWeight = bsp.weight * bsp.amout; // swTableAnn.get_Text(j, 6);//总重 bsp.remark = swTableAnn.get_Text(j, 7); //备注 string number = swTableAnn.get_Text(j, 8); //测试 if (bsp.number == "") { bsp.number = number; } if (bsp is SldPrt) { asmPrd.sldPrtList.Add((SldPrt)bsp); } else if (bsp is SldStd) { asmPrd.sldStdList.Add((SldStd)bsp); } else if (bsp is SldBuy) { asmPrd.sldBuyList.Add((SldBuy)bsp); } } return; }
private bool CheckSuffixModel(Component2 comp, string suffix, out bool notModel) { notModel = false; try { string tmp = Path.GetFileNameWithoutExtension(comp.GetPathName()); if (tmp.Substring(tmp.Length - 4, 4)[0] == '#' && (tmp.Substring(tmp.Length - 4, 4)[3] == 'P' || tmp.Substring(tmp.Length - 4, 4)[3] == 'p')) { return false; } var model = comp.IGetModelDoc(); if (model != null) { if (Properties.Settings.Default.CashModeOn && model.get_CustomInfo2("", "Accessories") == "Yes") return false; if (!Path.GetFileNameWithoutExtension(model.GetPathName()).Contains(suffix)) { if (model.GetConfigurationCount() == 1 && model.get_CustomInfo2("", "Articul") != "") return true; var configNames = (string[])model.GetConfigurationNames(); if (configNames.Any(configName => model.get_CustomInfo2(configName, "Articul") != "")) return true; var outComps = new LinkedList<Component2>(); bool val; if (GetComponents(comp, outComps, false, false) && outComps.Any(component2 => CheckSuffixModel(component2, suffix, out val))) return true; } else { if (model.GetType() != (int)swDocumentTypes_e.swDocASSEMBLY) return false; var comps = (object[])((AssemblyDoc)model).GetComponents(false); return (from Component2 c in comps select Path.GetFileNameWithoutExtension(c.GetPathName())). Any( name => !name.Contains(suffix)); } } else { SwDmDocumentOpenError oe; if (!Path.GetFileNameWithoutExtension(comp.GetPathName()).Contains(suffix)) { SwDMApplication swDocMgr = GetSwDmApp(); var swDoc = (SwDMDocument)swDocMgr.GetDocument(comp.GetPathName(), SwDmDocumentType.swDmDocumentAssembly, true, out oe); if (swDoc != null) { SwDmCustomInfoType swDm; if (swDoc.ConfigurationManager.GetConfigurationCount() == 1) { var names = (string[])swDoc.GetCustomPropertyNames(); if (names.Contains("Articul") && swDoc.GetCustomProperty("Articul", out swDm) != "") return true; } else { var names = (string[])swDoc.ConfigurationManager.GetConfigurationNames(); if ((from name in names select (SwDMConfiguration)swDoc.ConfigurationManager.GetConfigurationByName(name) into conf let nms = (string[])conf.GetCustomPropertyNames() where nms.Contains("Articul") && conf.GetCustomProperty("Articul", out swDm) != "" select conf).Any()) return true; } } else { notModel = true; return true; } } else { var outList = new LinkedList<Component2>(); if (GetComponents(comp, outList, true, false)) { return (from Component2 c in outList select Path.GetFileNameWithoutExtension(c.GetPathName())). Any( name => !name.Contains(suffix)); } } } } catch { notModel = true; return true; } return false; }
public void Main() { swSuccess = false; errors = 0; warnings = 0; string swSourcePath = swApp.GetCurrentWorkingDirectory(); string swExportPath = Path.Combine(swSourcePath, "IGS"); string[] tmp = Directory.GetFiles(swSourcePath, "*.SLDPRT", SearchOption.TopDirectoryOnly); if (Directory.Exists(swExportPath)) Directory.Delete(swExportPath, true); Directory.CreateDirectory(swExportPath); ModelDoc2 swModel = swApp.ActiveDoc as ModelDoc2; AssemblyDoc swAssem = (AssemblyDoc)swModel; #region TopLevel string igsFileName = MakeFileName(swModel.Extension.Document.GetTitle()); swModel.Extension.SaveAs(Path.Combine(swExportPath, igsFileName), (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Copy, null, ref errors, ref warnings); //PrintSaveResults(); #endregion TopLevel #region Subassemblies string swExportSubPath = Path.Combine(swExportPath, "Subassemblies"); Directory.CreateDirectory(swExportSubPath); object[] objComps = (object[])swAssem.GetComponents(true); ModelDoc2 igsModel; foreach (object obj in objComps) { swComponent = obj as Component2; Debug.WriteLine(String.Format("Working on {0}.. \n\t {1}", swComponent.Name2, swComponent.GetPathName())); igsModel = swApp.OpenDoc6(swComponent.GetPathName(), (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_ReadOnly, null, ref errors, ref warnings); swApp.ActivateDoc2(igsModel.GetTitle(), true, ref errors); igsFileName = MakeFileName(igsModel.Extension.Document.GetTitle()); igsModel.Extension.SaveAs(Path.Combine(swExportSubPath, igsFileName), (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Copy, null, ref errors, ref warnings); swApp.CloseDoc(igsModel.GetTitle()); } #endregion Subassemblies #region Parts string swExportPartPath = Path.Combine(swExportPath, "Parts"); Directory.CreateDirectory(swExportPartPath); string[] swPartFiles = Directory.GetFiles(swSourcePath, "*.SLDPRT", SearchOption.TopDirectoryOnly); foreach (string partFile in swPartFiles) { try { igsModel = swApp.OpenDoc6(partFile, (int)swDocumentTypes_e.swDocPART, (int)swOpenDocOptions_e.swOpenDocOptions_ReadOnly, null, ref errors, ref warnings); swApp.ActivateDoc2(igsModel.GetTitle(), true, ref errors); string[] swConfigs = (string[])igsModel.GetConfigurationNames(); int swConfigCount = igsModel.GetConfigurationCount(); string swConfigFilename; for (int i = 0; i < swConfigCount; i++) { igsModel.ShowConfiguration2(swConfigs[i]); swConfigFilename = igsModel.Extension.Document.GetTitle(); if (swConfigCount > 1) swConfigFilename += String.Format("-CFG{0}", (i+1).ToString()); igsFileName = MakeFileName(swConfigFilename); igsModel.Extension.SaveAs(Path.Combine(swExportPartPath, igsFileName), (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Copy, null, ref errors, ref warnings); } swApp.CloseDoc(igsModel.GetTitle()); } catch (NullReferenceException e) { Debug.WriteLine(e.Message); } } #endregion Parts string timeFilename = Path.Combine(swExportPath, "Timestamp.txt"); using (StreamWriter swTimeStamper = new StreamWriter(timeFilename)) { swTimeStamper.WriteLine("Exported on {0} at {1}", System.DateTime.Now.ToShortDateString(), System.DateTime.Now.ToShortTimeString()); swTimeStamper.Flush(); } }
private bool GetComponentModel(ModelDoc2 swModel, Component2 inComp, out ModelDoc2 swCompModel, out string modelFileName) { int i = 0; modelFileName = ""; do { var compState = (swComponentSuppressionState_e)inComp.GetSuppression(); if (compState.ToString() == "swComponentSuppressed") inComp.SetSuppression2((int)swComponentSuppressionState_e.swComponentFullyResolved); swCompModel = (ModelDoc2)inComp.GetModelDoc(); if (swCompModel == null) { string newModelPath = CheckIsCompInOurLib(inComp.GetPathName()); if (inComp.Select(false)) { ((AssemblyDoc)swModel).ReplaceComponents(newModelPath, "", true, true); //((AssemblyDoc) swModel).ComponentReload(); swCompModel = inComp.IGetModelDoc(); //((AssemblyDoc) swModel).OpenCompFile(); //��� �������������� ��������� ���������� OpenCompFile �� ��������! if (((ModelDoc2)_iSwApp.ActiveDoc).GetPathName() != swModel.GetPathName()) swCompModel = (ModelDoc2)_iSwApp.ActiveDoc; } } i++; } while (swCompModel == null && i < 10); if (swCompModel != null) modelFileName = swCompModel.GetPathName(); else { MessageBox.Show(@"��������� " + inComp.Name + @"�� ���������!", MyTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return false; } return true; }