public void Rebuild()
        {
            //PbLoadAddTable.Minimum = 0;

            //var confArray = ClassPropertySldWorks.ListColumn(_swModel);
            //PbLoadAddTable.Maximum = confArray.Count;
            //PbLoadAddTable.Value = 0;

            //double value = 0;

            // to the ProgressBar's SetValue method.
            //UpdateProgressBarDelegate updatePbDelegate = PbLoadAddTable.SetValue;

            string[] arrayConfig = _swModel.GetConfigurationNames();

            foreach (var confName in from confName in arrayConfig
                     let swConf = _swModel.GetConfigurationByName(confName)
                                  where ((Configuration)swConf).IsDerived() == false select confName)
            {
                _swModel.ShowConfiguration2(confName);

                //value += 1;

                _swModel.ForceRebuild3(false);

                //Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { ProgressBar.ValueProperty, value });
            }

            //PbLoadAddTable.Value = 0;
        }
        public SwModelWrapper(SwApiWrapper swApi, SldWorks swApp, swDocumentTypes_e swDocType, ModelDoc2 swMainModel, string strConfigName)
        {
            this.swApi       = swApi;
            this.swApp       = swApp;
            this.swMainModel = swMainModel;

            swModelDocExt = (ModelDocExtension)swMainModel.Extension;

            if (swDocType == swDocumentTypes_e.swDocASSEMBLY)
            {
                swMainAssembly = (AssemblyDoc)swMainModel;
            }

            if (strConfigName != null)
            {
                this.swMainConfig = (Configuration)swMainModel.GetConfigurationByName(strConfigName);
            }
            else
            {
                this.swMainConfig = (Configuration)swMainModel.GetActiveConfiguration();
            }
            strConfigName = this.swMainConfig.Name;


            // Write model info to shared variables
            string[] configsArray = swMainModel.GetConfigurationNames();
            this.configNames.AddRange(configsArray);
            this.configNames.Sort();
            this.pathName          = swMainModel.GetPathName();
            this.modelName         = swMainModel.GetTitle();
            this.currentConfigName = strConfigName;
        }
예제 #3
0
        public List <string> GetConfigurationNames(SldWorks swApp)
        {
            var ConfigNames = new List <string>();

            try
            {
                if (swApp == null)
                {
                    swApp = (SldWorks)Marshal.GetActiveObject("SldWorks.Application");
                }

                _swmodel = (ModelDoc2)swApp.ActiveDoc;

                object[] confignamearray = _swmodel.GetConfigurationNames();

                foreach (string cfgName in confignamearray)
                {
                    // только верхний уровень конфигураций
                    Configuration swConf = _swmodel.GetConfigurationByName(cfgName);

                    if (swConf.IsDerived() == false)
                    {
                        ConfigNames.Add(cfgName);
                    }
                }

                //ConfigNames.AddRange(from string cfgName in confignamearray let swConf = _swmodel.GetConfigurationByName(cfgName) where ((Configuration) swConf).IsDerived() == false select cfgName);
            }
            catch (Exception ex)
            {
                Error = ex.Message;
            }
            return(ConfigNames);
        }
예제 #4
0
        public static string [] GetAllConfigurations()
        {
            string[]      allNames       = {};
            List <string> notDerivedConf = new List <string>();

            allNames = swModel.GetConfigurationNames();

            for (int i = 0; i < allNames.Length; i++)
            {
                Configuration swConf = swModel.GetConfigurationByName(allNames[i]);

                if (swConf.IsDerived() == false)
                {
                    notDerivedConf.Add(allNames[i]);
                }
                else
                {
                    swModel.Extension.CustomPropertyManager[allNames[i]].Add3("PDMFlag", 30, "2", 0);
                }
            }

            configNames = (string[])swModel.GetConfigurationNames();



            return(notDerivedConf.ToArray());
        }
예제 #5
0
        }                                  // 0 - Раздел не материал, 1 - Раздел материал
        //
        public List <MatName> GetCustomProperty(string confname, SldWorks swApp)
        {
            var customnamelist = new List <MatName>();

            try
            {
                customnamelist.Clear();

                if (swApp == null)
                {
                    swApp = (SldWorks)Marshal.GetActiveObject("SldWorks.Application");
                }

                _swmodel = swApp.ActiveDoc;

                _swmodel.GetConfigurationByName(confname);



                var sMatDb = "";

                var valout  = _swmodel.CustomInfo2[confname, "RAL"];
                var valout1 = _swmodel.CustomInfo2[confname, "Тип покрытия"];
                var valout2 = _swmodel.CustomInfo2[confname, "Класс покрытия"];

                //var valout3 = "";

                //var matname = new MatName();

                //if (CheckType == 0)
                //{ valout3 = _swmodel.CustomInfo2[confname, "Наименование"];
                //        matname.Name = valout3; }

                //if (CheckType == 1)
                //{  var swpart = (PartDoc)_swmodel;
                //    matname.Name = swpart.GetMaterialPropertyName2(confname, out sMatDb); }

                //matname.ColorSQL = valout;
                //matname.CoatingType = valout1;
                //matname.CoatingClass = valout2;
                var swpart = (PartDoc)_swmodel;

                var matname = new MatName()
                {
                    Name = swpart.GetMaterialPropertyName2(confname, out sMatDb),

                    ColorSQL     = valout,
                    CoatingType  = valout1,
                    CoatingClass = valout2
                };

                customnamelist.Add(matname);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Message: {ex.Message}\r\nTargetSite: {ex.TargetSite}\r\nStackTrace: {ex.StackTrace}");
            }

            return(customnamelist);
        }
예제 #6
0
        public void LoadDataGrid()
        {
            try
            {
                _swmodel = (ModelDoc2)_swapp.ActiveDoc;
                DataGridConfig.Rows.Clear();

                var confarray = _matDll.GetConfigurationNames();

                foreach (var confname in confarray)
                {
                    if (confname == "По умолчанию")
                    {
                        var configuration = (IConfiguration)_swmodel.GetConfigurationByName("По умолчанию");

                        _swapp.SendMsgToUser2("Конфигурация \"По умолчанию\" будет переименована на \"00\"",
                                              (int)swMessageBoxIcon_e.swMbInformation, (int)swMessageBoxBtn_e.swMbOk);
                        configuration.Name = "00";
                    }
                    int n;
                    if (int.TryParse(confname, out n))
                    {
                        var matname = _matDll.GetCustomProperty(confname, null);

                        foreach (var customProperty in matname)
                        {
                            if (customProperty.ColorSQL == "")
                            {
                                DataGridConfig.Rows.Add(ColChB.Selected, confname, customProperty.Name, "Без покрытия");
                            }
                            else
                            {
                                DataGridConfig.Rows.Add(ColChB.Selected, confname, customProperty.Name,
                                                        customProperty.ColorSQL, customProperty.CoatingType, customProperty.CoatingClass);
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show(@"Конфигурацию """ + confname +
                                        @" ""необходимо переименовать в числовое значение!");

                        Close();
                        return;
                    }
                }

                var activeConfName = _matDll.GetActiveConfigurationName();
                DataGridConfig.Rows[Convert.ToInt32(activeConfName)].Cells[0].Value = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                throw;
            }
        }
        static public List <ColumnNameEditPropTable> ListColumnToEditProp(ModelDoc2 swModel)
        {
            var columnRow = new List <ColumnNameEditPropTable>();

            object[] configNamesDll = swModel.GetConfigurationNames();

            foreach (string configName in configNamesDll)
            {
                Configuration swConf = swModel.GetConfigurationByName(configName);

                if (swConf.IsDerived() == false)
                {
                    var customPropMan = swModel.Extension.CustomPropertyManager[configName];

                    var valOut      = "";
                    var number      = "";
                    var description = "";
                    var matName     = "";
                    var thickness   = "";
                    var codFb       = "";

                    customPropMan.Get4("Обозначение", true, out valOut, out number);
                    customPropMan.Get4("Наименование", true, out valOut, out description);
                    customPropMan.Get4("Код_ФБ", true, out valOut, out codFb);
                    customPropMan.Get4("Материал_Таблица", true, out valOut, out matName);
                    customPropMan.Get4("Толщина листового металла", true, out valOut, out thickness);

                    var columnNameClass = new ColumnNameEditPropTable();

                    if (configName == "00")
                    {
                        columnNameClass.ColumnNumber = number;
                    }
                    else
                    {
                        columnNameClass.ColumnNumber = "-" + configName;
                    }

                    columnNameClass.ColumnConfig      = configName;
                    columnNameClass.ColumnDescription = description;
                    columnNameClass.ColumnThickness   = thickness;
                    columnNameClass.CodFb             = codFb;
                    columnNameClass.ColumnMatName     = matName.Replace("$PRPSHEET:\"Толщина листового металла\"", thickness);

                    columnRow.Add(columnNameClass);
                }
            }

            return(columnRow);
        }
 private void SetConfigName(string configName)
 {
     if (configName == this.currentConfigName || configName == "")
     {
         return;
     }
     if (!configNames.Contains(configName))
     {
         string strExcept = String.Format("Config name {0} is not in this model", configName);
         throw new Exception(strExcept);
     }
     swMainConfig           = (Configuration)swMainModel.GetConfigurationByName(configName);
     this.currentConfigName = configName;
 }
예제 #9
0
        public static void GetConfig(ModelDoc2 Doc)
        {
            Configuration SwConfig2 = Doc.GetConfigurationByName("形状2");

            if (SwConfig2 != null)
            {
                string Comment       = SwConfig2.Comment;
                string AlternateName = SwConfig2.AlternateName;
                Doc.ShowConfiguration2("形状2");
                System.Windows.MessageBox.Show("配置[形状2]被激活\r\n" + Comment + "\r\n" + AlternateName);
            }
            else
            {
                System.Windows.MessageBox.Show("未找到配置2");
            }
        }
예제 #10
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));
                }
            }
        }
예제 #11
0
        //
        public List <MatName> GetCustomProperty(string confname, SldWorks swApp)
        {
            try
            {
                var customnamelist = new List <MatName>();

                customnamelist.Clear();

                if (swApp == null)
                {
                    swApp = (SldWorks)Marshal.GetActiveObject("SldWorks.Application");
                }

                _swmodel = swApp.ActiveDoc;

                _swmodel.GetConfigurationByName(confname);

                var swpart = (PartDoc)_swmodel;

                var sMatDb = "";

                var valout  = _swmodel.CustomInfo2[confname, "RAL"];
                var valout1 = _swmodel.CustomInfo2[confname, "Тип покрытия"];
                var valout2 = _swmodel.CustomInfo2[confname, "Класс покрытия"];

                var matname = new MatName()
                {
                    Name = swpart.GetMaterialPropertyName2(confname, out sMatDb),

                    ColorSQL     = valout,
                    CoatingType  = valout1,
                    CoatingClass = valout2
                };

                customnamelist.Add(matname);

                return(customnamelist);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                throw;
            }
        }
예제 #12
0
        private static void ExportDataToXmlSql(SldWorks swApp, Files.Info item, ModelDoc2 swModel, ref Exception exOut, object[] confArray, out bool isFix)
        {
            if (!item.ExistCutList)
            {
                try
                {
                    List <ExportXmlSql.DataToExport> listCutList = new List <ExportXmlSql.DataToExport>();                                                       // using export part data

                    // Проходимся по всем конфигурация для Fix, CutList
                    foreach (var confName in confArray)
                    {
                        Configuration swConf = swModel.GetConfigurationByName(confName.ToString());
                        if (swConf.IsDerived())
                        {
                            continue;                     // только детали верхнего уровня
                        }
                        swModel.ShowConfiguration2(confName.ToString());

                        // Проверка на CutList: false - XML отсутствует, true - XML есть
                        if (!item.ExistCutList)
                        {
                            var list = new List <Bends.SolidWorksFixPattern.PartBendInfo>(); // using export part data
                            Bends.Fix(swApp, out list, false);                               // разгиб

                            List <ExportXmlSql.DataToExport> listCutListConf;                // using export part data
                            ExportXmlSql.GetCurrentConfigPartData(swApp, item.CurrentVersion, item.IdPDM, false, false, out listCutListConf, out exOut);
                            listCutList.AddRange(listCutListConf);
                        }
                        if (exOut != null)
                        {
                            Logger.Add(exOut.Message);
                        }
                    }

                    isFix = true;

                    //CutList To Sql
                    if (listCutList != null)
                    {
                        //Logger.Add("=============================== Сохранение Cut list data через  ExportXmlSql.ExportDataToXmlSql метод =====================================");
                        //System.Text.StringBuilder messageBuilder = new System.Text.StringBuilder();
                        //foreach (var EachCut in listCutList)
                        //{
                        //    messageBuilder.Append("id " + EachCut.IdPdm+", ");

                        //    messageBuilder.Append("name " + EachCut.FileName + ", ");

                        //    messageBuilder.Append("ver. " + EachCut.Version + ", ");

                        //    messageBuilder.Append("conf. " + EachCut.Config + ", ");

                        //    messageBuilder.Append("Mat-l Id " + EachCut.MaterialId + ", ");

                        //    messageBuilder.Append("PaintX " + EachCut.PaintX + ", ");
                        //    messageBuilder.Append("PaintY " + EachCut.PaintY + ", ");
                        //    messageBuilder.Append("PaintZ " + EachCut.PaintZ + ", ");

                        //    messageBuilder.Append("ДлинаГраничнойРамки " + EachCut.ДлинаГраничнойРамки + ", ");
                        //    messageBuilder.Append("КодМатериала " + EachCut.КодМатериала + ", ");
                        //    messageBuilder.Append("Материал " + EachCut.Материал + ", ");
                        //    messageBuilder.Append("ПлощадьПокрытия " + EachCut.ПлощадьПокрытия + ", ");
                        //    messageBuilder.Append("Сгибы " + EachCut.Сгибы + ", ");

                        //    messageBuilder.Append("ТолщинаЛистовогоМеталла " + EachCut.ТолщинаЛистовогоМеталла + ", ");
                        //    messageBuilder.Append("ШиринаГраничнойРамки " + EachCut.ШиринаГраничнойРамки + ", ");
                        //    messageBuilder.Append("\n============================================================================================\n");
                        //}

                        //Logger.Add(messageBuilder.ToString());

                        ExportXmlSql.ExportDataToXmlSql(item.FileName.ToUpper().Replace(".SLDPRT", ""), listCutList, out exOut);                                            // using export part data
                        if (exOut != null)
                        {
                            Logger.Add(exOut.Message);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.Add("!item.ExistCutList ------ " + ex.Message + "; " + ex.StackTrace);
                }
            }
            isFix = false;
        }
예제 #13
0
        public void LoadDataGridConfig()
        {
            try
            {
                //SelectionMgr swSelMgr;
                //Configuration swConfig; ;
                string   sConfigName;
                object[] vConfNameArr;

                //swapp = CreateObject("SldWorks.Application")
                swapp   = (SldWorks)Marshal.GetActiveObject("SldWorks.Application");
                swmodel = swapp.ActiveDoc;

                swDraw = (DrawingDoc)swmodel;

                swSheet            = swDraw.GetCurrentSheet();
                strActiveSheetName = swSheet.GetName();

                vSheetNames = swDraw.GetSheetNames();
                swDraw.ActivateSheet(vSheetNames[0]);

                swSheet = swDraw.GetCurrentSheet();
                swView  = swDraw.GetFirstView();

                // Получаем параметры модели
                if (swSheet.CustomPropertyView == "По умолчанию" | swSheet.CustomPropertyView == "Default")
                {
                    swView = swView.GetNextView();
                }

                sConfigName = swView.ReferencedConfiguration;

                swmodel = swView.ReferencedDocument;
                swmodel.GetConfigurationByName(sConfigName);

                vConfNameArr = swmodel.GetConfigurationNames();

                // Конфигурация
                for (var i = 0; i <= vConfNameArr.GetUpperBound(0); i++)
                {
                    DataGridConfig.Rows.Add(ColChB.Selected, vConfNameArr[i]);
                }

                //Get customProperty from Assy
                CustomPropertyManager swCustProp = default(CustomPropertyManager);
                string valOut      = "";
                string Number      = "";
                string Description = "";

                swCustProp = swmodel.Extension.CustomPropertyManager[""];

                swCustProp.Get2("Обозначение", out valOut, out Number);
                swCustProp.Get2("Наименование", out valOut, out Description);

                addinform = new addincheckbox();
                try
                {
                    //Fill DataGriad
                    foreach (string line in System.IO.File.ReadAllLines("C:\\Program Files\\SW-Complex\\doc.txt"))
                    {
                        addinform.DGDoc.Rows.Add(addinform.DocChb.Selected, line);
                    }
                }
                catch (Exception ex)
                {
                    //Interaction.MsgBox("Отсутствует SW-Complex или Doc.txt");
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
예제 #14
0
        private void SaveAll()
        {
            try
            {
                int intVal;
                SwConfig = (Configuration)SwModel.GetConfigurationByName((string)CboxConfigName.SelectedValue);
                CustomPropertyManager swConfigCustMgr = SwConfig.CustomPropertyManager;

                intVal = swConfigCustMgr.Add2(TextBox1.Text, (int)swCustomInfoType_e.swCustomInfoText, TextBoxDeaNo.Text);
                if (intVal == -1)
                {
                    intVal = swConfigCustMgr.Set(TextBox1.Text, TextBoxDeaNo.Text.Trim());
                }

                intVal = swConfigCustMgr.Add2(TextBox2.Text, (int)swCustomInfoType_e.swCustomInfoText, TextBoxName.Text);
                if (intVal == -1)
                {
                    intVal = swConfigCustMgr.Set(TextBox2.Text, TextBoxName.Text.Trim());
                }

                intVal = swConfigCustMgr.Add2(TextBox3.Text, (int)swCustomInfoType_e.swCustomInfoText, TextBoxDesigner.Text);
                if (intVal == -1)
                {
                    intVal = swConfigCustMgr.Set(TextBox3.Text, TextBoxDesigner.Text.Trim());
                }

                intVal = swConfigCustMgr.Add2(TextBox4.Text, (int)swCustomInfoType_e.swCustomInfoDate, DatePickerDesignDate.SelectedDate.ToString());
                if (intVal == -1)
                {
                    intVal = swConfigCustMgr.Set(TextBox4.Text, DatePickerDesignDate.SelectedDate.ToString().Trim());
                }



                intVal = SwCustPropMgr.Add2(TextBox5.Text, (int)swCustomInfoType_e.swCustomInfoText, TextBoxDwgNo.Text);
                if (intVal == 0)
                {
                    intVal = SwCustPropMgr.Set(TextBox5.Text, TextBoxDwgNo.Text.Trim());
                }

                intVal = SwCustPropMgr.Add2(TextBox6.Text, (int)swCustomInfoType_e.swCustomInfoText, TextBoxDwgName.Text);
                if (intVal == 0)
                {
                    intVal = SwCustPropMgr.Set(TextBox6.Text, TextBoxDwgName.Text.Trim());
                }

                intVal = SwCustPropMgr.Add2(TextBox7.Text, (int)swCustomInfoType_e.swCustomInfoText, TextBoxNote.Text);
                if (intVal == 0)
                {
                    intVal = SwCustPropMgr.Set(TextBox7.Text, TextBoxNote.Text.Trim());
                }

                //intVal = swCustPropMgr.Set(textBox5.Text, textBoxDwgNo.Text);
                //intVal = swCustPropMgr.Set(textBox6.Text, textBoxDwgName.Text);
                //intVal = swCustPropMgr.Set(textBox7.Text, textBoxNote.Text);

                SwModel.ForceRebuild3(true);

                TextColorReset();

                TextBlock.Text = "写入完成。";
            }
            catch (Exception ex)
            {
                throw ex;
            }


            //this.Hide();
            //System.Threading.Thread th = new System.Threading.Thread(new System.Threading.ThreadStart(msg));
            //th.Start();
            //System.Threading.Thread.Sleep(1000);
            //System.Environment.Exit(0);
            this.Close();
        }
예제 #15
0
        protected override void Command()
        {
            try
            {
                AjouterPercage(CompPercage);

                if (SurTouteLesConfigs)
                {
                    _NomConfigCourante = _MdlBase.ConfigurationManager.ActiveConfiguration.Name;

                    var pidBase = new SwObjectPID <Component2>(CompBase, _MdlBase);
                    var pidFace = new SwObjectPID <Face2>(Face, _MdlBase);
                    var pidPlan = new SwObjectPID <Feature>(Plan, _MdlBase);

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

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

                        Configuration Conf = _MdlBase.GetConfigurationByName(NomConfig);
                        Conf.SuppressNewFeatures = true;
                        //Conf.eSetSupprimerNouvellesFonctions(true, MdlBase);
                    }

                    foreach (String NomConfig in ListeNomsConfig)
                    {
                        _NomConfigActive = NomConfig;
                        _MdlBase.ShowConfiguration2(NomConfig);
                        _MdlBase.EditRebuild3();

                        pidBase.Maj(ref CompBase);
                        pidFace.Maj(ref Face);
                        pidPlan.Maj(ref Plan);

                        Run(CompBase);
                    }

                    InsererDansUnDossier();

                    foreach (String NomConfig in ListeNomsConfig)
                    {
                        _NomConfigActive = NomConfig;
                        _MdlBase.ShowConfiguration2(NomConfig);
                        _MdlBase.EditRebuild3();

                        List <String> ListeComp = _DicConfigWithComp[NomConfig];
                        foreach (String NomComp in _ListePercage.Keys)
                        {
                            if (!ListeComp.Contains(NomComp))
                            {
                                _MdlBase.eSelectByIdComp(_ListePercage[NomComp]);
                                _AssBase.eModifierEtatComposant(swComponentSuppressionState_e.swComponentSuppressed);
                                _MdlBase.eEffacerSelection();
                            }
                        }
                    }

                    _MdlBase.ShowConfiguration2(_NomConfigCourante);
                }
                else
                {
                    Run(CompBase);
                    InsererDansUnDossier();
                }

                // On met les percages dans un dossier, c'est plus propre

                _MdlBase.EditRebuild3();
            }
            catch (Exception e)
            {
                this.LogErreur(new Object[] { e });
            }
        }
예제 #16
0
        private void saveSTL(link Link, string windowsMeshFileName)
        {
            int errors   = 0;
            int warnings = 0;

            string coordsysName = "";

            coordsysName = (Link.Joint == null || Link.Joint.CoordinateSystemName == null) ? Link.CoordSysName : Link.Joint.CoordinateSystemName;

            Dictionary <string, string> names = GetComponentRefGeoNames(coordsysName);
            ModelDoc2 ActiveDoc = ActiveSWModel;

            string     ComponentName     = "";
            string     ConfigurationName = "";
            string     DisplayStateName  = "";
            Component2 geoComponent      = default(Component2);

            if (names["component"].Length > 0)
            {
                foreach (Component2 comp in Link.SWcomponents)
                {
                    if (comp.Name2 == names["component"])
                    {
                        geoComponent      = comp;
                        ComponentName     = comp.GetPathName();
                        ConfigurationName = comp.ReferencedConfiguration;
                        DisplayStateName  = comp.ReferencedDisplayState;
                        bool usenamed = comp.UseNamedConfiguration;
                        ActiveDoc = (ModelDoc2)iSwApp.ActivateDoc3(ComponentName, false, 0, 0);

                        Configuration config = ActiveDoc.GetConfigurationByName(ConfigurationName);
                        ActiveDoc.ShowConfiguration2(ConfigurationName);
                        config.ApplyDisplayState(DisplayStateName);
                    }
                    break;
                }
            }

            if (ComponentName.Length == 0)
            {
                Common.showComponents(ActiveSWModel, Link.SWcomponents);
            }

            int saveOptions = (int)swSaveAsOptions_e.swSaveAsOptions_Silent;

            setLinkSpecificSTLPreferences(names["geo"], Link.STLQualityFine, ActiveDoc);

            ActiveDoc.Extension.SaveAs(windowsMeshFileName, (int)swSaveAsVersion_e.swSaveAsCurrentVersion, saveOptions, null, ref errors, ref warnings);
            if (ComponentName.Length > 0)
            {
                iSwApp.CloseDoc(ComponentName);
                geoComponent.ReferencedConfiguration = ConfigurationName;
            }
            else
            {
                Common.hideComponents(ActiveSWModel, Link.SWcomponents);
            }


            correctSTLMesh(windowsMeshFileName);
        }
예제 #17
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
                }
예제 #18
0
        public void GetXMLfromBOM()
        {
            swapp   = (SldWorks)Marshal.GetActiveObject("SldWorks.Application");
            swmodel = swapp.ActiveDoc;

            swModelDocExt = swmodel.Extension;

            //создаем MemoryStream, в который будем писать XML
            var myMemoryStream = new MemoryStream();

            //создаем XmlTextWriter, указываем объект – myMemoryStream, в который будем писать XML, и кодировку
            try
            {
                var myXml = new System.Xml.XmlTextWriter("C:\\Program Files\\SW-Complex\\SP-Temp.xml", System.Text.Encoding.UTF8);
                swDraw      = (DrawingDoc)swmodel;
                vSheetNames = swDraw.GetSheetNames();
                ok          = swDraw.ActivateSheet(vSheetNames[0]);
                swView      = swDraw.GetFirstView();

                // Получаем параметры модели
                swView  = swView.GetNextView();
                swmodel = swView.ReferencedDocument;

                //swSelMgr = swDraw.SelectionManager;

                myXml.WriteStartDocument();
                myXml.Formatting = System.Xml.Formatting.Indented;

                //длина отступа
                myXml.Indentation = 2;
                vConfName         = swmodel.GetConfigurationNames();


                swapp   = new SldWorks();
                swmodel = swapp.ActiveDoc;

                Feature swFeat = swmodel.FirstFeature();

                while ((swFeat != null))
                {
                    if (swFeat.GetTypeName() == "BomFeat")
                    {
                        swFeat.Select(true);
                        swBomFeature = swFeat.GetSpecificFeature2();
                    }
                    swFeat = swFeat.GetNextFeature();
                }

                //////////////////////////////////////////////////////
                //
                //           GetPropertyBomTableFromDrawDoc
                //
                //////////////////////////////////////////////////////

                object          vConfigurations   = null;
                object          vVisibility       = null;
                bool            bGetVisible       = false;
                long            lNumRow           = 0;
                long            lNumColumn        = 0;
                int             lRow              = 0;
                TableAnnotation swTableAnnotation = default(TableAnnotation);
                ModelDoc2       swDocument        = default(ModelDoc2);
                AssemblyDoc     swAssembly        = default(AssemblyDoc);
                int             lStartRow         = 0;
                string          strItemNumber     = "";
                string          strPartNumber     = "";
                string          strDescription    = "";

                var strDocumentName = swBomFeature.GetReferencedModelName();

                swDocument = swapp.GetOpenDocumentByName(strDocumentName);
                swAssembly = (AssemblyDoc)swDocument;

                //swBOMTableAnnotation = swBomFeature.GetTableAnnotations(0)
                var swBomTableAnnotation = (BomTableAnnotation)swBomFeature.GetTableAnnotations()[0];

                swTableAnnotation = (TableAnnotation)swBomTableAnnotation;

                lNumRow    = swTableAnnotation.RowCount;
                lNumColumn = swTableAnnotation.ColumnCount;

                lStartRow = 1;

                //If (Not (swTableAnnotation.TitleVisible = False)) Then
                if (swTableAnnotation.TitleVisible == false)
                {
                    lStartRow = 2;
                }

                bGetVisible     = false;
                vConfigurations = swBomFeature.GetConfigurations(bGetVisible, vVisibility);

                //swTableAnnotation = swTableAnnotation;

                ///////////////////////////////////////////////////////////////////

                swSheet            = swDraw.GetCurrentSheet();
                strActiveSheetName = swSheet.GetName();
                vSheetNames        = swDraw.GetSheetNames();
                ok      = swDraw.ActivateSheet(vSheetNames[0]);
                swSheet = swDraw.GetCurrentSheet();
                swView  = swDraw.GetFirstView();

                if (swSheet.CustomPropertyView == "По умолчанию" | swSheet.CustomPropertyView == "Default")
                {
                    swView = swView.GetNextView();
                }

                // get custom property

                var valout  = ""; //Обозначение
                var valout1 = ""; //Наименование


                CustomPropertyManager swCustProp = default(CustomPropertyManager);
                var resolvedValOut  = "";
                var resolvedValOut1 = "";
                //string resolvedValOut3 = "";
                //string resolvedValOut4 = "";
                //string resolvedValOut5 = "";
                swCustProp = swmodel.Extension.CustomPropertyManager[""];
                swCustProp.Get2("Обозначение", out valout, out resolvedValOut);
                swCustProp.Get2("Description", out valout1, out resolvedValOut1);

                // переменные для колонок

                int Jj = 0;             // наименование
                int aa = 0;             // раздел
                int oo = 0;             // обозначение
                int tt = 0;             // формат
                int yy = 0;             //
                int uu = 0;             // Код материала
                int ss = 0;             // Примечание

                string sRowStr  = null; // наименовани
                string sRowStr1 = null; // раздел
                string sRowStr2 = null; // обозначение
                string sRowStr3 = null; // формат
                string sRowStr4 = null; // ERP code
                string sRowStr5 = null; // Код материала
                string sRowStr6 = null; // Примечание

                // При выборе электромонтажа
                string Complect = "";

                if (addinform.ChkElectro1.Checked)
                {
                    Complect = "МЭ";
                }
                else if (addinform.ChkElectro2.Checked)
                {
                    Complect = "ТБ";
                }

                ////////////////////////////////////////////////////////////
                //
                //                          XML
                //
                ////////////////////////////////////////////////////////////

                //создаем элементы
                myXml.WriteStartElement("xml");
                //
                myXml.WriteStartElement("Item");

                // имя пути основного чертежа
                myXml.WriteStartElement("PathName");
                //записываем строку
                myXml.WriteString(swmodel.GetPathName());
                myXml.WriteEndElement();

                // Устанавливаем ДОК из формы добавление
                myXml.WriteStartElement("doc");
                //
                myXml.WriteStartElement("Обозначение");
                //записываем строку
                myXml.WriteString(resolvedValOut + "CБ");
                myXml.WriteEndElement();
                //
                myXml.WriteStartElement("Наименование");
                myXml.WriteString("Сборочный чертеж");
                myXml.WriteEndElement();
                //
                myXml.WriteEndElement(); //doc

                //dynamic CheckedRows2 = (from Rows in addinform.DGDoc.Rows.Cast<DataGridViewRow>()where Convert.ToBoolean(Rows.Cells(0).Value) == true).ToList;

                dynamic CheckedRows2 = (from Rows in addinform.DGDoc.Rows.Cast <DataGridViewRow>() where Convert.ToBoolean(Rows.Cells[0].Value.ToString()) select Rows).ToList();


                System.Text.StringBuilder sb = new System.Text.StringBuilder();

                foreach (DataGridViewRow row in CheckedRows2)
                {
                    sb.AppendLine(row.Cells[1].Value.ToString());
                    sb.ToString();

                    //Оставляем первые две буквы для обозначения разделитель

                    var literal   = row.Cells[1].Value.ToString();
                    var substring = literal.Substring(0, 2);

                    var literal2   = row.Cells[1].Value.ToString();
                    var substring2 = literal2.Substring(5);

                    myXml.WriteStartElement("doc");
                    ///
                    myXml.WriteStartElement("Обозначение");
                    //записываем строку
                    myXml.WriteString(resolvedValOut + substring);
                    myXml.WriteEndElement();
                    ///
                    myXml.WriteStartElement("Наименование");
                    myXml.WriteString(substring2);
                    myXml.WriteEndElement();
                    ///
                    myXml.WriteEndElement();
                    //doc
                }


                //<------------- Elec
                if (addinform.ChkElectro.Checked == true & addinform.ChkElectro1.Checked == false & addinform.ChkElectro2.Checked == false)
                {
                    myXml.WriteStartElement("Elec");
                    //Elec

                    myXml.WriteString("Устанавливают при электромонтаже");
                    myXml.WriteEndElement();
                    //Elec
                }

                //<------------- ChkElectro1
                if (addinform.ChkElectro.Checked == true & addinform.ChkElectro1.Checked == true)
                {
                    myXml.WriteStartElement("Elec");
                    //Elec
                    myXml.WriteString("Устанавливают по " + resolvedValOut + Complect);
                    myXml.WriteEndElement();
                    //Elec
                }

                //<------------- ChkElectro2
                if (addinform.ChkElectro.Checked == true & addinform.ChkElectro2.Checked == true)
                {
                    myXml.WriteStartElement("Elec");
                    //Elec
                    myXml.WriteString("Устанавливают по " + resolvedValOut + Complect);
                    myXml.WriteEndElement();
                    //Elec
                }

                //
                myXml.WriteStartElement("Обозначение");
                //записываем строку
                myXml.WriteString(resolvedValOut);
                myXml.WriteEndElement();
                ///
                myXml.WriteStartElement("Наименование");
                myXml.WriteString(resolvedValOut1);
                myXml.WriteEndElement();

                //\reference
                myXml.WriteStartElement("references");

                // ВЫГРУЖАЕМ ВЫБРАННЫЕ КОНФИГУРАЦИИ

                dynamic CheckedRows           = (from Rows in DataGridConfig.Rows.Cast <DataGridViewRow>() where Convert.ToBoolean(Rows.Cells[0].Value.ToString()) select Rows).ToList();
                System.Text.StringBuilder sb2 = new System.Text.StringBuilder();

                foreach (DataGridViewRow row in CheckedRows)
                {
                    sb2.AppendLine(row.Cells[1].Value.ToString());

                    swmodel = swView.ReferencedDocument;
                    var configuration = swView.ReferencedConfiguration;

                    var           sConfigName = swView.ReferencedConfiguration;
                    Configuration swConfig    = swmodel.GetConfigurationByName(sConfigName);

                    for (var i = 0; i <= vConfName.GetUpperBound(0); i++)
                    {
                        const string ucase = "";

                        if (vConfName[i] == row.Cells[1].Value.ToString())
                        {
                            configuration = vConfName[i];
                        }
                    }

                    swView.ReferencedConfiguration = sConfigName;

                    myXml.WriteStartElement("config");
                    myXml.WriteAttributeString("value", row.Cells[1].Value.ToString());


                    /////////////////////////////////////////////////////////////
                    //
                    //                           PART
                    //
                    /////////////////////////////////////////////////////////////

                    for (lRow = lStartRow; lRow <= (lNumRow - 1); lRow++)
                    {
                        if (swBomTableAnnotation.GetComponentsCount2((int)lRow, row.Cells[1].Value.ToString(), out strItemNumber, out strPartNumber) > 0)
                        {
                            myXml.WriteStartElement("part");
                            //PathNameComponent
                            string strModelPathName = null;
                            var    vModelPathNames  = swBomTableAnnotation.GetModelPathNames((int)lRow, out strItemNumber, out strPartNumber);
                            if (((vModelPathNames != null)))
                            {
                                myXml.WriteStartElement("PathNameComponent");
                                foreach (var vModelPathName_loopVariable in vModelPathNames)
                                {
                                    var vModelPathName = vModelPathName_loopVariable;
                                    strModelPathName = vModelPathName;
                                    myXml.WriteString(strModelPathName);
                                }
                                myXml.WriteEndElement();
                            }
                            //'\ Row
                            myXml.WriteStartElement("Row");
                            myXml.WriteString(Convert.ToString(lRow - lStartRow + 1));
                            myXml.WriteEndElement();
                            vModelPathNames = swBomTableAnnotation.GetModelPathNames((int)lRow, out strItemNumber, out strPartNumber);
                            //\ ItemNum
                            myXml.WriteStartElement("ItemNum");
                            myXml.WriteString(strItemNumber);
                            myXml.WriteEndElement();
                            //\ раздел
                            aa = 3;
                            /// раздел
                            sRowStr1 = "";
                            sRowStr1 = sRowStr1 + swTableAnnotation.Text[lRow, aa];
                            myXml.WriteStartElement("Раздел");
                            myXml.WriteString(sRowStr1);
                            myXml.WriteEndElement();
                            //\ обозначение
                            oo = 1;
                            /// обозначение
                            sRowStr2 = "";
                            sRowStr2 = sRowStr2 + swTableAnnotation.Text[lRow, oo];
                            myXml.WriteStartElement("Обозначение");
                            myXml.WriteString(sRowStr2);
                            myXml.WriteEndElement();
                            //\ наименование
                            Jj = 2;
                            /// наименование
                            sRowStr = "";
                            sRowStr = sRowStr + swTableAnnotation.Text[lRow, Jj];
                            myXml.WriteStartElement("Наименование");
                            myXml.WriteString(sRowStr);
                            myXml.WriteEndElement();
                            //\
                            tt = 4;
                            /// формат
                            sRowStr3 = "";
                            sRowStr3 = sRowStr3 + swTableAnnotation.Text[lRow, tt];
                            myXml.WriteStartElement("Формат");
                            myXml.WriteString(sRowStr3);
                            myXml.WriteEndElement();
                            //\
                            yy = 5;
                            /// ERP code
                            sRowStr4 = "";
                            sRowStr4 = sRowStr4 + swTableAnnotation.Text[lRow, yy];
                            myXml.WriteStartElement("ERP_code");
                            myXml.WriteString(sRowStr4);
                            myXml.WriteEndElement();
                            //\
                            uu = 6;
                            /// Код материала
                            sRowStr5 = "";
                            sRowStr5 = sRowStr5 + swTableAnnotation.Text[lRow, uu];
                            myXml.WriteStartElement("Код_материала");
                            myXml.WriteString(sRowStr5);
                            myXml.WriteEndElement();
                            //\
                            ss = 7;
                            /// наименование
                            sRowStr6 = "";
                            sRowStr6 = sRowStr6 + swTableAnnotation.Text[lRow, ss];
                            myXml.WriteStartElement("Примечание");
                            myXml.WriteString(sRowStr6);
                            myXml.WriteEndElement();
                            //\

                            myXml.WriteStartElement("Количество");
                            //myXml.WriteString(swTableAnnotation.GetComponentsCount2(lRow, strConfiguration, strItemNumber, strPartNumber))
                            myXml.WriteString(Convert.ToString(swBomTableAnnotation.GetComponentsCount2(lRow, row.Cells[1].Value.ToString(), out strItemNumber, out strPartNumber)));
                            myXml.WriteEndElement();
                            myXml.WriteEndElement();
                            //config
                        }
                    }


                    myXml.WriteEndElement(); //part
                }


                myXml.WriteEndElement(); //references
                //<~~~~~~~~~~~~~~~~~~~~~~~~~~~ Get the Total Number of Rows


                Annotation      swAnn   = default(Annotation);
                TableAnnotation swTable = default(TableAnnotation);
                long            nNumRow = 0;

                swmodel = swapp.ActiveDoc;

                swView  = swDraw.GetFirstView();
                swTable = swView.GetFirstTableAnnotation();
                swAnn   = swTable.GetAnnotation();

                nNumRow = swTable.RowCount;
                myXml.WriteStartElement("TotalRows");
                myXml.WriteString(Convert.ToString(nNumRow));
                myXml.WriteEndElement();
                //end TotalRows

                myXml.WriteEndElement();
                //Item
                myXml.WriteEndElement();
                //элемент XML

                //End If
                //заносим данные в myMemoryStream
                myXml.Flush();
                myXml.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                throw;
            }
        }
예제 #19
0
        /// <summary>
        ///  Method which the encapsulates proccess building dxf view on based SolidWorks part.
        /// </summary>
        /// <param name="partPath">path to sorce part file</param>
        /// <param name="idPdm">id in pdm system</param>
        /// <param name="version">current or last version build file</param>
        /// <param name="includeNonSheetParts">set whether you want build dxf views from non sheet parts</param>
        /// <returns></returns>
        private bool Build(string partPath, int idPdm, int version, bool includeNonSheetParts)
        {
            // callback message code from solidWorks
            // int error = 0, warnings = 0;

            MessageObserver.Instance.SetMessage("Start build Dxf file", MessageType.System);

            bool isSave = false;

            try
            {
                ModelDoc2 modelDoc = null;
                if (!string.IsNullOrEmpty(partPath))
                {
                    try
                    {
                        modelDoc = SolidWorksAdapter.OpenDocument(partPath, swDocumentTypes_e.swDocPART);// SolidWorksAdapter.SldWoksAppExemplare.OpenDoc6(partPath, (int)  swDocumentTypes_e.swDocPART , (int)swOpenDocOptions_e.swOpenDocOptions_Silent, emptyConfigyration, error, warnings);

                        //modelDoc = SolidWorksAdapter.SldWoksAppExemplare.IActiveDoc2;

                        MessageObserver.Instance.SetMessage("\tOpened document " + Path.GetFileName(partPath), MessageType.System);
                        // Проверяет наличие дерева постоения в моделе.
                        if (modelDoc == null)
                        {
                            return(isSave);
                        }
                    }
                    catch (Exception exception)
                    {
                        MessageObserver.Instance.SetMessage("\tFailed open SolidWorks document; message exception {" + exception.ToString() + " }", MessageType.Error);
                        throw exception;
                    }
                }
                bool isSheetmetal = true;
                //modelDoc.ForceRebuild3(false);

                IPartDoc part = (IPartDoc)modelDoc;
                if (!SolidWorksAdapter.IsSheetMetalPart(part))
                {
                    isSheetmetal = false;
                    if (!includeNonSheetParts) // disable build  no sheet metal parts if IsSheetMetalPart = false, and return
                    {
                        try
                        {
                            //SolidWorksAdapter.SldWoksAppExemplare.CloseDoc(modelDoc.GetTitle().ToLower().Contains(".sldprt") ? modelDoc.GetTitle() : modelDoc.GetTitle() + ".sldprt");
                            if (modelDoc != null)
                            {
                                SolidWorksAdapter.SldWoksAppExemplare.CloseDoc(modelDoc.GetTitle());
                            }
                            //SolidWorksAdapter.SldWoksAppExemplare.ExitApp();
                        }
                        catch (Exception ex)
                        {
                            MessageObserver.Instance.SetMessage("Неудалось закрыть файл " + ex.Message);
                        }
                        return(isSave);
                    }
                }
                string[] swModelConfNames2 = (string[])modelDoc.GetConfigurationNames();


                var configurations = from name in swModelConfNames2
                                     let config = (Configuration)modelDoc.GetConfigurationByName(name)
                                                  where !config.IsDerived()
                                                  select name;

                MessageObserver.Instance.SetMessage("\t got configuration " + configurations.Count() + " for opened document. Statrt bust configurations", MessageType.System);

                foreach (var eachConfiguration in configurations)
                {
                    modelDoc.ShowConfiguration2(eachConfiguration);
                    //modelDoc.Visible = true;
                    //modelDoc.EditRebuild3();

                    MessageObserver.Instance.SetMessage("\t Show configuration " + eachConfiguration, MessageType.System);
                    if (isSheetmetal)
                    {
                        Bends bends = Bends.Create(modelDoc, eachConfiguration);
                        bends.Fix();

                        MessageObserver.Instance.SetMessage("\t Fix bends " + eachConfiguration, MessageType.System);
                    }

                    byte[] dxfByteCode;
                    DXF    dxf;

                    if (!Directory.Exists(DxfFolder))
                    {
                        Directory.CreateDirectory(DxfFolder);
                    }

                    if (DxfFolder != null && DxfFolder != string.Empty)
                    {
                        dxf = new DXF(DxfFolder);
                    }
                    else
                    {
                        dxf = new DXF();
                    }

                    isSave = dxf.ConvertToDXF(eachConfiguration, modelDoc, out dxfByteCode, isSheetmetal);

                    var dataToExport = CutList.GetDataToExport(modelDoc);

                    if (isSave)
                    {
                        MessageObserver.Instance.SetMessage("\t" + eachConfiguration + " succsess building. Add to result list", MessageType.Success);
                        // конфигурация получена при выполнении GetDataToExport
                        try
                        {
                            dataToExport.DXFByte       = dxfByteCode;
                            dataToExport.Configuration = eachConfiguration;
                            dataToExport.IdPdm         = idPdm;
                            dataToExport.Version       = version;
                            if (FinishedBuilding != null)
                            {
                                FinishedBuilding(dataToExport);
                            }
                        }
                        catch (Exception exception)
                        {
                            MessageObserver.Instance.SetMessage("\tFailed at notification about finished; message exception {" + exception.ToString() + " }", MessageType.Error);
                        }
                    }
                }
                SolidWorksAdapter.SldWoksAppExemplare.CloseDoc(modelDoc.GetTitle().ToLower().Contains(".sldprt") ? modelDoc.GetTitle() : modelDoc.GetTitle() + ".sldprt"); // out in func...
                //SolidWorksAdapter.SldWoksAppExemplare.ExitApp( );
            }

            catch (Exception ex)
            {
                MessageObserver.Instance.SetMessage("\tFailed build dxf; message exception {" + ex.ToString() + " }", MessageType.Error);
                throw ex;
            }
            return(isSave);
        }
        static public List <ColumnNameTable> ListColumn(ModelDoc2 swModel)
        {
            var columnRow = new List <ColumnNameTable>();

            object[] configNamesDll = swModel.GetConfigurationNames();

            var i = 1;

            foreach (string configName in configNamesDll)
            {
                Configuration swConf = swModel.GetConfigurationByName(configName);

                if (swConf.IsDerived() == false)
                {
                    var customPropMan = swModel.Extension.CustomPropertyManager[configName];

                    string valOut;

                    string number;
                    string performance;
                    string mass;
                    string description;
                    string matName;
                    string thickness;
                    string codFb;

                    const string propNumber      = "Обозначение";
                    const string propPerformance = "Исполнение";
                    const string propMass        = "Масса";
                    const string propDescription = "Наименование";
                    const string propThickness   = "Толщина листового металла";

                    customPropMan.Get4(propNumber, true, out valOut, out number);
                    customPropMan.Get4(propPerformance, true, out valOut, out performance);
                    customPropMan.Get4(propMass, true, out valOut, out mass);
                    customPropMan.Get4(propDescription, true, out valOut, out description);

                    customPropMan.Get4("Код_ФБ", true, out valOut, out codFb);
                    customPropMan.Get4("Материал_Имя", true, out valOut, out matName);
                    customPropMan.Get4(propThickness, true, out valOut, out thickness);

                    // Удаление из строки до определенного символа
                    //var trimStr = matName.Substring(matName.IndexOf('>') + 1);
                    //var matNameTrim = trimStr.Substring(trimStr.IndexOf('>') + 1);

                    var columnNameClass = new ColumnNameTable()
                    {
                        Number      = number,
                        Performance = performance,
                        Mass        = mass,
                        Config      = configName,
                        Description = description,
                        Thickness   = thickness,
                        CodFb       = codFb,
                        //MatName = matName.Replace("$PRPSHEET:\"Толщина листового металла\"", thickness)
                        MatName = matName
                    };

                    columnNameClass.Riz = i++.ToString();

                    columnRow.Add(columnNameClass);
                }
            }

            return(columnRow);
        }
예제 #21
0
        public List <SldWorksPropClass> GetSldWorksListProp()
        {
            // MessageBox.Show(SwModel.GetPathName());
            var columnRow = new List <SldWorksPropClass>();

            try
            {
                string[] ConfigArray = SwModel.GetConfigurationNames();

                for (var i = 0; i <= ConfigArray.GetUpperBound(0); i++)
                {
                    Configuration swConf = SwModel.GetConfigurationByName(ConfigArray[i]);

                    if (swConf.IsDerived())
                    {
                        continue;
                    }
                    var customProp = SwModel.Extension.CustomPropertyManager[ConfigArray[i]];

                    string description;
                    string valOut;
                    string note;
                    //string matId;
                    string code1c;
                    string lenght;
                    string width;
                    string summ;

                    //const string propMatId = "MaterialID";
                    const string propDescription = "Наименование";
                    const string propLinght      = "Длина";
                    const string propWight       = "Ширина";
                    const string propSumm        = "Количество";
                    const string propNote        = "Примечание";
                    const string propCode1C      = "Код материала";

                    //customProp.Get4(propMatId, true, out valOut, out matId);
                    customProp.Get4(propDescription, true, out valOut, out description);
                    customProp.Get4(propLinght, true, out valOut, out lenght);
                    customProp.Get4(propWight, true, out valOut, out width);
                    customProp.Get4(propSumm, true, out valOut, out summ);
                    customProp.Get4(propNote, true, out valOut, out note);
                    customProp.Get4(propCode1C, true, out valOut, out code1c);

                    //if (matId == "")
                    //{
                    //    MessageBox.Show("Примените материал на модель!");
                    //    Close();
                    //    break;
                    //}

                    if (SwModel.GetType() == (int)swDocumentTypes_e.swDocPART)
                    {
                        foreach (var matName in _sM.GetCustomProperty(ConfigArray[i], SwApp))
                        {
                            var sldWorksPropArray = new SldWorksPropClass
                            {
                                Config      = ConfigArray[i],
                                Description = _sM.CheckType == 0 ? description : matName.Name,
                                //Description = matName.Name == "" ? "" : matName.Name,
                                //MatId = matId == "" ? "" : matId,
                                Code1C = code1c == "" ? "" : code1c,
                                Length = lenght == "" ? "" : lenght,
                                Width  = width == "" ? "" : width,
                                Summ   = summ == "" ? "" : summ,
                                Note   = note == "" ? "" : note
                            };

                            columnRow.Add(sldWorksPropArray);
                        }
                    }

                    if (SwModel.GetType() == (int)swDocumentTypes_e.swDocASSEMBLY)
                    {
                        var sldWorksPropArray = new SldWorksPropClass
                        {
                            Config      = ConfigArray[i],
                            Description = description,
                            Code1C      = code1c == "" ? "" : code1c,
                            Length      = lenght == "" ? "" : lenght,
                            Width       = width == "" ? "" : width,
                            Summ        = summ == "" ? "" : summ,
                            Note        = note == "" ? "" : note
                        };

                        columnRow.Add(sldWorksPropArray);
                    }



                    Debug.Print("Примечание - {0}, Материал ID - {1}, Длина - {2}, Ширина - {3}, Количество - {4}", note, "matId", lenght, width, summ);
                }
                return(columnRow);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Message: {ex.Message}\r\nTargetSite: {ex.TargetSite}\r\nStackTrace: {ex.StackTrace}");
            }

            return(columnRow);
        }