private Feature GetUpdatedCutList() { Feature swFeat = (Feature)swMainModel.FirstFeature(); while (swFeat != null) { if (swFeat.GetTypeName2() == "SolidBodyFolder") { BodyFolder swBodyFolder = swFeat.GetSpecificFeature2(); swBodyFolder.SetAutomaticCutList(true); swBodyFolder.SetAutomaticUpdate(true); Feature cutList = swFeat.GetFirstSubFeature(); while (cutList != null) { if (cutList.GetTypeName2() == "CutListFolder") { return(cutList); } cutList = cutList.GetNextSubFeature(); } return(null); } swFeat = swFeat.GetNextFeature(); } return(null); }
public void AjouterDossier(BodyFolder dossier, Component2 comp) { Body2 corps = dossier.ePremierCorps(); if (corps.IsNull()) { return; } String BaseMateriau; String Materiau = corps.eGetMateriauCorpsOuComp(comp, out BaseMateriau); string Profil; if (corps.eTypeDeCorps() == eTypeCorps.Tole) { Double Ep = corps.eEpaisseurCorpsOuDossier(dossier); if (Ep == -1) { WindowLog.EcrireF("Pb d'epaisseur sur le corps {0}", corps.Name); return; } Profil = "Ep " + Ep.ToString(); } else if (dossier.ePropExiste(CONSTANTES.PROFIL_NOM)) { Profil = dossier.eProp(CONSTANTES.PROFIL_NOM); } else { Profil = NomVolume; } Ajouter(BaseMateriau, Materiau, Profil, dossier, comp); }
private void Ajouter(String repere, BodyFolder dossier, Component2 cp) { List <Element> listElements = new List <Element>(); if (Dic.ContainsKey(repere)) { listElements = Dic[repere]; } else { Dic.Add(repere, listElements); } foreach (var corps in dossier.eListeDesCorps()) { listElements.Add(new Element(corps, cp)); } }
static string GetFromCutlist(IModelDoc2 swModel, string property) { var propertyValue = ""; try { Feature swFeat2 = swModel.FirstFeature(); while (swFeat2 != null) { if (swFeat2.GetTypeName2() == "SolidBodyFolder") { BodyFolder swBodyFolder = swFeat2.GetSpecificFeature2(); swFeat2.Select2(false, -1); swBodyFolder.SetAutomaticCutList(true); swBodyFolder.UpdateCutList(); Feature swSubFeat = swFeat2.GetFirstSubFeature(); while (swSubFeat != null) { if (swSubFeat.GetTypeName2() == "CutListFolder") { BodyFolder bodyFolder = swSubFeat.GetSpecificFeature2(); swSubFeat.Select2(false, -1); bodyFolder.SetAutomaticCutList(true); bodyFolder.UpdateCutList(); var swCustPrpMgr = swSubFeat.CustomPropertyManager; //swCustPrpMgr.Add("Площадь поверхности", "Текст", "\"SW-SurfaceArea@@@Элемент списка вырезов1@ВНС-901.81.002.SLDPRT\""); string valOut; swCustPrpMgr.Get4(property, true, out valOut, out propertyValue); } swSubFeat = swSubFeat.GetNextFeature(); } } swFeat2 = swFeat2.GetNextFeature(); } } catch (Exception exception) { MessageBox.Show(exception.ToString()); } return(propertyValue); }
static string GetFromCutlist(IModelDoc2 swModel, string property) { string propertyValue = null; try { Feature swFeat2 = swModel.FirstFeature(); while (swFeat2 != null) { if (swFeat2.GetTypeName2() == "SolidBodyFolder") { BodyFolder swBodyFolder = swFeat2.GetSpecificFeature2(); swFeat2.Select2(false, -1); swBodyFolder.SetAutomaticCutList(true); swBodyFolder.UpdateCutList(); Feature swSubFeat = swFeat2.GetFirstSubFeature(); while (swSubFeat != null) { if (swSubFeat.GetTypeName2() == "CutListFolder") { BodyFolder bodyFolder = swSubFeat.GetSpecificFeature2(); swSubFeat.Select2(false, -1); bodyFolder.SetAutomaticCutList(true); bodyFolder.UpdateCutList(); var swCustPrpMgr = swSubFeat.CustomPropertyManager; string valOut; swCustPrpMgr.Get4(property, true, out valOut, out propertyValue); } swSubFeat = swSubFeat.GetNextFeature(); } } swFeat2 = swFeat2.GetNextFeature(); } } catch (Exception) { // } return(propertyValue); }
public void AjouterDossier(BodyFolder dossier, Component2 comp) { Body2 corps = dossier.ePremierCorps(); if (corps.IsNull()) { return; } String Repere = ""; if (dossier.ePropExiste(CONSTANTES.REF_DOSSIER)) { Repere = dossier.eProp(CONSTANTES.REF_DOSSIER); } else { Repere = Erreur; } Ajouter(Repere, dossier, comp); }
/// <summary> /// Returns sheet metal cut list by configuration name /// </summary> /// <param name="configuratuinName"></param> /// <param name="SwModel"></param> /// <returns></returns> public static DataToExport GetDataToExport(ModelDoc2 swModel) { solidWorksDocument = swModel; DataToExport dataToExport = new DataToExport(); string valOut; const string BoundingBoxLengthRu = @"Длина граничной рамки"; // rename, change number to eng/rus const string BoundingBoxLengthEng = @"Bounding Box Length"; const string BoundingBoxWidthRu = @"Ширина граничной рамки"; const string BoundingBoxWidthEng = @"Bounding Box Width"; const string SheetMetalThicknessRu = @"Толщина листового металла"; const string SheetMetalThicknessEng = @"Sheet Metal Thickness"; const string BendsRu = @"Сгибы"; const string BendsEng = @"Bends"; Feature swFeat2 = solidWorksDocument.FirstFeature(); while (swFeat2 != null) { if (swFeat2.GetTypeName2() == "SolidBodyFolder") { BodyFolder swBodyFolder = swFeat2.GetSpecificFeature2(); swFeat2.Select2(false, -1); swBodyFolder.SetAutomaticCutList(true); swBodyFolder.UpdateCutList(); Feature swSubFeat = swFeat2.GetFirstSubFeature(); while (swSubFeat != null) { if (swSubFeat.GetTypeName2() == "CutListFolder") { //MessageObserver.Instance.SetMessage("GetTypeName2: " + swSubFeat.GetTypeName2() + "; swSubFeat.Name " + swSubFeat.Name); BodyFolder bodyFolder = swSubFeat.GetSpecificFeature2(); if (bodyFolder.GetCutListType() != (int)swCutListType_e.swSheetmetalCutlist) { goto m1; } swSubFeat.Select2(false, -1); bodyFolder.SetAutomaticCutList(true); bodyFolder.UpdateCutList(); var swCustProp = swSubFeat.CustomPropertyManager; string tempOutBoundingBoxLength; swCustProp.Get4(BoundingBoxLengthRu, true, out valOut, out tempOutBoundingBoxLength); if (string.IsNullOrEmpty(tempOutBoundingBoxLength)) { swCustProp.Get4(BoundingBoxLengthEng, true, out valOut, out tempOutBoundingBoxLength); } dataToExport.WorkpieceX = SafeConvertToDecemal(tempOutBoundingBoxLength);//Convert.ToDecimal(tempOutBoundingBoxLength.Replace(".", ",")); string ширинаГраничнойРамки; swCustProp.Get4(BoundingBoxWidthRu, true, out valOut, out ширинаГраничнойРамки); if (string.IsNullOrEmpty(ширинаГраничнойРамки)) { swCustProp.Get4(BoundingBoxWidthEng, true, out valOut, out ширинаГраничнойРамки); } dataToExport.WorkpieceY = SafeConvertToDecemal(ширинаГраничнойРамки);//Convert.ToDecimal(ширинаГраничнойРамки.Replace(".", ",")); string толщинаЛистовогоМеталла; swCustProp.Get4(SheetMetalThicknessRu, true, out valOut, out толщинаЛистовогоМеталла); if (string.IsNullOrEmpty(толщинаЛистовогоМеталла)) { swCustProp.Get4(SheetMetalThicknessEng, true, out valOut, out толщинаЛистовогоМеталла); } dataToExport.Thickness = SafeConvertToDecemal(толщинаЛистовогоМеталла);//Convert.ToDecimal(толщинаЛистовогоМеталла.Replace(".", ","), ); string сгибы; swCustProp.Get4(BendsRu, true, out valOut, out сгибы); if (string.IsNullOrEmpty(сгибы)) { swCustProp.Get4(BendsEng, true, out valOut, out сгибы); } // swCustProp.Set(BendsRu, сгибы); dataToExport.Bend = Convert.ToInt32(сгибы); dataToExport.PaintX = GetDimentions()[0]; dataToExport.PaintY = GetDimentions()[1]; dataToExport.PaintZ = GetDimentions()[2]; dataToExport.SurfaceArea = GetSurfaceArea(); } m1: swSubFeat = swSubFeat.GetNextFeature(); } } swFeat2 = swFeat2.GetNextFeature(); } solidWorksDocument = null; return(dataToExport); }
protected override void Command() { try { // On liste les composants var ListeComposants = MdlBase.pListerComposants(); // On boucle sur les modeles foreach (var mdl in ListeComposants.Keys) { mdl.eActiver(swRebuildOnActivation_e.swRebuildActiveDoc); foreach (var nomCfg in ListeComposants[mdl].Keys) { mdl.ShowConfiguration2(nomCfg); mdl.EditRebuild3(); var piece = mdl.ePartDoc(); var ListeDossier = piece.eListeDesFonctionsDePiecesSoudees( swD => { BodyFolder Dossier = swD.GetSpecificFeature2(); // Si le dossier est la racine d'un sous-ensemble soudé, il n'y a rien dedans if (Dossier.IsRef() && (Dossier.eEstExclu() == false) && (Dossier.eNbCorps() > 0) && (eTypeCorps.Barre).HasFlag(Dossier.eTypeDeDossier())) { return(true); } return(false); } ); var NbConfig = ListeComposants[mdl][nomCfg]; foreach (var fDossier in ListeDossier) { BodyFolder Dossier = fDossier.GetSpecificFeature2(); var SwCorps = Dossier.ePremierCorps(); var NomCorps = SwCorps.Name; var MateriauCorps = SwCorps.eGetMateriauCorpsOuPiece(piece, nomCfg); var NbCorps = Dossier.eNbCorps() * NbConfig; var Profil = Dossier.eProfilDossier(); var Longueur = Dossier.eLongueurProfilDossier().eToDouble(); for (int i = 0; i < NbCorps; i++) { var LgTmp = Longueur; while (LgTmp > LgMax) { RassemblerBarre(MateriauCorps, Profil, LgMax); LgTmp -= LgMax; } RassemblerBarre(MateriauCorps, Profil, LgTmp); } } } mdl.eFermerSiDifferent(MdlBase); } // On fait la mise en barre foreach (var Materiau in DicBarres.Keys) { WindowLog.SautDeLigne(); WindowLog.EcrireF("{0}", Materiau);; foreach (var Profil in DicBarres[Materiau].Keys) { WindowLog.SautDeLigne(); WindowLog.EcrireF(" {0}", Profil); var lst = DicBarres[Materiau][Profil]; lst.Sort(); lst.Reverse(); foreach (var lg in lst) { WindowLog.EcrireF(" - {0}", lg); } int i = 0; while (true) { var lg = lst[i]; if (AjouterBarre(Materiau, Profil, lg)) { lst.RemoveAt(i); if (lst.Count == 0) { break; } } else { i++; } if (i >= lst.Count) { i = 0; NouvelleBarre(Materiau, Profil); } } } } String Resume = ""; foreach (var Materiau in DicMateriau.Keys) { Resume += System.Environment.NewLine; Resume += String.Format("{0}", Materiau); foreach (var Profil in DicMateriau[Materiau].Keys) { var Ligne = DicMateriau[Materiau][Profil]; Resume += System.Environment.NewLine; Resume += String.Format(" {1,4}× {0,-25} [{2:N0}]", Profil, Ligne.NbBarre, Ligne.Reste); } } WindowLog.SautDeLigne(); WindowLog.Ecrire("A commander"); WindowLog.Ecrire(Resume); WindowLog.SautDeLigne(); File.WriteAllText(Path.Combine(MdlBase.eDossier(), "CommandeProfil.txt"), Resume); } catch (Exception e) { this.LogErreur(new Object[] { e }); } }
private void Ajouter(String baseMateriau, String materiau, String profil, BodyFolder dossier, Component2 cp) { SortedDictionary <String, SortedDictionary <String, List <Element> > > dicMat = new SortedDictionary <String, SortedDictionary <String, List <Element> > >(new WindowsStringComparer()); if (Dic.ContainsKey(baseMateriau)) { dicMat = Dic[baseMateriau]; } else { Dic.Add(baseMateriau, dicMat); } SortedDictionary <String, List <Element> > dicProfil = new SortedDictionary <String, List <Element> >(new WindowsStringComparer()); if (dicMat.ContainsKey(materiau)) { dicProfil = dicMat[materiau]; } else { dicMat.Add(materiau, dicProfil); } List <Element> listElements = new List <Element>(); if (dicProfil.ContainsKey(profil)) { listElements = dicProfil[profil]; } else { dicProfil.Add(profil, listElements); } foreach (var corps in dossier.eListeDesCorps()) { listElements.Add(new Element(corps, cp)); } }
protected override void Command() { try { var ListeComposants = MdlBase.ListerComposants(false); eTypeCorps Filtre = eTypeCorps.Barre | eTypeCorps.Tole; var Dic = new HashSet <String>(); Boolean Erreur = false; Predicate <Feature> Test = f => { BodyFolder dossier = f.GetSpecificFeature2(); if (dossier.IsRef() && dossier.eNbCorps() > 0 && Filtre.HasFlag(dossier.eTypeDeDossier())) { var RefDossier = dossier.eProp(CONSTANTES.REF_DOSSIER); if (String.IsNullOrWhiteSpace(RefDossier)) { return(true); } } return(false); }; foreach (var mdl in ListeComposants.Keys) { mdl.eActiver(swRebuildOnActivation_e.swRebuildActiveDoc); foreach (var t in ListeComposants[mdl]) { var cfg = t.Key; var nbCfg = t.Value; mdl.ShowConfiguration2(cfg); mdl.EditRebuild3(); var Piece = mdl.ePartDoc(); foreach (var fDossier in Piece.eListeDesFonctionsDePiecesSoudees(Test)) { WindowLog.EcrireF("{0} \"{1}\"", mdl.eNomSansExt(), cfg); WindowLog.EcrireF(" {0} : Pas de reference", fDossier.Name); Erreur = true; } } mdl.eFermerSiDifferent(MdlBase); } if (!Erreur) { WindowLog.Ecrire("Aucune erreur\n"); } } catch (Exception e) { this.LogErreur(new Object[] { e }); } }
protected override void Command() { CreerDossierDVP(); WindowLog.Ecrire(String.Format("Dossier :\r\n{0}", new DirectoryInfo(DossierExport).Name)); try { eTypeCorps Filtre = PrendreEnCompteTole ? eTypeCorps.Barre | eTypeCorps.Tole : eTypeCorps.Barre; HashSet <String> HashMateriaux = new HashSet <string>(ListeMateriaux); var dic = MdlBase.DenombrerDossiers(ComposantsExterne, fDossier => { BodyFolder swDossier = fDossier.GetSpecificFeature2(); if (Filtre.HasFlag(swDossier.eTypeDeDossier()) && HashMateriaux.Contains(swDossier.eGetMateriau())) { return(true); } return(false); } ); if (ListerUsinages) { Nomenclature.TitreColonnes("Barre ref.", "Materiau", "Profil", "Lg", "Nb", "Usinage Ext 1", "Usinage Ext 2", "Détail des Usinage interne"); } else { Nomenclature.TitreColonnes("Barre ref.", "Materiau", "Profil", "Lg", "Nb"); } int MdlPct = 0; foreach (var mdl in dic.Keys) { mdl.eActiver(swRebuildOnActivation_e.swRebuildActiveDoc); WindowLog.SautDeLigne(); WindowLog.EcrireF("[{1}/{2}] {0}", mdl.eNomSansExt(), ++MdlPct, dic.Count); int CfgPct = 0; foreach (var NomConfigPliee in dic[mdl].Keys) { WindowLog.SautDeLigne(); WindowLog.EcrireF(" [{1}/{2}] Config : \"{0}\"", NomConfigPliee, ++CfgPct, dic[mdl].Count); mdl.ShowConfiguration2(NomConfigPliee); mdl.EditRebuild3(); PartDoc Piece = mdl.ePartDoc(); var ListeDossier = dic[mdl][NomConfigPliee]; int DrPct = 0; foreach (var t in ListeDossier) { var IdDossier = t.Key; var QuantiteBarre = t.Value * Quantite; Feature fDossier = Piece.FeatureById(IdDossier); BodyFolder dossier = fDossier.GetSpecificFeature2(); var RefDossier = dossier.eProp(CONSTANTES.REF_DOSSIER); Body2 Barre = dossier.ePremierCorps(); String Profil = dossier.eProp(CONSTANTES.PROFIL_NOM); String Longueur = dossier.eProp(CONSTANTES.PROFIL_LONGUEUR); String Materiau = Barre.eGetMateriauCorpsOuPiece(Piece, NomConfigPliee); Materiau = ForcerMateriau.IsRefAndNotEmpty(Materiau); String NomFichierBarre = ConstruireNomFichierBarre(RefDossier, QuantiteBarre); WindowLog.SautDeLigne(); WindowLog.EcrireF(" - [{1}/{2}] Dossier : \"{0}\" x{3}", RefDossier, ++DrPct, ListeDossier.Count, QuantiteBarre); WindowLog.EcrireF(" Profil {0} Materiau {1}", Profil, Materiau); List <String> Liste = new List <String>() { RefDossier, Materiau, Profil, Math.Round(Longueur.eToDouble()).ToString(), "× " + QuantiteBarre.ToString() }; if (ListerUsinages) { var analyse = new AnalyseBarre(Barre, mdl); Dictionary <String, Double> Dic = new Dictionary <string, double>(); foreach (var u in analyse.ListeFaceUsinageSection) { String nom = u.ListeFaceDecoupe.Count + " face - Lg " + Math.Round(u.LgUsinage * 1000, 1); if (Dic.ContainsKey(nom)) { Dic[nom] += 1; } else { Dic.Add(nom, 1); } } Liste.Add(Math.Round(analyse.ListeFaceUsinageExtremite[0].LgUsinage * 1000, 1).ToString()); if (analyse.ListeFaceUsinageExtremite.Count > 1) { Liste.Add(Math.Round(analyse.ListeFaceUsinageExtremite[1].LgUsinage * 1000, 1).ToString()); } else { Liste.Add(""); } foreach (var nom in Dic.Keys) { Liste.Add(Dic[nom] + "x [ " + nom + " ]"); } } Nomenclature.AjouterLigne(Liste.ToArray()); if (ExporterBarres) { //mdl.ViewZoomtofit2(); //mdl.ShowNamedView2("*Isométrique", 7); String CheminFichier; ModelDoc2 mdlBarre = Barre.eEnregistrerSous(Piece, DossierExport, NomFichierBarre, TypeExport, out CheminFichier); if (CreerPdf3D) { String CheminPDF = Path.Combine(DossierExportPDF, NomFichierBarre + eTypeFichierExport.PDF.GetEnumInfo <ExtFichier>()); mdlBarre.SauverEnPdf3D(CheminPDF); } mdlBarre.eFermer(); } } } mdl.eFermerSiDifferent(MdlBase); } WindowLog.SautDeLigne(); WindowLog.Ecrire(Nomenclature.ListeLignes()); CheminNomenclature = Path.Combine(DossierExport, "Nomenclature.txt"); StreamWriter s = new StreamWriter(CheminNomenclature); s.Write(Nomenclature.GenererTableau()); s.Close(); } catch (Exception e) { this.LogErreur(new Object[] { e }); } }
protected override void Command() { try { if (ConvertirEsquisse) { WindowLog.Ecrire("Attention !!!"); WindowLog.Ecrire("Les dvp seront convertis en esquisse"); WindowLog.SautDeLigne(); } CreerDossierDVP(); eTypeCorps Filtre = eTypeCorps.Tole; HashSet <String> HashMateriaux = new HashSet <string>(ListeMateriaux); HashSet <String> HashEp = new HashSet <string>(ListeEp); var dic = MdlBase.DenombrerDossiers(ComposantsExterne, fDossier => { BodyFolder swDossier = fDossier.GetSpecificFeature2(); if (Filtre.HasFlag(swDossier.eTypeDeDossier()) && HashMateriaux.Contains(swDossier.eGetMateriau())) { String Ep = swDossier.ePremierCorps().eEpaisseurCorps().ToString(); if (HashEp.Contains(Ep)) { return(true); } } return(false); } ); int MdlPct = 0; foreach (var mdl in dic.Keys) { mdl.eActiver(swRebuildOnActivation_e.swRebuildActiveDoc); WindowLog.SautDeLigne(); WindowLog.EcrireF("[{1}/{2}] {0}", mdl.eNomSansExt(), ++MdlPct, dic.Count); int CfgPct = 0; foreach (var NomConfigPliee in dic[mdl].Keys) { WindowLog.SautDeLigne(); WindowLog.EcrireF(" [{1}/{2}] Config : \"{0}\"", NomConfigPliee, ++CfgPct, dic[mdl].Count); mdl.ShowConfiguration2(NomConfigPliee); mdl.EditRebuild3(); PartDoc Piece = mdl.ePartDoc(); var ListeDossier = dic[mdl][NomConfigPliee]; int DrPct = 0; foreach (var t in ListeDossier) { var IdDossier = t.Key; var QuantiteTole = t.Value * Quantite; Feature fDossier = Piece.FeatureById(IdDossier); BodyFolder dossier = fDossier.GetSpecificFeature2(); var RefDossier = dossier.eProp(CONSTANTES.REF_DOSSIER); Body2 Tole = dossier.eCorpsDeTolerie(); WindowLog.SautDeLigne(); WindowLog.EcrireF(" - [{1}/{2}] Dossier : \"{0}\" x{3}", RefDossier, ++DrPct, ListeDossier.Count, QuantiteTole); String Materiau = Tole.eGetMateriauCorpsOuPiece(Piece, NomConfigPliee); Materiau = ForcerMateriau.IsRefAndNotEmpty(Materiau); Double Epaisseur = Tole.eEpaisseurCorps(); String NomConfigDepliee = Sw.eNomConfigDepliee(NomConfigPliee, RefDossier); WindowLog.EcrireF(" Ep {0} / Materiau {1}", Epaisseur, Materiau); WindowLog.EcrireF(" Config {0}", NomConfigDepliee); if (ConvertirEsquisse) { if (!mdl.eListeNomConfiguration().Contains(NomConfigDepliee)) { mdl.CreerConfigDepliee(NomConfigDepliee, NomConfigPliee); } WindowLog.EcrireF(" Configuration crée : {0}", NomConfigDepliee); mdl.ShowConfiguration2(NomConfigDepliee); Tole.DeplierTole(mdl, NomConfigDepliee); } else if (!mdl.ShowConfiguration2(NomConfigDepliee)) { DicErreur.Add(mdl.eNomSansExt() + " -> cfg : " + NomConfigPliee + " - No : " + RefDossier + " = " + NomConfigDepliee); WindowLog.EcrireF("La configuration n'éxiste pas"); continue; } mdl.EditRebuild3(); DrawingDoc dessin = CreerPlan(Materiau, Epaisseur); dessin.eModelDoc2().eActiver(); Sheet Feuille = dessin.eFeuilleActive(); View v = CreerVueToleDvp(dessin, Feuille, Piece, NomConfigDepliee, RefDossier, Materiau, QuantiteTole, Epaisseur); if (ConvertirEsquisse) { mdl.ShowConfiguration2(NomConfigPliee); mdl.EditRebuild3(); mdl.DeleteConfiguration2(NomConfigDepliee); } } NouvelleLigne = true; } mdl.eFermerSiDifferent(MdlBase); } foreach (DrawingDoc dessin in DicDessins.Values) { int Errors = 0, Warnings = 0; dessin.eModelDoc2().eActiver(); dessin.eFeuilleActive().eAjusterAutourDesVues(); dessin.eModelDoc2().ViewZoomtofit2(); dessin.eModelDoc2().Save3((int)swSaveAsOptions_e.swSaveAsOptions_SaveReferenced + (int)swSaveAsOptions_e.swSaveAsOptions_Silent, ref Errors, ref Warnings); } if (FermerPlan) { foreach (ModelDoc2 dessin in DicDessins.Values) { dessin.eFermer(); } } if (DicErreur.Count > 0) { WindowLog.SautDeLigne(); WindowLog.Ecrire("Liste des erreurs :"); foreach (var item in DicErreur) { WindowLog.Ecrire(" - " + item); } WindowLog.SautDeLigne(); } else { WindowLog.Ecrire("Pas d'erreur"); } File.WriteAllText(Path.Combine(DossierDVP, "Log_CreerDvp.txt"), WindowLog.Resume); } catch (Exception e) { this.LogErreur(new Object[] { e }); } }
/// <summary> /// Pour pouvoir obtenir une référence unique pour chaque dossier de corps, identiques /// dans l'assemblage, on passe par la création d'une propriété dans chaque dossier. /// Cette propriété est liée à une cote dans une esquisse dont la valeur est égale au repère. /// Suivant la configuration, la valeur de la cote peut changer et donc le repère du dossier. /// C'est le seul moyen pour avoir un lien entre les dossiers et la configuration du modèle. /// Les propriétés des dossiers ne sont pas configurables. /// </summary> protected override void Command() { try { App.Sw.CommandInProgress = true; // Si aucun corps n'a déjà été repéré, on reinitialise tout if (ListeCorps.Count == 0) { // On supprime tout les fichiers foreach (FileInfo file in new DirectoryInfo(MdlBase.pDossierPiece()).GetFiles()) { file.Delete(); } } if (ReinitCampagneActuelle && (ListeCorps.Count > 0)) { // On supprime les repères de la campagne actuelle // On recherche les repères appartenant aux campagnes précédentes // pour ne pas supprimer les fichiers // Si la somme des quantités des campagnes précédente est superieure à 0 // on garde le repère ListeSortedCorps FichierAsauvegarder = new ListeSortedCorps(); FichierAsauvegarder.CampagneDepartDecompte = ListeCorps.CampagneDepartDecompte; foreach (var corps in ListeCorps.Values) { int nb = 0; foreach (var camp in corps.Campagne) { if (camp.Key < IndiceCampagne) { nb += camp.Value; } else { break; } } if (nb > 0) { FichierAsauvegarder.Add(corps.Repere, corps); } } // On nettoie les fichiers précedement crées foreach (var corps in ListeCorps.Values) { if (FichierAsauvegarder.ContainsKey(corps.Repere)) { continue; } corps.SupprimerFichier(); } ListeCorps = FichierAsauvegarder; } // On supprime les campagnes superieures à l'indice actuelle foreach (var corps in ListeCorps.Values) { for (int i = IndiceCampagne; i < corps.Campagne.Keys.Max(); i++) { if (corps.Campagne.ContainsKey(i + 1)) { corps.Campagne.Remove(i + 1); } } } WindowLog.SautDeLigne(); WindowLog.EcrireF("Campagne de départ : {0}", ListeCorps.CampagneDepartDecompte); // On charge les corps existant à partir des fichiers // et seulement ceux dont la quantité pour CampagneDepartDecompte est supérieure à 0 if (CombinerCorpsIdentiques && (ListeCorps.Count > 0)) { var FiltreCampagne = IndiceCampagne; if (CombinerAvecCampagnePrecedente) { FiltreCampagne = ListeCorps.CampagneDepartDecompte; } WindowLog.SautDeLigne(); WindowLog.Ecrire("Chargement des corps existants :"); foreach (var corps in ListeCorps.Values) { // On additionne les quantités pour les corps supperieur à filtreCampagne // S if (corps.Campagne.ContainsKey(FiltreCampagne) && corps.Campagne.Sum(d => d.Key >= FiltreCampagne? d.Value : 0) > 0 && File.Exists(corps.CheminFichierRepere) ) { WindowLog.EcrireF(" - {0}", corps.RepereComplet); corps.ChargerCorps(); } } } // On reinitialise la quantité pour la campagne actuelle à 0 foreach (var corps in ListeCorps.Values) { corps.InitCampagne(IndiceCampagne); } ////////////////////////////////// DEBUT DU REPERAGE //////////////////////////////////////////////////// MdlBase.eActiver(swRebuildOnActivation_e.swRebuildActiveDoc); MdlBase.eActiverManager(false); WindowLog.SautDeLigne(); WindowLog.Ecrire("Debut du repérage"); // On recherche l'indice de repere max if (ListeCorps.Count > 0) { _GenRepereDossier = ListeCorps.Keys.Max(); } // On liste les composants var ListeComposants = MdlBase.pListerComposants(); // On boucle sur les modeles foreach (var mdl in ListeComposants.Keys) { mdl.eActiver(swRebuildOnActivation_e.swRebuildActiveDoc); mdl.eActiverManager(false); // On met à jour les options mdl.Extension.SetUserPreferenceToggle(((int)(swUserPreferenceToggle_e.swDisableDerivedConfigurations)), 0, false); mdl.Extension.SetUserPreferenceToggle(((int)(swUserPreferenceToggle_e.swWeldmentRenameCutlistDescriptionPropertyValue)), 0, true); mdl.Extension.SetUserPreferenceToggle(((int)(swUserPreferenceToggle_e.swWeldmentCollectIdenticalBodies)), 0, true); mdl.Extension.SetUserPreferenceString(((int)(swUserPreferenceStringValue_e.swSheetMetalDescription)), 0, "Tôle"); if (mdl.ePartDoc().eDossierListeDesPiecesSoudees().GetAutomaticUpdate() == false) { mdl.ePartDoc().eMajListeDesPiecesSoudeesAuto(true); mdl.EditRebuild3(); } // On crée l'esquisse pour le reperage des dossiers mdl.pEsquisseRepere(); // Si le modele est a repérer complètement Boolean InitModele = true; // On recherche l'index de la dimension maximum int IndexDimension = 0; // On liste les dossiers déja traité pour l'attribution des nouveaux index de dimension HashSet <int> HashPieceIdDossiers = new HashSet <int>(); // Les données sont stockées dans des propriétés du modèle // Le nom du modèle est stocké dans une propriété, si le modèle est copié // la propriété n'est plus valable, on force le repérage // On récupère également le dernier indice de la dimension utilisée if (mdl.ePropExiste(CONST_PRODUCTION.ID_PIECE) && (mdl.eGetProp(CONST_PRODUCTION.ID_PIECE) == mdl.eNomSansExt())) { InitModele = false; if (mdl.ePropExiste(CONST_PRODUCTION.MAX_INDEXDIM)) { IndexDimension = mdl.eGetProp(CONST_PRODUCTION.MAX_INDEXDIM).eToInteger(); } if (mdl.ePropExiste(CONST_PRODUCTION.PIECE_ID_DOSSIERS)) { var tab = mdl.eGetProp(CONST_PRODUCTION.PIECE_ID_DOSSIERS).Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); foreach (var id in tab) { HashPieceIdDossiers.Add(id.eToInteger()); } } } ////////////////////////////////// BOUCLE SUR LES CONFIGS //////////////////////////////////////////////////// foreach (var nomCfg in ListeComposants[mdl].Keys) { mdl.ShowConfiguration2(nomCfg); mdl.EditRebuild3(); WindowLog.SautDeLigne(); WindowLog.EcrireF("{0} \"{1}\"", mdl.eNomSansExt(), nomCfg); HashSet <int> HashConfigIdDossiers = new HashSet <int>(); Boolean InitConfig = true; int IdCfg = mdl.GetConfigurationByName(nomCfg).GetID(); // Idem modèle, on stock l'id de la config dans une propriété. // Si une nouvelle config est crée, la valeur de cette propriété devient caduc, // on repère alors les dossiers // On en profite pour récupérer la liste des ids de dossiers déjà traité dans les précédentes // campagne de repérage if (!InitModele && mdl.ePropExiste(CONST_PRODUCTION.ID_CONFIG, nomCfg) && (mdl.eGetProp(CONST_PRODUCTION.ID_CONFIG, nomCfg) == IdCfg.ToString())) { InitConfig = false; if (mdl.ePropExiste(CONST_PRODUCTION.CONFIG_ID_DOSSIERS, nomCfg)) { var tab = mdl.eGetProp(CONST_PRODUCTION.CONFIG_ID_DOSSIERS, nomCfg).Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); foreach (var id in tab) { HashConfigIdDossiers.Add(id.eToInteger()); } } } var piece = mdl.ePartDoc(); var ListeDossier = piece.eListeDesFonctionsDePiecesSoudees( swD => { BodyFolder Dossier = swD.GetSpecificFeature2(); // Si le dossier est la racine d'un sous-ensemble soudé, il n'y a rien dedans if (Dossier.IsRef() && (Dossier.eNbCorps() > 0) && !Dossier.eEstExclu() && FiltrerCorps.HasFlag(Dossier.eTypeDeDossier())) { return(true); } return(false); } ); var NbConfig = ListeComposants[mdl][nomCfg]; ////////////////////////////////// BOUCLE SUR LES DOSSIERS //////////////////////////////////////////////////// foreach (var fDossier in ListeDossier) { BodyFolder Dossier = fDossier.GetSpecificFeature2(); int IdDossier = fDossier.GetID(); Dimension param = null; if (!HashPieceIdDossiers.Contains(IdDossier)) { param = CreerParam(mdl, fDossier, nomCfg, ++IndexDimension); } else { param = GetParam(mdl, fDossier, nomCfg); } var SwCorps = Dossier.ePremierCorps(); var NomCorps = SwCorps.Name; var MateriauCorps = SwCorps.eGetMateriauCorpsOuPiece(piece, nomCfg); eTypeCorps TypeCorps = Dossier.eTypeDeDossier(); var nbCorps = Dossier.eNbCorps() * NbConfig; int Repere = -1; if (CombinerCorpsIdentiques) { // On recherche s'il existe des corps identiques // Si oui, on applique le même repère au parametre foreach (var CorpsTest in ListeCorps.Values) { if (CorpsTest.SwCorps.IsRef() && (CombinerAvecCampagnePrecedente || CorpsTest.Campagne.ContainsKey(IndiceCampagne)) && (MateriauCorps == CorpsTest.Materiau) && (TypeCorps == CorpsTest.TypeCorps) && SwCorps.eComparerGeometrie(CorpsTest.SwCorps) == Sw.Comparaison_e.Semblable) { Repere = CorpsTest.Repere; SetRepere(param, CorpsTest.Repere, nomCfg); break; } } } // Initialisation du repère if (Repere.eEstNegatif()) { // A tester // Si on est mode "MajCampagnePrecedente", ça évite de repérer une seconde fois les pièces // Si on est pas en mode "Combiner les corps" // on recupère le repère du dossier // Sinon c'est forcément un nouveau repère if (!CombinerCorpsIdentiques) { Repere = GetRepere(param, nomCfg); } // Création d'un nouveau repère suivant conditions // Dans tous les cas, si la clé est négative, on crée un nouveau repère if (Repere.eEstNegatif() || InitConfig || !HashConfigIdDossiers.Contains(IdDossier) || !ListeCorps.ContainsKey(Repere)) { Repere = GenRepereDossier; SetRepere(param, Repere, nomCfg); } } // Initialisation du corps Corps corps = null; if (!ListeCorps.ContainsKey(Repere)) { corps = new Corps(SwCorps, TypeCorps, MateriauCorps, MdlBase); corps.InitCampagne(IndiceCampagne); ListeCorps.Add(Repere, corps); } else { corps = ListeCorps[Repere]; } corps.Campagne[IndiceCampagne] += nbCorps; corps.Repere = Repere; corps.InitCaracteristiques(Dossier, SwCorps); corps.AjouterModele(mdl, nomCfg, IdDossier, NomCorps); HashPieceIdDossiers.Add(IdDossier); HashConfigIdDossiers.Add(IdDossier); WindowLog.EcrireF(" - {1} -> {0}", fDossier.Name, corps.RepereComplet); } mdl.ePropAdd(CONST_PRODUCTION.ID_CONFIG, IdCfg, nomCfg); mdl.ePropAdd(CONST_PRODUCTION.CONFIG_ID_DOSSIERS, String.Join(" ", HashConfigIdDossiers), nomCfg); } mdl.ePropAdd(CONST_PRODUCTION.ID_PIECE, mdl.eNomSansExt()); mdl.ePropAdd(CONST_PRODUCTION.PIECE_ID_DOSSIERS, String.Join(" ", HashPieceIdDossiers)); mdl.ePropAdd(CONST_PRODUCTION.MAX_INDEXDIM, IndexDimension); mdl.eActiverManager(true); mdl.eSauver(); mdl.eFermerSiDifferent(MdlBase); } MdlBase.eActiverManager(true); MdlBase.eActiver(swRebuildOnActivation_e.swRebuildActiveDoc); MdlBase.EditRebuild3(); MdlBase.eSauver(); ////////////////////////////////// FIN DU REPERAGE //////////////////////////////////////////////////// // On fermer les fichiers chargé foreach (var corps in ListeCorps.Values) { Sw.eFermer(corps.CheminFichierRepere); } WindowLog.SautDeLigne(); if (ListeCorps.Count > 0) { WindowLog.EcrireF("Nb de repères : {0}", ListeCorps.Keys.Max()); } else { WindowLog.Ecrire("Aucun corps repéré"); } // S'il n'y a aucun corps, on se barre if (ListeCorps.Count == 0) { return; } ////////////////////////////////// EXPORTER LES CORPS ///////////////////////////////////////////////// WindowLog.SautDeLigne(); WindowLog.Ecrire("Export des corps :"); foreach (var corps in ListeCorps.Values) { if (corps.Modele.IsNull()) { continue; } // Si on est pas en mode "Combiner corps identique" et que le fichier existe // on le supprime pour le mettre à jour, sinon on peut se retrouver // avec des fichiers ne correpondants pas au corps if (!CombinerCorpsIdentiques) { corps.SupprimerFichier(); } // Si le fichier existe, on passe au suivant if (File.Exists(corps.CheminFichierRepere)) { continue; } WindowLog.EcrireF("- {0} exporté", CONSTANTES.PREFIXE_REF_DOSSIER + corps.Repere); corps.SauverRepere(CreerDvp); } ////////////////////////////////// RECAP ///////////////////////////////////////////////// // Petit récap WindowLog.SautDeLigne(); WindowLog.EcrireF("Nb de corps unique : {0}", ListeCorps.Count); int nbtt = 0; foreach (var corps in ListeCorps.Values) { nbtt += corps.Campagne[IndiceCampagne]; if (corps.Campagne[IndiceCampagne] > 0) { WindowLog.EcrireF("{2} P{0} ×{1}", corps.Repere, corps.Campagne[IndiceCampagne], IndiceCampagne); } } WindowLog.EcrireF("Nb total de corps : {0}", nbtt); ////////////////////////////////// SAUVEGARDE DE LA NOMENCLATURE ///////////////////////////////////////////// ListeCorps.EcrireNomenclature(MdlBase.pDossierPiece(), IndiceCampagne); //////////////////////////////////////////////////////////////////////////////////////////////////////////// MdlBase.eActiver(swRebuildOnActivation_e.swRebuildActiveDoc); App.Sw.CommandInProgress = false; var aff = new AffichageElementWPF(ListeCorps, IndiceCampagne); aff.ShowDialog(); ListeCorps = null; ListeComposants = null; } catch (Exception e) { this.LogErreur(new Object[] { e }); } }
private void IndiceMax() { eTypeCorps Filtre = eTypeCorps.Barre | eTypeCorps.Tole; var ListeComposants = MdlBase.ListerComposants(false); Func <Feature, Tuple <String, String> > ExtractRef = delegate(Feature dossier) { CustomPropertyManager PM = dossier.CustomPropertyManager; String val, result = ""; Boolean wasResolved, link; var r = PM.Get6(CONSTANTES.REF_DOSSIER, false, out val, out result, out wasResolved, out link); return(new Tuple <String, String>(result.Replace(CONSTANTES.PREFIXE_REF_DOSSIER, ""), val)); }; Predicate <Feature> Test = delegate(Feature f) { BodyFolder dossier = f.GetSpecificFeature2(); if (dossier.IsRef() && dossier.eNbCorps() > 0 && Filtre.HasFlag(dossier.eTypeDeDossier())) { CustomPropertyManager PM = f.CustomPropertyManager; String val, result = ""; Boolean wasResolved, link; var r = PM.Get6(CONSTANTES.REF_DOSSIER, false, out val, out result, out wasResolved, out link); var RefDossier = ExtractRef(f).Item1; if (RefDossier.eIsInteger()) { return(true); } } return(false); }; foreach (var mdl in ListeComposants.Keys) { mdl.eActiver(swRebuildOnActivation_e.swRebuildActiveDoc); foreach (var t in ListeComposants[mdl]) { var cfg = t.Key; var nbCfg = t.Value; mdl.ShowConfiguration2(cfg); mdl.EditRebuild3(); var Piece = mdl.ePartDoc(); foreach (var f in Piece.eListeDesFonctionsDePiecesSoudees(Test)) { var RefDossier = ExtractRef(f); indice = Math.Max(indice, RefDossier.Item1.eToInteger()); var hashDossier = HashDossier(mdl, f); DossierTraite.Add(hashDossier); // On recherche l'index max pour chaque modele var NomParam = ExtractNomParam(RefDossier.Item2); var dim = NomParam.Split('@')[0].CleanStringOfNonDigits().eToInteger(); var hashMdl = mdl.GetPathName(); if (IndexDimension.ContainsKey(hashMdl)) { IndexDimension[hashMdl] = Math.Max(IndexDimension[hashMdl], dim); } else { IndexDimension[hashMdl] = dim; } } } mdl.eFermerSiDifferent(MdlBase); } WindowLog.EcrireF("Indice Max : {0}", indice); }
/// <summary> /// Pour pouvoir obtenir une référence unique pour chaque dossier de corps, identiques /// dans l'assemblage, on passe par la création d'une propriété dans chaque dossier. /// Cette propriété est liée à une cote dans une esquisse dont la valeur est égale au repère. /// Suivant la configuration, la valeur de la cote peut changer et donc le repère du dossier. /// C'est le seul moyen pour avoir un lien entre les dossiers et la configuration du modèle. /// Les propriétés des dossiers ne sont pas configurables. /// </summary> protected override void Command() { try { if (MajDossiers) { IndiceMax(); } var ListeCorps = new List <Corps>(); var lst = MdlBase.ListerComposants(false); foreach (var mdl in lst.Keys) { mdl.eActiver(swRebuildOnActivation_e.swRebuildActiveDoc); EsquisseRepere(mdl); foreach (var cfg in lst[mdl].Keys) { mdl.ShowConfiguration2(cfg); mdl.EditRebuild3(); WindowLog.SautDeLigne(); WindowLog.EcrireF("{0} \"{1}\"", mdl.eNomSansExt(), cfg); var piece = mdl.ePartDoc(); var NbConfig = lst[mdl][cfg]; var ListeDossier = piece.eListeDesFonctionsDePiecesSoudees( swD => { BodyFolder Dossier = swD.GetSpecificFeature2(); // Si le dossier est la racine d'un sous-ensemble soudé, il n'y a rien dedans if (Dossier.IsRef() && Dossier.eNbCorps() > 0 && (eTypeCorps.Barre | eTypeCorps.Tole).HasFlag(Dossier.eTypeDeDossier())) { return(true); } return(false); } ); foreach (var fDossier in ListeDossier) { BodyFolder Dossier = fDossier.GetSpecificFeature2(); CustomPropertyManager PM = fDossier.CustomPropertyManager; // Si MajDossier et PropExiste, ne pas mettre à jour Boolean Maj = !(MajDossiers && PM.ePropExiste(CONSTANTES.REF_DOSSIER)); String NomParam = ""; WindowLog.EcrireF(" {0}", fDossier.Name); // On recherche si le dossier à déjà été traité. // Si non, on ajoute le dossier à la liste // On met à jour la liste des index des dimensions : // On ajoute le nom du modele et on itiniatile l'index à 1 // Ou, puisque c'est un nouveau dossier, on ajoute un à l'index existant. // On créer le nom du paramètre // On ajoute la propriété au dossier selon le modèle suivant : // P"D1@REPERAGE_DOSSIER@Nom_de_la_piece.SLDPRT" // Si oui, on récupère le nom du paramètre var clef = HashDossier(mdl, fDossier); if (!DossierTraite.Contains(clef)) { DossierTraite.Add(clef); IndexDimension.AddIfNotExistOrPlus(mdl.GetPathName()); NomParam = String.Format("D{0}@{1}", IndexDimension[mdl.GetPathName()]++, CONSTANTES.NOM_ESQUISSE_NUMEROTER); var propVal = String.Format("{0}\"{1}@{2}\"", CONSTANTES.PREFIXE_REF_DOSSIER, NomParam, mdl.eNomAvecExt()); var r = PM.ePropAdd(CONSTANTES.REF_DOSSIER, propVal); if (r > 0) { WindowLog.EcrireF("{0}-{1}-{2} : Pas de propriété ajoutée {3}", mdl.eNomSansExt(), cfg, fDossier.Name, (swCustomInfoAddResult_e)r); } PM.ePropAdd(CONSTANTES.DESC_DOSSIER, propVal); } else { String val, result = ""; Boolean wasResolved, link; var r = PM.Get6(CONSTANTES.REF_DOSSIER, false, out val, out result, out wasResolved, out link); if (r == 1) { WindowLog.EcrireF("{0}-{1}-{2} : Pas de propriété {3}", mdl.eNomSansExt(), cfg, fDossier.Name, (swCustomInfoGetResult_e)r); } NomParam = ExtractNomParam(val); } { String val, result = ""; Boolean wasResolved, link; var r = PM.Get6(CONSTANTES.REF_DOSSIER, false, out val, out result, out wasResolved, out link); PM.ePropAdd(CONSTANTES.DESC_DOSSIER, val); } // On ajoute la propriété NomDossier // permettant de récupérer le nom du dossier dans la mise en plan if (!PM.ePropExiste(CONSTANTES.NOM_DOSSIER)) { var propVal = String.Format("\"SW-CutListItemName@@@{0}@{1}\"", fDossier.Name, mdl.eNomAvecExt()); PM.ePropAdd(CONSTANTES.NOM_DOSSIER, propVal); } var SwCorps = Dossier.ePremierCorps(); Boolean Ajoute = false; var MateriauCorps = SwCorps.eGetMateriauCorpsOuPiece(piece, cfg); var nbCorps = Dossier.eNbCorps() * NbConfig; Dimension param = mdl.Parameter(NomParam); eTypeCorps TypeCorps = Dossier.eTypeDeDossier(); if (CombinerCorpsIdentiques) { // On recherche s'il existe des corps identiques // Si oui, on applique le même repère au parametre foreach (var CorpsTest in ListeCorps) { if ((MateriauCorps != CorpsTest.Materiau) || (TypeCorps != CorpsTest.TypeCorps)) { continue; } if (SwCorps.eComparerGeometrie(CorpsTest.SwCorps) == Sw.Comparaison_e.Semblable) { CorpsTest.Nb += nbCorps; if (Maj) { var errors = param.SetSystemValue3(CorpsTest.Repere * 0.001, (int)swSetValueInConfiguration_e.swSetValue_InSpecificConfigurations, cfg); if (errors > 0) { WindowLog.EcrireF(" Erreur de mise à jour {0}", (swSetValueReturnStatus_e)errors); } } CorpsTest.AjouterModele(mdl, cfg, fDossier.GetID()); Ajoute = true; break; } } } if ((Ajoute == false) && Maj) { var rep = GenRepereDossier; var errors = param.SetSystemValue3(rep * 0.001, (int)swSetValueInConfiguration_e.swSetValue_InSpecificConfigurations, cfg); if (errors > 0) { WindowLog.EcrireF(" Erreur de mise à jour {0}", (swSetValueReturnStatus_e)errors); } var corps = new Corps(SwCorps, TypeCorps, MateriauCorps); corps.Nb = nbCorps; corps.Repere = rep; corps.AjouterModele(mdl, cfg, fDossier.GetID()); ListeCorps.Add(corps); } } } mdl.eFermerSiDifferent(MdlBase); } MdlBase.eActiver(swRebuildOnActivation_e.swRebuildActiveDoc); int Errors = 0, Warnings = 0; MdlBase.Save3((int)swSaveAsOptions_e.swSaveAsOptions_SaveReferenced + (int)swSaveAsOptions_e.swSaveAsOptions_Silent, ref Errors, ref Warnings); MdlBase.EditRebuild3(); // Petit récap WindowLog.SautDeLigne(); WindowLog.EcrireF("Nb de corps unique : {0}", ListeCorps.Count); int nbtt = 0; foreach (var corps in ListeCorps) { nbtt += corps.Nb; WindowLog.EcrireF("P{0} ×{1}", corps.Repere, corps.Nb); } WindowLog.EcrireF("Nb total de corps : {0}", nbtt); } catch (Exception e) { this.LogErreur(new Object[] { e }); } }
public static void GetCurrentConfigPartData(SldWorks swApp, int lastVer, int idPdm, bool closeDoc, bool fixBends, out List <DataToExport> dataList, out Exception exception) //public static void GetCurrentConfigPartData(SldWorks swApp, bool closeDoc, bool fixBends, out List<DataToExport> dataList, out Exception exception) { // Проход по всем родительским конфигурациям exception = null; dataList = new List <DataToExport>(); var swModel = swApp.IActiveDoc2; if (swModel == null) { return; } var configName = ((Configuration)swModel.GetActiveConfiguration()).Name; swModel.ShowConfiguration2(configName); swModel.EditRebuild3(); var swModelDocExt = swModel.Extension; var fileName = swModel.GetTitle().ToUpper().Replace(".SLDPRT", ""); AddDimentions(swModel, configName, out exception); var confiData = new DataToExport { Config = configName, FileName = fileName, IdPdm = idPdm, Version = lastVer }; #region азгибание всех сгибов fixBends = true; if (fixBends) { swModel.EditRebuild3(); List <PartBendInfo> list; Bends.Fix(swApp, out list, false); } #endregion swModel.ForceRebuild3(false); var swCustProp = swModelDocExt.CustomPropertyManager[configName]; string valOut; string materialId; // TO DO LOOK swCustProp.Get4("MaterialID", true, out valOut, out materialId); if (string.IsNullOrEmpty(materialId)) { confiData.MaterialId = null; } else { confiData.MaterialId = int.Parse(materialId); } string paintX; swCustProp.Get4("Длина", true, out valOut, out paintX); if (string.IsNullOrEmpty(paintX)) { confiData.PaintX = null; } else { confiData.PaintX = double.Parse(paintX); } string paintY; swCustProp.Get4("Ширина", true, out valOut, out paintY); if (string.IsNullOrEmpty(paintY)) { confiData.PaintY = null; } else { confiData.PaintY = double.Parse(paintY); } string paintZ; swCustProp.Get4("Высота", true, out valOut, out paintZ); if (string.IsNullOrEmpty(paintZ)) { confiData.PaintZ = null; } else { confiData.PaintZ = double.Parse(paintZ); } string codMaterial; swCustProp.Get4("Код материала", true, out valOut, out codMaterial); confiData.КодМатериала = codMaterial; string материал; swCustProp.Get4("Материал", true, out valOut, out материал); confiData.Материал = материал; string обозначение; swCustProp.Get4("Обозначение", true, out valOut, out обозначение); confiData.Обозначение = обозначение; var swCustPropForDescription = swModelDocExt.CustomPropertyManager[""]; string наименование; swCustPropForDescription.Get4("Наименование", true, out valOut, out наименование); confiData.Наименование = наименование; //UpdateCustomPropertyListFromCutList const string длинаГраничнойРамкиName = @"Длина граничной рамки"; const string длинаГраничнойРамкиName2 = @"Bounding Box Length"; const string ширинаГраничнойРамкиName = @"Ширина граничной рамки"; const string ширинаГраничнойРамкиName2 = @"Bounding Box Width"; const string толщинаЛистовогоМеталлаNAme = @"Толщина листового металла"; const string толщинаЛистовогоМеталлаNAme2 = @"Sheet Metal Thickness"; const string сгибыName = @"Сгибы"; const string сгибыName2 = @"Bends"; const string площадьПокрытияName = @"Площадь покрытия";//const string площадьПокрытияName2 = @"Bounding Box Area"; Feature swFeat2 = swModel.FirstFeature(); while (swFeat2 != null) { if (swFeat2.GetTypeName2() == "SolidBodyFolder") { BodyFolder swBodyFolder = swFeat2.GetSpecificFeature2(); swFeat2.Select2(false, -1); swBodyFolder.SetAutomaticCutList(true); swBodyFolder.UpdateCutList(); Feature swSubFeat = swFeat2.GetFirstSubFeature(); while (swSubFeat != null) { if (swSubFeat.GetTypeName2() == "CutListFolder") { BodyFolder bodyFolder = swSubFeat.GetSpecificFeature2(); if (bodyFolder.GetCutListType() != (int)swCutListType_e.swSheetmetalCutlist) { goto m1; } swSubFeat.Select2(false, -1); bodyFolder.SetAutomaticCutList(true); bodyFolder.UpdateCutList(); var swCustPrpMgr = swSubFeat.CustomPropertyManager; swCustPrpMgr.Add("Площадь поверхности", "Текст", "\"SW-SurfaceArea@@@Элемент списка вырезов1@" + Path.GetFileName(swModel.GetPathName()) + "\""); string длинаГраничнойРамки; swCustPrpMgr.Get4(длинаГраничнойРамкиName, true, out valOut, out длинаГраничнойРамки); if (string.IsNullOrEmpty(длинаГраничнойРамки)) { swCustPrpMgr.Get4(длинаГраничнойРамкиName2, true, out valOut, out длинаГраничнойРамки); } swCustProp.Set(длинаГраничнойРамкиName, длинаГраничнойРамки); confiData.ДлинаГраничнойРамки = длинаГраничнойРамки; string ширинаГраничнойРамки; swCustPrpMgr.Get4(ширинаГраничнойРамкиName, true, out valOut, out ширинаГраничнойРамки); if (string.IsNullOrEmpty(ширинаГраничнойРамки)) { swCustPrpMgr.Get4(ширинаГраничнойРамкиName2, true, out valOut, out ширинаГраничнойРамки); } swCustProp.Set(ширинаГраничнойРамкиName, ширинаГраничнойРамки); confiData.ШиринаГраничнойРамки = ширинаГраничнойРамки; string толщинаЛистовогоМеталла; swCustPrpMgr.Get4(толщинаЛистовогоМеталлаNAme, true, out valOut, out толщинаЛистовогоМеталла); if (string.IsNullOrEmpty(толщинаЛистовогоМеталла)) { swCustPrpMgr.Get4(толщинаЛистовогоМеталлаNAme2, true, out valOut, out толщинаЛистовогоМеталла); } swCustProp.Set(толщинаЛистовогоМеталлаNAme, толщинаЛистовогоМеталла); confiData.ТолщинаЛистовогоМеталла = толщинаЛистовогоМеталла; string сгибы; swCustPrpMgr.Get4(сгибыName, true, out valOut, out сгибы); if (string.IsNullOrEmpty(сгибы)) { swCustPrpMgr.Get4(сгибыName2, true, out valOut, out сгибы); } swCustProp.Set(сгибыName, сгибы); confiData.Сгибы = сгибы; var myMassProp = swModel.Extension.CreateMassProperty(); var площадьПоверхности = Convert.ToString(Math.Round(myMassProp.SurfaceArea * 1000) / 1000); swCustProp.Set(площадьПокрытияName, площадьПоверхности); try { confiData.ПлощадьПокрытия = double.Parse(площадьПоверхности.Replace(".", ",")); } catch (Exception e) { exception = e; } } m1: swSubFeat = swSubFeat.GetNextFeature(); } } swFeat2 = swFeat2.GetNextFeature(); } dataList.Add(confiData); if (!closeDoc) { return; } var namePrt = swApp.IActiveDoc2.GetTitle().ToLower().Contains(".sldprt") ? swApp.IActiveDoc2.GetTitle() : swApp.IActiveDoc2.GetTitle() + ".sldprt"; swApp.CloseDoc(namePrt); }
public static void Export(SldWorks swApp, int verToExport, int idPdm, bool closeDoc, out Exception exception) { exception = null; CurrentVersion = verToExport; //verToExport; #region Сбор информации по детали и сохранение разверток if (swApp == null) { try { swApp = (SldWorks)Marshal.GetActiveObject("SldWorks.Application"); } catch (Exception) { swApp = new SldWorks { Visible = false }; } } IModelDoc2 swModel; try { swModel = swApp.IActiveDoc2; } catch (Exception) { swModel = swApp.IActiveDoc2; } if (swModel == null) { return; } var modelName = swModel.GetTitle(); try { IPartDoc partDoc; try { partDoc = (IPartDoc)((ModelDoc2)swModel); } catch (Exception) { return; } bool sheetMetal = false; try { sheetMetal = Part.IsSheetMetal(partDoc); } catch (Exception) { } if (!sheetMetal) { //swApp.CloseDoc(Path.GetFileName(swModel.GetPathName())); //13.10.2016 swApp.CloseAllDocuments(true); //swApp.ExitApp(); return; } var activeconfiguration = (Configuration)swModel.GetActiveConfiguration(); var swModelConfNames = (string[])swModel.GetConfigurationNames(); foreach (var name in from name in swModelConfNames let config = (Configuration)swModel.GetConfigurationByName(name) where config.IsDerived() select name) { swModel.DeleteConfiguration(name); } var swModelDocExt = swModel.Extension; var swModelConfNames2 = (string[])swModel.GetConfigurationNames(); // Проход по всем родительским конфигурациям var dataList = new List <DataToExport>(); var filePath = swModel.GetPathName(); foreach (var configName in from name in swModelConfNames2 let config = (Configuration)swModel.GetConfigurationByName(name) where !config.IsDerived() select name) { // swModel.ShowConfiguration2(configName); swModel.EditRebuild3(); AddDimentions(swModel, configName, out exception); var confiData = new DataToExport { Config = configName, FileName = filePath.Substring(filePath.LastIndexOf('\\') + 1), IdPdm = idPdm }; #region азгибание всех сгибов try { swModel.EditRebuild3(); List <PartBendInfo> list; Bends.Fix(swApp, out list, false); } catch (Exception) { // } #endregion swModel.ForceRebuild3(false); var swCustProp = swModelDocExt.CustomPropertyManager[configName]; string valOut; string materialId; swCustProp.Get4("MaterialID", true, out valOut, out materialId); if (string.IsNullOrEmpty(materialId)) { confiData.MaterialId = null; } else { confiData.MaterialId = int.Parse(materialId); } string paintX; swCustProp.Get4("Длина", true, out valOut, out paintX); if (string.IsNullOrEmpty(paintX)) { confiData.PaintX = null; } else { confiData.PaintX = double.Parse(paintX); } string paintY; swCustProp.Get4("Ширина", true, out valOut, out paintY); if (string.IsNullOrEmpty(paintY)) { confiData.PaintY = null; } else { confiData.PaintY = double.Parse(paintY); } string paintZ; swCustProp.Get4("Высота", true, out valOut, out paintZ); if (string.IsNullOrEmpty(paintZ)) { confiData.PaintZ = null; } else { confiData.PaintZ = double.Parse(paintZ); } string codMaterial; swCustProp.Get4("Код материала", true, out valOut, out codMaterial); confiData.КодМатериала = codMaterial; string материал; swCustProp.Get4("Материал", true, out valOut, out материал); confiData.Материал = материал; string обозначение; swCustProp.Get4("Обозначение", true, out valOut, out обозначение); confiData.Обозначение = обозначение; var swCustPropForDescription = swModelDocExt.CustomPropertyManager[""]; string наименование; swCustPropForDescription.Get4("Наименование", true, out valOut, out наименование); confiData.Наименование = наименование; //UpdateCustomPropertyListFromCutList const string длинаГраничнойРамкиName = @"Длина граничной рамки"; const string длинаГраничнойРамкиName2 = @"Bounding Box Length"; const string ширинаГраничнойРамкиName = @"Ширина граничной рамки"; const string ширинаГраничнойРамкиName2 = @"Bounding Box Width"; const string толщинаЛистовогоМеталлаNAme = @"Толщина листового металла"; const string толщинаЛистовогоМеталлаNAme2 = @"Sheet Metal Thickness";//Sheet Metal Thickness const string сгибыName = @"Сгибы"; const string сгибыName2 = @"Bends"; const string площадьПокрытияName = @"Площадь покрытия"; const string площадьПокрытияName2 = @"Bounding Box Area"; Feature swFeat2 = swModel.FirstFeature(); while (swFeat2 != null) { if (swFeat2.GetTypeName2() == "SolidBodyFolder") { // List<Bends.SolidWorksFixPattern.PartBendInfo> list; // Bends.Fix(swApp, out list, false); BodyFolder swBodyFolder = swFeat2.GetSpecificFeature2(); swFeat2.Select2(false, -1); swBodyFolder.SetAutomaticCutList(true); swBodyFolder.UpdateCutList(); Feature swSubFeat = swFeat2.GetFirstSubFeature(); while (swSubFeat != null) { if (swSubFeat.GetTypeName2() == "CutListFolder") { BodyFolder bodyFolder = swSubFeat.GetSpecificFeature2(); if (bodyFolder.GetCutListType() != (int)swCutListType_e.swSheetmetalCutlist) { goto m1; } swSubFeat.Select2(false, -1); bodyFolder.SetAutomaticCutList(true); bodyFolder.UpdateCutList(); var swCustPrpMgr = swSubFeat.CustomPropertyManager; swCustPrpMgr.Add("Площадь поверхности", "Текст", "\"SW-SurfaceArea@@@Элемент списка вырезов1@" + Path.GetFileName(swModel.GetPathName()) + "\""); string длинаГраничнойРамки; swCustPrpMgr.Get4(длинаГраничнойРамкиName, true, out valOut, out длинаГраничнойРамки); if (string.IsNullOrEmpty(длинаГраничнойРамки)) { swCustPrpMgr.Get4(длинаГраничнойРамкиName2, true, out valOut, out длинаГраничнойРамки); } swCustProp.Set(длинаГраничнойРамкиName, длинаГраничнойРамки); confiData.ДлинаГраничнойРамки = длинаГраничнойРамки; string ширинаГраничнойРамки; swCustPrpMgr.Get4(ширинаГраничнойРамкиName, true, out valOut, out ширинаГраничнойРамки); if (string.IsNullOrEmpty(ширинаГраничнойРамки)) { swCustPrpMgr.Get4(ширинаГраничнойРамкиName2, true, out valOut, out ширинаГраничнойРамки); } swCustProp.Set(ширинаГраничнойРамкиName, ширинаГраничнойРамки); confiData.ШиринаГраничнойРамки = ширинаГраничнойРамки; string толщинаЛистовогоМеталла; swCustPrpMgr.Get4(толщинаЛистовогоМеталлаNAme, true, out valOut, out толщинаЛистовогоМеталла); if (string.IsNullOrEmpty(толщинаЛистовогоМеталла)) { swCustPrpMgr.Get4(толщинаЛистовогоМеталлаNAme2, true, out valOut, out толщинаЛистовогоМеталла); } swCustProp.Set(толщинаЛистовогоМеталлаNAme, толщинаЛистовогоМеталла); confiData.ТолщинаЛистовогоМеталла = толщинаЛистовогоМеталла; string сгибы; swCustPrpMgr.Get4(сгибыName, true, out valOut, out сгибы); if (string.IsNullOrEmpty(сгибы)) { swCustPrpMgr.Get4(сгибыName2, true, out valOut, out сгибы); } swCustProp.Set(сгибыName, сгибы); confiData.Сгибы = сгибы; var myMassProp = swModel.Extension.CreateMassProperty(); var площадьПоверхности = Convert.ToString(Math.Round(myMassProp.SurfaceArea * 1000) / 1000); swCustProp.Set(площадьПокрытияName, площадьПоверхности); try { confiData.ПлощадьПокрытия = double.Parse(площадьПоверхности.Replace(".", ",")); } catch (Exception e) { exception = e; } } m1: swSubFeat = swSubFeat.GetNextFeature(); } } swFeat2 = swFeat2.GetNextFeature(); } dataList.Add(confiData); } swModel.ShowConfiguration2(activeconfiguration.Name); ExportDataToXmlSql(swModel.GetTitle().ToUpper().Replace(".SLDPRT", ""), dataList, out exception); #endregion if (!closeDoc) { return; } var namePrt = swApp.IActiveDoc2.GetTitle().ToLower().Contains(".sldprt") ? swApp.IActiveDoc2.GetTitle() : swApp.IActiveDoc2.GetTitle() + ".sldprt"; swApp.CloseDoc(namePrt); } catch (Exception e) { exception = e; } finally { swApp.CloseDoc(Path.GetFileName(swModel.GetPathName())); } }
public ListeLgProfil Analyser() { InitTime(); try { listeElement = new ListeElement(LgBarre); eTypeCorps Filtre = PrendreEnCompteTole ? eTypeCorps.Barre | eTypeCorps.Tole : eTypeCorps.Barre; HashSet <String> HashMateriaux = new HashSet <string>(ListeMateriaux); var dic = MdlBase.DenombrerDossiers(ComposantsExterne, fDossier => { BodyFolder swDossier = fDossier.GetSpecificFeature2(); if (Filtre.HasFlag(swDossier.eTypeDeDossier()) && HashMateriaux.Contains(swDossier.eGetMateriau())) { return(true); } return(false); } ); foreach (var mdl in dic.Keys) { mdl.eActiver(swRebuildOnActivation_e.swRebuildActiveDoc); foreach (var NomConfigPliee in dic[mdl].Keys) { mdl.ShowConfiguration2(NomConfigPliee); mdl.EditRebuild3(); PartDoc Piece = mdl.ePartDoc(); var ListeDossier = dic[mdl][NomConfigPliee]; foreach (var t in ListeDossier) { var IdDossier = t.Key; var QuantiteBarre = t.Value * Quantite; Feature fDossier = Piece.FeatureById(IdDossier); BodyFolder dossier = fDossier.GetSpecificFeature2(); var RefDossier = dossier.eProp(CONSTANTES.REF_DOSSIER); String Profil = dossier.eProp(CONSTANTES.PROFIL_NOM); Double Longueur = dossier.eProp(CONSTANTES.PROFIL_LONGUEUR).eToDouble(); Double A = dossier.eProp(CONSTANTES.PROFIL_ANGLE1).eToDouble(); Double B = dossier.eProp(CONSTANTES.PROFIL_ANGLE2).eToDouble(); if (String.IsNullOrWhiteSpace(Profil) || (Longueur == 0)) { continue; } if (String.IsNullOrWhiteSpace(RefDossier)) { WindowLog.EcrireF("{0}-{1}-{2} : Pas de reférence profil", mdl.eNomSansExt(), NomConfigPliee, fDossier.Name); continue; } var Materiau = dossier.ePremierCorps().eGetMateriauCorpsOuPiece(Piece, NomConfigPliee); if (!HashMateriaux.Contains(Materiau)) { continue; } Materiau = ForcerMateriau.IsRefAndNotEmpty(Materiau); listeElement.AjouterElement(QuantiteBarre, RefDossier, Materiau, Profil, Longueur, A, B); } } } ExecuterEn(); return(listeElement.ListeLgProfil); } catch (Exception e) { this.LogErreur(new Object[] { e }); } return(null); }
/// <summary> /// 天花子装配导出DXF图纸 /// </summary> /// <param name="swApp"></param> /// <param name="tree"></param> /// <param name="dxfPath"></param> /// <param name="userId"></param> public void CeilingAssyToDxf(SldWorks swApp, SubAssy subAssy, string dxfPath, int userId) { swApp.CommandInProgress = true; List <CeilingCutList> celingCutLists = new List <CeilingCutList>(); string assyPath = subAssy.SubAssyPath; if (assyPath.Length == 0) { return; } try { //打开模型 ModelDoc2 swModel = swApp.OpenDoc6(assyPath, (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings) as ModelDoc2; if (swModel == null) { MessageBox.Show("模型不存在,请认真检查", "模型不存在"); return; } string modulePath = dxfPath + @"\" + subAssy.SubAssyName; if (!Directory.Exists(modulePath)) { Directory.CreateDirectory(modulePath); } swModel.ForceRebuild3(true); AssemblyDoc swAssy = swModel as AssemblyDoc; //获取所有零部件集合 var compList = swAssy.GetComponents(false); //遍历集合中的所有零部件对象 foreach (var swComp in compList) { //判断零件是否被压缩,不显示,封套,零件名称不是以sldprt或SLDPRT结尾 if (swComp.Visible == 1 && !swComp.IsEnvelope() && !swComp.IsSuppressed() && (swComp.GetPathName().EndsWith(".sldprt") || swComp.GetPathName().EndsWith(".SLDPRT"))) { Component2 swParentComp = swComp.GetParent(); //总装没有父装配体 if (swParentComp == null) { ConfigurationManager swConfigMgr = swModel.ConfigurationManager; Configuration swConfig2 = swConfigMgr.ActiveConfiguration; swParentComp = swConfig2.GetRootComponent3(true); } //判断父装配体是否可视,并且不封套 if (swParentComp.Visible == 1 && !swParentComp.IsEnvelope() && !swComp.IsSuppressed()) { PartDoc swPart = swComp.GetModelDoc2(); //获取文档中的额Body对象集合 var bodyList = swPart.GetBodies2(0, false); //遍历集合中的所有Body对象,判断是否为钣金 foreach (var swBody in bodyList) { //如果是钣金则将零件地址添加到列表中 if (swBody.IsSheetMetal()) { if (sheetMetaDic.ContainsKey(swComp.GetPathName())) { sheetMetaDic[swComp.GetPathName()] += 1; } else { sheetMetaDic.Add(swComp.GetPathName(), 1); } } } } } } //关闭装配体零件 swApp.CloseDoc(assyPath); //遍历钣金零件 foreach (var sheetMeta in sheetMetaDic) { //打开模型 ModelDoc2 swPart = swApp.OpenDoc6(sheetMeta.Key, (int)swDocumentTypes_e.swDocPART, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings) as ModelDoc2; Feature swFeat = (Feature)swPart.FirstFeature(); CeilingCutList cutRecord = new CeilingCutList() { SubAssyId = subAssy.SubAssyId, Quantity = sheetMeta.Value, UserId = userId }; while (swFeat != null) { var suppStatus = swFeat.IsSuppressed2((int)swInConfigurationOpts_e.swThisConfiguration, null); if (suppStatus[0] == false && swFeat.GetTypeName() == "SolidBodyFolder") { BodyFolder swBodyFolder = (BodyFolder)swFeat.GetSpecificFeature2(); swBodyFolder.SetAutomaticCutList(true); swBodyFolder.SetAutomaticUpdate(true); Feature SubFeat = swFeat.GetFirstSubFeature(); if (SubFeat != null) { Feature ownerFeature = SubFeat.GetOwnerFeature(); BodyFolder swSubBodyFolder = ownerFeature.GetSpecificFeature2(); swSubBodyFolder.UpdateCutList(); string val = string.Empty; string valout = string.Empty; bool wasResolved = false; bool linkToProp = false; SubFeat.CustomPropertyManager.Get4("Bounding Box Length", false, out val, out valout); cutRecord.Length = Convert.ToDecimal(valout); SubFeat.CustomPropertyManager.Get4("Bounding Box Width", false, out val, out valout); cutRecord.Width = Convert.ToDecimal(valout); SubFeat.CustomPropertyManager.Get4("Sheet Metal Thickness", false, out val, out valout); cutRecord.Thickness = Convert.ToDecimal(valout); SubFeat.CustomPropertyManager.Get4("Material", false, out val, out valout); cutRecord.Materials = valout; swPart.GetActiveConfiguration().CustomPropertyManager.Get6("Description", false, out valout, out val, out wasResolved, out linkToProp); cutRecord.PartDescription = valout; cutRecord.PartNo = swPart.GetTitle().Substring(0, swPart.GetTitle().Length - 7); celingCutLists.Add(cutRecord);//将信息添加到集合中 } } swFeat = swFeat.GetNextFeature(); } PartToDxf(swApp, swPart, modulePath); //关闭零件 swApp.CloseDoc(sheetMeta.Key); } } catch (Exception ex) { throw new Exception(assyPath + "导图过程发生异常,详细:" + ex.Message); } finally { sheetMetaDic.Clear(); swApp.CloseDoc(assyPath); //关闭,很快 swApp.CommandInProgress = false; //及时关闭外部命令调用,否则影响SolidWorks的使用 } //基于事务ceilingCutLists提交SQLServer if (celingCutLists.Count == 0) { return; } try { if (objCeilingCutListService.ImportCutList(celingCutLists)) { celingCutLists.Clear(); } } catch (Exception ex) { throw new Exception("Cutlist导入数据库失败" + ex.Message); } }
protected override void Command() { try { int NbDvp = 0; var dic = MdlBase.ListerComposants(false); int MdlPct = 0; foreach (var mdl in dic.Keys) { WindowLog.SautDeLigne(); WindowLog.EcrireF("[{1}/{2}] {0}", mdl.eNomSansExt(), ++MdlPct, dic.Count); mdl.eActiver(swRebuildOnActivation_e.swRebuildActiveDoc); var cfgActive = mdl.eNomConfigActive(); var ListeNomConfigs = dic[mdl]; if (ToutesLesConfigurations) { mdl.eParcourirConfiguration( (String c) => { if (c.eEstConfigPliee() && !ListeNomConfigs.ContainsKey(c)) { ListeNomConfigs.Add(c, 1); } return(false); } ); } if (MasquerEsquisses) { cmdMasquerEsquisses(mdl); } if (SupprimerLesAnciennesConfigs) { cmdSupprimerLesAnciennesConfigs(mdl); } if (!mdl.Extension.LinkedDisplayState) { mdl.Extension.LinkedDisplayState = true; foreach (var c in mdl.eListeConfigs(eTypeConfig.Tous)) { c.eRenommerEtatAffichage(); } } int CfgPct = 0; foreach (var NomConfigPliee in ListeNomConfigs.Keys) { WindowLog.SautDeLigne(); WindowLog.EcrireF(" [{1}/{2}] Config : \"{0}\"", NomConfigPliee, ++CfgPct, ListeNomConfigs.Count); mdl.ShowConfiguration2(NomConfigPliee); mdl.EditRebuild3(); if (SupprimerFonctions) { cmdSupprimerFonctions(mdl, NomConfigPliee); } PartDoc Piece = mdl.ePartDoc(); var ListeDossier = Piece.eListePIDdesFonctionsDePiecesSoudees( swD => { BodyFolder dossier = swD.GetSpecificFeature2(); if (dossier.eEstExclu() || dossier.IsNull() || (dossier.GetBodyCount() == 0) || dossier.eTypeDeDossier() != eTypeCorps.Tole) { return(false); } return(true); } ); for (int noD = 0; noD < ListeDossier.Count; noD++) { var f = ListeDossier[noD]; BodyFolder dossier = f.GetSpecificFeature2(); var RefDossier = dossier.eProp(CONSTANTES.REF_DOSSIER); Body2 Tole = dossier.eCorpsDeTolerie(); var pidTole = new SwObjectPID <Body2>(Tole, MdlBase); String NomConfigDepliee = Sw.eNomConfigDepliee(NomConfigPliee, RefDossier); WindowLog.EcrireF(" - [{1}/{2}] Dossier : \"{0}\" -> {3}", f.Name, noD + 1, ListeDossier.Count, NomConfigDepliee); Configuration CfgDepliee = null; if (ReconstuireLesConfigs) { CfgDepliee = MdlBase.GetConfigurationByName(NomConfigDepliee); } if (CfgDepliee.IsNull()) { CfgDepliee = mdl.CreerConfigDepliee(NomConfigDepliee, NomConfigPliee); } else if (!ReconstuireLesConfigs) { continue; } if (CfgDepliee.IsNull()) { WindowLog.Ecrire(" - Config non crée"); continue; } NbDvp++; try { mdl.ShowConfiguration2(NomConfigDepliee); // On ajoute le numero de la config parent aux propriétés de la configuration depliée CfgDepliee.CustomPropertyManager.Add3(CONSTANTES.NO_CONFIG, (int)swCustomInfoType_e.swCustomInfoText, NomConfigPliee, (int)swCustomPropertyAddOption_e.swCustomPropertyDeleteAndAdd); pidTole.Maj(ref Tole); Tole.DeplierTole(mdl, NomConfigDepliee); } catch (Exception e) { DicErreur.Add(mdl.eNomSansExt() + " -> cfg : " + NomConfigPliee + " - No : " + RefDossier + " = " + NomConfigDepliee); WindowLog.Ecrire("Erreur de depliage"); this.LogMethode(new Object[] { e }); } try { mdl.ShowConfiguration2(NomConfigPliee); pidTole.Maj(ref Tole); Tole.PlierTole(mdl, NomConfigPliee); } catch (Exception e) { WindowLog.Ecrire("Erreur de repliage"); this.LogMethode(new Object[] { e }); } } } mdl.ShowConfiguration2(cfgActive); WindowLog.SautDeLigne(); mdl.eFermerSiDifferent(MdlBase); } if (DicErreur.Count > 0) { WindowLog.SautDeLigne(); WindowLog.Ecrire("Liste des erreurs :"); foreach (var item in DicErreur) { WindowLog.Ecrire(" - " + item); } WindowLog.SautDeLigne(); } else { WindowLog.Ecrire("Pas d'erreur"); } WindowLog.SautDeLigne(); WindowLog.Ecrire("Resultat :"); WindowLog.Ecrire("----------------"); WindowLog.EcrireF(" {0} dvp crées", NbDvp); File.WriteAllText(Path.Combine(MdlBase.eDossier(), "Log_CreerConfigDvp.txt"), WindowLog.Resume); MdlBase.eActiver(swRebuildOnActivation_e.swRebuildActiveDoc); MdlBase.ShowConfiguration2(nomConfigBase); MdlBase.EditRebuild3(); } catch (Exception e) { this.LogErreur(new Object[] { e }); } }
//public static IEdmObject5 GetObject(IEdmVault12 vault, int objectId, EdmObjectType objectType) //{ // try // { // var obj = vault.GetObject(objectType, objectId); // return obj; // } // catch (Exception e) // { // Console.WriteLine("Ошибка в процедуре public static IEdmObject5 GetObject {0}:", e); // } // foreach (EdmObjectType enumObjectType in Enum.GetValues(typeof(EdmObjectType))) // { // try // { // var obj = vault.GetObject(enumObjectType, objectId); // return obj; // } // catch (Exception e) // { // Console.WriteLine("Ошибка в процедуре public static IEdmObject5 GetObject {0}:", e); // } // } // //nothing found // return null; //} static void CreateFlattPatternUpdateCutlist(string filePath, bool savedxf) { //var vault1 = new EdmVault5(); //IEdmFolder5 oFolder; //vault1.LoginAuto("Vents-PDM", 0); //var edmFile5 = vault1.GetFileFromPath("D:\\Vents-PDM\\Библиотека проектирования\\Templates\\flattpattern.drwdot", out oFolder); //edmFile5.GetFileCopy(0, 0, oFolder.ID, (int)EdmGetFlag.EdmGet_Simple); try { SwApp = (SldWorks)Marshal.GetActiveObject("SldWorks.Application"); } catch (Exception) { SwApp = new SldWorks { Visible = true }; } if (SwApp == null) { return; } var swModel = SwApp.OpenDoc6(filePath, (int)swDocumentTypes_e.swDocPART, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", 0, 0); SwApp.SetUserPreferenceStringValue(((int)(swUserPreferenceStringValue_e.swFileLocationsDocumentTemplates)), "D:\\Vents-PDM\\Библиотека проектирования\\Templates\\"); try { if (!IsSheetMetalPart((IPartDoc)swModel)) { SwApp.CloseDoc(swModel.GetTitle()); return; } } catch (Exception) { return; } var activeconfiguration = (Configuration)swModel.GetActiveConfiguration(); var swModelConfNames = (string[])swModel.GetConfigurationNames(); foreach (var name in from name in swModelConfNames let config = (Configuration)swModel.GetConfigurationByName(name) where config.IsDerived() select name) { swModel.DeleteConfiguration(name); } var swModelDocExt = swModel.Extension; var swModelConfNames2 = (string[])swModel.GetConfigurationNames(); // Проход по всем родительским конфигурациям (т.е. - конфигурациям деталей) var dataList = new List <DataToExport>(); foreach (var configName in from name in swModelConfNames2 let config = (Configuration)swModel.GetConfigurationByName(name) where !config.IsDerived() select name) { swModel.ShowConfiguration2(configName); swModel.EditRebuild3(); var confiData = new DataToExport { Config = configName }; var swDraw = (DrawingDoc)SwApp.NewDrawing2((int)swDwgTemplates_e.swDwgTemplateA0size, "D:\\Vents-PDM\\Библиотека проектирования\\Templates\\flattpattern.drwdot",// "D:\\Vents-PDM\\Библиотека проектирования\\Templates\\flattpattern.drwdot", (int)swDwgPaperSizes_e.swDwgPaperA0size, 0.841, 0.594); swDraw.CreateFlatPatternViewFromModelView3(swModel.GetPathName(), configName, 0.841 / 2, 0.594 / 2, 0, true, true); swModel.ForceRebuild3(false); var swCustProp = swModelDocExt.CustomPropertyManager[configName]; string valOut; string codMaterial; swCustProp.Get4("Код материала", true, out valOut, out codMaterial); confiData.КодМатериала = codMaterial; string материал; swCustProp.Get4("Материал", true, out valOut, out материал); confiData.Материал = материал; string обозначение; swCustProp.Get4("Обозначение", true, out valOut, out обозначение); confiData.Обозначение = обозначение; var swCustPropForDescription = swModelDocExt.CustomPropertyManager[""]; string наименование; swCustPropForDescription.Get4("Наименование", true, out valOut, out наименование); confiData.Наименование = наименование; if (savedxf) { var newDxf = (IModelDoc2)swDraw; SwApp.CloseDoc(newDxf.GetPathName()); } else { var newDxf = (IModelDoc2)swDraw; SwApp.CloseDoc(newDxf.GetTitle()); } //UpdateCustomPropertyListFromCutList const string длинаГраничнойРамкиName = "Длина граничной рамки"; const string ширинаГраничнойРамкиName = "Ширина граничной рамки"; const string толщинаЛистовогоМеталлаNAme = "Толщина листового металла"; const string сгибыName = "Сгибы"; const string площадьПокрытияName = "Площадь покрытия"; Feature swFeat2 = swModel.FirstFeature(); while (swFeat2 != null) { if (swFeat2.GetTypeName2() == "SolidBodyFolder") { BodyFolder swBodyFolder = swFeat2.GetSpecificFeature2(); swFeat2.Select2(false, -1); swBodyFolder.SetAutomaticCutList(true); swBodyFolder.UpdateCutList(); Feature swSubFeat = swFeat2.GetFirstSubFeature(); while (swSubFeat != null) { if (swSubFeat.GetTypeName2() == "CutListFolder") { BodyFolder bodyFolder = swSubFeat.GetSpecificFeature2(); swSubFeat.Select2(false, -1); bodyFolder.SetAutomaticCutList(true); bodyFolder.UpdateCutList(); var swCustPrpMgr = swSubFeat.CustomPropertyManager; swCustPrpMgr.Add("Площадь поверхности", "Текст", "\"SW-SurfaceArea@@@Элемент списка вырезов1@" + Path.GetFileName(swModel.GetPathName()) + "\""); string длинаГраничнойРамки; swCustPrpMgr.Get4(длинаГраничнойРамкиName, true, out valOut, out длинаГраничнойРамки); swCustProp.Set(длинаГраничнойРамкиName, длинаГраничнойРамки); confiData.ДлинаГраничнойРамки = длинаГраничнойРамки; string ширинаГраничнойРамки; swCustPrpMgr.Get4(ширинаГраничнойРамкиName, true, out valOut, out ширинаГраничнойРамки); swCustProp.Set(ширинаГраничнойРамкиName, ширинаГраничнойРамки); confiData.ШиринаГраничнойРамки = ширинаГраничнойРамки; string толщинаЛистовогоМеталла; swCustPrpMgr.Get4(толщинаЛистовогоМеталлаNAme, true, out valOut, out толщинаЛистовогоМеталла); swCustProp.Set(толщинаЛистовогоМеталлаNAme, толщинаЛистовогоМеталла); confiData.ТолщинаЛистовогоМеталла = толщинаЛистовогоМеталла; string сгибы; swCustPrpMgr.Get4(сгибыName, true, out valOut, out сгибы); swCustProp.Set(сгибыName, сгибы); confiData.Сгибы = сгибы; string площадьПоверхности; swCustPrpMgr.Get4("Площадь поверхности", true, out valOut, out площадьПоверхности); swCustProp.Set(площадьПокрытияName, площадьПоверхности); confiData.ПлощадьПокрытия = площадьПоверхности; } swSubFeat = swSubFeat.GetNextFeature(); } } swFeat2 = swFeat2.GetNextFeature(); } dataList.Add(confiData); } swModel.ShowConfiguration2(activeconfiguration.Name); //GetXml(swModel); ExportDataToXmlSql(swModel, dataList); SwApp.CloseDoc(swModel.GetTitle()); }
/// <summary> /// Renvoi la liste des modeles avec la liste des configurations, des dossiers /// et les quantites de chaque dossier dans l'assemblage /// Modele : ModelDoc2 /// |-Config1 : Nom de la configuration /// | |-Dossier1 : Comparaison avec la propriete RefDossier, référence à l'Id de la fonction pour pouvoir le selectionner plus tard /// | | |- Nb : quantite de corps identique dans le modele complet /// | | /// | |-Dossier2 /// | |- Nb /// |-Config 2 /// | etc... /// </summary> /// <param name="mdlBase"></param> /// <param name="composantsExterne"></param> /// <param name="filtreDossier"></param> /// <returns></returns> public static SortedDictionary <ModelDoc2, SortedDictionary <String, SortedDictionary <int, int> > > DenombrerDossiers(this ModelDoc2 mdlBase, Boolean composantsExterne, Predicate <Feature> filtreDossier = null, Boolean fermerFichier = false) { SortedDictionary <ModelDoc2, SortedDictionary <String, SortedDictionary <int, int> > > dic = new SortedDictionary <ModelDoc2, SortedDictionary <String, SortedDictionary <int, int> > >(new CompareModelDoc2()); try { var ListeComposants = mdlBase.ListerComposants(composantsExterne); var ListeDossiers = new Dictionary <String, Dossier>(); Predicate <Feature> Test = delegate(Feature fDossier) { BodyFolder SwDossier = fDossier.GetSpecificFeature2(); if (SwDossier.IsRef() && SwDossier.eNbCorps() > 0 && !SwDossier.eEstExclu() && (filtreDossier.IsNull() || filtreDossier(fDossier))) { return(true); } return(false); }; foreach (var mdl in ListeComposants.Keys) { mdl.eActiver(swRebuildOnActivation_e.swRebuildActiveDoc); foreach (var t in ListeComposants[mdl]) { var cfg = t.Key; var nbCfg = t.Value; mdl.ShowConfiguration2(cfg); mdl.EditRebuild3(); var Piece = mdl.ePartDoc(); foreach (var fDossier in Piece.eListeDesFonctionsDePiecesSoudees(Test)) { BodyFolder SwDossier = fDossier.GetSpecificFeature2(); var RefDossier = SwDossier.eProp(CONSTANTES.REF_DOSSIER); if (ListeDossiers.ContainsKey(RefDossier)) { ListeDossiers[RefDossier].Nb += SwDossier.eNbCorps() * nbCfg; } else { var dossier = new Dossier(RefDossier, mdl, cfg, fDossier.GetID()); dossier.Nb = SwDossier.eNbCorps() * nbCfg; ListeDossiers.Add(RefDossier, dossier); } } } if (fermerFichier) { mdl.eFermerSiDifferent(mdlBase); } ; } // Conversion d'une liste de dossier // en liste de modele foreach (var dossier in ListeDossiers.Values) { if (dic.ContainsKey(dossier.Mdl)) { var lcfg = dic[dossier.Mdl]; if (lcfg.ContainsKey(dossier.Config)) { var ldossier = lcfg[dossier.Config]; ldossier.Add(dossier.Id, dossier.Nb); } else { var ldossier = new SortedDictionary <int, int>(); ldossier.Add(dossier.Id, dossier.Nb); lcfg.Add(dossier.Config, ldossier); } } else { var ldossier = new SortedDictionary <int, int>(); ldossier.Add(dossier.Id, dossier.Nb); var lcfg = new SortedDictionary <String, SortedDictionary <int, int> >(new WindowsStringComparer()); lcfg.Add(dossier.Config, ldossier); dic.Add(dossier.Mdl, lcfg); } } } catch (Exception e) { Log.LogErreur(new Object[] { e }); } return(dic); }