예제 #1
0
        private void OnClickFeuille(object sender, EventArgs e)
        {
            try
            {
                if (DessinActif.IsNull())
                {
                    return;
                }

                var Feuille = DessinActif.eFeuilleActive();
                var echelle = TextBoxFeuille.Text.Split(':');
                if (echelle.Length == 2)
                {
                    var e1 = echelle[0].eToDouble();
                    var e2 = echelle[1].eToDouble();
                    if (e1 > 0 && e2 > 0)
                    {
                        Feuille.SetScale(e1, e2, false, false);
                        MdlActif.EditRebuild3();
                    }
                }
            }
            catch
            {
                Deconnecter();
            }
        }
 public static void SetCompConfig(ModelDoc2 AssemDoc, Component2 SwComp)
 {
     SwComp.ReferencedConfiguration = "配置2";
     AssemDoc.EditRebuild3();
     System.Windows.MessageBox.Show("部件" + SwComp.Name2 + ":使用了配置2");
     SwComp.ReferencedConfiguration = "Default";
     AssemDoc.EditRebuild3();
     System.Windows.MessageBox.Show("部件" + SwComp.Name2 + ":使用了Default配置");
 }
예제 #3
0
            protected override void Command()
            {
                try
                {
                    _NomConfigCourante = MdlBase.eNomConfigActive();

                    if (SurTouteLesConfigs)
                    {
                        var pidF_Dessus  = new SwObjectPID <Face2>(F_Dessus, MdlBase);
                        var pidF_Devant  = new SwObjectPID <Face2>(F_Devant, MdlBase);
                        var pidPltG_Plan = new SwObjectPID <Feature>(PltG_Plan, MdlBase);
                        var pidPltD_Plan = new SwObjectPID <Feature>(PltD_Plan, MdlBase);
                        var pidPltG      = new SwObjectPID <Component2>(PltG, MdlBase);
                        var pidPltD      = new SwObjectPID <Component2>(PltD, MdlBase);

                        List <String> ListeNomsConfig = MdlBase.eListeNomConfiguration(eTypeConfig.DeBase);

                        foreach (String NomConfig in ListeNomsConfig)
                        {
                            MdlBase.ShowConfiguration2(NomConfig);
                            MdlBase.EditRebuild3();

                            //pidF_Dessus.Maj(ref F_Dessus);
                            //pidF_Devant.Maj(ref F_Devant);
                            //pidPltG_Plan.Maj(ref PltG_Plan);
                            //pidPltD_Plan.Maj(ref PltD_Plan);
                            //pidPltG.Maj(ref PltG);
                            //pidPltD.Maj(ref PltD);

                            pidF_Dessus.Maj();
                            pidF_Devant.Maj();
                            pidPltG_Plan.Maj();
                            pidPltD_Plan.Maj();
                            pidPltG.Maj();
                            pidPltD.Maj();

                            Run(F_Dessus, F_Devant, PltG_Plan, PltD_Plan, PltG, PltD);
                        }

                        MdlBase.ShowConfiguration2(_NomConfigCourante);
                    }
                    else
                    {
                        Run(F_Dessus, F_Devant, PltG_Plan, PltD_Plan, PltG, PltD);
                    }

                    MdlBase.EditRebuild3();
                }
                catch (Exception e)
                {
                    this.LogErreur(new Object[] { e });
                }
            }
예제 #4
0
        protected override void Command()
        {
            try
            {
                var NomCfgActive = MdlBase.eNomConfigActive();
                var ListeCfg     = MdlBase.eListeNomConfiguration();

                if (!ToutesLesConfigs)
                {
                    ListeCfg = new List <string>()
                    {
                        NomCfgActive
                    }
                }
                ;

                var lcfg = MdlBase.eListeNomConfiguration();

                foreach (var cfg in ListeCfg)
                {
                    MdlBase.ShowConfiguration2(cfg);
                    MdlBase.EditRebuild3();

                    for (int idLumiere = 0; idLumiere < MdlBase.GetLightSourceCount(); idLumiere++)
                    {
                        var nomLumiere = MdlBase.LightSourceUserName[idLumiere];

                        if (nomLumiere.StartsWith("Ambiante"))
                        {
                            MajAmbiant(MdlBase, idLumiere, ValAmbiante);
                        }
                        else if (DesactiverDirectionnelles && nomLumiere.StartsWith("Directionnelle"))
                        {
                            var fl = MdlBase.eFonctionParLeNom(nomLumiere);
                            if (fl.IsRef())
                            {
                                fl.eModifierEtat(SolidWorks.Interop.swconst.swFeatureSuppressionAction_e.swSuppressFeature, lcfg);
                            }
                        }
                    }

                    MdlBase.GraphicsRedraw();
                }

                MdlBase.ShowConfiguration2(NomCfgActive);
                MdlBase.EditRebuild3();
            }
            catch (Exception e)
            {
                this.LogErreur(new Object[] { e });
            }
        }
예제 #5
0
        private void cmdSupprimerLesAnciennesConfigs(ModelDoc2 mdl)
        {
            WindowLog.SautDeLigne();

            if (mdl.eNomConfigActive().eEstConfigDepliee())
            {
                mdl.ShowConfiguration2(mdl.eListeNomConfiguration()[0]);
            }

            mdl.EditRebuild3();

            WindowLog.Ecrire("  - Suppression des cfgs depliées :");
            var liste = mdl.eListeConfigs(eTypeConfig.Depliee);

            if (liste.Count == 0)
            {
                WindowLog.EcrireF("   Aucune configuration à supprimer");
            }

            foreach (Configuration Cf in liste)
            {
                String IsSup = Cf.eSupprimerConfigAvecEtatAff(mdl) ? "Ok" : "Erreur";
                WindowLog.EcrireF("  {0} : {1}", Cf.Name, IsSup);
            }
        }
예제 #6
0
        public void Build(UpdateState us)
        {
            us(16, "Запускаем Solidworks");
            SldWorks swApp = new SldWorks();

            int error   = 0;
            int warning = 0;

            us(32, "Построение 3Д модели");

            ModelDoc2  part        = swApp.OpenDoc6(pathToBeam, (int)swDocumentTypes_e.swDocPART, 0, "", ref error, ref warning);
            IModelView myModelView = part.ActiveView;

            myModelView.FrameState = (int)swWindowState_e.swWindowMaximized;
            us(48, "Устанавливаем размеры");
            part.Parameter("length@BeamSketch").SystemValue = length / 1000.0;
            part.Parameter("depth@BeamSketch").SystemValue  = depth / 1000.0;
            part.Parameter("externalDiameter@BeamSketch").SystemValue
                = externalDiameter / 1000.0;
            us(64, "Перестраиваем");
            part.EditRebuild3();
            part.ForceRebuild3(false);
            us(80, "Отображаем");
            swApp.FrameState = (int)swWindowState_e.swWindowMaximized;
            us(100, "Готов");
        }
예제 #7
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (pictureBox1.Image != null)
            {
                pictureBox1.Image.Dispose();
                pictureBox1.Image = null;
                pictureBox1.Load();
                pictureBox1.Update();
            }

            double a = Convert.ToDouble(textBox1.Text) / 1e3;
            double b = Convert.ToDouble(textBox2.Text) / 1e3;
            double c = Convert.ToDouble(textBox3.Text) / 1e3;

            SldWorks sw = new SldWorks();

            sw.Visible = true;
            int       err = 0, war = 0;
            ModelDoc2 swModel = sw.OpenDoc6(Application.StartupPath + "\\cube.sldprt", 1, 0, "", ref err, ref war);

            swModel.Parameter("D1@Эскиз1").SystemValue            = a; // Задание размера
            swModel.Parameter("D2@Эскиз1").SystemValue            = b; // Задание размера
            swModel.Parameter("D1@Бобышка-Вытянуть1").SystemValue = c; // Задание размера

            swModel.EditRebuild3();                                    // перестроение
            swModel.SaveAs(Application.StartupPath + "\\image.jpg");
            swModel.Save2(false);                                      // сохранение
            // sw.CloseDoc("cube");
            pictureBox1.Load(Application.StartupPath + "\\image.jpg");
        }
예제 #8
0
파일: GetMass.cs 프로젝트: gaodansoft/sw
        public string GetProperty(ModelDoc2 swModelDoc2)
        {
            if (swModelDoc2 == null)
            {
                return("0");
            }
            double val = 0;

            if (cfg != string.Empty)
            {
                try
                {
                    object aaa = swModelDoc2.GetConfigurationNames();
                    swModelDoc2.ShowConfiguration2(cfg);
                    swModelDoc2.EditRebuild3();
                    int      ren     = 0;
                    double[] MassAll = (double[])swModelDoc2.GetMassProperties2(ref ren);
                    val = MassAll[5];
                }
                catch
                {
                    return("0");
                }


                //object aaa = swModelDoc2.GetConfigurationNames();
                //swModelDoc2.ShowConfiguration2(cfg);
                //swModelDoc2.EditRebuild3();
                //int ren = 0;
                //double[] MassAll = (double[])swModelDoc2.GetMassProperties2(ref ren);
                //val = MassAll[5];
            }
            return(val.ToString("F3"));
        }
예제 #9
0
        public static void SetDim(ModelDoc2 Doc, string DimName, Dictionary <string, double> Vals)
        {
            Dimension SwDim = Doc.Parameter(DimName);

            foreach (string cfg in Vals.Keys)
            {
                SwDim.SetValue3(Vals[cfg], (int)swSetValueInConfiguration_e.swSetValue_InSpecificConfigurations, new string[] { cfg });
            }
            Doc.EditRebuild3();
        }
예제 #10
0
            protected override void Command()
            {
                try
                {
                    _NomConfigCourante = MdlBase.eNomConfigActive();

                    if (SurTouteLesConfigs)
                    {
                        var pidF_Dessus = new SwObjectPID <Face2>(F_Dessus, MdlBase);
                        var pidF_Devant = new SwObjectPID <Face2>(F_Devant, MdlBase);
                        var pidContreMarche_Esquisse_Comp     = new SwObjectPID <Component2>(ContreMarche_Esquisse_Comp, MdlBase);
                        var pidContreMarche_Esquisse_Fonction = new SwObjectPID <Feature>(ContreMarche_Esquisse_Fonction, MdlBase);

                        List <String> ListeNomsConfig = MdlBase.eListeNomConfiguration(eTypeConfig.DeBase);

                        foreach (String NomConfig in ListeNomsConfig)
                        {
                            MdlBase.ShowConfiguration2(NomConfig);
                            MdlBase.EditRebuild3();

                            pidF_Dessus.Maj(ref F_Dessus);
                            pidF_Devant.Maj(ref F_Devant);
                            pidContreMarche_Esquisse_Comp.Maj(ref ContreMarche_Esquisse_Comp);
                            pidContreMarche_Esquisse_Fonction.Maj(ref ContreMarche_Esquisse_Fonction);

                            Run(F_Dessus, F_Devant, ContreMarche_Esquisse_Comp, ContreMarche_Esquisse_Fonction);
                        }

                        MdlBase.ShowConfiguration2(_NomConfigCourante);
                    }
                    else
                    {
                        Run(F_Dessus, F_Devant, ContreMarche_Esquisse_Comp, ContreMarche_Esquisse_Fonction);
                    }

                    MdlBase.EditRebuild3();
                }
                catch (Exception e)
                {
                    this.LogErreur(new Object[] { e });
                }
            }
예제 #11
0
        private void Rechercher_Reperes()
        {
            Bdd = new BDD();

            Predicate <Component2> Test = c =>
            {
                if (c.ExcludeFromBOM)
                {
                    return(false);
                }

                bool filtre = false;

                if (_CheckBox_ComposantsCache.IsChecked)
                {
                    filtre = c.IsSuppressed();
                }
                else
                {
                    filtre = c.IsHidden(true);
                }

                if (!filtre && (c.TypeDoc() == eTypeDoc.Piece))
                {
                    ModelDoc2 mdl = c.eModelDoc2();
                    mdl.eActiver(swRebuildOnActivation_e.swRebuildActiveDoc);
                    mdl.ShowConfiguration2(c.eNomConfiguration());
                    mdl.EditRebuild3();
                    PartDoc piece = mdl.ePartDoc();

                    foreach (var dossier in piece.eListeDesDossiersDePiecesSoudees(d => { return(!d.eEstExclu()); }))
                    {
                        Bdd.AjouterDossier(dossier, c);
                    }
                }

                return(false);
            };

            if (MdlBase.TypeDoc() == eTypeDoc.Piece)
            {
                Test(MdlBase.eComposantRacine());
            }
            else
            {
                MdlBase.eRecParcourirComposants(Test, c => { if (c.ExcludeFromBOM)
                                                             {
                                                                 return(false);
                                                             }
                                                             return(true); });
            }

            MdlBase.eActiver();
        }
예제 #12
0
        protected override void Command()
        {
            _Ass = MdlBase.eAssemblyDoc();

            foreach (Component2 cp in ListeComposants)
            {
                Run(cp);
            }

            MdlBase.EditRebuild3();
        }
예제 #13
0
        private void SymetriserPiece(ModelDoc2 mdl, Feature plan, List <Body2> listeCorps)
        {
            try
            {
                Feature Symetrie  = null;
                Feature Supprimer = null;

                // Création de la symetrie
                mdl.eEffacerSelection();
                mdl.eSelectMulti(plan, 2, true);
                mdl.eSelectMulti(listeCorps, 256, true);
                Symetrie = mdl.FeatureManager.InsertMirrorFeature2(true, false, false, false, (int)swFeatureScope_e.swFeatureScope_AllBodies);

                if (SupprimerOriginal)
                {
                    // Suppression des pièces symétrisée
                    mdl.eEffacerSelection();
                    mdl.eSelectMulti(listeCorps, -1, false);
                    Supprimer = mdl.FeatureManager.InsertDeleteBody2(false);
                }

                // On met le tout dans un dossier correctement renommé
                mdl.eEffacerSelection();
                mdl.EditRebuild3();

                Symetrie.eSelect();
                Supprimer.eSelect(true);

                Feature Dossier = mdl.FeatureManager.InsertFeatureTreeFolder2((int)swFeatureTreeFolderType_e.swFeatureTreeFolder_Containing);
                Dossier.eRenommerFonction(mdl.eNomConfigActive() + "-Symetrie");

                // On nettoie
                mdl.eEffacerSelection();
                mdl.EditRebuild3();
            }
            catch (Exception e)
            { this.LogMethode(new Object[] { e }); }
        }
예제 #14
0
        private void AlterarDimensao(Coletor c)
        {
            myDimension = swModel.Parameter("D1_RAMAL_RACK@Sketch3");
            string s1 = c.DiametroEncaixeSuccaoRack.Replace(",", ".");
            string s2 = c.DiametroEncaixeSuccaoCompressor.Replace(",", ".");

            double d1 = Double.Parse(s1, CultureInfo.InvariantCulture);
            double d2 = Double.Parse(s2, CultureInfo.InvariantCulture);

            myDimension.SystemValue = d1 / 1000; // Converte pra metros.
            myDimension             = swModel.Parameter("D1_RAMAL_CP@Sketch4");
            myDimension.SystemValue = d2 / 1000; // Converte pra metros.
            swModel.EditRebuild3();
        }
예제 #15
0
        // Строит или изменяет модель
        public void Build()
        {
            InitAndRunSwApp();
            // имена размеров в документе полумуфты
            string fingerParameter1          = "fingers@Круговой массив1";
            string fingerParameter2          = "fingers@Круговой массив2";
            string nomianalDiameterParameter = "nominalDiameter@Эскиз1";

            // имя полумуфты в сборке (имя компонента верхнего уровня)
            string assemblyPolumuftaName = "Полумуфта-1";
            // Менеджер выделения, выбора
            SelectionMgr swSelMgr = (SelectionMgr)swModel.SelectionManager;

            // удалить выделение
            swModel.ClearSelection2(true);
            Component2 swComp = assembly.GetComponentByName(assemblyPolumuftaName);

            // выбрать полумуфту, не добавлять к выбранным, дата?, показать всплывающее кокшко
            swComp.Select4(false, null, false);
            int info = 0;

            // начать изменение полумуфты
            assembly.EditPart2(false, false, ref info);
            // получить редактируемую модель
            ModelDoc2 polumufta = (ModelDoc2)assembly.GetEditTarget();

            // установка изменяемых параметров для всех конфигураций
            polumufta.Parameter(fingerParameter1).SetSystemValue3(
                countFingers,
                (int)swSetValueInConfiguration_e.swSetValue_InAllConfigurations
                );
            polumufta.Parameter(fingerParameter2).SetSystemValue3(
                countFingers,
                (int)swSetValueInConfiguration_e.swSetValue_InAllConfigurations
                );

            polumufta.Parameter(nomianalDiameterParameter).SetSystemValue3(
                nominalDiameter,
                (int)swSetValueInConfiguration_e.swSetValue_InAllConfigurations
                );
            // ??
            bool retVal = polumufta.EditSuppress2();

            //Debug.Assert(retVal);
            // ??
            assembly.EditAssembly();
            swModel.EditRebuild3();
            swModel.ForceRebuild3(false);
            swModel.ViewZoomtofit2();
        }
예제 #16
0
        public void AutoRenameBodies()
        {
            List <BodyModel> needRenameBodies = bodyModels.FindAll(x => x.comment != "");

            ModelDoc2 swModel = null;

            swModel = (ModelDoc2)iswApp.ActiveDoc;

            PartDoc swPart = (PartDoc)swModel;

            for (int i = 0; i < needRenameBodies.Count; i++)
            {
                swModel.ClearSelection2(true);

                string actionbodyName = needRenameBodies[i].name.ToString();

                Boolean boolstatus = swModel.Extension.SelectByID2(actionbodyName, "SOLIDBODY", 0, 0, 0, false, 0, null, 0);

                if (boolstatus == true)
                {
                    var swSelectionManager = (SelectionMgr)swModel.SelectionManager;

                    var b = (Feature)swSelectionManager.GetSelectedObject6(1, -1);

                    int maxQ = bodyModels.FindAll(x => x.name.Contains(needRenameBodies[i].refBodyname) == true).Count;

                    string tempbodyName = "";    // needRenameBodies[i].comment + (maxQ + 1).ToString();

                    Boolean haveThisName = true; // swModel.Extension.SelectByID2(tempbodyName, "SOLIDBODY", 0, 0, 0, false, 0, null, 0);

                    if (haveThisName)
                    {
                        while (haveThisName == true)
                        {
                            maxQ = maxQ + 1;

                            tempbodyName = needRenameBodies[i].comment + maxQ.ToString();

                            swModel.ClearSelection2(true);

                            haveThisName = swModel.Extension.SelectByID2(tempbodyName, "SOLIDBODY", 0, 0, 0, false, 0, null, 0);
                        }
                    }

                    b.Name = tempbodyName;
                    swModel.EditRebuild3();
                }
            }
        }
예제 #17
0
        private IConfiguration createNewConfiguration(Component2 swComponent)
        {
            string componentName = Utilities.stripIdentifier(swComponent.Name);
            string newConfigName = "SAURON-" + Utilities.randomString();

            IModelDoc2     component = swComponent.GetModelDoc2();
            IConfiguration newConfig = component.AddConfiguration3(newConfigName,
                                                                   "automatically generated configuration",
                                                                   "",
                                                                   0);

            swComponent.ReferencedConfiguration = newConfig.Name;
            swDoc.EditRebuild3();

            return(newConfig);
        }
            protected override void Command()
            {
                String TypeSel = "";

                MdlBase.Extension.SelectByID2(Plan.GetNameForSelection(out TypeSel), TypeSel, 0, 0, 0, false, -1, null, 0);

                SketchManager Sk = MdlBase.SketchManager;

                Sk.InsertSketch(true);


                SketchSegment F = Sk.CreateLine(0, 0, 0, -0.064085, 0.171639, 0);

                Sk.InsertSketch(true);

                MdlBase.EditRebuild3();
            }
예제 #19
0
        internal void GetPropertyBox(string configname)
        {
            const long valueset      = 1000;;
            const int  swDocPart     = 1;
            const int  swDocAssembly = 2;

            _swapp   = (SldWorks)Marshal.GetActiveObject("SldWorks.Application");
            _swmodel = _swapp.ActiveDoc;

            Configuration swConf = _swmodel.GetConfigurationByName(configname);

            if (swConf.IsDerived() == false)
            {
                //swmodel.ShowConfiguration2(configname);
                _swmodel.EditRebuild3();

                if (_swmodel.GetType() == swDocPart)
                {
                    var part = (PartDoc)_swmodel;
                    var box  = part.GetPartBox(true);

                    _swmodel.AddCustomInfo3(configname, "Длина", 30, "");
                    _swmodel.AddCustomInfo3(configname, "Ширина", 30, "");
                    _swmodel.AddCustomInfo3(configname, "Высота", 30, "");

                    _swmodel.CustomInfo2[configname, "Длина"]  = Convert.ToString(Math.Round(Convert.ToDecimal(Math.Abs(box[0] - box[3]) * valueset), 0));
                    _swmodel.CustomInfo2[configname, "Ширина"] = Convert.ToString(Math.Round(Convert.ToDecimal(Math.Abs(box[1] - box[4]) * valueset), 0));
                    _swmodel.CustomInfo2[configname, "Высота"] = Convert.ToString(Math.Round(Convert.ToDecimal(Math.Abs(box[2] - box[5]) * valueset), 0));
                }
                else if (_swmodel.GetType() == swDocAssembly)
                {
                    var swAssy = (AssemblyDoc)_swmodel;

                    var boxAss = swAssy.GetBox((int)swBoundingBoxOptions_e.swBoundingBoxIncludeRefPlanes);

                    _swmodel.AddCustomInfo3(configname, "Длина", 30, "");
                    _swmodel.AddCustomInfo3(configname, "Ширина", 30, "");
                    _swmodel.AddCustomInfo3(configname, "Высота", 30, "");

                    _swmodel.CustomInfo2[configname, "Длина"]  = Convert.ToString(Math.Round(Convert.ToDecimal(Math.Abs(boxAss[0] - boxAss[3]) * valueset), 0));
                    _swmodel.CustomInfo2[configname, "Ширина"] = Convert.ToString(Math.Round(Convert.ToDecimal(Math.Abs(boxAss[1] - boxAss[4]) * valueset), 0));
                    _swmodel.CustomInfo2[configname, "Высота"] = Convert.ToString(Math.Round(Convert.ToDecimal(Math.Abs(boxAss[2] - boxAss[5]) * valueset), 0));
                }
            }
        }
예제 #20
0
        private void setLoftTerminalTo(string name)
        {
            IFeature         fov             = fieldOfView.FeatureByName("field of view");
            ILoftFeatureData fieldOfViewLoft = (ILoftFeatureData)fov.GetDefinition();

            fieldOfViewLoft.AccessSelections(swDoc, fieldOfView);

            Object[] fovProfiles    = fieldOfViewLoft.Profiles;
            IFeature sizedSketch    = fieldOfView.FeatureByName(name);
            IFeature originalSketch = fovProfiles[0] as IFeature;

            IFeature[] newProfiles = new IFeature[] { fovProfiles[0] as IFeature, sizedSketch };

            fieldOfViewLoft.Profiles = newProfiles;
            fov.ModifyDefinition(fieldOfViewLoft, swDoc, fieldOfView);

            fieldOfViewLoft.ReleaseSelectionAccess();
            swDoc.EditRebuild3();
            swAssembly.EditAssembly();
        }
예제 #21
0
        public static void AddMate(SldWorks swApp, ModelDoc2 Doc, string newpartpath)
        {
            #region 添加部件
            swApp.OpenDoc(newpartpath, 1);
            ((AssemblyDoc)Doc).AddComponent5(newpartpath, 0, "", false, "", 0, 0.3, 0);
            swApp.CloseDoc(newpartpath);
            #endregion

            Component2 BaseComp  = ((AssemblyDoc)Doc).GetComponentByName("底座-1");
            Component2 RoateComp = ((AssemblyDoc)Doc).GetComponentByName("转轴-1");

            int err = 0;
            #region 轴装配
            Feature BaseAxi  = BaseComp.FeatureByName("基准轴1");
            Feature RoateAxi = RoateComp.FeatureByName("转轴中心轴");
            BaseAxi.Select(false);
            RoateAxi.Select(true);
            ((AssemblyDoc)Doc).AddMate5((int)swMateType_e.swMateCOINCIDENT, (int)swMateAlign_e.swMateAlignALIGNED, false, 0, 0, 0, 0, 0, 0, 0, 0, false, false, 0, out err);
            #endregion

            #region 底面装配距离
            Feature BaseBp  = BaseComp.FeatureByName("Top");
            Feature RoateBp = RoateComp.FeatureByName("Top");
            BaseBp.Select(false);
            RoateBp.Select(true);
            ((AssemblyDoc)Doc).AddMate5((int)swMateType_e.swMateDISTANCE, (int)swMateAlign_e.swMateAlignALIGNED, false, 10 / 1000.0, 10 / 1000.0, 10 / 1000.0, 0, 0, 0, 0, 0, false, false, 0, out err);
            #endregion

            #region 方位装配
            Feature BaseOir  = BaseComp.FeatureByName("Right");
            Feature RoateOir = RoateComp.FeatureByName("Right");
            BaseOir.Select(false);
            RoateOir.Select(true);
            ((AssemblyDoc)Doc).AddMate5((int)swMateType_e.swMateANGLE, (int)swMateAlign_e.swMateAlignALIGNED, false, 0, 0, 0, 0, 0, (30 / 180.0) * Math.PI, (30 / 180.0) * Math.PI, (30 / 180.0) * Math.PI, false, false, 0, out err);
            #endregion

            Doc.EditRebuild3();
        }
예제 #22
0
        public void updateExtrusionDepth(double depthInInches)
        {
            if (depthInInches < 0)
            {
                return;
            }

            double depthInMeters = Utilities.inchesToMeters(depthInInches);

            IDisplayDimension dispDim = (IDisplayDimension)extrusion.GetFirstDisplayDimension();
            IDimension        dim     = dispDim.IGetDimension();

            dim.SetSystemValue3(depthInMeters,
                                (int)swSetValueInConfiguration_e.swSetValue_InSpecificConfigurations,
                                new string[] { belongsTo.ReferencedConfiguration });

            swFeatureMgr.EditRollback((int)swMoveRollbackBarTo_e.swMoveRollbackBarToEnd, extrusion.Name);

            swAssembly.EditRebuild();
            swDoc.EditRebuild3();
            swDoc.ForceRebuild3(false);

            swAssembly.EditAssembly();
        }
예제 #23
0
        public string Build(SpigotType_e type, int width, int height)
        {
            string modelName = GetModelName(type);

            NewSpigotName = GetSpigotName(type, width, height);


            Dimension dimension;

            int addDimH = modelName == "12-30" ? 10 : 1;

            string newSpigotPath = $@"{RootFolder}{SubjectDestinationFolder}\{NewSpigotName}";

            string drawingName = modelName == "12-30" ? modelName : "12-00";

            var modelSpigotDrw = $@"{RootFolder}{SourceFolder}\{drawingName}.SLDDRW";

            ModelDoc2 swDrawingSpigot = SolidWorksAdapter.OpenDocument(modelSpigotDrw, swDocumentTypes_e.swDocDRAWING);

            solidWorksDocument = SolidWorksAdapter.AcativeteDoc("12-00");
            AssemblyDoc assemblyDocument = (AssemblyDoc)solidWorksDocument;

            assemblyDocument.ResolveAllLightWeightComponents(false);

            DeleteEquations(modelName);
            solidWorksDocument.ForceRebuild3(true);

            #region formuls
            var          w          = (Convert.ToDouble(width) - 1) / 1000;                                   // ????????????
            var          h          = Convert.ToDouble((Convert.ToDouble(height) + addDimH) / 1000);          // ????????????
            const double step       = 50;
            var          weldWidth  = Convert.ToDouble((Math.Truncate(Convert.ToDouble(width) / step) + 1));  // ????????????
            var          weldHeight = Convert.ToDouble((Math.Truncate(Convert.ToDouble(height) / step) + 1)); // ????????????
            #endregion

            DeleteComponents((int)type);
            if (modelName == "12-20")
            {
                PartName = $"12-20-{height}.SLDPRT";
                if (CheckExistPart != null)
                {
                    CheckExistPart(PartName, out IsPartExist, out NewPartPath);
                }
                else
                {
                    MessageObserver.Instance.SetMessage("CheckExistPartEvent can not be null", MessageType.Warning);
                }

                if (IsPartExist)
                {
                    solidWorksDocument.Extension.SelectByID2("12-20-001-1@12-00", "COMPONENT", 0, 0, 0, false, 0, null, 0);
                    assemblyDocument.ReplaceComponents(NewPartPath, "", true, true);
                }
                else
                {
                    NewPartPath = $@"{RootFolder}\{SubjectDestinationFolder}\{NewPartPath}";
                    solidWorksDocument.Extension.SelectByID2("D1@Вытянуть1@12-20-001-1@12-00", "DIMENSION", 0, 0, 0, false, 0, null, 0);
                    dimension             = ((Dimension)(solidWorksDocument.Parameter("D1@Вытянуть[email protected]")));
                    dimension.SystemValue = h - 0.031;
                    solidWorksDocument.Extension.SelectByID2("D1@Кривая1@12-20-001-1@12-00", "DIMENSION", 0, 0, 0, false, 0, null, 0);
                    dimension             = ((Dimension)(solidWorksDocument.Parameter("D1@Кривая[email protected]")));
                    dimension.SystemValue = weldHeight;
                    SolidWorksDocument.Extension.SaveAs(NewPartPath, (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref error, ref warning);
                    InitiatorSaveExeption(error, warning, NewPartPath);
                    ComponentsPathList.Add(NewPartPath);
                    SolidWorksAdapter.SldWoksAppExemplare.CloseDoc(NewPartPath);
                }

                //12-20-002

                PartName = $"12-20-{width}.SLDPRT";

                MessageObserver.Instance.SetMessage("Check exist part. " + NewPartPath);
                if (CheckExistPart != null)
                {
                    MessageObserver.Instance.SetMessage("\tCheckExistPartEvent");
                    CheckExistPart(PartName, out IsPartExist, out NewPartPath);
                }
                else
                {
                    MessageObserver.Instance.SetMessage("CheckExistPartEvent can not be null", MessageType.Warning);
                }

                if (IsPartExist)
                {
                    solidWorksDocument.Extension.SelectByID2("12-20-002-1@12-00", "COMPONENT", 0, 0, 0, false, 0, null, 0);
                    assemblyDocument.ReplaceComponents(PartName, "", true, true);
                }
                else
                {
                    NewPartPath = $@"{RootFolder}\{SubjectDestinationFolder}\{NewPartPath}";
                    solidWorksDocument.Extension.SelectByID2("D1@Вытянуть1@12-20-002-1@12-00", "DIMENSION", 0, 0, 0, false, 0, null, 0);
                    dimension             = ((Dimension)(solidWorksDocument.Parameter("D1@Вытянуть[email protected]")));
                    dimension.SystemValue = w - 0.031;
                    solidWorksDocument.Extension.SelectByID2("D1@Кривая1@12-20-002-1@12-00", "DIMENSION", 0, 0, 0, false, 0, null, 0);
                    dimension             = ((Dimension)(solidWorksDocument.Parameter("D1@Кривая[email protected]")));
                    dimension.SystemValue = weldWidth;
                    SolidWorksDocument.Extension.SaveAs(NewPartPath, (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref error, ref warning);
                    InitiatorSaveExeption(error, warning, NewPartPath);
                    ComponentsPathList.Add(NewPartPath);
                }

                //12-003
                PartName = $"12-03-{width}-{height}.SLDPRT";
                if (CheckExistPart != null)
                {
                    CheckExistPart(PartName, out IsPartExist, out NewPartPath);
                }
                else
                {
                    MessageObserver.Instance.SetMessage("CheckExistPartEvent can not be null", MessageType.Warning);
                }
                if (IsPartExist)
                {
                    solidWorksDocument.Extension.SelectByID2("12-003-1@12-00", "COMPONENT", 0, 0, 0, false, 0, null, 0);
                    assemblyDocument.ReplaceComponents(PartName, "", true, true);
                }
                else
                {
                    NewPartPath = $@"{RootFolder}\{SubjectDestinationFolder}\{NewPartPath}";
                    solidWorksDocument.Extension.SelectByID2("D3@Эскиз1@12-003-1@12-00", "DIMENSION", 0, 0, 0, false, 0, null, 0);
                    dimension             = ((Dimension)(solidWorksDocument.Parameter("D3@Эскиз[email protected]")));
                    dimension.SystemValue = w;
                    solidWorksDocument.Extension.SelectByID2("D2@Эскиз1@12-003-1@12-00", "DIMENSION", 0, 0, 0, false, 0, null, 0);
                    dimension             = ((Dimension)(solidWorksDocument.Parameter("D2@Эскиз[email protected]")));
                    dimension.SystemValue = h;
                    solidWorksDocument.EditRebuild3();
                    SolidWorksDocument.Extension.SaveAs(NewPartPath, (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref error, ref warning);
                    InitiatorSaveExeption(error, warning, NewPartPath);
                    ComponentsPathList.Add(NewPartPath);
                    SolidWorksAdapter.SldWoksAppExemplare.CloseDoc(NewPartPath);
                }
            }
            if (modelName == "12-30")
            {
                //12-30-001

                PartName = $"12-30-{height}.SLDPRT";

                MessageObserver.Instance.SetMessage("Check exist part. " + NewPartPath);
                if (CheckExistPart != null)
                {
                    CheckExistPart(PartName, out IsPartExist, out NewPartPath);
                }
                else
                {
                    MessageObserver.Instance.SetMessage("CheckExistPartEvent can not be null", MessageType.Warning);
                }

                if (IsPartExist)
                {
                    solidWorksDocument.Extension.SelectByID2("12-30-001-1@12-00", "COMPONENT", 0, 0, 0, false, 0, null, 0);
                    assemblyDocument.ReplaceComponents(PartName, "", true, true);
                }
                else
                {
                    NewPartPath = $@"{RootFolder}\{SubjectDestinationFolder}\{NewPartPath}";
                    solidWorksDocument.Extension.SelectByID2("D1@Вытянуть1@12-30-001-1@12-00", "DIMENSION", 0, 0, 0, false, 0, null, 0);
                    dimension             = ((Dimension)(solidWorksDocument.Parameter("D1@Вытянуть[email protected]")));
                    dimension.SystemValue = h - 0.031;
                    solidWorksDocument.Extension.SelectByID2("D1@Кривая1@12-30-001-1@12-00", "DIMENSION", 0, 0, 0, false, 0, null, 0);
                    dimension             = ((Dimension)(solidWorksDocument.Parameter("D1@Кривая[email protected]")));
                    dimension.SystemValue = weldHeight;
                    SolidWorksDocument.Extension.SaveAs(NewPartPath, (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref error, ref warning);
                    InitiatorSaveExeption(error, warning, NewPartPath);
                    ComponentsPathList.Add(NewPartPath);
                }
                //12-30-002
                PartName = $"12-30-{width}.SLDPRT";


                if (CheckExistPart != null)
                {
                    CheckExistPart(PartName, out IsPartExist, out NewPartPath);
                }
                else
                {
                    MessageObserver.Instance.SetMessage("CheckExistPartEvent can not be null", MessageType.Warning);
                }

                if (IsPartExist)
                {
                    solidWorksDocument.Extension.SelectByID2("12-30-002-1@12-00", "COMPONENT", 0, 0, 0, false, 0, null, 0);
                    assemblyDocument.ReplaceComponents(PartName, "", true, true);
                }
                else
                {
                    NewPartPath = $@"{RootFolder}\{SubjectDestinationFolder}\{NewPartPath}";
                    solidWorksDocument.Extension.SelectByID2("D1@Вытянуть1@12-30-002-1@12-00", "DIMENSION", 0, 0, 0, false, 0, null, 0);
                    dimension             = ((Dimension)(solidWorksDocument.Parameter("D1@Вытянуть[email protected]")));
                    dimension.SystemValue = w - 0.031;
                    solidWorksDocument.Extension.SelectByID2("D1@Кривая1@12-30-002-1@12-00", "DIMENSION", 0, 0, 0, false, 0, null, 0);
                    dimension             = ((Dimension)(solidWorksDocument.Parameter("D1@Кривая[email protected]")));
                    dimension.SystemValue = weldHeight;
                    SolidWorksDocument.Extension.SaveAs(NewPartPath, (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref error, ref warning);
                    InitiatorSaveExeption(error, warning, NewPartPath);
                    ComponentsPathList.Add(NewPartPath);
                }
                //12-003

                PartName = $"12-03-{width}-{height}.SLDPRT";
                if (CheckExistPart != null)
                {
                    CheckExistPart(PartName, out IsPartExist, out NewPartPath);
                }
                else
                {
                    MessageObserver.Instance.SetMessage("CheckExistPartEvent can not be null", MessageType.Warning);
                }

                if (IsPartExist)
                {
                    solidWorksDocument.Extension.SelectByID2("12-003-2@12-00", "COMPONENT", 0, 0, 0, false, 0, null, 0);
                    assemblyDocument.ReplaceComponents(PartName, "", true, true);
                }
                else
                {
                    NewPartPath = $@"{RootFolder}\{SubjectDestinationFolder}\{NewPartPath}";
                    solidWorksDocument.Extension.SelectByID2("D3@Эскиз1@12-003-2@12-00", "DIMENSION", 0, 0, 0, false, 0, null, 0);
                    dimension             = ((Dimension)(solidWorksDocument.Parameter("D3@Эскиз[email protected]")));
                    dimension.SystemValue = w;
                    solidWorksDocument.Extension.SelectByID2("D2@Эскиз1@12-003-2@12-00", "DIMENSION", 0, 0, 0, false, 0, null, 0);
                    dimension             = ((Dimension)(solidWorksDocument.Parameter("D2@Эскиз[email protected]")));
                    dimension.SystemValue = h;
                    solidWorksDocument.EditRebuild3();
                    SolidWorksDocument.Extension.SaveAs(NewPartPath, (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref error, ref warning);
                    InitiatorSaveExeption(error, warning, NewPartPath);
                    ComponentsPathList.Add(NewPartPath);
                }
            }

            solidWorksDocument.ForceRebuild3(true);
            solidWorksDocument.Extension.SaveAs(newSpigotPath + ".SLDASM", (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref error, ref warning);
            InitiatorSaveExeption(error, warning, newSpigotPath + ".SLDASM");

            SolidWorksAdapter.SldWoksAppExemplare.CloseDoc(NewSpigotName + ".SLDASM");
            ComponentsPathList.Add(newSpigotPath + ".SLDASM");
            swDrawingSpigot.Extension.SelectByID2("DRW1", "SHEET", 0, 0, 0, false, 0, null, 0);
            var drw = (DrawingDoc)SolidWorksAdapter.AcativeteDoc(drawingName + ".SLDDRW");
            drw.ActivateSheet("DRW1");
            drw.SetupSheet5("DRW1", 12, 12, 1, GetDrawingScale(width, height), true, @"\\pdmsrv\SolidWorks Admin\Templates\Основные надписи\A3-A-1.slddrt", 0.42, 0.297, "По умолчанию", false);
            swDrawingSpigot.Extension.SaveAs(newSpigotPath + ".SLDDRW", (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref error, ref warning);
            InitiatorSaveExeption(error, warning, newSpigotPath + ".SLDDRW");

            ComponentsPathList.Add(newSpigotPath + ".SLDDRW");
            SolidWorksAdapter.CloseAllDocumentsAndExit();
            return(newSpigotPath);
        }
예제 #24
0
                public void OpenDoc(int idPdm, int revision, int taskType, string filePath, string fileName)
                {
        
                    swApp = new SldWorks() {Visible = true};

                    Process[] processes = Process.GetProcessesByName("SLDWORKS");

                    var errors = 0;
                    var warnings = 0;

                    #region Case

                    switch (taskType)
                    {
                        case 1:

                            Program.HostForm.richTextBoxLog.Invoke(new Action(() => Program.HostForm.richTextBoxLog.SelectionColor = Color.Black));
                            Program.HostForm.richTextBoxLog.Invoke(new Action(() => Program.HostForm.richTextBoxLog.SelectedText += (String.Format("Выполняется: {0}\r\n", filePath))));
  
                            swModel = swApp.OpenDoc6(filePath, (int) swDocumentTypes_e.swDocPART, (int) swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);
                            swModel = swApp.ActiveDoc;

                            if (!IsSheetMetalPart((IPartDoc) swModel))
                            {

                                Program.HostForm.richTextBoxLog.Invoke(new Action(() => Program.HostForm.richTextBoxLog.SelectionColor = Color.DarkBlue));
                                Program.HostForm.richTextBoxLog.Invoke(new Action(() => Program.HostForm.richTextBoxLog.SelectedText += ("Не листовой металл!\r\n")));
                                Program.HostForm.richTextBoxLog.Invoke(new Action(() => Program.HostForm.richTextBoxLog.SelectedText += ("--------------------------------------------------------------------------------------------------------------\r\n")));
                                Program.HostForm.richTextBoxLog.Invoke(new Action(() => Program.HostForm.richTextBoxLog.SelectedText += ("\r\n")));

                                swApp.CloseDoc(filePath);
                                swApp.ExitApp();
                                swApp = null;

                                foreach (Process process in processes)
                                {
                                    process.CloseMainWindow();
                                    process.Kill();
                                }
                                return;
                            }

                            swExtension = (ModelDocExtension) swModel.Extension;
                            swModel.EditRebuild3();
                            swModel.ForceRebuild3(false);

                            CreateFlattPatternUpdate();

                            object[] confArray = swModel.GetConfigurationNames();
                            foreach (var confName in confArray)
                            {
                                Configuration swConf = swModel.GetConfigurationByName(confName.ToString());
                                if (swConf.IsDerived()) continue;
                                    
                                Area(confName.ToString());
                                GabaritsForPaintingCamera(confName.ToString());
                            }

                            ExportDataToXmlSql(fileName, idPdm, revision);

                            ConvertToErpt(filePath);
                            Program.HostForm.richTextBoxLog.Invoke(new Action(() => Program.HostForm.richTextBoxLog.SelectionColor = Color.Black));
                            Program.HostForm.richTextBoxLog.Invoke(new Action(() => Program.HostForm.richTextBoxLog.SelectedText += (String.Format("{0} - Выполнен!\r\n", filePath))));
                            Program.HostForm.richTextBoxLog.Invoke(new Action(() => Program.HostForm.richTextBoxLog.SelectedText += ("-----------------------------------------------------------------\r\n")));
                            Program.HostForm.richTextBoxLog.Invoke(new Action(() => Program.HostForm.richTextBoxLog.SelectedText += ("\r\n")));

                            break;
                        case 2:

                            swModel = swApp.OpenDoc6(filePath, (int) swDocumentTypes_e.swDocDRAWING, (int) swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);

                            //if (warnings == (int)swFileLoadWarning_e.swFileLoadWarning_ReadOnly)
                            //{MessageBox.Show("This file is read-only.");}

                            swDraw = (DrawingDoc) swModel;
                            swExtension = (ModelDocExtension) swModel.Extension;
                            ConvertToPdf(filePath);

                            break;
                        case 3:

                            //swModel = swApp.OpenDoc6(filePath, (int)swDocumentTypes_e.swDocPART, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);

                            MessageBox.Show("3");
                            break;
                    }

                    //TODO: swApp exit
                    swApp.CloseDoc(filePath);
                    swApp.ExitApp();
                    swApp = null;
                    
                    foreach (Process process in processes)
                    {
                        process.CloseMainWindow();
                        process.Kill();
                    }
                    #endregion
                }
예제 #25
0
        public void AddFeature(SldWorks SwApp, ModelDoc2 SwModel, Point2D P1, Point2D P2)
        {
            if (CheckUsing() == false)
            {
                return;
            }
            SwModel.ClearSelection2(true);
            Helper         helper         = new Helper(SwModel, SwApp);
            SelectionMgr   selectionMgr   = SwModel.SelectionManager;
            SketchManager  sketchManager  = SwModel.SketchManager;
            FeatureManager featureManager = SwModel.FeatureManager;
            const double   Aprox          = 0.0005; // needs to make correct theard
            Sketch         swSketch       = default(Sketch);

            double L = P2.x - P1.x;

            helper.select_feature("RefPlane", 2, false, 0);

            if (P1.x > 0)
            {
                SwModel.CreatePlaneAtOffset(P1.x, false);
            }


            sketchManager.InsertSketch(true);

            // create helix
            sketchManager.CreateCircleByRadius(0, 0, 0, P1.y);
            SwModel.InsertHelix(false, theardCW, false, true, 2, L, theardPinch, 0, 0, 0);
            SwModel.ClearSelection2(true);


            #region //Triangle profile

            if (theardType == (object)"Triangle")
            {
                double XL = (P1.y - theardR) / 2;      // haf of triangle base
                double YL = XL * (double)Math.Sqrt(3); // median of triangle

                helper.select_feature("RefPlane", 1, false, 0);
                sketchManager.InsertSketch(true);
                sketchManager.CreateLine((P1.x - XL + Aprox), P1.y, 0, (P1.x + XL - Aprox), P1.y, 0);
                sketchManager.CreateLine((P1.x - XL + Aprox), P1.y, 0, P1.x, (P1.y - YL), 0);
                sketchManager.CreateLine((P1.x + XL - Aprox), P1.y, 0, P1.x, (P1.y - YL), 0);
            }

            #endregion

            #region //Trapeze profile

            if (theardType == (object)"Trapeze")
            {
                helper.select_feature("RefPlane", 1, false, 0);
                sketchManager.InsertSketch(true);
                double H    = (P1.y - theardR) / 2;            // haf of trapaze top base and heigth
                double ctgA = 1 / Math.Tan(helper.ToRad(105)); // ctg value of bottom base angle
                double A    = 2 * (H - Aprox) + 4 * H * ctgA;

                sketchManager.CreateLine((P1.x - H / 2 + Aprox), P1.y, 0, (P1.x + H / 2 - Aprox), P1.y, 0);
                sketchManager.CreateLine((P1.x - H / 2 + Aprox), P1.y, 0, (P1.x - (A / 4)), P1.y - H, 0);
                sketchManager.CreateLine((P1.x + H / 2 - Aprox), P1.y, 0, (P1.x + (A / 4)), P1.y - H, 0);
                sketchManager.CreateLine((P1.x - (A / 4)), P1.y - H, 0, (P1.x + (A / 4)), P1.y - H, 0);
            }

            #endregion

            swSketch = SwModel.GetActiveSketch2() as Sketch;
            SwModel.EditRebuild3(); // model rebuild needs to make cutsweep feature avaible

            Entity ent = swSketch as Entity;
            ent.Select2(false, 1); // select sketch using mark 1 for sweep cut
            helper.select_feature("Helix", helper.get_features_count("Helix") - 1, true, 4);

            featureManager.InsertCutSwept4(false, true, 0, false, false, 0, 0, false, 0, 0, 0, 0, true, true, 0,
                                           true, true, true, false);

            helper.HidePlanes();
        }
예제 #26
0
        private void AutoDimensionDrawing2(ModelDoc2 swModel, bool many )
        {
            bool del3List = false;
            var thrdList = new List<string>();
            int shi = 0;
            isValidXml = true;

            var swDrawing = (DrawingDoc)swModel;
            if (swModel.GetCustomInfoValue("", "AutoDim") == "No")
            {
                if (many)
                {
                    MessageBox.Show(@"Если хотите образмерить чертеж, смените No на Yes в поле 'AutoDim' свойств данного чертежа",
                        @"MrDoors", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                isValidXml = false;
            }
            if (swModel.GetCustomInfoValue("", "MakeCNCprog") == "Yes")
            {
                _createProgramm = true;
            }
            if (!isValidXml && !_createProgramm) // если не надо создавать программу и авто дим = но, то образмеривать просто не нужно.
                return;
            swModel.Extension.SetUserPreferenceDouble((int)swUserPreferenceDoubleValue_e.swDetailingDimToDimOffset,
                                                      (int)swUserPreferenceOption_e.swDetailingNoOptionSpecified, 0.006);
            swModel.Extension.SetUserPreferenceDouble((int)swUserPreferenceDoubleValue_e.swDetailingObjectToDimOffset,
                                                      (int)swUserPreferenceOption_e.swDetailingNoOptionSpecified, 0.010);

            Dictionary<string, bool> listSide;
            string targetModelPath = null;
            if (!File.Exists(Path.Combine(Path.GetDirectoryName(_swAdd.RootModel.GetPathName()), "fpTime.txt")))
            {
                //MessageBox.Show("Образмеривание детали может пройти некорректно! Для корректного образмеривания детали необходимо произвести Окончательную обработку заказа.");
                throw new Exception("Образмеривание детали может пройти некорректно! Для корректного образмеривания детали необходимо произвести Окончательную обработку заказа.");
            }
            else
            {
                //просто взять Sketch Number

               string fnameWithoutExt = Path.GetFileNameWithoutExtension(swModel.GetPathName());
                fnameWithoutExt = fnameWithoutExt.Substring(fnameWithoutExt.Length - 4, 4);
                SwDMDocument8 swDoc = null;
                SwDMApplication swDocMgr = SwAddin.GetSwDmApp();
                SwDmDocumentOpenError oe;
                SwDmCustomInfoType type;
                if (!(fnameWithoutExt[0] == '#' && (fnameWithoutExt[3] == 'P' || fnameWithoutExt[3] == 'p')))
                {

                    swDoc = (SwDMDocument8) swDocMgr.GetDocument(Path.ChangeExtension(swModel.GetPathName(), "SLDASM"),SwDmDocumentType.swDmDocumentAssembly, true, out oe);

                }
                else
                {
                    object brokenRefVar;
                    SwDMSearchOption src = swDocMgr.GetSearchOptionObject();

                    var swDocDraw = (SwDMDocument8)swDocMgr.GetDocument(swModel.GetPathName(), SwDmDocumentType.swDmDocumentDrawing, true, out oe);
                    var varRef = (object[])swDocDraw.GetAllExternalReferences2(src, out brokenRefVar);
                    swDocDraw.CloseDoc();
                    targetModelPath = (string)varRef[0];
                    swDoc = (SwDMDocument8)swDocMgr.GetDocument(targetModelPath, SwDmDocumentType.swDmDocumentAssembly, true, out oe);
                }
                if (swDoc != null)
                {
                    var prop = swDoc.GetCustomProperty("Sketch Number", out type);
                    if (string.IsNullOrEmpty(prop) || prop == "0")
                        throw new Exception("Образмеривание детали прервано, т.к. может пройти некорректно ! Для корректного образмеривания детали необходимо произвести Окончательную обработку заказа.");
                    swDoc.CloseDoc();
                }
                _swAdd.SetModelProperty(swModel, "WasMesure", string.Empty, swCustomInfoType_e.swCustomInfoYesOrNo, "Yes", true);
            }
            string pathXml = WriteXmlFile(swModel, isValidXml, targetModelPath);

            bool isNeededSheetNumber = PrepareDrawingDoc(swModel, out listSide);
            bool dimOnlyNew = false;
            if (swModel.GetCustomInfoValue("", "DimOnlyNew") == "Yes")
                dimOnlyNew = true;
            var vSheetNames = (string[])swDrawing.GetSheetNames();
            var rootNode = _node;
            bool atLeastOneF1View = false;

            foreach (var vSheetName in vSheetNames)
            {
                bool iftherewasAhole = false;
                XmlElement element = null;
                XmlElement sheetNode = null;
                KeyValuePair<string,string> tableNameAttribute = new KeyValuePair<string, string>();
                if (_createProgramm && !string.IsNullOrEmpty(pathXml))
                {
                    element = _cxml.CreateElement("Sheet");
                    element.SetAttribute("Name", vSheetName);
                    _node = rootNode.AppendChild(element);
                    sheetNode = element;
                }

                double vScale = 0;
                var type = new List<string>();
                var listSize = new List<SizeForDim>();
                swDrawing.ActivateSheet(vSheetName);
                swModel.Extension.SelectByID2(vSheetName, "SHEET", 0, 0, 0, true,
                                              (int)swSelectionMarkAction_e.swSelectionMarkAppend, null, 0);
                swModel.ViewZoomToSelection();
                swModel.ClearSelection();
                var swSheet = (Sheet)swDrawing.GetCurrentSheet();
                var swViews = (object[])swSheet.GetViews();
                bool side = shi == 1;
                if (isNeededSheetNumber && listSide.ContainsKey(vSheetName.Substring(vSheetName.Length - 1)))
                    side = listSide[vSheetName.Substring(vSheetName.Length - 1)];
                if (vSheetName.ToUpper().Contains("FACE"))
                    side = true;
                if (vSheetName.ToUpper().Contains("BACK"))
                    side = false;

                if (swViews != null)
                {
                    var rootViewElement = _node;
                    if (Properties.Settings.Default.ViewsBeforeDimen)
                        ReplaceViews(swViews, swDrawing);
                    foreach (var t in swViews)
                    {
                        #region Образмеривание вида
                        var swView = (View) t;
                        swModel.ClearSelection2(true);

                        const string expr = "^F[1-6]$";

                        Match isMatch = Regex.Match(swView.Name, expr, RegexOptions.IgnoreCase);

                        if (_createProgramm && swView.Name.ToLower().Contains("const"))
                        {

                            //Logging.Log.Instance.Fatal(@"На данный чертеж программа не будет создана! " + swModel.GetPathName() + "swView.Name = " + swView.Name);
                            //MessageBox.Show(@"На данный чертеж программа не будет создана!", @"MrDoors",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
                        }

                        if (!(isMatch.Success || swView.Name.Contains("Чертежный вид")) ||
                            swView.Name.ToLower().Contains("const") ||
                            swView.Type == (int)swDrawingViewTypes_e.swDrawingDetailView) continue;

                        if (_createProgramm && !isMatch.Success)
                        {
                            _createProgramm = false;
                            //Logging.Log.Instance.Fatal(@"На данный чертеж программа не будет создана! " + swModel.GetPathName() + "swView.Name = " + swView.Name);
                            //MessageBox.Show(@"На данный чертеж программа не будет создана!", @"MrDoors",
                            //                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        }

                        swDrawing.ActivateView(swView.GetName2());
                        swView.UseSheetScale = 0;

                        var list = HideUnusedComponents(swView, dimOnlyNew);

                        try
                        {
                            vScale = ((double[]) swView.ScaleRatio)[1];
                            swView.SetDisplayMode3(false, (int) swDisplayMode_e.swFACETED_HIDDEN, true, true);

                            #region Процесс образмеривания

                            using (var d = new DimensionView(_swApp, BlockPositionExtension.FromBool(side), dimOnlyNew))
                            {

                                d.DimView(side);
                                if (!iftherewasAhole)
                                    iftherewasAhole = d.IsHole;
                                if (!isNeededSheetNumber && !side && !iftherewasAhole)
                                    del3List = true;
                                else
                                {
                                    if (isNeededSheetNumber && !iftherewasAhole)
                                    {
                                        del3List = true;
                                        thrdList.Add(vSheetName);
                                    }
                                }
                                foreach (var tp in d.List)
                                {
                                    if (!type.Contains(tp))
                                        type.Add(tp);
                                }
                                listSize.Add(d.AddSize);

                                #region Запись данных в xml файл

                                if (element != null)
                                {
                                    element = _cxml.CreateElement("View");
                                    element.SetAttribute("Name", swView.Name);
                                    if (swView.Name == "F1")
                                    {
                                        atLeastOneF1View = true;

                                            SwDmDocumentOpenError oe;
                                            SwDMApplication swDocMgr = SwAddin.GetSwDmApp();
                                            var swDoc = (SwDMDocument8)swDocMgr.GetDocument(Path.ChangeExtension(swModel.GetPathName(), "SLDASM"),
                                                                                             SwDmDocumentType.swDmDocumentAssembly, true, out oe);
                                            if (swDoc != null)
                                            {
                                                var cit = new SwDmCustomInfoType();
                                                string[] names = swDoc.GetCustomPropertyNames();
                                                string extFeats = null,faner11 = null,faner12 = null,faner21 = null,faner22 = null;

                                                if (names.Contains("ExtFanerFeats"))
                                                    extFeats = swDoc.GetCustomProperty("ExtFanerFeats", out cit);
                                                double angle = 57.29577951308232*swView.Angle; //(180/П)
                                                if (Math.Abs(angle) < 0.000001 || Math.Abs(angle + 90) < 0.000001 || Math.Abs(angle - 270) < 0.000001 || Math.Abs(angle - 180) < 0.000001 || Math.Abs(angle - 90) < 0.000001) //!string.IsNullOrEmpty(extFeats) && extFeats == "Yes" &&
                                                {
                                                    if (names.Contains("Faner11"))
                                                        faner11 = swDoc.GetCustomProperty("Faner11", out cit);
                                                    if (names.Contains("Faner12"))
                                                        faner12 = swDoc.GetCustomProperty("Faner12", out cit);
                                                    if (names.Contains("Faner21"))
                                                        faner21 = swDoc.GetCustomProperty("Faner21", out cit);
                                                    if (names.Contains("Faner22"))
                                                        faner22 = swDoc.GetCustomProperty("Faner22", out cit);

                                                    var tmpElem = _cxml.CreateElement("Comment");
                                                    string comment = FrmEdge.GetCommentFromProperties(faner11,faner12,faner21,faner22, angle, _swAdd,swModel);
                                                    double angle2 = angle + 90;
                                                    double angle4 = angle + 180;
                                                    double angle3 = angle + 270;
                                                    if (angle2 > 270)
                                                        angle2 = angle2%360;
                                                    if (angle3 > 270)
                                                        angle3 = angle3 % 360;
                                                    if (angle4 > 270)
                                                        angle4 = angle4 % 360;
                                                    string comment2 = FrmEdge.GetCommentFromProperties(faner11, faner12, faner21, faner22, angle2, _swAdd, swModel);
                                                    string comment3 = FrmEdge.GetCommentFromProperties(faner11, faner12, faner21, faner22, angle3, _swAdd, swModel);
                                                    string comment4 = FrmEdge.GetCommentFromProperties(faner11, faner12, faner21, faner22, angle4, _swAdd, swModel);
                                                    tmpElem.SetAttribute("Rot270",comment3);
                                                    tmpElem.SetAttribute("Rot180",comment4);
                                                    tmpElem.SetAttribute("Rot90", comment2);
                                                    tmpElem.SetAttribute("Rot0", comment);
                                                    rootNode.PrependChild(tmpElem);
                                                }

                                            }

                                        //swDoc.CloseDoc();

                                        //int warnings = 0;
                                        //int errors = 0;
                                        //var swModelDoc = _swApp.OpenDoc6(Path.ChangeExtension(swModel.GetPathName(), "SLDASM"), (int)swDocumentTypes_e.swDocASSEMBLY,
                                        //                  (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", errors,
                                        //                  warnings);
                                        //if (!string.IsNullOrEmpty(swModelDoc.CustomInfo2["", "ExtFanerFeats"]) && swModelDoc.CustomInfo2["", "ExtFanerFeats"] == "Yes")
                                        //{
                                        //    var tmpElem = _cxml.CreateElement("Comment");
                                        //    string comment = FrmEdge.GetComment(swModelDoc, swView.Angle, _swAdd);
                                        //    tmpElem.SetAttribute("Rot270", string.Empty);
                                        //    tmpElem.SetAttribute("Rot90", string.Empty);
                                        //    tmpElem.SetAttribute("Rot0", comment);
                                        //    rootNode.PrependChild(tmpElem);
                                        //}

                                    }
                                    if (_node != null)
                                    {
                                        _node = rootViewElement.AppendChild(element);
                                        switch (d.Side)
                                        {
                                            case BlockPosition.LeftTopToRightBottom:

                                                if (swView.Name == "F1")
                                                    tableNameAttribute = new KeyValuePair<string, string>("F1","J");
                                                if (swView.Name == "F6")
                                                {
                                                    if (tableNameAttribute.Key!="F1") // F1 -  приоритетнее
                                                        tableNameAttribute = new KeyValuePair<string, string>("F6", "B");
                                                }
                                                if (string.IsNullOrEmpty(tableNameAttribute.Key))
                                                {
                                                    tableNameAttribute = new KeyValuePair<string, string>("none","J");
                                                }
                                                break;
                                            case BlockPosition.RightTopToLeftBottom:
                                                if (swView.Name == "F1")
                                                    tableNameAttribute = new KeyValuePair<string, string>("F1","B");
                                                if (swView.Name == "F6")
                                                {
                                                    if (tableNameAttribute.Key!="F1") // F1 -  приоритетнее
                                                        tableNameAttribute = new KeyValuePair<string, string>("F6", "J");
                                                }
                                                if (string.IsNullOrEmpty(tableNameAttribute.Key))
                                                {
                                                    tableNameAttribute = new KeyValuePair<string, string>("none", "B");
                                                }
                                                break;
                                            case BlockPosition.LeftBottomToRightTop:
                                            case BlockPosition.RigthBottomToLeftTop:
                                                //MessageBox.Show(
                                                //    "В этом чертеже начало координат находится внизу. Программа может быть создана некорректно!",
                                                //    @"MrDoors", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                                // element = _cxml.CreateElement("Table");
                                                // element.SetAttribute("Name", "Не удалось определить наименование стола!");
                                                //_node=_node.AppendChild(element);
                                                break;

                                        }
                                    }

                                    int i = 0;
                                    string id = "id" + i;
                                    element = _cxml.CreateElement(id);

                                    element.SetAttribute("X", Math.Round(d.X).ToString(CultureInfo.CreateSpecificCulture("ru-RU")));
                                    element.SetAttribute("Y", Math.Round(d.Y).ToString(CultureInfo.CreateSpecificCulture("ru-RU")));
                                    if (swView.Name == "F1" || swView.Name == "F6")
                                        element.SetAttribute("Z", _z.ToString(CultureInfo.CreateSpecificCulture("ru-RU")));
                                    if (_node != null)
                                        _node.AppendChild(element);

                                    foreach (var ls in d.ListSize)
                                    {
                                        i++;
                                        id = "id" + i;
                                        element = _cxml.CreateElement(id);

                                        element.SetAttribute("X", ls.X.ToString(CultureInfo.CreateSpecificCulture("ru-RU")));
                                        element.SetAttribute("Y",  ls.Y.ToString(CultureInfo.CreateSpecificCulture("ru-RU")));
                                        element.SetAttribute("Diameter",  ls.Diameter.ToString(CultureInfo.CreateSpecificCulture("ru-RU")));
                                        element.SetAttribute("Depth",ls.Depth.ToString(CultureInfo.CreateSpecificCulture("ru-RU")));

                                        if (_node != null)
                                            _node.AppendChild(element);
                                    }
                                    _node = _node.ParentNode;
                                }

                                #endregion
                            }

                            #endregion

                            swView.SetDisplayMode3(false, (int) swDisplayMode_e.swFACETED_HIDDEN_GREYED, true, true);

                            swDrawing.ActivateSheet(vSheetName);
                        }
                        catch (Exception e)
                        {
                            MessageBox.Show(@"Ошибка при образмеривании! " + e.Message, @"MrDoors",
                                            MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        finally
                        {
                            if (dimOnlyNew)
                                ShowHiddenComponents(list);
                        }

                        #endregion
                    }
                }
                if (type.Count != 0)
                    LegendMaker(swModel, swDrawing, type, vScale);
                if (!string.IsNullOrEmpty(tableNameAttribute.Value))
                    sheetNode.SetAttribute("TableName", tableNameAttribute.Value);
                if (Properties.Settings.Default.ScaleWhenDimen && !del3List && shi != 0)
                    AutoScaleSheet(listSize, swSheet, vScale, side);
                shi++;
                if(_node!=null)
                    _node = _node.ParentNode;
                AutoArrangeDimentions(vSheetName,dimOnlyNew);
            }
            swModel.EditRebuild3();
            if (shi == 3)
            {
                if (del3List)
                {
                    if (isNeededSheetNumber && thrdList.Count > 0)
                        foreach (var sh in thrdList)
                            swModel.Extension.SelectByID2(sh, "SHEET", 0, 0, 0, true, 0, null, 0);
                    else
                    {
                     if (!swModel.Extension.SelectByID2("Лист3", "SHEET", 0, 0, 0, false, 0, null, 0))
                     {
                         swModel.Extension.SelectByID2("Back3", "SHEET", 0, 0, 0, false, 0, null, 0);
                     }
                    }
                    swModel.DeleteSelection(true);
                }
                else
                    SheetNumering(swModel, swDrawing);
            }
            swModel.ForceRebuild3(false);
            bool writeXml = true;
            if (atLeastOneF1View)
            {
                try
                {
                    writeXml=SomeLogicChanges(swModel);
                }
                catch(Exception e)
                {
                    if (swModel.GetPathName() != null)
                        Logging.Log.Instance.Fatal(e, "Ошибка при применении логики к XML. " + swModel.GetPathName());
                    else
                        Logging.Log.Instance.Fatal(e, "Ошибка при применении логики к XML. ");

                }
                if (writeXml)
                    StopWriteXml(pathXml);
            }

            return;
        }
예제 #27
0
        public void Build(Vector3 frameSize, int profileType, ServiceSide serviceSide)
        {
            string caseAssemblyPath = Path.Combine(RootFolder, SourceFolder, modelName);

            Patterns.Observer.MessageObserver.Instance.SetMessage("\n" + caseAssemblyPath + "\n");
            ModelDoc2 SolidWorksDocument = SolidWorksAdapter.OpenDocument(caseAssemblyPath, swDocumentTypes_e.swDocASSEMBLY);// SolidWorksDocumentumentTypes_e.SolidWorksDocumentASSEMBLY);

            Patterns.Observer.MessageObserver.Instance.SetMessage("открылась сборка");
            //AssemblyDocument = SolidWorksAdapter.ToAssemblyDocument( SolidWorksDocument);
            double rivetL;
            string newName     = "01-P150-45-" + (frameSize.Z - 140);
            string newPartPath = GetFrameCasePath(newName);


            if (File.Exists(new FileInfo(newPartPath).FullName))
            {
                SolidWorksDocument = SolidWorksAdapter.AcativeteDoc(modelName);
                SolidWorksDocument.Extension.SelectByID2("01-P150-45-1640-27@" + modelName.Replace(".SLDASM", ""), "COMPONENT", 0, 0, 0, false, 0, null, 0);
                AssemblyDocument.ReplaceComponents(newPartPath, "", true, true);
                SolidWorksAdapter.SldWoksAppExemplare.CloseDoc("01-P150-45-1640.SLDPRT");
            }
            else if (File.Exists(newPartPath) != true) // TO DO delegate
            {
                rivetL = (Math.Truncate((frameSize.Z - 170) / step) + 1) * 1000;
                parameters.Add("D1@Вытянуть1", frameSize.Z - 140);
                parameters.Add("D1@Кривая1", rivetL);
                EditPartParameters("01-P150-45-1640", newPartPath, 0);

                //frameSize.X

                newName     = "01-P150-45-" + (frameSize.X - 140);
                newPartPath = GetFrameCasePath(newName);
                if (File.Exists(new FileInfo(newPartPath).FullName))
                {
                    SolidWorksDocument = SolidWorksAdapter.AcativeteDoc(modelName);
                    SolidWorksDocument.Extension.SelectByID2("01-003-50-22@" + modelName.Replace(".SLDASM", ""), "COMPONENT", 0, 0, 0, false, 0, null, 0);
                    AssemblyDocument.ReplaceComponents(newPartPath, "", true, true);
                    SolidWorksAdapter.SldWoksAppExemplare.CloseDoc("01-003-50.SLDPRT");
                }
                else
                {
                    rivetL = (Math.Truncate((frameSize.X - 170) / step) + 1) * 1000;
                    parameters.Add("D1@Вытянуть1", frameSize.X - 140);
                    parameters.Add("D1@Кривая1", rivetL);
                    EditPartParameters("01-P150-45-1640", newPartPath, 0);
                }

                //01-P252-45-770
                newName     = "01-P252-45-" + (frameSize.X - 100);
                newPartPath = newPartPath = GetFrameCasePath(newName);
                if (File.Exists(new FileInfo(newPartPath).FullName))
                {
                    SolidWorksDocument = SolidWorksAdapter.AcativeteDoc(modelName);
                    SolidWorksDocument.Extension.SelectByID2("01-P252-45-770-6@" + modelName.Replace(".SLDASM", ""), "COMPONENT", 0, 0, 0, false, 0, null, 0);
                    AssemblyDocument.ReplaceComponents(newPartPath, "", true, true);
                    SolidWorksAdapter.SldWoksAppExemplare.CloseDoc("01-P252-45-770.SLDPRT");
                }
                else
                {
                    parameters.Add("D1@Вытянуть1", frameSize.X - 100);
                    EditPartParameters("01-P150-45-1640", newPartPath, 0);
                }

                //frameSize.Y

                newName     = "01-P150-45-" + (frameSize.Y - 140);
                newPartPath = newPartPath = GetFrameCasePath(newName);
                if (File.Exists(new FileInfo(newPartPath).FullName))
                {
                    SolidWorksDocument = SolidWorksAdapter.AcativeteDoc(modelName);
                    SolidWorksDocument.Extension.SelectByID2("01-P150-45-510-23@" + modelName.Replace(".SLDASM", ""), "COMPONENT", 0, 0, 0, false, 0, null, 0);
                    AssemblyDocument.ReplaceComponents(newPartPath, "", true, true);
                    SolidWorksAdapter.SldWoksAppExemplare.CloseDoc("01-P150-45-510.SLDPRT");
                }
                else
                {
                    rivetL = (Math.Truncate((frameSize.Y - 170) / step) + 1) * 1000;

                    parameters.Add("D1@Вытянуть1", (frameSize.Y - 140));
                    parameters.Add("D1@Кривая1", rivetL);
                    EditPartParameters("01-P150-45-1640", newPartPath, 0);
                }

                //  01-P252-45-550
                newName     = "01-P252-45-" + (frameSize.Y - 100);
                newPartPath = newPartPath = GetFrameCasePath(newName);
                if (File.Exists(new FileInfo(newPartPath).FullName))
                {
                    SolidWorksDocument = SolidWorksAdapter.AcativeteDoc(modelName);
                    SolidWorksDocument.Extension.SelectByID2("01-P252-45-550-10@" + modelName.Replace(".SLDASM", ""), "COMPONENT", 0, 0, 0, false, 0, null, 0);
                    AssemblyDocument.ReplaceComponents(newPartPath, "", true, true);
                    SolidWorksAdapter.SldWoksAppExemplare.CloseDoc("01-P252-45-550.SLDPRT");
                }
                else
                {
                    parameters.Add("D1@Вытянуть1", frameSize.Y - 100);
                    EditPartParameters("01-P252-45-550", newPartPath, 0);
                }

                SolidWorksDocument = SolidWorksAdapter.AcativeteDoc(modelName);
                SolidWorksDocument.EditRebuild3();
                SolidWorksDocument.ForceRebuild3(true);
                //   AssemblyDocument = (AssemblyDoc)SolidWorksDocument;

                if (serviceSide == ServiceSide.Left)
                {
                    SolidWorksDocument.Extension.SelectByID2("M8-Panel block-one side-1@" + modelName.Replace(".SLDASM", ""), "COMPONENT", 0, 0, 0, true, 0, null, 0);
                    SolidWorksDocument.Extension.SelectByID2("M8-Panel block-one side-6@" + modelName.Replace(".SLDASM", ""), "COMPONENT", 0, 0, 0, true, 0, null, 0);
                    SolidWorksDocument.Extension.SelectByID2("M8-Panel block-one side-7@" + modelName.Replace(".SLDASM", ""), "COMPONENT", 0, 0, 0, true, 0, null, 0);
                    SolidWorksDocument.Extension.SelectByID2("Threaded Rivets с насечкой-10@" + modelName.Replace(".SLDASM", ""), "COMPONENT", 0, 0, 0, true, 0, null, 0);
                    SolidWorksDocument.Extension.SelectByID2("Threaded Rivets с насечкой-4@" + modelName.Replace(".SLDASM", ""), "COMPONENT", 0, 0, 0, true, 0, null, 0);
                    SolidWorksDocument.Extension.SelectByID2("Threaded Rivets с насечкой-12@" + modelName.Replace(".SLDASM", ""), "COMPONENT", 0, 0, 0, true, 0, null, 0);
                    SolidWorksDocument.Extension.SelectByID2("Threaded Rivets с насечкой-12@" + modelName.Replace(".SLDASM", ""), "COMPONENT", 0, 0, 0, false, 0, null, 0);
                    SolidWorksDocument.EditDelete();
                }
                else if (serviceSide == ServiceSide.Right)
                {
                    SolidWorksDocument.Extension.SelectByID2("M8-Panel block-one side-16@" + modelName.Replace(".SLDASM", ""), "COMPONENT", 0, 0, 0, true, 0, null, 0);
                    SolidWorksDocument.Extension.SelectByID2("Threaded Rivets с насечкой-21@" + modelName.Replace(".SLDASM", ""), "COMPONENT", 0, 0, 0, true, 0, null, 0);
                    SolidWorksDocument.Extension.SelectByID2("Threaded Rivets с насечкой-22@" + modelName.Replace(".SLDASM", ""), "COMPONENT", 0, 0, 0, true, 0, null, 0);
                    SolidWorksDocument.Extension.SelectByID2("M8-Panel block-one side-17@" + modelName.Replace(".SLDASM", ""), "COMPONENT", 0, 0, 0, true, 0, null, 0);
                    SolidWorksDocument.Extension.SelectByID2("Threaded Rivets с насечкой-23@" + modelName.Replace(".SLDASM", ""), "COMPONENT", 0, 0, 0, true, 0, null, 0);
                    SolidWorksDocument.Extension.SelectByID2("M8-Panel block-one side-18@" + modelName.Replace(".SLDASM", ""), "COMPONENT", 0, 0, 0, true, 0, null, 0);
                    SolidWorksDocument.Extension.SelectByID2("M8-Panel block-one side-18@" + modelName.Replace(".SLDASM", ""), "COMPONENT", 0, 0, 0, false, 0, null, 0);
                    SolidWorksDocument.EditDelete();
                }
            }
        }
예제 #28
0
파일: Drawings.cs 프로젝트: mdcnbu/TDG
        /// <summary>
        /// 出工程图
        /// </summary>
        /// <param name="dicValues"></param>
        /// <param name="prtTemp"></param>
        /// <param name="compTemp"></param>
        /// <param name="bomPaths"></param>
        /// <param name="savePaths">保存路径</param>
        /// <param name="newPath">新路径</param>
        private void Drawing(List <string> dicValues, string prtTemp, string compTemp, string bomPaths, string savePaths, string newPath)
        {
            string          viewType   = string.Empty;
            bool            isometric  = false;
            bool            bom        = false;
            string          dimesion   = string.Empty;
            double          spaceX     = 0.06;                  //x方向留白区域
            double          scale      = 1;                     //定义比例初始值
            List <double[]> viewBox    = new List <double[]>(); //集合存放视图box
            List <double[]> viewOrigin = new List <double[]>(); //集合存放视图原点值

            double[] outLine = new double[4];                   //视图box值
            double[] postion = new double[2];                   //视图原点值
            _swApp = (SldWorks)ConnectSW.iSwApp;                //连接sw
            if (_swApp == null)
            {
                return;
            }
            foreach (string item in dicValues)
            {
                int    errors   = 0;
                int    warnings = 0;
                double view1X   = 0;
                double view1Y   = 0;
                string filePath = item;                                             //文件路径
                string fileEx   = filePath.Substring(filePath.LastIndexOf("."), 7); //获得后缀名
                string filename = filePath.Substring(filePath.LastIndexOf("\\") + 1, filePath.LastIndexOf(".") - filePath.LastIndexOf("\\") - 1);
                if (fileEx == ".SLDPRT")
                {
                    _swModelDoc = (ModelDoc2)_swApp.OpenDoc6(filePath, (int)swDocumentTypes_e.swDocPART, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);
                    __swDrawDoc = (DrawingDoc)_swApp.NewDrawing2((int)swDwgTemplates_e.swDwgTemplateCustom, prtTemp, (int)swDwgPaperSizes_e.swDwgPapersUserDefined, 0, 0);
                }
                if (fileEx == ".SLDASM")
                {
                    _swModelDoc = (ModelDoc2)_swApp.OpenDoc6(filePath, (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);
                    __swDrawDoc = (DrawingDoc)_swApp.NewDrawing2((int)swDwgTemplates_e.swDwgTemplateCustom, compTemp, (int)swDwgPaperSizes_e.swDwgPapersUserDefined, 0, 0);
                }
                _swModelEx = (ModelDocExtension)_swModelDoc.Extension;
                if (newPath != null)
                {
                    savePaths = newPath.Substring(0, newPath.LastIndexOf("\\"));
                }
                //新建工程图
                _swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swAutomaticScaling3ViewDrawings, true); //自动缩放新工程图比例
                if (standarView == false && isometric)                                                               //如果只生成等轴测视图
                {
                    CreatIsometric(__swDrawDoc, filePath);
                    _currentSheet = (Sheet)__swDrawDoc.GetCurrentSheet();
                    __swDrawDoc.ActivateSheet(_currentSheet.GetName());
                    _swView = __swDrawDoc.GetFirstView();
                    _swView = _swView.GetNextView();
                    ChangeViewShow(tag, _swView);
                    _swApp.CloseDoc(_swModelDoc.GetTitle());//
                    ModelDoc2 tempDoc = (ModelDoc2)__swDrawDoc;
                    bool      ss0     = false;
                    if (newPath != null && IfDwg)
                    {
                        ss0 = tempDoc.Extension.SaveAs(newPath, (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref errors, ref warnings);
                    }
                    else if (newPath != null && IfDwg == false)
                    {
                        ss0 = tempDoc.Extension.SaveAs(savePaths + "\\" + (_swModelDoc.GetTitle()).Substring(0, (_swModelDoc.GetTitle()).LastIndexOf(".")) + ".DWG", (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref errors, ref warnings);
                    }
                    else if (newPath == null && IfDwg)
                    {
                        ss0 = tempDoc.Extension.SaveAs(savePaths + "\\" + (_swModelDoc.GetTitle()).Substring(0, (_swModelDoc.GetTitle()).LastIndexOf(".")) + ".DWG", (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref errors, ref warnings);
                    }
                    else
                    {
                        ss0 = tempDoc.Extension.SaveAs(savePaths + "\\" + (_swModelDoc.GetTitle()).Substring(0, (_swModelDoc.GetTitle()).LastIndexOf(".")) + ".slddrw", (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref errors, ref warnings);
                    }

                    bool isHidden = tempDoc.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swViewDisplayHideAllTypes, true); //隐藏所有类型
                    _swApp.CloseDoc(tempDoc.GetTitle());
                    _numSucess += 1;                                                                                                //转换成功的数量
                    sucessFile.Add(filePath);
                    return;
                }
                bool isCreate = false;
                #region 第三视角投影
                if (thirProject)
                {
                    isCreate = __swDrawDoc.Create3rdAngleViews2(filePath);//创建第三视角投影视图(视图位置有差别)
                    //调整视图位置
                    _swView = __swDrawDoc.GetFirstView();
                    while (_swView != null)
                    {
                        double[] vBox   = new double[] { };
                        double[] vPoint = new double[] { };
                        vBox   = (double[])_swView.GetOutline();
                        vPoint = (double[])_swView.Position;
                        viewBox.Add(vBox);
                        viewOrigin.Add(vPoint);
                        _swView = _swView.GetNextView();
                    }
                    //调整视图1、2位置
                    if (viewBox[0][3] > viewBox[0][2])//纵向
                    {
                        double[] posView1 = new double[] { viewBox[0][2] / 3.0, viewOrigin[1][1] };
                        _swView          = __swDrawDoc.GetFirstView();
                        _swView          = _swView.GetNextView();
                        _swView.Position = posView1;
                        double[] posView2 = new double[] { viewOrigin[2][0], viewOrigin[2][1] - (viewBox[2][1] - viewBox[1][3]) / 1.9 };//调整视图2位置
                        _swView          = _swView.GetNextView();
                        _swView.Position = posView2;
                    }
                    else
                    {
                        double[] posView1 = new double[] { viewBox[0][2] / 4.0, viewOrigin[1][1] };
                        _swView          = __swDrawDoc.GetFirstView();
                        _swView          = _swView.GetNextView();
                        _swView.Position = posView1;
                        double[] posView2 = new double[] { viewOrigin[2][0], viewOrigin[2][1] - (viewBox[2][1] - viewBox[1][3]) / 2.0 };//调整视图2位置
                        _swView          = _swView.GetNextView();
                        _swView.Position = posView2;
                    }
                    viewOrigin.Clear();
                    viewBox.Clear();
                    _swView = __swDrawDoc.GetFirstView();
                    while (_swView != null)
                    {
                        double[] vBox   = new double[] { };
                        double[] vPoint = new double[] { };
                        vBox   = (double[])_swView.GetOutline();
                        vPoint = (double[])_swView.Position;
                        viewBox.Add(vBox);
                        viewOrigin.Add(vPoint);
                        _swView = _swView.GetNextView();
                    }
                    if (isometric)//等轴测
                    {
                        _swView = (IView)__swDrawDoc.CreateDrawViewFromModelView3(filePath, "*等轴测", viewOrigin[3][0], viewOrigin[2][1], 0);
                        _swView = __swDrawDoc.GetFirstView();
                        double[] sca = new double[2];
                        sca                = _swView.ScaleRatio;//获取比例
                        _swView            = _swView.GetNextView();
                        _swView            = _swView.GetNextView();
                        _swView            = _swView.GetNextView();
                        _swView            = _swView.GetNextView();
                        _swView.ScaleRatio = sca;
                        double[] rePos = new double[] { viewOrigin[3][0] + 0.015, viewOrigin[2][1] };
                        _swView.Position = rePos;
                        ChangeViewShow(tag, _swView);                     //视图样式
                        AddDimension(dimesion, __swDrawDoc, _swModelDoc); //尺寸标注
                    }
                }
                #endregion
                #region 第一视角投影
                else
                {
                    isCreate = __swDrawDoc.Create1stAngleViews(filePath);//创建第一视角投影视图
                    //获取视图boundingbox
                    _swView = __swDrawDoc.GetFirstView();
                    while ((_swView != null))
                    {
                        outLine = (double[])_swView.GetOutline(); //(x,y坐标最值)
                        postion = (double[])_swView.Position;     //视图位置值
                        viewBox.Add(outLine);
                        viewOrigin.Add(postion);
                        _swView = _swView.GetNextView();
                    }

                    double newScale = CalcuScale(viewBox, __swDrawDoc, scale, spaceX, 3);
                    //调整视图位置(position)
                    if (viewBox[0][3] > viewBox[0][2])
                    {
                        view1X = viewBox[0][2] / 2.8;                  //视图1的X坐标放在图纸坐标的三分之一处
                        view1Y = viewBox[0][3] - viewBox[0][3] / 4.85; //视图1的Y坐标放在图纸坐标的五分之一处
                    }
                    else
                    {
                        view1X = viewBox[0][2] / 3.5;                 //视图1的X坐标放在图纸坐标的三分之一处
                        view1Y = viewBox[0][3] - viewBox[0][3] / 4.0; //视图1的Y坐标放在图纸坐标的四分之一处
                    }
                    double[] view1Pos = new double[] { view1X, view1Y };
                    _swView          = __swDrawDoc.GetFirstView(); //获取图纸
                    _swView          = _swView.GetNextView();      //获取第一个视图
                    _swView.Position = view1Pos;
                    bool isRebuild = _swModelDoc.EditRebuild3();
                    //viewBox.Clear();
                    List <double[]> tempBox = new List <double[]>();
                    viewOrigin.Clear();
                    while ((_swView != null))
                    {
                        ChangeViewShow(tag, _swView);                     //改变视图显示样式
                        AddDimension(dimesion, __swDrawDoc, _swModelDoc); //添加尺寸
                        outLine = (double[])_swView.GetOutline();         //(x,y坐标最值)
                        postion = (double[])_swView.Position;             //视图位置值
                        tempBox.Add(outLine);
                        viewOrigin.Add(postion);
                        _swView = _swView.GetNextView();
                    }
                    if (isometric)  //是否创建等轴测视图(非钣金)
                    {
                        double[] scalArry = new double[2];
                        _swView = (IView)__swDrawDoc.CreateDrawViewFromModelView3(filePath, "*等轴测", viewOrigin[2][0], viewOrigin[1][1], 0);
                        _swView = __swDrawDoc.GetFirstView(); //获取图纸
                        _swView = _swView.GetNextView();      //获取第一个视图
                        double sca = _swView.get_IScaleRatio();
                        if (sca == 1)                         //缩小比例
                        {
                            scalArry[0] = 1;
                            scalArry[1] = newScale;
                        }
                        else
                        {
                            scalArry[0] = sca;
                            scalArry[1] = 1;
                        }
                        _swView            = _swView.GetNextView();
                        _swView            = _swView.GetNextView();
                        _swView            = _swView.GetNextView();
                        _swView.ScaleRatio = scalArry;//调整轴测图比例
                        ChangeViewShow(tag, _swView);
                        _swModelDoc.EditRebuild3();
                    }
                    ////关掉文件(不保存)
                    //_swApp.CloseDoc(_swModelDoc.GetTitle());
                    if (fileEx == ".SLDASM" && bom)        //是否创建明细表
                    {
                        //viewBox.Clear();
                        //viewOrigin.Clear();
                        double[] outArry  = new double[4];
                        double[] posArry  = new double[2];
                        double[] posArry1 = null;
                        double[] posArry2 = null;
                        double[] posArry3 = null;
                        _currentSheet = (Sheet)__swDrawDoc.GetCurrentSheet();
                        __swDrawDoc.ActivateSheet(_currentSheet.GetName());
                        _swView        = __swDrawDoc.GetFirstView(); //获取图纸
                        _swView        = _swView.GetNextView();      //获取第一个视图
                        swBomTableAnno = (BomTableAnnotation)_swView.InsertBomTable4(true, 0.4, 0.1, (int)swBOMConfigurationAnchorType_e.swBOMConfigurationAnchor_BottomRight, (int)swBomType_e.swBomType_TopLevelOnly, "", bomPaths, false, 0, false);
                        TableAnnotation tableAnnotation = (TableAnnotation)swBomTableAnno;
                        tableAnnotation.GetAnnotation();
                        BomFeature bomFeature     = swBomTableAnno.BomFeature;
                        bool[]     array          = new bool[bomFeature.GetConfigurationCount(false)];
                        object     Visible        = array;
                        object     configurations = bomFeature.GetConfigurations(false, ref Visible);
                        array[0] = true;
                        bomFeature.SetConfigurations(true, array, configurations);
                        FeatureManager featureManager = _swModelDoc.FeatureManager;
                        featureManager.UpdateFeatureTree();
                        double num = 0.007;
                        tableAnnotation.SetRowHeight(-2, num, 0);
                        double totleHeight = num * tableAnnotation.RowCount; //计算总的tableBom高度
                        double heightSum   = totleHeight + 0.070;            //加上标题栏总高度
                        int    columCount  = tableAnnotation.ColumnCount;    //获取总的列数
                        double columWidth  = 0;
                        for (int i = 0; i < columCount; i++)
                        {
                            double wid = tableAnnotation.GetColumnWidth(i);
                            columWidth += wid;
                        }
                        _swView = _swView.GetNextView();
                        _swView = _swView.GetNextView();
                        outArry = (double[])_swView.GetOutline();
                        if (outArry[1] < heightSum)//有可能被遮挡
                        {
                            //__swView = _swDrawDoc.GetFirstView();
                            //double[] tempArry = new double[] { };
                            //tempArry=(double[])__swView.GetOutline();
                            //viewBox.Insert(0, tempArry);
                            scale = ((viewBox[1][2] - viewBox[1][0]) + (viewBox[3][2] - viewBox[3][0])) / (viewBox[0][2] - columWidth - 0.025);//计算X方向的比例
                            if (scale > 11)
                            {
                                double scaleCeil = System.Math.Ceiling(scale);
                                if (scaleCeil > 11 && scaleCeil < 16)
                                {
                                    scale = 20;
                                }
                                if (scaleCeil > 15 && scaleCeil < 21)
                                {
                                    scale = 25;
                                }
                                if (scaleCeil > 20 && scaleCeil < 26)
                                {
                                    scale = 30;
                                }
                                if (scaleCeil > 25 && scaleCeil < 34)
                                {
                                    scale = 40;
                                }
                                if (scaleCeil > 33 && scaleCeil < 45)
                                {
                                    scale = 50;
                                }
                                if (scaleCeil > 44 && scaleCeil < 55)
                                {
                                    scale = 60;
                                }
                            }
                            else if (scale > 5.8 && scale < 10.5)
                            {
                                double scaleCeil = System.Math.Ceiling(scale);
                                //scale = scaleCeil + 4.0;          //比例为10、11、12、13、14、15
                                if (scaleCeil > 5 && scaleCeil < 8)
                                {
                                    scale = 10;
                                }
                                if (scaleCeil > 7 && scaleCeil < 12)
                                {
                                    scale = 15;
                                }
                            }
                            _currentSheet = (Sheet)__swDrawDoc.GetCurrentSheet();
                            __swDrawDoc.ActivateSheet(_currentSheet.GetName());
                            bool isScale = _currentSheet.SetScale(1, scale, false, false); //设置视图和图纸比例
                            _swView = __swDrawDoc.GetFirstView();
                            _swView = _swView.GetNextView();                               //获取视图1
                            double[] pos1 = new double[2];
                            pos1             = _swView.Position;
                            posArry1         = new double[] { pos1[0] - columWidth / 3.45, pos1[1] };
                            _swView.Position = posArry1;              //重置视图1的位置
                            _swView          = _swView.GetNextView(); //获取视图2
                            double[] pos2 = new double[2];
                            pos2             = _swView.Position;
                            posArry2         = new double[] { pos2[0] - columWidth / 3.45, pos2[1] + 0.0015 };
                            _swView.Position = posArry2;              //设置视图2位置
                            _swView          = _swView.GetNextView(); //获取视图三
                            posArry          = (double[])_swView.Position;
                            posArry3         = new double[] { posArry[0] - columWidth / 3.5, posArry[1] };
                            _swView.Position = posArry3;//视图3坐标
                        }
                    }
                }//第一视角投影
                #endregion
                if (isCreate)
                {
                    _numSucess += 1;//转换成功的数量
                    sucessFile.Add(filePath);
                }
                ModelDoc2 tempModelDoc = (ModelDoc2)__swDrawDoc;                                                                    //获取到swDraw的父级(ModelDoc)
                _swApp.CloseDoc(_swModelDoc.GetTitle());
                bool isHiden = tempModelDoc.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swViewDisplayHideAllTypes, true); //隐藏所有类型

                _swModelDoc.ForceRebuild3(false);
                string saveName = (_swModelDoc.GetTitle()).Substring(0, (_swModelDoc.GetTitle()).LastIndexOf("."));
                bool   ss;
                if (newPath != null && IfDwg)
                {
                    ss = tempModelDoc.Extension.SaveAs(savePaths + "\\" + (_swModelDoc.GetTitle()) + ".DWG", (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref errors, ref warnings);
                }
                else if (newPath != null && IfDwg == false)
                {
                    ss = tempModelDoc.Extension.SaveAs(savePaths + "\\" + (_swModelDoc.GetTitle()) + ".slddrw", (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref errors, ref warnings);
                }
                else if (newPath == null && IfDwg)
                {
                    ss = tempModelDoc.Extension.SaveAs(savePaths + "\\" + (_swModelDoc.GetTitle()) + ".DWG", (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref errors, ref warnings);
                }
                else
                {
                    ss = tempModelDoc.Extension.SaveAs(savePaths + "\\" + (_swModelDoc.GetTitle()) + ".slddrw", (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref errors, ref warnings);
                }
                _swApp.CloseDoc(tempModelDoc.GetTitle());//关闭转换完成的文件
            }
        }
예제 #29
0
        /// <summary>
        /// Метод построения детали
        /// </summary>
        public void BuildCandle(CandleParametrs objParametr)
        {
            /// <summary>
            /// Экземпляру присваиваем значение объекта класса
            /// </summary>
            _parametr = objParametr;

            /// <summary>
            /// Проверка построена ли деталь
            /// </summary>
            _parametr.ExistDetail = true;

            /// <summary>
            /// Путь до рабочего стола
            /// </summary>
            var pathName = System.Environment.GetFolderPath(System.Environment.SpecialFolder.DesktopDirectory);

            /// <summary>
            /// Присваивание параметров
            /// </summary>
            var carvingLength   = _parametr.CarvingLength;
            var nutLength       = _parametr.NutLength;
            var nutSize         = _parametr.NutSize;
            var isolatorLength  = _parametr.IsolatorLength;
            var chamferRadius   = _parametr.ChamferRadius;
            var plinthLength    = _parametr.PlinthLength;
            var headLength      = _parametr.HeadLength;
            var pitchSize       = _parametr.PitchSize;
            var carvingRadius   = _parametr.CarvingRadius;
            var textEtching     = _parametr.TextEtching;
            var electrodeLength = _parametr.ElectrodeLength;

            /// <summary>
            /// Методы класса CandleCreator
            /// </summary>
            if (_parametr.ExistHead == true)
            {
                CandleCreator.CreateHead(headLength, SwApp, SwModel, _detailNames, pathName);
            }
            CandleCreator.CreatePlinth(plinthLength, SwApp, SwModel, _detailNames, textEtching, pathName);
            CandleCreator.CreateNut(nutLength, nutSize, SwApp, SwModel, _detailNames, chamferRadius, pathName);
            CandleCreator.CreateIsolator(isolatorLength, SwApp, SwModel, _detailNames, pathName);
            CandleCreator.CreateCarving(carvingLength, SwApp, SwModel, _detailNames, pitchSize, carvingRadius, electrodeLength, pathName);

            /// <summary>
            /// Создание сборки
            /// </summary>
            AssemblyDoc swAssembly = SwApp.NewAssembly();

            SwModel = ((ModelDoc2)(SwApp.ActiveDoc));
            if (_parametr.ExistHead == true)
            {
                swAssembly.AddComponent2(_detailNames[0], 0, 0, headLength / 2);
                swAssembly.AddComponent2(_detailNames[1], 0, 0, plinthLength / 2 + headLength);
                swAssembly.AddComponent2(_detailNames[2], 0, 0, nutLength / 2 + headLength + plinthLength);
                swAssembly.AddComponent(_detailNames[3], 0, 0, isolatorLength / 2 + headLength + plinthLength + nutLength);
                swAssembly.AddComponent(_detailNames[4], 0, 0, carvingLength / 2 + headLength + plinthLength + isolatorLength + nutLength);
            }
            else
            {
                swAssembly.AddComponent2(_detailNames[0], 0, 0, plinthLength / 2 + headLength);
                swAssembly.AddComponent2(_detailNames[1], 0, 0, nutLength / 2 + headLength + plinthLength);
                swAssembly.AddComponent(_detailNames[2], 0, 0, isolatorLength / 2 + headLength + plinthLength + nutLength);
                swAssembly.AddComponent(_detailNames[3], 0, 0, carvingLength / 2 + headLength + plinthLength + isolatorLength + nutLength);
            }
            /// <summary>
            /// Выбор вида "Изометрия"
            /// </summary>
            SwModel.Extension.SelectByID2("", "FACE", 0, 0, 0, true, 0, null, 0);
            swAssembly.AddMate((int)swMateType_e.swMateCONCENTRIC, (int)swMateAlign_e.swAlignAGAINST, false, 1, 0);
            SwModel.ShowNamedView("*Изометрия");
            SwModel.ClearSelection();
            SwModel.EditRebuild3();

            /// <summary>
            /// Закрытие созданных документов
            /// </summary>
            SwApp.CloseDoc(_detailNames[0]);
            SwApp.CloseDoc(_detailNames[1]);
            SwApp.CloseDoc(_detailNames[2]);
            SwApp.CloseDoc(_detailNames[3]);
            if (_parametr.ExistHead == true)
            {
                SwApp.CloseDoc(_detailNames[4]);
            }

            /// <summary>
            /// Сохранение сборки
            /// </summary>
            string modelName = pathName + "Свеча.SLDASM";

            SwModel.SaveAs(modelName);
        }
예제 #30
0
        /// <summary>
        /// 如果有一个视图为选中状态,则对这个视图进行重排序,
        /// 否则,对一个图纸下的所有视图进行重排序
        /// </summary>
        private void ReSortAllView()
        {
            this.arCheckRepect.Clear();
            if (this.rdoTemp1.Checked)
            {
                if (StringOperate.Alert("序号为项目号时,无法重排序,要继续吗?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
                {
                    return;
                }
            }

            ModelDoc2 swModel = (ModelDoc2)AllData.iSwApp.ActiveDoc;

            if (swModel == null)
            {
                return;
            }

            DrawingDoc   swDraw = (DrawingDoc)swModel;
            SelectionMgr SelMgr = (SelectionMgr)swModel.SelectionManager;

            swModel.ClearSelection2(true);

            //101,$数量×"序号",$数量×"属性名"
            string strTxt = this.cmbStartIndex.Text;
            int    abc    = 1;
            bool   bText  = false;

            try
            {
                abc = Convert.ToInt16(this.cmbStartIndex.Text);//序号从一开始
            }
            catch
            {
                bText = true;
            }

            SolidWorks.Interop.sldworks.View swView = (SolidWorks.Interop.sldworks.View)swDraw.ActiveDrawingView;
            if (swView == null)//对所有的视图进行重排序
            {
                swView = (SolidWorks.Interop.sldworks.View)swDraw.GetFirstView();
                //遍历视图
                while (swView != null)
                {
                    swDraw.ActivateView(swView.Name);

                    if (bText)
                    {
                        SaidiResortOneView(swView, swModel);//对这个视图进行排序
                    }
                    else
                    {
                        abc = ReSortOneView(abc, swView, swModel);//对这个视图进行排序
                    }

                    //转到下一个视图
                    swView = (SolidWorks.Interop.sldworks.View)swView.GetNextView();
                }
            }
            else//只对当前视图进行重排序
            {
                if (bText)
                {
                    SaidiResortOneView(swView, swModel);//对这个视图进行排序
                }
                else
                {
                    ReSortOneView(abc, swView, swModel);
                }
            }

            //重建,以更新明细表
            swModel.EditRebuild3();

            this.arCheckRepect.Clear();
        }
        private Feature EsquisseRepere(ModelDoc2 mdl, Boolean creer = true)
        {
            // On recherche l'esquisse contenant les parametres
            Feature Esquisse = mdl.eChercherFonction(fc => { return(fc.Name == CONSTANTES.NOM_ESQUISSE_NUMEROTER); });

            if (Esquisse.IsNull() && creer)
            {
                var SM = mdl.SketchManager;

                // On recherche le chemin du bloc
                String cheminbloc = CheminBlocEsquisseNumeroter();

                if (String.IsNullOrWhiteSpace(cheminbloc))
                {
                    return(null);
                }

                // On supprime la definition du bloc
                SupprimerDefBloc(mdl, cheminbloc);

                // On recherche le plan de dessus, le deuxième dans la liste des plans de référence
                Feature Plan = mdl.eListeFonctions(fc => { return(fc.GetTypeName2() == FeatureType.swTnRefPlane); })[1];

                // Selection du plan et création de l'esquisse
                Plan.eSelect();
                SM.InsertSketch(true);
                SM.AddToDB          = false;
                SM.DisplayWhenAdded = true;

                mdl.eEffacerSelection();

                // On récupère la fonction de l'esquisse
                Esquisse = mdl.Extension.GetLastFeatureAdded();

                // On insère le bloc
                MathUtility Mu      = App.Sw.GetMathUtility();
                MathPoint   Origine = Mu.CreatePoint(new double[] { 0, 0, 0 });
                var         def     = SM.MakeSketchBlockFromFile(Origine, cheminbloc, false, 1, 0);

                // On récupère la première instance
                // et on l'explose
                var Tab = (Object[])def.GetInstances();
                var ins = (SketchBlockInstance)Tab[0];
                SM.ExplodeSketchBlockInstance(ins);

                // Fermeture de l'esquisse
                SM.AddToDB          = false;
                SM.DisplayWhenAdded = true;
                SM.InsertSketch(true);

                //// On supprime la definition du bloc
                //SupprimerDefBloc(mdl, cheminbloc);

                // On renomme l'esquisse
                Esquisse.Name = CONSTANTES.NOM_ESQUISSE_NUMEROTER;

                mdl.eEffacerSelection();

                // On l'active dans toutes les configurations
                Esquisse.SetSuppression2((int)swFeatureSuppressionAction_e.swUnSuppressFeature, (int)swInConfigurationOpts_e.swAllConfiguration, null);
            }

            if (Esquisse.IsRef())
            {
                // On selectionne l'esquisse, on la cache
                // et on la masque dans le FeatureMgr
                // elle ne sera pas du tout acessible par l'utilisateur
                Esquisse.eSelect();
                mdl.BlankSketch();
                Esquisse.SetUIState((int)swUIStates_e.swIsHiddenInFeatureMgr, true);
                mdl.eEffacerSelection();

                mdl.EditRebuild3();
            }

            return(Esquisse);
        }
예제 #32
0
 public void Rebuild()
 {
     swDoc.EditRebuild3();
 }
예제 #33
0
        public static void RecopyHeare(SwAddin swAddin, ISldWorks swApp,ModelDoc2 swModelDoc)
        {
            try
            {
            SwAddin.IsEventsEnabled = false;
            swModelDoc.Save();
            ModelDocExtension swModelDocExt = default(ModelDocExtension);
            PackAndGo swPackAndGo = default(PackAndGo);
            Dictionary<string,string> filesToHideAndShow = new Dictionary<string, string>();
            WaitTime.Instance.ShowWait();
            WaitTime.Instance.SetLabel("Отрыв сборки от библиотеки.");
            int warnings = 0;
            int errors = 0;
            string _openFile = swModelDoc.GetPathName();

            swAddin.currentPath = string.Empty;
            swApp.CloseAllDocuments(true);
            if (!Directory.Exists("C:\\Temp"))
                Directory.CreateDirectory("C:\\Temp");
            string tempDir = Path.Combine("C:\\Temp", Path.GetFileNameWithoutExtension(_openFile));
            if (Directory.Exists(tempDir))
            {
                Directory.Delete(tempDir, true);
            }
            Directory.CreateDirectory(tempDir);
            string fileToOpenTemp = Path.Combine(tempDir, Path.GetFileName(_openFile));
            //File.Copy(_openFile, fileToOpenTemp);
            Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(Path.GetDirectoryName(_openFile), tempDir);
            if (!File.Exists(fileToOpenTemp))
            {
                throw new Exception("Ошибка. Не найден файл: " + fileToOpenTemp);
            }
            swAddin.DetachEventHandlers();
            swModelDoc = (ModelDoc2)swApp.OpenDoc6(fileToOpenTemp, (int)swDocumentTypes_e.swDocASSEMBLY,
                                                    (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", errors,
                                                    warnings);
            swAddin.AttachEventHandlers();
            try
            {
                foreach (var file in Directory.GetFiles(Path.GetDirectoryName(_openFile)))
                {
                    File.Delete(file);
                }
                foreach (var directory in Directory.GetDirectories(Path.GetDirectoryName(_openFile)))
                {
                    Microsoft.VisualBasic.FileIO.FileSystem.DeleteDirectory(directory, Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, Microsoft.VisualBasic.FileIO.RecycleOption.SendToRecycleBin);
                    //Directory.Delete(directory, true);
                }
            }
            catch (Exception e)
            {
                Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory( tempDir,Path.GetDirectoryName(_openFile),true);
                swAddin.DetachEventHandlers();
                swApp.CloseAllDocuments(true);
                swModelDoc = (ModelDoc2)swApp.OpenDoc6(_openFile, (int)swDocumentTypes_e.swDocASSEMBLY,
                                                        (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", errors,
                                                        warnings);
                swAddin.AttachEventHandlers();
                MessageBox.Show(@"Из-за ошибки: """ + e.Message + @""" не удалось оторвать проект. Перезапустите SW и попробуйте еще раз.");
                return;
            }

            //File.Delete(_openFile);
            swModelDocExt = (ModelDocExtension)swModelDoc.Extension;

            swPackAndGo = (PackAndGo)swModelDocExt.GetPackAndGo();

            //swModelDoc = (ModelDoc2)swApp.OpenDoc6(openFile, (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);
            //swModelDocExt = (ModelDocExtension)swModelDoc.Extension;

            int namesCount = swPackAndGo.GetDocumentNamesCount();

            object fileNames;
            object[] pgFileNames = new object[namesCount - 1];
            bool status = swPackAndGo.GetDocumentNames(out fileNames);
            string[] newFileNames = new string[namesCount];
            string[] rFileNames1 = fileNames as string[];
            if (rFileNames1 == null)
                throw new Exception("Не удалось оторвать заказ.");
            string[] rFileNames = new string[rFileNames1.Length];

            for (int ii = 0; ii < rFileNames1.Length;ii++ )
            {
                var tt1 = Microsoft.VisualBasic.FileSystem.Dir(rFileNames1[ii]);
                if (tt1==null)
                    tt1 = Microsoft.VisualBasic.FileSystem.Dir(rFileNames1[ii], Microsoft.VisualBasic.FileAttribute.Hidden);
                rFileNames[ii] = Path.Combine(Path.GetDirectoryName(rFileNames1[ii]),tt1);
            }
            //удалить неактуальные программы..
            DeleteXmlFiles(tempDir, rFileNames,_openFile);
            //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))
            //{
            //}

            string xName = swAddin.GetXNameForAssembly(false, Path.GetFileNameWithoutExtension(_openFile));
            string furnDir = Path.Combine(Path.GetDirectoryName(_openFile), "ФУРНИТУРА");
            string furnHelpDir = Path.Combine(Path.GetDirectoryName(_openFile), "ФУРНИТУРА", "Модели фурнитуры");
            string partDir = Path.Combine(Path.GetDirectoryName(_openFile), "ДЕТАЛИ");
            string partDirHelp = Path.Combine(Path.GetDirectoryName(_openFile), "ДЕТАЛИ", "Вспомогательные детали");
            string partForAssDir = Path.Combine(Path.GetDirectoryName(_openFile), "ДЕТАЛИ", "Детали для сборок");

            //DSOFile.OleDocumentProperties m_oDocument = null;
            //m_oDocument = new DSOFile.OleDocumentPropertiesClass();
            for (int i = 0; i<namesCount;i++)
            {

                //вот пример как выглядит массив элементов в fileNames. Переделать их в newFileNames и все...
            //                [0]	"c:\\temp\\2222\\2222.sldasm"	string
            //[1]	"d:\\_swlib_backup\\крепежная фурнитура\\вспомогательные\\3090_штифт для эксцентрика пластикового 20 мм.sldprt"	string
            //[2]	"d:\\_swlib_backup\\крепежная фурнитура\\вспомогательные\\3093_эксцентрик пластиковый для дсп 16 мм 20 мм.sldprt"	string
            //[3]	"d:\\_swlib_backup\\крепежная фурнитура\\вспомогательные\\отв для арт. 3090.sldprt"	string
            //[4]	"d:\\_swlib_backup\\крепежная фурнитура\\3093+3090_(эксцентрик пластиковый 20 мм для дсп 16 мм+штифт для эксцентрика пластикового 20 мм).sldasm"	string
            //[5]	"d:\\_swlib_backup\\шкафы-купе\\каркасные детали\\дсп 16 мм\\вспомогательные\\8504_панель вкладная 000a01p.sldprt"	string
            //[6]	"d:\\_swlib_backup\\шкафы-купе\\каркасные детали\\дсп 16 мм\\8504f_панель вкладная 000a01p.sldasm"	string

                //в rFileNames[i] вот что:
                //d:\_swlib_backup\шкафы-купе\каркасы шкафов-купе\вспомогательные\детали для сборок\Панель боковая правая_K02214P.SLDPRT
                //если содержит _swlib_backup и на конце 2 цифры + "P" = заменяем эти 2 цифры на 01 и помещаем оба файлика в список
                //потом пробегусь по списку. 01 - убрать скрытие, для старого - скрыть

                string fileName = Path.GetFileName(rFileNames[i]);
                string tmprFileName = rFileNames[i];
                if (!Directory.Exists(partDir))
                    Directory.CreateDirectory(partDir);
                if (fileName.ToLower().Contains(Path.GetFileName(_openFile.ToLower())))
                {
                    newFileNames[i] = _openFile;
                    continue;
                }
                if (rFileNames[i].ToLower().Contains(tempDir.ToLower()))
                {
                    newFileNames[i] = rFileNames[i].Replace(tempDir.ToLower(), Path.GetDirectoryName(_openFile));
                    continue;
                }
                string idCopyTo = rFileNames[i].Substring(rFileNames[i].Length - 10, 2);
                  int newNumber;
                char lastChar = Path.GetFileNameWithoutExtension(rFileNames[i]).Last();
                if ((lastChar != 'p' && lastChar!='P') || !int.TryParse(idCopyTo, out newNumber))//(rFileNames[i].ToLower().Contains("крепежная фурнитура") || rFileNames[i].ToLower().Contains("фурнитура для каркасов"))
                {
                    if (!Directory.Exists(furnDir))
                        Directory.CreateDirectory(furnDir);

                    if (rFileNames[i].ToLower().Contains("вспомогательные"))
                    {
                        //2222//ФУРНИТУРА//Модели фурнитуры
                        if (!Directory.Exists(furnHelpDir))
                            Directory.CreateDirectory(furnHelpDir);
                        newFileNames[i] = Path.Combine(furnHelpDir, Path.GetFileNameWithoutExtension(rFileNames[i]) + " #" + xName+"-1" + Path.GetExtension(rFileNames[i]));
                        continue;
                    }
                    else
                    {
                        //2222//ФУРНИТУРА//
                        newFileNames[i] = Path.Combine(furnDir, Path.GetFileNameWithoutExtension(rFileNames[i]) + " #" + xName +"-1"+ Path.GetExtension(rFileNames[i]));
                        continue;
                    }
                }
                else
                {
                    tmprFileName = GetFileNameWithoutSuff(rFileNames[i]);
                }
                string fnext = Path.GetFileNameWithoutExtension(tmprFileName);
                string[] arr = fnext.Split('-').ToArray();
                if (arr.Length != 2)
                {
                    //учитывать только последний "-"
                    string[] tmp = new string[2];
                    for (int j = 0; j < arr.Length-1; j++)
                    {
                        tmp[0] = string.Format("{0}-{1}", tmp[0], arr[j]);
                    }
                    tmp[0] = tmp[0].Remove(0, 1);
                    tmp[1] = arr.Last();
                    arr = tmp;
                }
                string newName = arr[0] + " #" + xName+"-" + arr[1] + Path.GetExtension(tmprFileName);
                if (tmprFileName.ToLower().Contains("вспомогательные"))
                {
                    //if (true)//(tmprFileName.ToLower().Contains("детали для сборок"))//|| Path.GetExtension(tmprFileName).ToLower()==".sldprt" )
                    //{
                        if (!Directory.Exists(partForAssDir))
                            Directory.CreateDirectory(partForAssDir);
                        newFileNames[i] = Path.Combine(partForAssDir, newName);
                        continue;
                    //}
                    ////2222\ДЕТАЛИ\Вспомогательные детали
                    //if (!Directory.Exists(partDirHelp))
                    //    Directory.CreateDirectory(partDirHelp);

                    //newFileNames[i] = Path.Combine(partDirHelp, newName);
                    //continue;
                }
                newFileNames[i] = Path.Combine(partDir, newName);
            }
            BStrWrapper[] pgSetFileNames;
            //тут надо немного поправить newFileNames так, чтобы не было одинаковых..
            string[] tmpFileNames = new string[newFileNames.Length];
            int jj = 0;
            foreach (var tmpFileName in newFileNames)
            {
                int same = tmpFileNames.Count(f => f!=null ? f.ToLower() == tmpFileName.ToLower() : false);
                if (same > 0 && !tmpFileName.Contains("фурнитура") && !tmpFileName.Contains("ФУРНИТУРА"))
                {
                    string tmp = Path.GetFileNameWithoutExtension(tmpFileName).Split('-').LastOrDefault();
                    if (string.IsNullOrEmpty(tmp))
                        continue;
                    int tmpNumb;
                    if (!int.TryParse(tmp, out tmpNumb))
                        continue;

                    int index = Path.GetFileNameWithoutExtension(tmpFileName).IndexOf('-');
                    string substr = Path.GetFileNameWithoutExtension(tmpFileName).Substring(0, index)+"-"+(tmpNumb+1).ToString() + Path.GetExtension(tmpFileName);
                    string res = Path.Combine(Path.GetDirectoryName(tmpFileName), substr);
                next:
                    same = tmpFileNames.Count(f => f != null ? f.ToLower() == res.ToLower() : false);
                    if (same > 0)
                    {
                        tmp = Path.GetFileNameWithoutExtension(res).Split('-').LastOrDefault();
                        if (string.IsNullOrEmpty(tmp))
                            continue;
                        if (!int.TryParse(tmp, out tmpNumb))
                            continue;
                        index = Path.GetFileNameWithoutExtension(res).IndexOf('-');
                        substr = Path.GetFileNameWithoutExtension(res).Substring(0, index) + "-" + (tmpNumb + 1).ToString() + Path.GetExtension(tmpFileName);
                        res = Path.Combine(Path.GetDirectoryName(res), substr);
                        goto next;
                    }
                    tmpFileNames[jj] = res;
                }
                else
                {
                    tmpFileNames[jj] = tmpFileName;
                }
                jj++;
            }
            newFileNames = tmpFileNames;
            pgSetFileNames = ObjectArrayToBStrWrapperArray(newFileNames);
            //var documentsToRemove = ObjectArrayToBStrWrapperArray(newFileNames.Where(x => x == "C:\\temp").ToArray());
            //swPackAndGo.RemoveExternalDocuments(documentsToRemove);
            status = swPackAndGo.SetDocumentSaveToNames(pgSetFileNames);

            var statuses = (int[])swModelDocExt.SavePackAndGo(swPackAndGo);
            //перед открытием создать файлик dictionary
            string dictFile= Path.Combine(Path.GetDirectoryName(_openFile), Path.GetFileNameWithoutExtension(_openFile) + "_dictionary.txt");
            if (File.Exists(dictFile))
                File.Delete(dictFile);
            using (File.CreateText(dictFile)) { }; //File.Create(dictFile);
            List<string> strArr = new List<string>();
            foreach (string file in Directory.GetFiles(partDir, "*.SLDASM", SearchOption.TopDirectoryOnly))
            {
                strArr.Add(file);
            }
            File.SetAttributes(dictFile, FileAttributes.Normal);
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(dictFile, true))
            {
                foreach (var line in strArr)
                {
                    file.WriteLine(line);
                }
                file.Close();
            }
            //File.WriteAllLines(dictFile, strArr);
            File.SetAttributes(dictFile, FileAttributes.Hidden);

            //тут проверить что все оторвалось. Если что, поправить ссылки
            SwDMApplication swDocMgr = SwAddin.GetSwDmApp();
            SwDmDocumentOpenError oe;
            SwDMSearchOption src = swDocMgr.GetSearchOptionObject();
            object brokenRefVar;
            string[] files = Directory.GetFiles(Path.GetDirectoryName(_openFile),"*.*",SearchOption.AllDirectories);
            foreach (string fileName in files)
            {
                SwDMDocument8 swDoc = null;
                if (fileName.ToLower().Contains("sldasm"))
                    swDoc = (SwDMDocument8) swDocMgr.GetDocument(fileName,
                                                                 SwDmDocumentType.swDmDocumentAssembly,
                                                                 false, out oe);
                if (swDoc != null)
                {

                    var varRef = (string[]) swDoc.GetAllExternalReferences2(src, out brokenRefVar);
                    if (varRef != null && varRef.Length != 0)
                    {
                        foreach (string o in varRef)
                        {
                            if (o.ToUpper().Contains("_SWLIB_BACKUP"))
                            {
                                string tt = Path.GetFileNameWithoutExtension(o);
                                string newRef = null;
                                foreach (var fn in files)
                                {
                                    if (fn.Contains(tt))
                                    {
                                        newRef = fn;
                                        break;
                                    }
                                }
                                if (newRef != null)
                                {
                                    swDoc.ReplaceReference(o, newRef);
                                    swDoc.Save();
                                }

                            }
                        }
                    }
                    else
                    {
                        swDoc.CloseDoc();
                        continue;
                    }
                    swDoc.CloseDoc();
                }
            }
            swApp.CloseAllDocuments(true);
            if (!File.Exists(_openFile))
                throw new Exception("Ошибка. Не найден файл: " + _openFile);
            foreach (var file in newFileNames)
            {
                File.SetAttributes(file,FileAttributes.Normal);
            }
            //Logging.Log.Instance.Debug("SetAttributes ");
            SwAddin.IsEventsEnabled = true;
            swModelDoc = (ModelDoc2)swApp.OpenDoc6(_openFile, (int)swDocumentTypes_e.swDocASSEMBLY,
                                                    (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", errors,
                                                    warnings);
            SwAddin.IsEventsEnabled = false;
            //Logging.Log.Instance.Debug("OpenDoc6");
            swModelDoc.EditRebuild3();
            swAddin.AttachModelDocEventHandler(swModelDoc);
            //теперь тут пробежатся по всем файлам в filesToHideAndShow. key -хайдить , value - показывать
            //foreach (var files in filesToHideAndShow)
            //{
            //    if (File.Exists(files.Key) && File.Exists(files.Value))
            //    {
            //        File.SetAttributes(files.Value, FileAttributes.Normal);
            //        File.SetAttributes(files.Key, FileAttributes.Hidden);
            //        string nextFile,sourceFile = files.Key;
            //        while (SwAddin.IfNextExist(sourceFile, out nextFile))
            //        {
            //            sourceFile = nextFile;
            //            File.SetAttributes(nextFile, FileAttributes.Hidden);
            //        }
            //    }
            //}
            SwDmCustomInfoType swDmCstInfoType;
            if (Directory.Exists(furnDir))
            {
                foreach (string path in Directory.GetFiles(furnDir, "*.sldasm", SearchOption.TopDirectoryOnly))
                {
                    if (!File.Exists(path))
                        continue;
                    var swDoc = swDocMgr.GetDocument(path, SwDmDocumentType.swDmDocumentAssembly, true, out oe);
                    if (Path.GetFileNameWithoutExtension(path).First() == '~' || swDoc == null)
                        continue;
                    string valueOfName = swDoc.GetCustomProperty("Accessories", out swDmCstInfoType);
                    swDoc.CloseDoc();
                    if (valueOfName != null && (valueOfName == "No" || valueOfName == "no"))
                    {
                        File.Delete(path);
                    }
                }
            }
            var oComps = (object[])((AssemblyDoc)swModelDoc).GetComponents(true);
            if (oComps != null)
            {

                foreach (var oComp in oComps)
                {
                    var comp = (Component2)oComp;
                    var model = (ModelDoc2)comp.GetModelDoc();
                    if (model != null)
                    {
                        File.SetAttributes(model.GetPathName(), FileAttributes.Normal);
                        var swDoc = swDocMgr.GetDocument(model.GetPathName(), SwDmDocumentType.swDmDocumentUnknown, true, out oe);
                        if (swDoc != null)
                        {
                            var names = (string[])swDoc.GetCustomPropertyNames();
                            try
                            {
                                foreach (var name in names)
                                {

                                    string valueOfName = swDoc.GetCustomProperty(name, out swDmCstInfoType);
                                    string lowValOfName = valueOfName.ToLower();

                                    if (lowValOfName.Contains("@") &&
                                        lowValOfName.Contains("#") &&
                                        (lowValOfName.Contains(".sld")))
                                    {
                                        var split = valueOfName.Split('.');
                                        string tmp = split.First();
                                        string ext = split.Last();
                                        if (lowValOfName.Contains("#" + xName) || tmp.ToUpper().Last()!='P')
                                            continue;
                                        string sid = tmp.Substring(tmp.Length - 3, 2);
                                        int id;
                                        if (!int.TryParse(sid,out id))
                                            continue;
                                        tmp = tmp.Substring(0, tmp.Length - 4);
                                        tmp = tmp +" #" +xName+"-"+id +"."+ext;

                                        swAddin.SetModelProperty(model, name, "",
                                                                swCustomInfoType_e.
                                                                    swCustomInfoText,
                                                                tmp);
                                        model.Save();

                                        //swDoc.SetCustomProperty(name, tmp);
                                    }
                                }
                            }
                            catch (Exception)
                            {
                                Logging.Log.Instance.Debug("Ошибка при попытке обратится к св-ву. Деталь: " + swDoc.FullName);
                            }
                            finally
                            {
                                swDoc.CloseDoc();
                            }
                        }

                    }
                }
            }

            Cash.ActualizaAllCash();
            SwAddin.IsEventsEnabled = true;
            linksToCash.Remove(_openFile);
            //скопировать fpTime.txt
            string fpTime = Path.Combine(tempDir, "fpTime.txt");
            if (File.Exists(fpTime))
                File.Copy(fpTime, Path.Combine(Path.GetDirectoryName(_openFile), "fpTime.txt"));
            CopyDrawings(rFileNames, newFileNames, tempDir, _openFile);
            CopyProgramms(rFileNames, newFileNames,tempDir, _openFile);

            }
            catch(Exception e)
            {
                MessageBox.Show(e.Message);
                return;
            }
            finally
            {
                WaitTime.Instance.HideWait();

            }
        }