Esempio n. 1
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());
        }
        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);
        }
Esempio n. 3
0
        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"));
        }
Esempio n. 4
0
        public List <Files.Info> Convert(SldWorks swApp, List <Files.Info> filesToConvert)
        {
            var ListForBatchAdd = new List <Files.Info>();
            var fileNameErr     = "";

            foreach (var item in filesToConvert)
            {
                fileNameErr = item.FullFilePath;
                edmTaskInstance.SetProgressPos(filesToProceed++, item.FullFilePath);

                Logger.Add($"Open in Solidworks : {item.FileName}");

                ModelDoc2 swModel = swApp.OpenDoc6(item.FullFilePath, (int)swDocumentTypes_e.swDocPART, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", 0, 0);

                // Запуск конвертации только для литовых деталей

                if (IsSheetMetalPart(swModel))
                {
                    Exception exOut = null;

                    var confArray = (object[])swModel.GetConfigurationNames();

                    bool isFix = false;
                    ExportDataToXmlSql(swApp, item, swModel, ref exOut, confArray, out isFix);
                    ConvertToDxf(swApp, item, swModel, ref exOut, confArray, isFix);

                    //   ConvertToEprt(swApp, ListForBatchAdd, item, swModel);
                }

                Logger.Add($"CloseDoc: {item.FileName}");
                swApp.CloseDoc(item.FullFilePath);
            }

            return(ListForBatchAdd);
        }
        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;
        }
        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;
        }
Esempio n. 7
0
        public void PurgeUnused()
        {
            ModelDoc2            swModel  = iSwApp.ActiveDoc;
            Configuration        swConf   = swModel.GetActiveConfiguration();
            var                  cfgNames = swModel.GetConfigurationNames();
            ConfigurationManager swCfgMgr = swModel.ConfigurationManager;

            Component2 swRootComp = swConf.GetRootComponent3(true);
            Boolean    bRet       = true;
            int        i;
            string     configName   = "";
            object     ConfigValues = new object();
            object     ConfigParams = new object();
            var        vChildComp   = swRootComp.GetChildren();

            for (i = 0; i <= vChildComp.GetUpperBound(0); i++)
            {
                Component2 swChildComp = vChildComp[i];

                bRet = swCfgMgr.GetConfigurationParams(configName, out ConfigParams, out ConfigValues);

                //if (swChildComp.GetSuppression() == 0)
                //{
                //    MessageBox.Show(swChildComp.Name2 + " is suppressed");
                //    swChildComp.Select(true);
                //    swModel.EditDelete();

                //}
            }
        }
        /// <summary>
        /// Sets the current robot that is linked to this page
        /// </summary>
        /// <param name="robot">robot to be used</param>
        /// <param name="model">model to be used</param>
        public void setRobot(RobotModel robot, ModelDoc2 model)
        {
            this.robot = robot;
            robotName.Text = robot.Name;

            string[] configurations = model.GetConfigurationNames();

            IncludeFRCfieldBox.Visible = PluginSettings.UseFRCsim;
            if (PluginSettings.UseFRCsim)
            {
                switch (robot.FRCfield)
                {
                    case 2014:
                        FRC2014FieldButton.Checked = true;
                        break;
                    case 2015:
                        FRC2015FieldButton.Checked = true;
                        break;
                    default:
                        NoFieldButton.Checked = true;
                        break;
                }
            }
            if (robot.ExportType == 0)
                SDFExportTypeButton.Checked = true;
            else
                URDFExportTypeButton.Checked = true;
        }
        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            if (Connect())
            {
                // Set step v214 as default
                app.SetUserPreferenceIntegerValue((int)swUserPreferenceIntegerValue_e.swStepAP, 214);

                // Get extention
                ComboBoxItem selectedItem = (ComboBoxItem)FormatCombo.SelectedItem;
                string       extention    = selectedItem.Content.ToString();

                // Get path
                string newPath = DirectoryTextBox.Text;
                if (newPath is "")
                {
                    newPath = path;
                }

                // Check newPath
                if (!Directory.Exists(newPath))
                {
                    MessageBox.Show("Error: Invalid output directory!");
                    return;
                }

                // Save all configurations
                foreach (string configurationName in (string[])doc.GetConfigurationNames())
                {
                    // Activate configuration
                    doc.ShowConfiguration2(configurationName);
                    Configuration config = doc.ConfigurationManager.ActiveConfiguration;

                    // Save all display states
                    foreach (string displayStateName in (string[])config.GetDisplayStates())
                    {
                        // Filename
                        string filename = String.Format(
                            "{0}{1}-{2}{3}",
                            newPath + System.IO.Path.DirectorySeparatorChar,
                            configurationName,
                            displayStateName,
                            extention
                            );

                        // Select display state
                        config.ApplyDisplayState(displayStateName);

                        // Save model
                        doc.SaveAs2(filename, (int)swSaveAsVersion_e.swSaveAsCurrentVersion, true, true);
                    }
                }
            }
        }
Esempio n. 10
0
        bool IsSuppressedEdgeFlange(string featureName)
        {
            modelDoc.Extension.SelectByID2(featureName, "BODYFEATURE", 0, 0, 0, false, 0, null, 0);
            var swSelMgr = (SelectionMgr)modelDoc.SelectionManager;
            var swFeat   = (Feature)swSelMgr.GetSelectedObject6(1, -1);

            bool[] states = swFeat.IsSuppressed2(2, modelDoc.GetConfigurationNames());
            bool   stat   = states[0];

            modelDoc.ClearSelection2(true);
            return(stat);
        }
Esempio n. 11
0
        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                this.Close();
            }
            else if (e.Key == Key.S && e.KeyboardDevice.IsKeyDown(Key.LeftCtrl))
            {
                SaveAll();
            }
            else if (e.Key == Key.F5)
            {
                SwModel = (ModelDoc2)SwApp.ActiveDoc;
                if (SwModel != null)
                {
                    if (((int)SwModel.GetType() != (int)swDocumentTypes_e.swDocPART) && ((int)SwModel.GetType() != (int)swDocumentTypes_e.swDocASSEMBLY))
                    {
                        MessageBox.Show("当前文件不是零件或装配体文件!");
                        Environment.Exit(0);
                    }
                }
                else
                {
                    MessageBox.Show("请打开零件或装配体文件!");
                    Environment.Exit(0);
                }

                SwConfigMgr   = SwModel.ConfigurationManager;
                SwModelExt    = SwModel.Extension;
                SwCustPropMgr = SwModelExt.get_CustomPropertyManager("");

                string[] configNames = null;
                configNames = (string[])SwModel.GetConfigurationNames();
                CboxConfigName.Items.Clear();
                for (int i = 0; i < configNames.Length; i++)
                {
                    CboxConfigName.Items.Add(configNames[i]);
                    if (configNames[i].Contains(SwConfigMgr.ActiveConfiguration.Name))
                    {
                        CboxConfigName.Text = SwConfigMgr.ActiveConfiguration.Name;
                    }
                }

                DatePickerDesignDate.SelectedDate = DateTime.Today;

                TextColorReset();

                TextBlock.Text = "已成功连接到SolidWorks文件!   按F5重新载入!";
            }
        }
        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);
        }
Esempio n. 13
0
 public static string [] GetAllConfigurations(out bool lockForConfBox)
 {
     lockForConfBox = false;
     string[] mas = {};
     if (Class.docType != swDocumentTypes_e.swDocDRAWING)
     {
         mas = swModel.GetConfigurationNames();
     }
     else
     {
         lockForConfBox = true;
     }
     return(mas);
 }
Esempio n. 14
0
        private void Reset()
        {
            SwApp = new SldWorks();
            if (SwApp == null)
            {
                MessageBox.Show("未找到已启动的Solidworks主程序!");
                Environment.Exit(0);
            }
            SwApp.Visible = true;

            SwModel = (ModelDoc2)SwApp.ActiveDoc;
            if (SwModel != null)
            {
                if (((int)SwModel.GetType() != (int)swDocumentTypes_e.swDocPART) && ((int)SwModel.GetType() != (int)swDocumentTypes_e.swDocASSEMBLY))
                {
                    MessageBox.Show("当前文件不是零件或装配体文件!");
                    Environment.Exit(0);
                }
            }
            else
            {
                MessageBox.Show("请打开零件或装配体文件!");
                Environment.Exit(0);
            }

            SwConfigMgr   = SwModel.ConfigurationManager;
            SwModelExt    = SwModel.Extension;
            SwCustPropMgr = SwModelExt.get_CustomPropertyManager("");

            string[] configNames = null;
            configNames = (string[])SwModel.GetConfigurationNames();
            CboxConfigName.Items.Clear();
            for (int i = 0; i < configNames.Length; i++)
            {
                CboxConfigName.Items.Add(configNames[i]);
                if (configNames[i].Contains(SwConfigMgr.ActiveConfiguration.Name))
                {
                    //cboxConfigName.SelectedIndex = i;
                    CboxConfigName.Text = SwConfigMgr.ActiveConfiguration.Name;
                }
            }

            DatePickerDesignDate.SelectedDate = DateTime.Today;

            TextColorReset();

            TextBlock.Text = "已成功连接到SolidWorks文件!   按F5重新载入!";
        }
Esempio n. 15
0
        bool IsSuppressedEdgeFlange(string featureName)
        {
            var state = false;

            try
            {
                _swModel.Extension.SelectByID2(featureName, "BODYFEATURE", 0, 0, 0, false, 0, null, 0);
                var swSelMgr = (SelectionMgr)_swModel.SelectionManager;
                var swFeat   = (Feature)swSelMgr.GetSelectedObject6(1, -1);
                var states   = (bool[])swFeat.IsSuppressed2(1, _swModel.GetConfigurationNames());
                state = states[0];
                _swModel.ClearSelection2(true);
            }
            catch (Exception)
            {
            }
            return(state);
        }
Esempio n. 16
0
        public void Change()
        {
            ModelDoc2 swModel = (ModelDoc2)Component.GetModelDoc2();

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

            for (int i = 0; i < names.Length; i++)
            {
                if (NewConfig == names[i])
                {
                    return;
                }
            }

            swModel.ShowConfiguration(OldConfig);
            swModel.AddConfiguration2(NewConfig, "", "", false, false, false, true, 0);

            swModel.Save();
        }
Esempio n. 17
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);
        }
        private async void MessageForm_Load(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();

            dialog.Multiselect = false;
            dialog.Filter      = "Solidworks 3d (*.sldprt;*.sldasm)|*.sldprt;*.sldasm|Parts (*.sldprt)|*.sldprt|Assemblies (*.sldasm)|*.sldasm";

            if (dialog.ShowDialog() != DialogResult.OK)
            {
                this.Close();
                return;
            }

            path = dialog.FileName;
            if (!File.Exists(path))
            {
                this.Close();
                return;
            }


            this.Text = "Loading...";
            this.button_import.Enabled   = false;
            this.comboBox_config.Enabled = false;

            Form1 f = (Form1)this.Owner;

            this.label1.Text      = "Start Solidworks";
            button_import.Enabled = false;
            if (swApp == null)
            {
                swApp = await SolidworksSingleton.GetSwAppAsync();
            }

            this.label1.Text      = "Choose configugation name\n and press import.";
            button_import.Enabled = true;

            string            ext = Path.GetExtension(path);
            swDocumentTypes_e type;

            if (ext.ToLower().Contains("sldprt"))
            {
                type = swDocumentTypes_e.swDocPART;
            }
            else if (ext.ToLower().Contains("sldasm"))
            {
                type = swDocumentTypes_e.swDocASSEMBLY;
            }
            else
            {
                this.Close();
                return;
            }

            try
            {
                int Error   = 0;
                int Warning = 0;
                doc = swApp.OpenDoc6(path, (int)type, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref Error, ref Warning);

                if (Error != 0)
                {
                    MessageBox.Show("Fail to open file");
                    this.Close();
                    return;
                }
                configurations.AddRange(doc.GetConfigurationNames());
                comboBox_config.DataSource = configurations;
                comboBox_config.Enabled    = true;
            }
            catch (Exception)
            {
                throw;
            }
        }
Esempio n. 19
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);
            }
        }
Esempio n. 20
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;
            }
        }
Esempio n. 21
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
                }
Esempio n. 22
0
        private void ListBodies()
        {
            ModelDoc2 swModel = null;
            PartDoc   swPart  = null;
            object    vBody;
            bool      bRet;

            swModel = (ModelDoc2)iswApp.ActiveDoc;
            swModel.ClearSelection2(true);
            Debug.Print("File = " + swModel.GetPathName());

            txtPath.Text = swModel.GetPathName();

            this.Text = System.IO.Path.GetFileName(txtPath.Text);

            switch (swModel.GetType())
            {
            case (int)swDocumentTypes_e.swDocPART:
                swPart = (PartDoc)swModel;
                // Solid bodies
                object[] vBodyArr = null;
                Body2    swBody   = default(Body2);

                MathTransform swMathTrans = null;
                vBodyArr = (object[])swPart.GetBodies2((int)swBodyType_e.swSolidBody, true);

                if ((vBodyArr != null))
                {
                    // Debug.Print("  Number of solid bodies: " + vBodyArr.Length);

                    foreach (object vBody_loopVariable in vBodyArr)
                    {
                        vBody  = vBody_loopVariable;
                        swBody = (Body2)vBody;

                        string[] vConfigName = null;
                        vConfigName = (string[])swModel.GetConfigurationNames();
                        string sMatDB   = "";
                        string sMatName = swBody.GetMaterialPropertyName("", out sMatDB);

                        //bRet = swBody.RemoveMaterialProperty((int)swInConfigurationOpts_e.swAllConfiguration, (vConfigName));

                        // Debug.Print("Body--> " + swBody.Name + " " + "");

                        FeatureType Ftype = 0;

                        var childFeature = (object[])swBody.GetFeatures();

                        foreach (var item in childFeature)
                        {
                            Feature f = (Feature)item;

                            Debug.Print(swBody.Name + "-->" + f.GetTypeName());

                            if (f.GetTypeName() == "MoveCopyBody")
                            {
                                Ftype = FeatureType.Copy;
                            }
                            if (f.GetTypeName() == "MirrorSolid")
                            {
                                Ftype = FeatureType.Mirror;
                            }
                        }

                        Body2 swOriBody = null;

                        string swOriBodyName = "";
                        string swOriBodyBox  = "";

                        if (Ftype != 0)
                        {
                            try
                            {
                                swOriBody = swBody.GetOriginalPatternedBody(out swMathTrans);

                                swOriBodyName = swOriBody.Name;

                                swOriBodyBox = GetBodyBox(swOriBody);
                            }
                            catch (Exception)
                            {
                            }
                        }

                        string bbox = GetBodyBox(swBody);

                        BodyModel tempBodyM = new BodyModel(swBody.Name, sMatName, swOriBodyName, Ftype, bbox);

                        if (bbox == swOriBodyBox && swBody.Name.ToString().Contains(swOriBodyName.ToString()) == false)
                        {
                            if ((int)tempBodyM.featureT == 0)
                            {
                                listBodies_Normally.Items.Add(tempBodyM.name);
                            }
                            else if ((int)tempBodyM.featureT == 1 && tempBodyM.name.Contains("镜向") == true)     //mirror
                            {
                                listBodies_MirrorCopy.Items.Add(tempBodyM.name + "<--M--" + tempBodyM.refBodyname);
                                tempBodyM.comment = "镜向-" + tempBodyM.refBodyname;
                                //tempBodyM.name = "镜像-" + tempBodyM.refBodyname + "-" ;
                            }
                            else if ((int)tempBodyM.featureT == 2 && (tempBodyM.name.Contains("复制") == true || tempBodyM.name.Contains("阵列") == true))      //copy
                            {
                                listBodies_MirrorCopy.Items.Add(tempBodyM.name + "<--C--" + tempBodyM.refBodyname);

                                tempBodyM.comment = "复制-" + tempBodyM.refBodyname;
                            }
                        }
                        else
                        {
                            listBodies_Normally.Items.Add(tempBodyM.name);
                        }

                        bodyModels.Add(tempBodyM);
                    }
                }
                break;

            case (int)swDocumentTypes_e.swDocASSEMBLY:
                //ProcessAssembly(swApp, swModel);
                break;

            default:
                return;
            }

            Debug.Print(bodyModels.Count.ToString());
        }
Esempio n. 23
0
        private void ReloadAllSetParameters(Component2 swTestSelComp)
        {
            #region Очистить все словари местные переменные
            int downPos = 0;

            //закоменчено, т.к. этот код вызывает ошибку внутри солида и его закрытие.
            //замена на похожие методы (ClearSelection2 и т.п.) не помогает
            /*/
            if (!_isMate)
            {
                _swAsmDoc.NewSelectionNotify -= NewSelection;
                _swModel.ClearSelection();
                _swAsmDoc.NewSelectionNotify += NewSelection;
            }
            /*/

            _dictHeightPage.Clear();
            _dictPathPict.Clear();
            _dictionary.Clear();
            _dictConfig.Clear();
            _commonList.Clear();
            _objListChanged.Clear();
            _setNewListForComboBox = true;
            _butPlusTxt.Clear();
            _dimensionConfig.Clear();
            _textBoxListForRedraw.Clear();
            _numbAndTextBoxes.Clear();
            _comboBoxListForRedraw.Clear();
            _namesOfColumnNameFromDimLimits.Clear();
            refobj = null;
            #endregion

            if (swTestSelComp != null)
            {
                if (_mSwAddin.GetParentLibraryComponent(swTestSelComp, out _swSelComp))
                {
                    ModelDoc2 specModel;
                    _swSelComp = _mSwAddin.GetMdbComponentTopLevel(_swSelComp, out specModel);
                    _swSelModel = _swSelComp.IGetModelDoc();

                    #region ссылочный эскиз
                    //bool draft = (specModel.CustomInfo2["", "Required Draft"] == "Yes" ||
                    //    specModel.CustomInfo2[specModel.IGetActiveConfiguration().Name, "Required Draft"] == "Yes");

                    //if (draft)
                    //{
                    //    tabMain.Location = new Point(8, 70);
                    //    var dir = new DirectoryInfo(Path.GetDirectoryName(_mSwAddin.SwModel.GetPathName()));

                    //    var paths =
                    //        dir.GetFiles(
                    //            Path.GetFileNameWithoutExtension(specModel.GetPathName()) + ".SLDDRW",
                    //            SearchOption.AllDirectories);
                    //    string path=null;

                    //    if (paths.Any())
                    //        path = paths[0].FullName;
                    //    else
                    //    {
                    //        if (SwAddin.needWait)
                    //        {
                    //            path = Path.Combine(Path.GetDirectoryName(specModel.GetPathName()),
                    //                                Path.GetFileNameWithoutExtension(specModel.GetPathName()) +
                    //                                ".SLDDRW");
                    //            ThreadPool.QueueUserWorkItem(CheckDWRexistAfterCopy, path);
                    //        }
                    //    }

                    //    if (!string.IsNullOrEmpty(path))
                    //    {
                    //        linkLabel1.Name = path;
                    //        linkLabel1.Click += LinkLabel1Click;
                    //        string textInfo = specModel.CustomInfo2["", "Sketch Number"];
                    //        if (textInfo == "" || textInfo == "0" || textInfo == "Sketch Number")
                    //            linkLabel1.Text = @"ЭСКИЗ № н/о";
                    //        else
                    //            linkLabel1.Text = @"ЭСКИЗ № " + textInfo;
                    //    }
                    //    else
                    //        tabMain.Location = new Point(8, 40);
                    //}
                    //else
                    //{
                    //    tabMain.Location = new Point(8, 40);
                    //    linkLabel1.Text = "";
                    //}
                    #endregion

                    _lblPrm.Clear();
                    _btnPrm.Clear();

                    tbpParams.Controls.Clear();
                    tbpPos.Controls.Clear();

                    lblCompName.Text = _swSelComp.Name2;

                    OleDbConnection oleDb;

                    int i;
                    if (_mSwAddin.OpenModelDatabase(_swSelModel, out oleDb))
                    {
                        using (oleDb)
                        {
                            #region Обработка файла *.mdb

                            if (!tabMain.Controls.Contains(tbpParams))
                            {
                                tabMain.Controls.Remove(tbpPos);
                                tabMain.Controls.Add(tbpParams);
                                tabMain.Controls.Add(tbpPos);
                            }
                            if (Properties.Settings.Default.KitchenModeOn)
                            {
                                tabMain.SelectTab(tbpPos);
                            }
                            else
                            {
                                if (tabMain.SelectedTab != tbpParams)
                                {
                                    tabMain.SelectTab(tbpParams);
                                }
                            }
                            var oleSchem = oleDb.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,
                                                                     new object[] { null, null, null, "TABLE" });

                            OleDbCommand cm;
                            OleDbDataReader rd;
                            listForDimensions = new List<DimensionConfForList>();

                            #region Если есть objects

                            if (oleSchem.Rows.Cast<DataRow>().Any(
                                row => (string)row["TABLE_NAME"] == "objects"))
                            {
                                _chkMeasure = new CheckBox
                                {
                                    Appearance = Appearance.Button,
                                    Location = new Point(133, 12),
                                    Name = @"chkMeasure",
                                    Size = new Size(80, 24),
                                    Text = @"Измерить",
                                    TextAlign = ContentAlignment.MiddleCenter,
                                    UseVisualStyleBackColor = true
                                };
                                tbpParams.Controls.Add(_chkMeasure);
                                _chkMeasure.CheckedChanged += StartMeasure;

                                i = 0;

                                bool isNumber = false, isIdSlave = false, isAsmConfig = false, isFixedValues = false;

                                #region Dimension Configuration

                                if (
                                    oleSchem.Rows.Cast<DataRow>().Any(
                                        row => (string)row["TABLE_NAME"] == "dimension_conf"))
                                {
                                    cm = new OleDbCommand("SELECT * FROM dimension_conf ORDER BY id", oleDb);
                                    rd = cm.ExecuteReader();
                                    var outComps = new LinkedList<Component2>();
                                    if (_mSwAddin.GetComponents(
                                        _swSelModel.IGetActiveConfiguration().IGetRootComponent2(),
                                        outComps, true, false))
                                    {
                                        _dimensionConfig = Decors.GetListComponentForDimension(_mSwAddin, rd,
                                                                                               outComps);
                                        _dimensionConfig.Sort((x, y) => x.Number.CompareTo(y.Number));
                                        rd.Close();
                                    }
                                }
                                #endregion

                                var thisDataSet = new DataSet();
                                var testAdapter = new OleDbDataAdapter("SELECT * FROM objects", oleDb);
                                testAdapter.Fill(thisDataSet, "objects");
                                testAdapter.Dispose();
                                bool captConfigBool = thisDataSet.Tables["objects"].Columns.Contains("captConf");
                                foreach (var v in thisDataSet.Tables["objects"].Columns)
                                {
                                    var vc = (DataColumn)v;
                                    if (vc.ColumnName == "number")
                                        isNumber = true;
                                    if (vc.ColumnName == "idslave")
                                    {
                                        if (vc.DataType.Name != "String")
                                            MessageBox.Show(
                                                @"Неверно указан тип данных в столбце 'ismaster'",
                                                _mSwAddin.MyTitle, MessageBoxButtons.OK,
                                                MessageBoxIcon.Information);
                                        isIdSlave = true;
                                    }
                                    if (vc.ColumnName == "mainasmconf" &&
                                        _swSelModel.GetConfigurationCount() > 1)
                                        isAsmConfig = true;
                                    if (vc.ColumnName == "fixedvalues")
                                        isFixedValues = true;
                                }
                                thisDataSet.Clear();

                                if (Properties.Settings.Default.CheckParamLimits &&
                                    oleSchem.Rows.Cast<DataRow>().Any(
                                        row => (string)row["TABLE_NAME"] == "dimlimits"))
                                {
                                    testAdapter = new OleDbDataAdapter("SELECT * FROM dimlimits", oleDb);
                                    testAdapter.Fill(thisDataSet, "dimlimits");
                                    testAdapter.Dispose();
                                    foreach (var v in thisDataSet.Tables["dimlimits"].Columns)
                                    {
                                        var vc = (DataColumn)v;
                                        _namesOfColumnNameFromDimLimits.Add(vc.ColumnName);
                                    }
                                    thisDataSet.Clear();
                                }

                                string currentConf = _swSelComp.ReferencedConfiguration;

                                cm = isNumber
                                         ? new OleDbCommand(
                                               "SELECT * FROM objects WHERE number>0 ORDER BY number",
                                               oleDb)
                                         : new OleDbCommand("SELECT * FROM objects ORDER BY id", oleDb);

                                rd = cm.ExecuteReader();

                                #region Размеры

                                #region Считывание данных из objects

                                int k = 1;
                                var dictWithDiscretValues = new Dictionary<string, List<int>>();

                                while (rd.Read())
                                {
                                    if (captConfigBool && rd["captConf"] != null && rd["captConf"].ToString() != "all" && rd["captConf"].ToString() != currentConf && !string.IsNullOrEmpty(rd["captConf"].ToString()))
                                        continue;
                                    if (rd["caption"].ToString() == null || rd["caption"].ToString() == "" ||
                                        rd["caption"].ToString().Trim() == "")
                                        continue;

                                    #region Обработка поля mainasmconf

                                    if (isAsmConfig)
                                    {
                                        var neededConf = rd["mainasmconf"].ToString();
                                        bool isNeededConf = neededConf.Split('+').Select(v => v.Trim()).Any(
                                            f => f == currentConf);
                                        if (neededConf == "all")
                                            isNeededConf = true;
                                        if (!isNeededConf)
                                            continue;
                                    }

                                    #endregion

                                    string strObjName = rd["name"].ToString();

                                    double strObjVal;
                                    if (_swSelModel.GetPathName().Contains("_SWLIB_BACKUP"))
                                    {
                                        string pn = Path.GetFileNameWithoutExtension(_swSelModel.GetPathName());
                                        string last3 = pn.Substring(pn.Length - 4, 4);
                                        string[] arr = strObjName.Split('@');
                                        if (arr.Length != 3)
                                            throw new Exception("что-то не так");
                                        arr[2] = Path.GetFileNameWithoutExtension(arr[2]) + last3 + Path.GetExtension(arr[2]);
                                        strObjName = string.Format("{0}@{1}@{2}", arr[0], arr[1], arr[2]);
                                    }
                                    if (_mSwAddin.GetObjectValue(_swSelModel, strObjName, (int)rd["type"],
                                                                 out strObjVal))
                                    {
                                        int val = GetCorrectIntValue(strObjVal);

                                        int number = isNumber ? (int)rd["number"] : (int)rd["id"];
                                        while (number != k && _dimensionConfig.Count != 0)
                                        {
                                            listForDimensions.AddRange(
                                                from dimensionConfiguration in _dimensionConfig
                                                where dimensionConfiguration.Number == k
                                                select
                                                    new DimensionConfForList(dimensionConfiguration.Number,
                                                                             dimensionConfiguration.Caption,
                                                                             "", -1,
                                                                             GetListIntFromString(
                                                                                 dimensionConfiguration.
                                                                                     IdSlave),
                                                                             dimensionConfiguration.
                                                                                 Component,
                                                                             false,
                                                                             dimensionConfiguration.Id));
                                            //Logging.Log.Instance.Debug("listForDimensions1:" + listForDimensions.Count.ToString());
                                            k++;
                                        }

                                        var listId = new List<int>();
                                        try
                                        {
                                            if (isIdSlave)
                                                listId = GetListIntFromString((string)rd["idslave"]);
                                        }
                                        catch
                                        {
                                            listId = null;
                                        }
                                        string labelName;
                                        try
                                        {
                                            labelName = rd["caption"].ToString();
                                        }
                                        catch
                                        {
                                            string[] strObjNameParts = strObjName.Split('@');
                                            labelName = strObjNameParts[0];
                                        }

                                        if (isFixedValues)
                                        {
                                            try
                                            {
                                                var arr = (string)rd["fixedvalues"];
                                                string[] arrs = arr.Split(',');
                                                var list = arrs.Select(s => Convert.ToInt32(s)).ToList();
                                                if (!dictWithDiscretValues.ContainsKey(strObjName))
                                                    dictWithDiscretValues.Add(strObjName, list);
                                            }
                                            catch { }
                                        }

                                        listForDimensions.Add(new DimensionConfForList(number, labelName,
                                                                                       strObjName, val,
                                                                                       listId,
                                                                                       null,
                                                                                       (bool)rd["ismaster"],
                                                                                       (int)rd["id"]));
                                        //Logging.Log.Instance.Debug("listForDimensions2:" + listForDimensions.Count.ToString());
                                        k++;
                                    }
                                }
                                rd.Close();

                                #endregion

                                listForDimensions.AddRange(
                                    _dimensionConfig.Where(x => x.Number >= k).Select(
                                        b =>
                                        new DimensionConfForList(b.Number, b.Caption, "", -1,
                                                                 GetListIntFromString(b.IdSlave),
                                                                 b.Component,
                                                                 false,
                                                                 b.Id)));
                                listForDimensions.Sort((x, y) => x.Number.CompareTo(y.Number));
                                //Logging.Log.Instance.Debug("listForDimensions3:" + listForDimensions.Count.ToString());
                                foreach (var dimensionConfForList in listForDimensions)
                                {
                                    var lblNew = new Label { Size = new Size(125, 24) };
                                    lblNew.Location = new Point(0, 48 + i * (lblNew.Size.Height + 6));
                                    lblNew.Name = "lblPrm" + i;
                                    lblNew.TextAlign = ContentAlignment.MiddleRight;
                                    lblNew.Text = dimensionConfForList.LabelName;
                                    lblNew.Tag = dimensionConfForList.StrObjName;
                                    tbpParams.Controls.Add(lblNew);
                                    _lblPrm.AddLast(lblNew);

                                    downPos = lblNew.Location.Y + lblNew.Size.Height;
                                    if (dimensionConfForList.StrObjName != "")
                                    {
                                        #region TextBox с размерами

                                        if (dictWithDiscretValues.ContainsKey(dimensionConfForList.StrObjName))
                                        {
                                            #region Если дискретные значения
                                            var comboBoxWithDiscretValues = new ComboBox
                                            {
                                                Size = new Size(53, 24),
                                                Location =
                                                    new Point(
                                                    lblNew.Location.X +
                                                    lblNew.Size.Width + 4,
                                                    lblNew.Location.Y),
                                                Tag = dimensionConfForList.StrObjName,
                                                TabIndex = i
                                            };

                                            int val = dimensionConfForList.ObjVal;

                                            foreach (int vals in dictWithDiscretValues[dimensionConfForList.StrObjName])
                                            {
                                                int ordNumb = comboBoxWithDiscretValues.Items.Add(vals);
                                                if (vals == val)
                                                    comboBoxWithDiscretValues.SelectedIndex = ordNumb;
                                            }

                                            tbpParams.Controls.Add(comboBoxWithDiscretValues);

                                            _comboBoxListForRedraw.Add(comboBoxWithDiscretValues,
                                                                       dimensionConfForList.IdSlave);
                                            comboBoxWithDiscretValues.SelectedIndexChanged +=
                                            ComboBoxWithDiscretValuesSelectedIndexChanged;
                                            #endregion
                                        }
                                        else
                                        {
                                            #region Если обычные значения
                                            int val = GetCorrectIntValue(dimensionConfForList.ObjVal);

                                            var txtNew = new TextBox
                                            {
                                                Size = new Size(35, 24),
                                                Location =
                                                    new Point(
                                                    lblNew.Location.X + lblNew.Size.Width +
                                                    4,
                                                    lblNew.Location.Y),
                                                Name =
                                                    lblNew.Text + "@" +
                                                    dimensionConfForList.ObjVal,
                                                Text = val.ToString(),
                                                TextAlign = HorizontalAlignment.Right,
                                                Tag = dimensionConfForList.StrObjName,
                                                TabIndex = i
                                            };

                                            _numbAndTextBoxes.Add(dimensionConfForList.Id, txtNew);
                                            if (!dimensionConfForList.IsGrey)
                                                txtNew.ReadOnly = true;
                                            else
                                            {
                                                _textBoxListForRedraw.Add(txtNew,
                                                                          dimensionConfForList.IdSlave);
                                                txtNew.KeyDown += TxtPrmKeyDown;
                                                txtNew.TextChanged += TxtNewTextChanged;

                                                var btnNew = new Button
                                                {
                                                    ImageKey = @"Units1.ico",
                                                    ImageList = imageList1,
                                                    Size = new Size(24, 24),
                                                    Location =
                                                        new Point(
                                                        txtNew.Location.X +
                                                        txtNew.Size.Width +
                                                        4,
                                                        lblNew.Location.Y),
                                                    Name =
                                                        dimensionConfForList.ObjVal.
                                                        ToString(),
                                                    Text = "",
                                                    Tag = txtNew.Name,
                                                    Enabled = false
                                                };

                                                if (!_butPlusTxt.ContainsKey(btnNew))
                                                    _butPlusTxt.Add(btnNew, txtNew);

                                                tbpParams.Controls.Add(btnNew);
                                                _btnPrm.AddLast(btnNew);

                                                btnNew.Click += MeasureLength;

                                                #region если есть таблица ref_objects  и в ней есть хоть одна строка с соотв-щем id
                                                if (refobj == null)
                                                {
                                                    refobj = new List<ref_object>();
                                                    if (oleSchem.Rows.Cast<DataRow>().Any(row => (string)row["TABLE_NAME"] == "ref_objects_axe"))
                                                    {

                                                        cm = new OleDbCommand("SELECT * FROM ref_objects  LEFT JOIN ref_objects_axe  ON ref_objects_axe.id=ref_objects.objectsId", oleDb);
                                                        rd = cm.ExecuteReader();

                                                        while (rd.Read())
                                                        {
                                                            refobj.Add(new ref_object((string)rd["componentName"], (int)rd["objectsId"], (string)rd["axe"], (float)rd["correctionLeft_Up"], (float)rd["correctionRight_Down"]));
                                                        }
                                                        rd.Close();
                                                    }
                                                }
                                                ref_object[] currentrefs = refobj.Where(d => d.ObjectId == dimensionConfForList.Id).ToArray();
                                                if (currentrefs.Length > 0)
                                                {
                                                    //добавить кнопку
                                                    //выбрать из refobj только dimensionConfigForList.Id
                                                    var btnRef = new Button
                                                    {
                                                        ImageKey = @"expand.gif",
                                                        ImageList = imageList1,
                                                        Size = new Size(24, 24),
                                                        Location =
                                                            new Point(
                                                            txtNew.Location.X +
                                                            txtNew.Size.Width + btnNew.Size.Width +
                                                            8,
                                                            lblNew.Location.Y),
                                                        Name =
                                                            dimensionConfForList.ObjVal.
                                                            ToString(),
                                                        Text = "",
                                                        Tag = currentrefs,
                                                        Enabled = true
                                                    };

                                                    tbpParams.Controls.Add(btnRef);
                                                    //_btnPrm.AddLast(btnNew);

                                                    btnRef.Click += ExpandBtn;
                                                    if (!_butPlusTxt.ContainsKey(btnRef))
                                                        _butPlusTxt.Add(btnRef, txtNew);
                                                }
                                                #endregion
                                            }
                                            tbpParams.Controls.Add(txtNew);
                                            _commonList.Add(txtNew);

                                            #endregion
                                        }

                                        #endregion
                                    }
                                    else
                                    {
                                        #region ComboBox с конфигурациями

                                        var cmp = dimensionConfForList.Component;
                                        var comboBoxConfForDimTab = new ComboBox
                                        {
                                            Size = new Size(56, 24),
                                            Location =
                                                new Point(
                                                lblNew.Location.X +
                                                lblNew.Size.Width + 4,
                                                lblNew.Location.Y),
                                            Tag = cmp,
                                            TabIndex = i
                                        };

                                        var confNames =
                                            (string[])cmp.IGetModelDoc().GetConfigurationNames();
                                        foreach (var confName in confNames)
                                        {
                                            int lonhName = confName.Length * 6;
                                            if (comboBoxConfForDimTab.DropDownWidth < lonhName)
                                                comboBoxConfForDimTab.DropDownWidth = lonhName;
                                            comboBoxConfForDimTab.Items.Add(confName);
                                        }
                                        comboBoxConfForDimTab.SelectedItem = cmp.ReferencedConfiguration;
                                        tbpParams.Controls.Add(comboBoxConfForDimTab);

                                        _comboBoxListForRedraw.Add(comboBoxConfForDimTab,
                                                                   dimensionConfForList.IdSlave);

                                        comboBoxConfForDimTab.SelectedIndexChanged +=
                                            ComboBoxConfForDimTabSelectedIndexChanged;

                                        #endregion
                                    }
                                    i++;
                                }

                                #region Добавить выбор конфигурации
                                try
                                {
                                    if (_swSelModel.GetConfigurationCount() > 1)
                                    {
                                        var lblNew = new Label { Size = new Size(125, 24) };
                                        lblNew.Location = new Point(0, 48 + i * (lblNew.Size.Height + 6));
                                        lblNew.Name = "lblPrm" + i;
                                        lblNew.TextAlign = ContentAlignment.MiddleRight;
                                        lblNew.Text = "Конфигурации:";
                                        tbpParams.Controls.Add(lblNew);
                                        //lblNew.Tag = dimensionConfForList.StrObjName;
                                        downPos = lblNew.Location.Y + lblNew.Size.Height;
                                        string[] configurations = _swSelModel.GetConfigurationNames();
                                        var comboBoxConfig = new ComboBox
                                        {
                                            Size = new Size(56, 24),
                                            Location = new Point(lblNew.Location.X + lblNew.Size.Width + 4, lblNew.Location.Y),
                                        };
                                        string activeConf = _swSelComp.ReferencedConfiguration;//_swSelModel.IGetActiveConfiguration().Name;
                                        foreach (var configuration in configurations)
                                        {
                                            int currentIndex = comboBoxConfig.Items.Add(configuration);
                                            if (configuration == activeConf)
                                                comboBoxConfig.SelectedIndex = currentIndex;
                                        }
                                        Size size = TextRenderer.MeasureText(activeConf, comboBoxConfig.Font);
                                        int lonhName = size.Width; //nameOfConfiguration.Length * 5;
                                        if (comboBoxConfig.DropDownWidth < lonhName)
                                            comboBoxConfig.DropDownWidth = lonhName;
                                        tbpParams.Controls.Add(comboBoxConfig);
                                        comboBoxConfig.SelectedIndexChanged += ConfigurationChanged;
                                    }
                                }
                                catch
                                { }

                                #endregion
                                #endregion
                                _dictHeightPage.Add(tbpParams, downPos);
                            }

                            #endregion
                            #region Если есть comments
                            if (oleSchem.Rows.Cast<DataRow>().Any(
                               row => (string)row["TABLE_NAME"] == "comments"))
                            {
                                cm = new OleDbCommand("SELECT * FROM comments ORDER BY id", oleDb);
                                rd = cm.ExecuteReader();
                                if (rd.Read())
                                {
                                    try
                                    {
                                        CommentLayout.Visible = true;
                                        WarningPB.Visible = (bool)rd["showSimbol"];
                                        commentsTb.Text = (string)rd["comment"];

                                        Size size = TextRenderer.MeasureText(commentsTb.Text, commentsTb.Font);

                                        commentsTb.Height = (size.Width / (commentsTb.Width - 10)) * 30;

                                    }
                                    catch
                                    {
                                        CommentLayout.Visible = false;
                                    }
                                }
                                rd.Close();

                            }
                            else
                            {
                                CommentLayout.Visible = false;
                            }
                            #endregion

                            #region Decors

                            if (!ReloadDecorTab(oleDb, oleSchem))
                                return;

                            #endregion

                            oleDb.Close();

                            #endregion
                        }
                    }
                    else
                        if (_tabDec != null)
                            tabMain.Controls.Remove(_tabDec);

                    var swFeat = (Feature)_swSelModel.FirstFeature();
                    i = 0;

                    #region Position

                    var mates = _swSelComp.GetMates();
                    Dictionary<string, Mate2> existingMates = new Dictionary<string, Mate2>();
                    if (mates != null)
                    {
                        foreach (var mate in mates)
                        {
                            if (mate is Mate2)
                            {
                                var spec = (Mate2)mate;
                                int mec = spec.GetMateEntityCount();
                                if (mec > 1)
                                {
                                    for (int ik = 0; ik < mec; ik++)
                                    {
                                        MateEntity2 me = spec.MateEntity(ik);
                                        if (me.ReferenceComponent.Name.Contains(_swSelComp.Name))
                                        {
                                            Entity tt = me.Reference;
                                            var tt2 = tt as Feature;

                                            if (tt is RefPlane && tt2 != null)
                                            {

                                                if (!existingMates.ContainsKey(tt2.Name))
                                                    existingMates.Add(tt2.Name, spec);
                                            }

                                        }
                                    }
                                }
                            }
                        }
                    }

                    int downPosPosition = 0;
                    int tabIndex = 0;
                    while (swFeat != null)
                    {
                        if (swFeat.GetTypeName2() == "RefPlane")
                        {
                            string strPlaneName = swFeat.Name;

                            if (strPlaneName.Length > 1)
                            {
                                if (strPlaneName.Substring(0, 1) == "#")
                                {
                                    var btnNew = new Button { Size = new Size(120, 20) };
                                    btnNew.Location = new Point(62, 24 + i * (btnNew.Size.Height + 6));
                                    //if (Properties.Settings.Default.KitchenModeOn)
                                    //    btnNew.Name = strPlaneName;//"btnPos" + i;
                                    //else
                                    btnNew.Name = "btnPos" + i;

                                    btnNew.Text = strPlaneName.Substring(5);
                                    btnNew.Tag = strPlaneName;
                                    btnNew.TabIndex = tabIndex;
                                    tabIndex++;
                                    tbpPos.Controls.Add(btnNew);
                                    btnNew.Click += AddMate;
                                    downPosPosition = btnNew.Location.Y + btnNew.Size.Height;
                                    if (existingMates.ContainsKey(strPlaneName))
                                    {
                                        //добавить кнопку для отвязки
                                        var btnDeattach = new Button { Size = new Size(20, 20) };
                                        btnDeattach.Location = new Point(62 + btnNew.Size.Width + 10, 24 + i * (btnNew.Size.Height + 6));
                                        btnDeattach.Name = strPlaneName;
                                        btnDeattach.Text = "X";
                                        btnDeattach.Tag = existingMates[strPlaneName];
                                        tbpPos.Controls.Add(btnDeattach);
                                        btnDeattach.Click += DeleteMate;
                                    }
                                    i++;

                                }
                            }
                        }
                        swFeat = (Feature)swFeat.GetNextFeature();
                    }
                    _dictHeightPage.Add(tbpPos, downPosPosition);

                    #endregion

                    if (_lblPrm.Count == 0)
                    {
                        tabMain.SelectTab(tbpPos);
                        downPos = downPosPosition;
                        SetSizeForTab(downPos);
                        if (tabMain.Controls.Contains(tbpParams))
                        {
                            tabMain.Controls.Remove(tbpParams);
                            //Logging.Log.Instance.Fatal("Вкладка на РПД не показана.Смотреть listForDimensions");
                        }
                    }
                    if (rbMode1 != null && rbMode2 != null)
                    {
                        if (controlsToHideWhenChangeMode == null || controlsToHideWhenChangeMode.Count == 0)
                            pnlMode.Visible = false;
                        if (Properties.Settings.Default.DefaultRPDView)
                        {
                            rbMode1.CheckedChanged += new EventHandler(ModeCheckedChanged);
                            rbMode1.Checked = true;
                        }
                        else
                        {
                            rbMode2.Checked = true;
                            rbMode1.CheckedChanged += new EventHandler(ModeCheckedChanged);
                        }
                    }
                    SetSizeForTab(_dictHeightPage[tabMain.SelectedTab]);
                }
            }
        }
Esempio n. 24
0
        /////

        internal static HelperResult processModel(SldWorks swApp, FileObj file, BindingList <PropertyObject> prop_list, PropProcessFlag flag, CancellationToken cancellationToken)
        {
            if (swApp == null)
            {
                return(HelperResult.SLDWORKS_NOT_RUNNING);
            }

            Console.WriteLine("Helper.processModel");

            int Warning = 0;
            int Error   = 0;

            try
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    file.Note = "Cancel";
                    return(HelperResult.CANCELED);
                }

                if (file.Read_only)
                {
                    file.Note = "Skiped (Read only!)";
                    return(HelperResult.SKIPED);
                }

                ModelDoc2 swDoc = swApp.OpenDoc6(file.PathToFile, (int)file.SwType_e, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref Error, ref Warning);

                if (Error != 0 || swDoc == null)
                {
                    file.Note = "Error to open file";
                    return(HelperResult.OPEN_ERROR);
                }

                //*  //this code error
                if (file.SwType_e == swDocumentTypes_e.swDocASSEMBLY || file.SwType_e == swDocumentTypes_e.swDocPART)
                {
                    file.ConfigNames.AddRange(swDoc.GetConfigurationNames());
                    if (!file.ConfigNames.Any())
                    {
                        swApp.QuitDoc(swDoc.GetTitle());
                        swDoc     = null;
                        file.Note = "Skiped (Unknown error)";
                        return(HelperResult.UNKNOWN);
                    }
                }

                //*/

                if ((flag & PropProcessFlag.MAIN_CUSTOM) == PropProcessFlag.MAIN_CUSTOM)
                {
                    try
                    {
                        CustomPropertyManager manager = swDoc.Extension.CustomPropertyManager[""];
                        foreach (PropertyObject property in prop_list)
                        {
                            Console.WriteLine("field={0},type={1},value={2}", property.FieldName, property.FieldType, property.Value);
                            int ret = manager.Add3(property.FieldName, (int)property.FieldType, property.Value, (int)swCustomPropertyAddOption_e.swCustomPropertyReplaceValue);
                            if (ret != 0)
                            {
                                file.Note = "Error to add, err num = " + ret;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("error in add method" + ex.Message);
                        file.Note = "error(" + ex.Message + ")";
                        //throw ex;
                    }
                }

                if (((flag & PropProcessFlag.CONFIG_CUSTOM) == PropProcessFlag.CONFIG_CUSTOM) && file.ConfigNames.Any())
                {
                    try
                    {
                        foreach (string conf in file.ConfigNames)
                        {
                            Console.WriteLine(conf);
                            CustomPropertyManager manager = swDoc.Extension.CustomPropertyManager[conf];
                            foreach (PropertyObject property in prop_list)
                            {
                                string value   = property.Value;
                                string pattern = @"[^@]+";

                                MatchCollection matches = Regex.Matches(value, pattern);

                                if (matches.Count >= 3)
                                {
                                    property.Value = Regex.Replace(value, matches[matches.Count - 2].Value, conf);
                                }

                                Console.WriteLine("field={0},type={1},value={2},config{3}", property.FieldName, property.FieldType, property.Value, conf);
                                int ret = manager.Add3(property.FieldName, (int)property.FieldType, property.Value, (int)swCustomPropertyAddOption_e.swCustomPropertyReplaceValue);
                                if (ret != 0)
                                {
                                    file.Note = "Error to add, err num = " + ret;
                                    break;
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("error in add method" + ex.Message);
                        file.Note = "error(" + ex.Message + ")";
                        //throw ex;
                    }
                }

                file.Note = "Done";
                swDoc.SaveSilent();
                swApp.QuitDoc(swDoc.GetTitle());
                swDoc = null;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw e;
            }
            return(HelperResult.SUCCESS);
        }
Esempio n. 25
0
        /// <summary>
        /// 当结果返回True 时 表示两个零件不一样,结果false时表示 两个零件一样
        /// </summary>
        /// <param name="sendTocustomer"></param>
        /// <param name="localModel"></param>
        /// <returns></returns>
        public bool CheckTwoParts(string sendTocustomer, string localModel)
        {
            bool different1 = false;

            bool different2 = false;

            swApp = ConnectToSolidWorks();
            // swApp = ConnectToSolidWorks();

            //加载参考关系零件
            swApp.SetUserPreferenceIntegerValue((int)swUserPreferenceIntegerValue_e.swLoadExternalReferences, (int)swLoadExternalReferences_e.swLoadExternalReferences_ChangedOnly);

            //后台模式 前台不显示界面

            swApp.EnableBackgroundProcessing = true;

            //禁止记录文件路径
            swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swLockRecentDocumentsList, true);

            swApp.OpenDoc(localModel, 1);

            swApp.OpenDoc(sendTocustomer, 1);

            ModelDoc2 swModel = (ModelDoc2)swApp.ActiveDoc;

            string LocalPath = System.IO.Directory.GetParent(swModel.GetPathName()).ToString();

            string tempAssembly = swApp.GetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swDefaultTemplateAssembly);

            AssemblyDoc assemblyDoc = (AssemblyDoc)swApp.NewDocument(tempAssembly, 0, 0, 0);

            Component2 insertComponentSendtoCustomer = assemblyDoc.AddComponent5(sendTocustomer, 0, "", false, "", 0, 0, 0);
            Component2 insertComponentLocal          = assemblyDoc.AddComponent5(localModel, 0, "", false, "", 0, 0, 0);

            string sendSelect  = insertComponentSendtoCustomer.GetSelectByIDString();
            string localSelect = insertComponentLocal.GetSelectByIDString();

            swModel = (ModelDoc2)swApp.ActiveDoc;

            bool b1 = swModel.Extension.SelectByID2("Point1@Origin" + "@" + sendSelect, "EXTSKETCHPOINT", 0, 0, 0, false, 0, null, 0);
            bool b2 = swModel.Extension.SelectByID2("Point1@Origin" + "@" + localSelect, "EXTSKETCHPOINT", 0, 0, 0, true, 0, null, 0);
            int  longstatus;

            Mate2 mate2 = assemblyDoc.AddMate5(20, -1, false, 0, 0.001, 0.001, 0.001, 0.001, 0, 0, 0, false, false, 0, out longstatus);

            swModel = (ModelDoc2)swApp.ActiveDoc;

            swModel.SaveAs(LocalPath + @"\TopCheck.sldasm");

            //不显示特征树
            //swModel.Extension.HideFeatureManager(true);

            swModel.ClearSelection2(true);
            //swModel.FeatureManager.ViewFeatures = false;

            //FeatureManager featureManager = swModel.FeatureManager;

            //禁用特征树
            //featureManager.EnableFeatureTree = false;

            // swModel.FeatureManager.EnableFeatureTreeWindow = false;

            #region first join

            Component2        sendToCustomerBodies     = default(Component2);
            List <Component2> sendToCustomerBodiesList = new List <Component2>();

            object swFaceOrPlane = default(object);

            assemblyDoc.InsertNewVirtualPart(swFaceOrPlane, out sendToCustomerBodies);

            sendToCustomerBodies.Select(true);

            assemblyDoc.FixComponent();
            sendToCustomerBodies.Select(true);
            assemblyDoc.EditPart();

            insertComponentSendtoCustomer.Select(false);
            insertComponentLocal.Select(true);

            assemblyDoc.InsertJoin2(false, false);

            swModel = (ModelDoc2)swApp.ActiveDoc;
            swModel.BreakAllExternalReferences();

            object[] splits = sendToCustomerBodies.Name2.Split('^');
            // string compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + splits[0];
            string compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + "localBodies-1";

            ModelDoc2 compModel = default(ModelDoc2);
            compModel = (ModelDoc2)sendToCustomerBodies.GetModelDoc();

            if (compModel.GetType() == (int)swDocumentTypes_e.swDocPART)
            {
                compName = compName + ".sldprt";
            }
            else
            {
                compName = compName + ".sldasm";
            }

            bool ret;

            ret = sendToCustomerBodies.SaveVirtualComponent(compName);

            sendToCustomerBodiesList.Add(sendToCustomerBodies);

            insertComponentSendtoCustomer.Select(false);

            swModel = (ModelDoc2)sendToCustomerBodies.GetModelDoc2();

            #region 获取所有零件中的零件,每一个实体做一次反切

            List <string> bodyNamesCustomer = new List <string>();

            PartDoc swPart = null;
            object  vBody;
            swPart = (PartDoc)swModel;
            // Solid bodies
            object[] vBodyArr = null;
            Body2    swBody   = default(Body2);

            MathTransform swMathTrans = null;
            vBodyArr = (object[])swPart.GetBodies2((int)swBodyType_e.swSolidBody, true);

            if ((vBodyArr != null))
            {
                // Debug.Print("  Number of solid bodies: " + vBodyArr.Length);

                foreach (object vBody_loopVariable in vBodyArr)
                {
                    vBody  = vBody_loopVariable;
                    swBody = (Body2)vBody;

                    string[] vConfigName = null;
                    vConfigName = (string[])swModel.GetConfigurationNames();
                    string sMatDB   = "";
                    string sMatName = swBody.GetMaterialPropertyName("", out sMatDB);

                    //bRet = swBody.RemoveMaterialProperty((int)swInConfigurationOpts_e.swAllConfiguration, (vConfigName));

                    //Debug.Print("Body--> " + swBody.Name + " " + "");

                    bodyNamesCustomer.Add(swBody.Name);
                }
            }

            //如果实体数量大于1,则继续新建对应数量的join 实体。

            OnlyKeepNamedBody(bodyNamesCustomer[0], sendToCustomerBodies.GetSelectByIDString(), assemblyDoc, sendToCustomerBodies, insertComponentSendtoCustomer, ref different1);

            if (bodyNamesCustomer.Count > 1)
            {
                assemblyDoc.EditAssembly();

                for (int i = 0; i < bodyNamesCustomer.Count - 1; i++)
                {
                    Component2 returnpart = default(Component2);
                    var        partSelect = CreateNewJoinPart(assemblyDoc, insertComponentSendtoCustomer, insertComponentLocal, swModel, "localBodies-" + (i + 2), out returnpart);
                    sendToCustomerBodiesList.Add(returnpart);

                    OnlyKeepNamedBody(bodyNamesCustomer[i + 1], partSelect, assemblyDoc, returnpart, insertComponentSendtoCustomer, ref different1);
                }
            }
            // boolstatus = Part.Extension.SelectByID2("Join1[2]@localBodies-1@TopCheck", "SOLIDBODY", 0, 0, 0, True, 0, Nothing, 0)
            //Dim myFeature As Object
            //Set myFeature = Part.FeatureManager.InsertDeleteBody2(True)

            #endregion 获取所有零件中的零件,每一个实体做一次反切

            //assemblyDoc.InsertCavity4(0, 0, 0, true, 1, -1);
            Feature theFeature;

            //theFeature = swModel.FeatureByPositionReverse(0);

            //if (theFeature.Name.Contains("Cavity"))
            //{
            //    //theFeature.Select(true);

            //    swModel = (ModelDoc2)swApp.ActiveDoc;

            //    bool b = swModel.Extension.SelectByID2(theFeature.Name + "@" + sendToCustomerBodies.GetSelectByIDString(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0);

            //    swModel.BreakAllExternalReferences();
            //    different1 = true;
            //    //JoinPart1 留下的: 发给客户的没有此部分。 而本地零件中有
            //}
            //else
            //{
            //    //无法Join时表示 全切了。
            //    swModel = (ModelDoc2)swApp.ActiveDoc;

            //    bool b = swModel.Extension.SelectByID2(theFeature.Name + "@" + sendToCustomerBodies.GetSelectByIDString(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0);

            //    swModel.EditSuppress();
            //}
            //sendToCustomerBodies.Select(true);

            assemblyDoc.EditAssembly();

            #endregion first join

            #region sercond join2

            Component2        localBodies     = default(Component2);
            List <Component2> LocalBodiesList = new List <Component2>();
            assemblyDoc.InsertNewVirtualPart(swFaceOrPlane, out localBodies);

            localBodies.Select(true);

            assemblyDoc.FixComponent();
            localBodies.Select(true);
            assemblyDoc.EditPart();

            insertComponentSendtoCustomer.Select(false);
            insertComponentLocal.Select(true);

            assemblyDoc.InsertJoin2(false, false);

            swModel = (ModelDoc2)swApp.ActiveDoc;
            swModel.BreakAllExternalReferences();

            splits = localBodies.Name2.Split('^');
            // string compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + splits[0];
            compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + "sendToCustomerBodies-1";

            compModel = default(ModelDoc2);
            compModel = (ModelDoc2)localBodies.GetModelDoc();

            if (compModel.GetType() == (int)swDocumentTypes_e.swDocPART)
            {
                compName = compName + ".sldprt";
            }
            else
            {
                compName = compName + ".sldasm";
            }

            ret = localBodies.SaveVirtualComponent(compName);
            LocalBodiesList.Add(localBodies);
            insertComponentLocal.Select(false);

            swModel = (ModelDoc2)localBodies.GetModelDoc2();

            #region 获取所有零件中的零件,每一个实体做一次反切

            List <string> bodyNamesLocal = new List <string>();

            PartDoc swPart2 = null;
            object  vBody2;
            swPart2 = (PartDoc)swModel;
            // Solid bodies
            object[] vBodyArr2 = null;
            Body2    swBody2   = default(Body2);

            MathTransform swMathTrans2 = null;
            vBodyArr2 = (object[])swPart2.GetBodies2((int)swBodyType_e.swSolidBody, true);

            if ((vBodyArr2 != null))
            {
                // Debug.Print("  Number of solid bodies: " + vBodyArr.Length);

                foreach (object vBody_loopVariable in vBodyArr2)
                {
                    vBody2  = vBody_loopVariable;
                    swBody2 = (Body2)vBody2;

                    string[] vConfigName = null;
                    vConfigName = (string[])swModel.GetConfigurationNames();
                    string sMatDB   = "";
                    string sMatName = swBody2.GetMaterialPropertyName("", out sMatDB);

                    //bRet = swBody.RemoveMaterialProperty((int)swInConfigurationOpts_e.swAllConfiguration, (vConfigName));

                    bodyNamesLocal.Add(swBody2.Name);
                }
            }

            //如果实体数量大于1,则继续新建对应数量的join 实体。

            OnlyKeepNamedBody(bodyNamesLocal[0], localBodies.GetSelectByIDString(), assemblyDoc, localBodies, insertComponentLocal, ref different2);

            if (bodyNamesLocal.Count > 1)
            {
                assemblyDoc.EditAssembly();

                for (int i = 0; i < bodyNamesLocal.Count - 1; i++)
                {
                    Component2 returnpart = default(Component2);
                    var        partSelect = CreateNewJoinPart(assemblyDoc, insertComponentSendtoCustomer, insertComponentLocal, swModel, "sendToCustomerBodies-" + (i + 2), out returnpart);
                    LocalBodiesList.Add(returnpart);
                    OnlyKeepNamedBody(bodyNamesLocal[i + 1], partSelect, assemblyDoc, returnpart, insertComponentLocal, ref different2);
                }
            }
            // boolstatus = Part.Extension.SelectByID2("Join1[2]@localBodies-1@TopCheck", "SOLIDBODY", 0, 0, 0, True, 0, Nothing, 0)
            //Dim myFeature As Object
            //Set myFeature = Part.FeatureManager.InsertDeleteBody2(True)

            #endregion 获取所有零件中的零件,每一个实体做一次反切

            //assemblyDoc.InsertCavity4(0, 0, 0, true, 1, -1);

            //theFeature = swModel.FeatureByPositionReverse(0);

            //swModel = (ModelDoc2)localBodies.GetModelDoc2();

            //theFeature = swModel.FeatureByPositionReverse(0);

            //if (theFeature.Name.Contains("Cavity"))
            //{
            //    //theFeature.Select(true);

            //    swModel = (ModelDoc2)swApp.ActiveDoc;

            //    bool b = swModel.Extension.SelectByID2(theFeature.Name + "@" + localBodies.GetSelectByIDString(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0);

            //    swModel.BreakAllExternalReferences();
            //    different2 = true;
            //    //JoinPart2 留下的: 发给客户的有此部分。 而本地零件中没有
            //}
            //else
            //{
            //    //无法Join时表示 全切了。
            //    swModel = (ModelDoc2)swApp.ActiveDoc;

            //    bool b = swModel.Extension.SelectByID2(theFeature.Name + "@" + sendToCustomerBodies.GetSelectByIDString(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0);

            //    swModel.EditSuppress();
            //}

            //localBodies.Select(true);

            //assemblyDoc.EditAssembly();

            #endregion sercond join2

            #region joinPartPublic

            Component2 publicBodies = default(Component2);

            assemblyDoc.InsertNewVirtualPart(swFaceOrPlane, out publicBodies);

            publicBodies.Select(true);

            assemblyDoc.FixComponent();
            publicBodies.Select(true);
            assemblyDoc.EditPart();

            insertComponentSendtoCustomer.Select(false);
            insertComponentLocal.Select(true);

            assemblyDoc.InsertJoin2(false, false);

            swModel = (ModelDoc2)swApp.ActiveDoc;
            swModel.BreakAllExternalReferences();

            splits = publicBodies.Name2.Split('^');
            // string compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + splits[0];
            compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + "publicBodies";

            compModel = default(ModelDoc2);
            compModel = (ModelDoc2)publicBodies.GetModelDoc();

            if (compModel.GetType() == (int)swDocumentTypes_e.swDocPART)
            {
                compName = compName + ".sldprt";
            }
            else
            {
                compName = compName + ".sldasm";
            }

            ret = publicBodies.SaveVirtualComponent(compName);

            swModel.ClearSelection();

            foreach (var item in sendToCustomerBodiesList)
            {
                item.Select(false);

                assemblyDoc.InsertCavity4(0, 0, 0, true, 1, -1);

                theFeature = (Feature)swModel.FeatureByPositionReverse(0);

                swModel    = (ModelDoc2)publicBodies.GetModelDoc2();
                theFeature = (Feature)swModel.FeatureByPositionReverse(0);

                if (theFeature.Name.Contains("Cavity"))
                {
                    //theFeature.Select(true);

                    swModel = (ModelDoc2)swApp.ActiveDoc;

                    bool b = swModel.Extension.SelectByID2(theFeature.Name + "@" + publicBodies.GetSelectByIDString(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0);

                    swModel.BreakAllExternalReferences();

                    //joinPartPublic 留下的: 发给客户的有此部分。 而本地零件中没有
                }
                else
                {
                }
            }
            foreach (var item in LocalBodiesList)
            {
                item.Select(false);

                assemblyDoc.InsertCavity4(0, 0, 0, true, 1, -1);

                theFeature = (Feature)swModel.FeatureByPositionReverse(0);

                swModel    = (ModelDoc2)publicBodies.GetModelDoc2();
                theFeature = (Feature)swModel.FeatureByPositionReverse(0);

                if (theFeature.Name.Contains("Cavity"))
                {
                    //theFeature.Select(true);

                    swModel = (ModelDoc2)swApp.ActiveDoc;

                    bool b = swModel.Extension.SelectByID2(theFeature.Name + "@" + publicBodies.GetSelectByIDString(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0);

                    swModel.BreakAllExternalReferences();

                    //joinPartPublic 留下的: 发给客户的有此部分。 而本地零件中没有
                }
                else
                {
                }
            }

            publicBodies.Select(true);

            assemblyDoc.EditAssembly();

            #endregion joinPartPublic

            foreach (var item in sendToCustomerBodiesList)
            {
                item.Select(false);
                setColour(Color.Red);
            }
            foreach (var item in LocalBodiesList)
            {
                item.Select(false);
                setColour(Color.Blue);
            }

            swModel = (ModelDoc2)swApp.ActiveDoc;
            swModel.ClearSelection2(true);

            insertComponentLocal.Select(false);
            insertComponentSendtoCustomer.Select(true);
            swModel.HideComponent2();
            swModel.ClearSelection2(true);

            publicBodies.Select(false);
            assemblyDoc.SetComponentTransparent(true);
            setColour(Color.Green);
            swModel.EditRebuild3();
            swModel.Save();

            swModel.SaveAs3(LocalPath + @"\01_CheckResult.sldprt", 0, 0);

            swApp.CloseDoc("TopCheck.sldasm");
            swApp.CloseAllDocuments(true);
            swApp.OpenDoc(LocalPath + @"\01_CheckResult.sldprt", 1);
            swModel = (ModelDoc2)swApp.ActiveDoc;
            swModel.ShowNamedView2("*Isometric", 7);

            swModel.ViewZoomtofit2();

            swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swLockRecentDocumentsList, false);
            try
            {
                System.IO.File.Delete(LocalPath + @"\TopCheck.sldasm");
                System.IO.File.Delete(LocalPath + @"\localBodies.sldprt");
                System.IO.File.Delete(LocalPath + @"\sendToCustomerBodies.sldprt");
                System.IO.File.Delete(LocalPath + @"\publicBodies.sldprt");
            }
            catch (Exception)
            {
            }

            //第二次反向剪切

            swApp.CloseDoc(sendTocustomer);
            swApp.CloseDoc(localModel);

            swModel.FeatureManager.EnableFeatureTree = true;

            swApp.SetUserPreferenceIntegerValue((int)swUserPreferenceIntegerValue_e.swLoadExternalReferences, 2);

            if (different1 == false && different2 == false)
            {
                return(false);
            }
            else
            {
                return(true);
            }
        }
Esempio n. 26
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);
        }
Esempio n. 28
0
        public bool SetObjectValue(ModelDoc2 inModel, string inName, int inType, double inVal, bool noArtIfSuppressed = false)
        {
            object swObj;
            Dimension swDim;
            Feature swFeature;
            Component2 swComp;
            bool ret = false;

            if (GetObjectByName(inModel, inName, inType, out swObj))
            {
                double dTestVal;
                switch (inType)
                {
                    case 14:
                        swDim = (Dimension)swObj;
                        dTestVal = swDim.GetSystemValue2("") * 1000;

                        if (dTestVal != inVal)
                        {
                            ret = (swDim.SetSystemValue2(inVal / 1000,
                                                         (int)
                                                         swSetValueInConfiguration_e.swSetValue_InAllConfigurations) ==
                                   (int)swSetValueReturnStatus_e.swSetValue_Successful);
                        }
                        else
                            ret = true;
                        break;

                    case 22:
                        swFeature = (Feature)swObj;
                        dTestVal = (swFeature.IsSuppressed() ? 0 : 1);

                        if (dTestVal != inVal)
                        {
                            //ret = swFeature.SetSuppression(inVal == 0 ? (int) swFeatureSuppressionAction_e.swSuppressFeature : (int)swFeatureSuppressionAction_e.swUnSuppressFeature);
                            ret =
                                swFeature.SetSuppression2(
                                    inVal == 0
                                        ? (int)swFeatureSuppressionAction_e.swSuppressFeature
                                        : (int)swFeatureSuppressionAction_e.swUnSuppressFeature,
                                    (int)swInConfigurationOpts_e.swAllConfiguration, inModel.GetConfigurationNames());

                            #region ������ ��������

                            Component2 newComp = null;

                            var config = inModel.IGetActiveConfiguration();
                            if (config != null)
                            {
                                swComp = config.IGetRootComponent2();
                                if (swComp != null)
                                {
                                    var outComps = new LinkedList<Component2>();
                                    if (GetComponents(swComp, outComps, false, false))
                                    {
                                        foreach (var component2 in outComps)
                                        {
                                            var mod = component2.IGetModelDoc();
                                            if (mod != null)
                                            {
                                                var texture = component2.GetTexture("");
                                                if (mod.GetType() == (int)swDocumentTypes_e.swDocPART &&
                                                    texture != null)
                                                {
                                                    newComp = component2;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            if (newComp != null)
                            {
                                inModel.Save();
                                if (newComp.Select(false))
                                    ((AssemblyDoc)inModel).ComponentReload();
                            }

                            #endregion
                        }
                        else
                            ret = true;
                        break;

                    case 20:
                        swComp = (Component2)swObj;
                        try
                        {
                            if ((swComp.IsSuppressed() ? 0 : 1) == inVal)
                            {
                                ret = true;
                            }
                            else
                            {
                                int k = inVal == 0
                                            ? (int)swComponentSuppressionState_e.swComponentSuppressed
                                            : (int)swComponentSuppressionState_e.swComponentFullyResolved;

                                bool isCavity = false;
                                if (inVal == 0)
                                {
                                    var outC = new LinkedList<Component2>();
                                    if (GetComponents(swComp, outC, true, false))
                                    {
                                        isCavity =
                                            outC.Select(component2 => component2.IGetModelDoc()).Any(
                                                m => m != null && m.get_CustomInfo2("", "swrfIsCut") == "Yes");
                                    }
                                }
                                int tmp = k;
                                if (k == (int)swComponentSuppressionState_e.swComponentFullyResolved)
                                    tmp = swComp.SetSuppression2(k);
                                if (noArtIfSuppressed)
                                {
                                    //���� ���� ������, �� ������ �����..
                                    //���� ���� ��������- �� �������� ��..
                                    ModelDoc2 outModel;

                                    if (GetModelByName(inModel, inName, false, out outModel, true))
                                    {
                                        if (k == (int)swComponentSuppressionState_e.swComponentSuppressed)
                                        {
                                            //������� �������
                                            RenameCustomProperty(outModel, string.Empty, "Articul", "Noarticul");
                                        }
                                        else if (k == (int)swComponentSuppressionState_e.swComponentFullyResolved)
                                        {
                                            //����� �������
                                            RenameCustomProperty(outModel, string.Empty, "Noarticul", "Articul");
                                        }
                                    }
                                }
                                if (k == (int)swComponentSuppressionState_e.swComponentSuppressed)
                                    tmp = swComp.SetSuppression2(k);
                                k = tmp;

                                #region ��������� ���������

                                var equMrg = inModel.GetEquationMgr();
                                if (equMrg != null)
                                {
                                    var outList = new LinkedList<Component2>();
                                    if (GetComponents(inModel.IGetActiveConfiguration().IGetRootComponent2(), outList,
                                                      true,
                                                      false))
                                    {
                                        bool notSuppComp =
                                            outList.All(
                                                component2 =>
                                                !swComp.IsSuppressed() ||
                                                swComp.GetPathName() != component2.GetPathName() ||
                                                component2.IsSuppressed());
                                        for (int i = 0; i < inModel.GetEquationMgr().GetCount(); i++)
                                        {
                                            if (equMrg.Equation[i].Contains(
                                                Path.GetFileNameWithoutExtension(swComp.GetPathName())))
                                            {
                                                if ((equMrg.get_Suppression(i) ? 0 : 1) != inVal)
                                                {
                                                    equMrg.set_Suppression(i, inVal == 0 && notSuppComp);
                                                }
                                            }
                                        }
                                    }
                                }

                                #endregion

                                #region ��������� ���������

                                if (isCavity)
                                {
                                    LinkedList<Component2> swComps;
                                    List<Feature> list;
                                    if (_features.Count == 0 || _comps.Count == 0)
                                        list = GetAllCavitiesFeatures(out swComps);
                                    else
                                    {
                                        list = _features;
                                        swComps = _comps;
                                    }
                                    string nameMod = Path.GetFileNameWithoutExtension(inModel.GetPathName());

                                    var delList = (from component2 in swComps
                                                   where
                                                       component2.Name.Contains(nameMod) &&
                                                       component2.Name.Contains(swComp.Name)
                                                   from feature in list
                                                   where
                                                       component2.Name ==
                                                       GetSpecialNameFromFeature(feature.IGetFirstSubFeature().Name).
                                                           Split('/').First() + "/" +
                                                       GetSpecialNameFromFeature(feature.IGetFirstSubFeature().Name).
                                                           Split('/').ToArray()[1]
                                                   select feature).ToList();
                                    SwModel.ClearSelection();
                                    foreach (var feature in delList)
                                    {
                                        feature.Select(true);
                                    }
                                    SwModel.DeleteSelection(false);
                                }

                                #endregion

                                ret = (k == (int)swSuppressionError_e.swSuppressionChangeOk);
                            }
                        }
                        catch
                        {
                        }
                        break;
                }
            }
            return ret;
        }