예제 #1
0
        //获取当前文件的Material属性
        public static MaterialModel GetMaterialInfo()
        {
            //【1】打开指定的SW文件,并获取文件名
            ModelDoc2 swDoc    = swAppHelper.ActiveDoc();
            string    fileName = swDoc.GetPathName();//文件名

            if (fileName == null || fileName.Length == 0)
            {
                Msg.ShowError("无法获取文件名,请保存文件后重试!");
                return(null);
            }
            //【2】从模型中获取属性并封装到物料实体类中
            //2.1-配置特定属性
            //string configName = swDoc.ConfigurationManager.ActiveConfiguration.Name;//当前激活配置名
            //2.2-自定义属性
            string        configName  = "";//特别说明:获取自定义属性时,只需要将配置名设置为空白""即可
            MaterialModel objMaterial = new MaterialModel()
            {
                //DrawingCode = swDoc.GetCustomInfoValue(configName, "图号"),
                //MaterialName = swDoc.GetCustomInfoValue(configName, "名称"),
                //DrawingCode = swDoc.GetCustomInfoValue(configName, "Identification Nb"),
                MaterialName        = swDoc.GetCustomInfoValue(configName, "Description"),
                MaterialSpec        = swDoc.GetCustomInfoValue(configName, "规格"),
                MaterialType        = swDoc.GetCustomInfoValue(configName, "型号"),
                Unit                = swDoc.GetCustomInfoValue(configName, "单位"),
                Mquality            = swDoc.GetCustomInfoValue(configName, "Material"),
                Weight              = swDoc.GetCustomInfoValue(configName, "Weight"),
                MachiningPropertyId = swDoc.GetCustomInfoValue(configName, "加工属性"),
                PaintingColor       = swDoc.GetCustomInfoValue(configName, "涂装颜色"),
                BrandId             = swDoc.GetCustomInfoValue(configName, "品牌")
            };

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                        var list = HideUnusedComponents(swView, dimOnlyNew);

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

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

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

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

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

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

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

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

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

                                            }

                                        //swDoc.CloseDoc();

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

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

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

                                        }
                                    }

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

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

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

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

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

                                #endregion
                            }

                            #endregion

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

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

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

                }
                if (writeXml)
                    StopWriteXml(pathXml);
            }

            return;
        }
예제 #3
0
        private void FillForProductQuery(ModelDoc2 swSelModel, string config, ref int size1, ref int size2, ref int size3, ref int size4, ref int size5, ref int size6, ref int size7, ref int size8, ref string idColor1, ref string idColor2, ref string idColor3, ref string idColor4, ref string idColor5)
        {
            int tmpInt;
            if (int.TryParse(swSelModel.GetCustomInfoValue(config, "Size1"), out tmpInt))
                size1 = tmpInt;
            if (int.TryParse(swSelModel.GetCustomInfoValue(config, "Size2"), out tmpInt))
                size2 = tmpInt;
            if (int.TryParse(swSelModel.GetCustomInfoValue(config, "Size3"), out tmpInt))
                size3 = tmpInt;
            if (int.TryParse(swSelModel.GetCustomInfoValue(config, "Size4"), out tmpInt))
                size4 = tmpInt;
            if (int.TryParse(swSelModel.GetCustomInfoValue(config, "Size5"), out tmpInt))
                size5 = tmpInt;
            if (int.TryParse(swSelModel.GetCustomInfoValue(config, "Size6"), out tmpInt))
                size6 = tmpInt;
            if (int.TryParse(swSelModel.GetCustomInfoValue(config, "Size7"), out tmpInt))
                size7 = tmpInt;
            if (int.TryParse(swSelModel.GetCustomInfoValue(config, "Size8"), out tmpInt))
                size8 = tmpInt;

            string tmpString = swSelModel.GetCustomInfoValue(config, "Color1");
            if (tmpString.Contains("Color") || tmpString == "-")
                tmpString = string.Empty;
            if (!string.IsNullOrEmpty(tmpString))
                idColor1 = tmpString;
            tmpString = swSelModel.GetCustomInfoValue(config, "Color2");
            if (tmpString.Contains("Color") || tmpString == "-")
                tmpString = string.Empty;
            if (!string.IsNullOrEmpty(tmpString))
                idColor2 = tmpString;
            tmpString = swSelModel.GetCustomInfoValue(config, "Color3");
            if (tmpString.Contains("Color") || tmpString == "-")
                tmpString = string.Empty;
            if (!string.IsNullOrEmpty(tmpString))
                idColor3 = tmpString;
            tmpString = swSelModel.GetCustomInfoValue(config, "Color4");
            if (tmpString.Contains("Color") || tmpString == "-")
                tmpString = string.Empty;
            if (!string.IsNullOrEmpty(tmpString))
                idColor4 = tmpString;
            tmpString = swSelModel.GetCustomInfoValue(config, "Color5");
            if (tmpString.Contains("Color") || tmpString == "-")
                tmpString = string.Empty;
            if (!string.IsNullOrEmpty(tmpString))
                idColor5 = tmpString;
        }
예제 #4
0
        private void FillForNonProductQuery(ModelDoc2 swSelModel, string config, ref int size1, ref int size2, ref int size1Work, ref int size2Work, ref string idColor1, ref string idColor2, ref string idColor3, ref string faner11, ref string faner12, ref string faner21, ref string faner22, ref string colorfaner11, ref string colorfaner12, ref string colorfaner21, ref string colorfaner22)
        {
            int tmpInt;
            if (int.TryParse(swSelModel.GetCustomInfoValue(config, "Size1"), out tmpInt))
                size1 = tmpInt;
            if (int.TryParse(swSelModel.GetCustomInfoValue(config, "Size2"), out tmpInt))
                size2 = tmpInt;
            if (int.TryParse(swSelModel.GetCustomInfoValue(config, "Part Size1"), out tmpInt))
                size1Work = tmpInt;
            if (int.TryParse(swSelModel.GetCustomInfoValue(config, "Part Size2"), out tmpInt))
                size2Work = tmpInt;

            string tmpString = swSelModel.GetCustomInfoValue(config, "Color1");
            if (tmpString.Contains("Color") || tmpString == "-")
                tmpString = string.Empty;
            if (!string.IsNullOrEmpty(tmpString))
                idColor1 = tmpString;
            tmpString = swSelModel.GetCustomInfoValue(config, "Color2");
            if (tmpString.Contains("Color") || tmpString == "-")
                tmpString = string.Empty;
            if (!string.IsNullOrEmpty(tmpString))
                idColor2 = tmpString;
            tmpString = swSelModel.GetCustomInfoValue(config, "Color3");
            if (tmpString.Contains("Color") || tmpString == "-")
                tmpString = string.Empty;
            if (!string.IsNullOrEmpty(tmpString))
                idColor3 = tmpString;

            tmpString = swSelModel.GetCustomInfoValue(config, "Faner11");
            if (!string.IsNullOrEmpty(tmpString))
                faner11 = tmpString;
            tmpString = swSelModel.GetCustomInfoValue(config, "Faner12");
            if (!string.IsNullOrEmpty(tmpString))
                faner12 = tmpString;
            tmpString = swSelModel.GetCustomInfoValue(config, "Faner21");
            if (!string.IsNullOrEmpty(tmpString))
                faner21 = tmpString;
            tmpString = swSelModel.GetCustomInfoValue(config, "Faner22");
            if (!string.IsNullOrEmpty(tmpString))
                faner22 = tmpString;
            tmpString = swSelModel.GetCustomInfoValue(config, "colorFaner11");
            if (!string.IsNullOrEmpty(tmpString))
                colorfaner11 = tmpString;
            tmpString = swSelModel.GetCustomInfoValue(config, "colorFaner12");
            if (!string.IsNullOrEmpty(tmpString))
                colorfaner12 = tmpString;
            tmpString = swSelModel.GetCustomInfoValue(config, "colorFaner21");
            if (!string.IsNullOrEmpty(tmpString))
                colorfaner21 = tmpString;
            tmpString = swSelModel.GetCustomInfoValue(config, "colorFaner22");
            if (!string.IsNullOrEmpty(tmpString))
                colorfaner22 = tmpString;
        }
예제 #5
0
        //через открытое соединение
        private decimal execQueryProduct(string sql, ModelDoc2 swSelModel)
        {
            string currentConfig = swSelModel.IGetActiveConfiguration().Name;
            if (currentConfig.ToLower().Contains("по умолчани") || currentConfig.ToLower().Contains("default"))
                currentConfig = string.Empty;
            string articul = swSelModel.GetCustomInfoValue(currentConfig, "Articul");
            if (string.IsNullOrEmpty(articul))
            {
                articul = swSelModel.GetCustomInfoValue(string.Empty, "Articul");
                if (string.IsNullOrEmpty(articul))
                    throw new ArticleNotFoundException("Отсутствует артикул!", swSelModel);
            }
            int size1 = 0, size2 = 0, size3 = 0, size4 = 0, size5 = 0, size6 = 0, size7 = 0, size8 = 0;
            string idColor1 = string.Empty, idColor2 = string.Empty, idColor3 = string.Empty, idColor4 = string.Empty, idColor5 = string.Empty;
            FillForProductQuery(swSelModel, string.Empty, ref size1, ref size2, ref size3, ref size4, ref size5, ref size6, ref size7, ref size8, ref idColor1, ref idColor2, ref idColor3, ref idColor4, ref idColor5);
            if (currentConfig != string.Empty)
                FillForProductQuery(swSelModel, currentConfig, ref size1, ref size2, ref size3, ref size4, ref size5, ref size6, ref size7, ref size8, ref idColor1, ref idColor2, ref idColor3, ref idColor4, ref idColor5);

            using (OracleCommand cmd = new OracleCommand(sql))
            {
                cmd.Connection = Connection;
                cmd.CommandType = CommandType.Text;
                cmd.BindByName = true;
                cmd.Parameters.Add(new OracleParameter("P_NUMAGREE", _orderNumber));//"040714-1255-0101"));
                cmd.Parameters.Add(new OracleParameter("P_IDCOMPONENT", articul));
                cmd.Parameters.Add(new OracleParameter("P_SIZE1", size1));
                cmd.Parameters.Add(new OracleParameter("P_SIZE2", size2));
                cmd.Parameters.Add(new OracleParameter("P_SIZE3", size3));
                cmd.Parameters.Add(new OracleParameter("P_SIZE4", size4));
                cmd.Parameters.Add(new OracleParameter("P_SIZE5", size5));
                cmd.Parameters.Add(new OracleParameter("P_SIZE6", size6));
                cmd.Parameters.Add(new OracleParameter("P_SIZE7", size7));
                cmd.Parameters.Add(new OracleParameter("P_SIZE8", size8));

                cmd.Parameters.Add(new OracleParameter("P_IDCOLOR1", idColor1));
                cmd.Parameters.Add(new OracleParameter("P_IDCOLOR2", idColor2));
                cmd.Parameters.Add(new OracleParameter("P_IDCOLOR3", idColor3));
                cmd.Parameters.Add(new OracleParameter("P_IDCOLOR4", idColor4));
                cmd.Parameters.Add(new OracleParameter("P_IDCOLOR5", idColor5));

                OracleDataReader reader = cmd.ExecuteReader();

                if (reader.Read())
                {
                    if (reader["PRICE"] is decimal)
                        return (decimal)reader["PRICE"];
                    else
                        throw new Exception("Неправильный результат цены:" + reader["PRICE"]);
                }
                else
                    throw new Exception("Ошибка соединения с БД.");
            }
        }
예제 #6
0
        private decimal execQueryNonProduct(string sql, ModelDoc2 swSelModel)
        {
            string currentConfig = swSelModel.IGetActiveConfiguration().Name;
            if (currentConfig.ToLower().Contains("по умолчани") || currentConfig.ToLower().Contains("default"))
                currentConfig = string.Empty;
            string articul = swSelModel.GetCustomInfoValue(currentConfig, "Articul");
            if (string.IsNullOrEmpty(articul))
            {
                articul = swSelModel.GetCustomInfoValue(string.Empty, "Articul");
                if (string.IsNullOrEmpty(articul))
                    throw new ArticleNotFoundException("Отсутствует артикул!", swSelModel);
            }
            int size1Work = 0, size2Work = 0, size1 = 0, size2 = 0;
            string idColor1 = string.Empty, idColor2 = string.Empty, idColor3 = string.Empty, faner11 = string.Empty, faner12 = string.Empty, faner21 = string.Empty, faner22 = string.Empty, colorfaner11 = string.Empty, colorfaner12 = string.Empty, colorfaner21 = string.Empty, colorfaner22 = string.Empty;
            FillForNonProductQuery(swSelModel, string.Empty, ref size1, ref size2, ref size1Work, ref size2Work, ref idColor1, ref idColor2, ref idColor3, ref faner11, ref faner12, ref faner21, ref faner22, ref colorfaner11, ref colorfaner12, ref colorfaner21, ref colorfaner22);
            if (currentConfig != string.Empty)
                FillForNonProductQuery(swSelModel, currentConfig, ref size1, ref size2, ref size1Work, ref size2Work, ref idColor1, ref idColor2, ref idColor3, ref faner11, ref faner12, ref faner21, ref faner22, ref colorfaner11, ref colorfaner12, ref colorfaner21, ref colorfaner22);

            using (OracleCommand cmd = new OracleCommand(sql))
            {
                cmd.Connection = Connection;
                cmd.CommandType = CommandType.Text;
                cmd.BindByName = true;
                cmd.Parameters.Add(new OracleParameter("P_NUMAGREE", _orderNumber));//"040714-1255-0101"));
                cmd.Parameters.Add(new OracleParameter("P_IDCOMPONENT", articul));
                cmd.Parameters.Add(new OracleParameter("P_SIZE1", size1));
                cmd.Parameters.Add(new OracleParameter("P_SIZE2", size2));
                var curPrm = new OracleParameter("P_SIZE1WORK", OracleDbType.Int32, ParameterDirection.Input);
                curPrm.Value = size1Work;
                cmd.Parameters.Add(curPrm);
                curPrm = new OracleParameter("P_SIZE2WORK", OracleDbType.Int32, ParameterDirection.Input);
                curPrm.Value = size2Work;
                cmd.Parameters.Add(curPrm);
                cmd.Parameters.Add(new OracleParameter("P_IDCOLOR1", idColor1));
                cmd.Parameters.Add(new OracleParameter("P_IDCOLOR2", idColor2));
                cmd.Parameters.Add(new OracleParameter("P_IDCOLOR3", idColor3));
                cmd.Parameters.Add(new OracleParameter("P_IDFANER11", faner11));
                cmd.Parameters.Add(new OracleParameter("P_IDFANER12", faner12));
                cmd.Parameters.Add(new OracleParameter("P_IDCOLORFANER11", colorfaner11));
                cmd.Parameters.Add(new OracleParameter("P_IDCOLORFANER12", colorfaner12));
                cmd.Parameters.Add(new OracleParameter("P_IDFANER21", faner21));
                cmd.Parameters.Add(new OracleParameter("P_IDFANER22", faner22));
                cmd.Parameters.Add(new OracleParameter("P_IDCOLORFANER21", colorfaner21));
                cmd.Parameters.Add(new OracleParameter("P_IDCOLORFANER22", colorfaner22));
                cmd.Parameters.Add(new OracleParameter("P_ITPRODCALCPARENT", DBNull.Value));
                OracleDataReader reader = cmd.ExecuteReader();
                if (reader.Read())
                {
                    if (reader["PRICE"] is decimal)
                        return (decimal)reader["PRICE"];
                    else
                        return 0;
                }
                else
                    throw new Exception("Ошибка соединения с БД.");
            }
        }
예제 #7
0
        /// <summary>
        /// Возвращает цену компонента из БД
        /// </summary>
        /// <param name="model">Модель компонента</param>
        /// <returns>Цена</returns>
        private decimal сalculatePriceForModel(ModelDoc2 model)
        {
            try
            {
                bool isProduct = false;
                string isProductStr = model.GetCustomInfoValue("", "IsProduct");
                if (!string.IsNullOrEmpty(currentState))
                    throw new NullReferenceException("currentState");

                if (string.IsNullOrEmpty(isProductStr))
                    isProduct = false;
                if (isProductStr.ToLower().Contains("yes"))
                    isProduct = true;
                if (!isProduct)
                    return execQueryNonProduct("SELECT SCENTRE.GETSCICOMPPRICE_SWR(:P_NUMAGREE,:P_IDCOMPONENT,:P_SIZE1,:P_SIZE2,:P_SIZE1WORK,:P_SIZE2WORK,:P_IDCOLOR1,:P_IDCOLOR2,:P_IDCOLOR3,:P_IDFANER11,:P_IDFANER12,:P_IDCOLORFANER11,:P_IDCOLORFANER12,:P_IDFANER21,:P_IDFANER22,:P_IDCOLORFANER21,:P_IDCOLORFANER22,:P_ITPRODCALCPARENT) AS PRICE FROM DUAL", model);
                else
                    return execQueryProduct("SELECT SCENTRE.GETSCIPRODPRICE_SWR(:P_NUMAGREE,:P_IDCOMPONENT,:P_SIZE1,:P_SIZE2,:P_SIZE3,:P_SIZE4,:P_SIZE5,:P_SIZE6,:P_SIZE7,:P_SIZE8,:P_IDCOLOR1,:P_IDCOLOR2,:P_IDCOLOR3,:P_IDCOLOR4,:P_IDCOLOR5) AS PRICE FROM DUAL", model);

            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("ORA-01012") || ex.Message.Contains("ORA - 02396"))
                {
                    instance = new Repository();
                }
                throw ex;
            }
        }
예제 #8
0
        private void sendAttributes(ModelDoc2 model, Collection<AttributeInfo> componentsAttributesCollection, string path, string orderNumber, int fileType, string filePath, string fileName, string configuration)
        {
            string[] attributeNames = model.GetCustomInfoNames2(configuration);

            foreach (string attributeName in attributeNames)
            {
                string attributeValue = model.GetCustomInfoValue(configuration, attributeName);

                //Проверка записано ли свойство такого файла
                AttributeInfo attributeInfo = new AttributeInfo { Path = path, AttributeName = attributeName, AttributeValue = attributeValue };

                KeyValuePair<string, string> componentAttribute = new KeyValuePair<string, string>(path, attributeName);
                if (!componentsAttributesCollection.Contains(attributeInfo))
                {
                    componentsAttributesCollection.Add(attributeInfo);

                    //конвертация булевых атрибутов в формат БД
                    if (model.GetCustomInfoType3(configuration, attributeName) == 11)
                        attributeValue = (attributeValue == "Yes") ? "T" : "F";

                    //пропуск свойств без значений
                    if (!string.IsNullOrEmpty(attributeValue))

                        using (OracleCommand cmd = new OracleCommand())
                        {
                            cmd.Connection = Connection;
                            cmd.CommandText = "GENERAL.SWR_FILEDATA_ADD_SW";
                            cmd.CommandType = CommandType.StoredProcedure;
                            cmd.Parameters.Add("P_NUMAGREE", OracleDbType.Varchar2).Value = orderNumber;
                            cmd.Parameters.Add("P_CODEFILETYPE", OracleDbType.Int32).Value = fileType;
                            cmd.Parameters.Add("P_FILEPATH", OracleDbType.Varchar2).Value = filePath;
                            cmd.Parameters.Add("P_FILENAME", OracleDbType.Varchar2).Value = fileName;
                            cmd.Parameters.Add("P_IDFILEATTRIBUTE", OracleDbType.Varchar2).Value = attributeName;
                            cmd.Parameters.Add("P_ATTRIBUTEVALUE", OracleDbType.Varchar2).Value = attributeValue;
                            cmd.Parameters.Add("P_COMMIT", OracleDbType.Char).Value = 'T';
                            cmd.ExecuteNonQuery();
                        }

                }
                else
                {
                }
            }
        }
예제 #9
0
        private void getPriceForComponent(ModelDoc2 model, bool ParentCalcStruct, Action<decimal> nextPrice, Action<Exception, string> nextError)
        {
            string currentConfig = model.IGetActiveConfiguration().Name;

            if (currentConfig.ToLower().Contains("по умолчани") || currentConfig.ToLower().Contains("default"))
                currentConfig = string.Empty;

            string isProduct = model.GetCustomInfoValue(currentConfig, "IsProduct");
            if (string.IsNullOrEmpty(isProduct))
            {
                isProduct = model.GetCustomInfoValue(string.Empty, "IsProduct");
                if (string.IsNullOrEmpty(isProduct))
                    isProduct = "No";
            }

            if (isProduct == "Yes")
            {
                //изделие

                //Проверка существования артикула для компонента в случает отсутствия, расчет цены на сам компонент не производится
                string articul = model.GetCustomInfoValue(string.Empty, "Articul");
                if (string.IsNullOrEmpty(articul))
                    articul = model.GetCustomInfoValue(currentConfig, "Articul");

                if (!string.IsNullOrEmpty(articul))
                {
                    try
                    {
                        nextPrice(сalculatePriceForModel(model));
                    }
                    catch (Exception e)
                    {
                        if (checkError(e))
                            nextError(e, Path.GetFileName(model.GetPathName()));
                    }
                }

                string s = model.GetPathName();
                AssemblyDoc model_assembly = model as AssemblyDoc;
                if (model_assembly != null)
                {
                    bool calcStruct = true;
                    if (!string.IsNullOrEmpty(articul))
                    {
                        string calcStructStr = model.get_CustomInfo2(string.Empty, "CalcStruct");
                        if (calcStructStr.ToLower() == "no")
                            calcStruct = false;
                    }

                    var components = (object[])((AssemblyDoc)model).GetComponents(true);
                    foreach (var component in components)
                    {
                        var comp = (Component2)component;
                        ModelDoc2 _model = comp.IGetModelDoc();
                        if (_model != null)
                        {
                            getPriceForComponent(_model, calcStruct, nextPrice, nextError);
                        }
                    }
                }
            }
            else
            {
                //не изделие

                string articul = model.GetCustomInfoValue(string.Empty, "Articul");
                if (string.IsNullOrEmpty(articul))
                    articul = model.GetCustomInfoValue(currentConfig, "Articul");

                string isIndependentStr = model.get_CustomInfo2(string.Empty, "IsIndependent");
                bool isIndependent = true;
                if (string.IsNullOrEmpty(isIndependentStr) || isIndependentStr.ToLower() == "no")
                    isIndependent = false;

                if (isIndependent)
                {
                    bool calcStruct = true;
                    if (!string.IsNullOrEmpty(articul))
                    {
                        //независимый и с артикулом
                        try
                        {
                            nextPrice(сalculatePriceForModel(model));
                        }
                        catch (Exception e)
                        {
                            if (checkError(e))
                                nextError(e, Path.GetFileName(model.GetPathName()));
                        }
                        string calcStructStr = model.get_CustomInfo2(string.Empty, "CalcStruct");

                        if (calcStructStr.ToLower() == "no")
                            calcStruct = false;
                    }

                    if (calcStruct)
                    {
                        AssemblyDoc model_assembly = model as AssemblyDoc;
                        if (model_assembly != null)
                        {
                            var components = (object[])((AssemblyDoc)model).GetComponents(true);
                            foreach (var component in components)
                            {
                                var comp = (Component2)component;
                                ModelDoc2 _model = comp.IGetModelDoc();
                                if (_model != null)
                                {
                                    getPriceForComponent(_model, calcStruct, nextPrice, nextError);
                                }
                            }
                        }
                    }
                }
                else
                {
                    //компонент входит в состав изделия
                    if (ParentCalcStruct)
                    {
                        //нужно получить цену
                        bool calcStruct = true;
                        if (!string.IsNullOrEmpty(articul))
                        {
                            try
                            {
                                nextPrice(сalculatePriceForModel(model));
                            }
                            catch (Exception e)
                            {
                                if (checkError(e))
                                    nextError(e, Path.GetFileName(model.GetPathName()));
                            }
                            string calcStructStr = model.get_CustomInfo2(string.Empty, "CalcStruct");
                            if (calcStructStr.ToLower() == "no")
                                calcStruct = false;
                        }

                        AssemblyDoc model_assembly = model as AssemblyDoc;
                        if (model_assembly != null)
                        {
                            var components = (object[])((AssemblyDoc)model).GetComponents(true);
                            foreach (var component in components)
                            {
                                var comp = (Component2)component;
                                ModelDoc2 _model = comp.IGetModelDoc();
                                if (_model != null)
                                {
                                    getPriceForComponent(_model, calcStruct, nextPrice, nextError);
                                }
                            }
                        }
                    }
                    else
                    {
                        if (model as AssemblyDoc != null)
                        {
                            var components = (object[])((AssemblyDoc)model).GetComponents(true);
                            foreach (var component in components)
                            {
                                var comp = (Component2)component;
                                ModelDoc2 _model = comp.IGetModelDoc();
                                if (_model != null)
                                {
                                    getPriceForComponent(_model, false, nextPrice, nextError);
                                }
                            }
                        }
                    }
                }
            }
        }
예제 #10
0
 private bool CheckPropForArticul(ModelDoc2 model)
 {
     bool ret = false;
     var commonPropNames = (string[])model.GetCustomInfoNames();
     foreach (var commonPropName in commonPropNames)
     {
         if (commonPropName.ToLower() == "articul" && model.GetCustomInfoValue("", commonPropName) != "")
             ret = true;
     }
     if (model.GetConfigurationCount() >= 1)
     {
         string confName = model.IGetActiveConfiguration().Name;
         var confPropNames = (string[])model.GetCustomInfoNames2(confName);
         foreach (var confPropName in confPropNames)
         {
             if (confPropName.ToLower() == "articul" && model.GetCustomInfoValue(confName, confPropName) != "")
                 ret = true;
         }
     }
     return ret;
 }
예제 #11
0
 public bool SetModelProperty(ModelDoc2 model, string fieldName, string cfgName, swCustomInfoType_e fieldType, string val, bool checkFirst = false)
 {
     bool isPropertyChanged = false;
     string fieldValue = string.Empty;
     if (checkFirst)
     {
         fieldValue = model.GetCustomInfoValue(cfgName, fieldName);
         if (fieldValue == val)
             return isPropertyChanged;
     }
     if (!string.IsNullOrEmpty(fieldValue.Trim()) && fieldValue != "-" && !fieldValue.Contains("Color"))
         isPropertyChanged = true;
     model.AddCustomInfo3(cfgName, fieldName, (int)fieldType, val);
     model.set_CustomInfo2(cfgName, fieldName, val);
     return isPropertyChanged;
 }
예제 #12
0
        public void SaveDrawingV2()
        {
            //This callback is for a utility to save an un-saved drawing of a part with a BPA part number into the correct Vault directory with the correct file name.

            DrawingDoc swDraw = iSwApp.ActiveDoc;

            SolidWorks.Interop.sldworks.View swView = swDraw.IGetFirstView();
            swView = swView.GetNextView();
            ModelDoc2 swDrawModel   = swView.ReferencedDocument;
            int       errors        = 0;
            int       warnings      = 0;
            String    configName    = swView.ReferencedConfiguration;
            String    drawingNumber = swDrawModel.GetCustomInfoValue(configName, "Drawing Number");

            //MessageBox.Show("The drawing number is: " + drawingNumber);


            if (drawingNumber == "" || drawingNumber == " ")
            {
                MessageBox.Show("Please fill out the drawing number field on the model's file data card before proceeding.", "Missing Drawing Number", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }

            String modelPath = swDrawModel.GetPathName().ToString();

            MessageBox.Show("The model's path is: " + modelPath);
            if (modelPath == "" || modelPath == " ")
            {
                MessageBox.Show("Please save the model before proceeding", "Save the Model", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }

            swDrawModel = iSwApp.ActiveDoc;
            String swDrawPath = swDrawModel.GetPathName().ToString();

            //MessageBox.Show("The drawing path is: " + swDrawPath);
            if (swDrawPath != "")
            {
                MessageBox.Show("The drawing has already been saved as '" + swDrawPath + "' in the Vault.", "Drawng Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else
            {
                string[]     pathDir       = modelPath.Split('\\');
                int          pathDirLength = pathDir.Length;
                string       path          = pathDir[0] + "\\" + pathDir[1] + "\\" + pathDir[2] + "\\" + pathDir[3] + "\\" + pathDir[4] + "\\";
                string       dwgPath       = path + drawingNumber + ".SLDDRW";
                string       dialogText    = "The drawing path is: \n" + dwgPath + "\nContinue?";
                DialogResult result        = MessageBox.Show(dialogText, "Save Drawing?", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                if (result == DialogResult.OK)
                {
                    ModelDoc2 Model = SwApp.ActiveDoc;
                    Boolean   Save;
                    Save = Model.SaveAs4(dwgPath, 0, 1, errors, warnings);
                }
            }


            //ModelDocExtension swModExt = default(ModelDocExtension);
            //Return the filepath of the referenced model in the parent view in the active drawing document.
            //string swModel = swView.GetReferencedModelName();
        }
예제 #13
0
        public static void Actualization(ModelDoc2 model, SwAddin _mSwAddin)
        {
            Component2 _swSelectedComponent = model.ConfigurationManager.ActiveConfiguration.GetRootComponent3(true);
            OleDbCommand cm;
            OleDbDataReader rd;
            OleDbConnection oleDb;
            if (!_mSwAddin.OpenModelDatabase(model, out oleDb))
                return;
            cm = new OleDbCommand("SELECT * FROM faners ORDER BY FanerName ", oleDb);
            rd = cm.ExecuteReader();
            List<Faner> faners = new List<Faner>();
            while (rd.Read())
            {
                if (rd["FanerType"] as string != null)
                {
                    faners.Add(new Faner((string)rd["FanerName"], (string)rd["FanerType"], (string)rd["DecorGroup"]));
                }
                else
                {
                    faners.Add(new Faner((string)rd["FanerName"], string.Empty, (string)rd["DecorGroup"]));
                }
            }
            rd.Close();
            Feature feature;
            foreach (var faner in faners)
            {
                string suffix = faner.FanerName.Substring(faner.FanerName.Length - 2, 2);

                feature = FindEdge(_swSelectedComponent, faner.AxFanerName);
                if (feature != null)
                {
                    if (feature.IsSuppressed())
                    {
                        _mSwAddin.SetModelProperty(model, "Faner" + suffix, "", swCustomInfoType_e.swCustomInfoText, string.Empty, true);
                        _mSwAddin.SetModelProperty(model, "colorFaner" + suffix, "", swCustomInfoType_e.swCustomInfoText, string.Empty, true);
                    }
                    else
                    {
                        string fieldValue = model.GetCustomInfoValue(string.Empty, "Faner" + suffix);
                        if (fieldValue == string.Empty)
                        {
                            string msgText = "Для данной детали: " + model.GetPathName() + " кромка Faner" + suffix + " в модели не соответствует свойствам файла сборки. Данная кромка не будет импортирована в программу Покупки! Чтобы исправить эту ошибку используйте опцию \"MrDoors - Отделка кромки\"";
                            MessageBox.Show(msgText, @"MrDoors", MessageBoxButtons.OK);
                        }
                    }
                }
            }
        }
예제 #14
0
        //获取当前文件的Drawing属性
        public static DrawingModel GetDrawingInfo()
        {
            DrawingModel objDrawing = new DrawingModel();
            //【1】打开指定的SW文件,并获取文件名
            ModelDoc2 swDoc      = swAppHelper.ActiveDoc();
            string    fileName   = swDoc.GetPathName();                                 //文件名
            string    configName = swDoc.ConfigurationManager.ActiveConfiguration.Name; //当前激活配置名

            if (fileName == null || fileName.Length == 0)
            {
                Msg.ShowError("无法获取文件名,请保存文件后重试!");
                return(null);
            }

            //【2】从模型中获取主要属性值
            string drawingcode      = swDoc.GetCustomInfoValue(configName, "图号");
            string materialname     = swDoc.GetCustomInfoValue(configName, "名称");
            string materialspec     = swDoc.GetCustomInfoValue(configName, "规格型号");
            string weight           = swDoc.GetCustomInfoValue(configName, "重量");
            string unit             = swDoc.GetCustomInfoValue(configName, "单位");
            string purchasetypeid   = swDoc.GetCustomInfoValue(configName, "采购类型");
            string selectiontypeid  = swDoc.GetCustomInfoValue(configName, "选型分类");
            string surfacetreatment = swDoc.GetCustomInfoValue(configName, "表面处理");
            string heattreatment    = swDoc.GetCustomInfoValue(configName, "热处理");
            string brand            = swDoc.GetCustomInfoValue(configName, "品牌");
            string remark           = swDoc.GetCustomInfoValue(configName, "备注");

            //【3】封装图号实体类对象属性
            objDrawing.FileName         = fileName;
            objDrawing.ConfigName       = configName;
            objDrawing.DrawingCode      = drawingcode;
            objDrawing.MaterialName     = materialname;
            objDrawing.MaterialSpec     = materialspec;//XorG:规格型号
            objDrawing.Weight           = weight;
            objDrawing.Unit             = unit;
            objDrawing.PurchaseTypeId   = purchasetypeid;
            objDrawing.SelectionTypeId  = selectiontypeid;
            objDrawing.SurfaceTreatment = surfacetreatment;
            objDrawing.HeatTreatment    = heattreatment;
            objDrawing.Brand            = brand;
            objDrawing.ReMark           = remark;
            return(objDrawing);
        }