private Feature GetUpdatedCutList()
        {
            Feature swFeat = (Feature)swMainModel.FirstFeature();

            while (swFeat != null)
            {
                if (swFeat.GetTypeName2() == "SolidBodyFolder")
                {
                    BodyFolder swBodyFolder = swFeat.GetSpecificFeature2();
                    swBodyFolder.SetAutomaticCutList(true);
                    swBodyFolder.SetAutomaticUpdate(true);
                    Feature cutList = swFeat.GetFirstSubFeature();
                    while (cutList != null)
                    {
                        if (cutList.GetTypeName2() == "CutListFolder")
                        {
                            return(cutList);
                        }
                        cutList = cutList.GetNextSubFeature();
                    }
                    return(null);
                }
                swFeat = swFeat.GetNextFeature();
            }
            return(null);
        }
예제 #2
0
    private void find_bom()
    {
        bool    found   = false;
        Feature feature = (Feature)part.FirstFeature();

        if (part != null)
        {
            while (feature != null)
            {
                if (feature.GetTypeName2().ToUpper() == "BOMFEAT")
                {
                    feature.Select2(false, -1);
                    BomFeature bom = (BomFeature)swSelMgr.GetSelectedObject6(1, -1);
                    fill_table(bom);
                    if (identify_table(_cols, _masterHashes))
                    {
                        found = true;
                        System.Diagnostics.Debug.WriteLine("Found a table.");
                        break;
                    }
                }
                feature = (Feature)feature.GetNextFeature();
            }
        }
        if (!found)
        {
            throw new SWTableTypeException("I couldn't find the correct table.");
        }
    }
        public static void KL_ReadMates(ModelDoc2 swModel, SldWorks swApplication)
        {
            var swFeature = (Feature)swModel.FirstFeature();

            while (swFeature != null)
            {
                if ("MateGroup" == swFeature.GetTypeName())
                {
                    swApplication.SendMsgToUser(swFeature.Name);
                    var swSubFeature = (Feature)swFeature.GetFirstSubFeature();

                    while (swSubFeature != null)
                    {
                        var swMate = (Mate2)swSubFeature.GetSpecificFeature2();
                        if (swMate != null)
                        {
                            swApplication.SendMsgToUser("C'è la constraint: " + swMate.Type.ToString());
                        }
                        swSubFeature = swSubFeature.GetNextSubFeature();
                    }
                }

                swFeature = swFeature.GetNextFeature();
            }
        }
예제 #4
0
파일: Process.cs 프로젝트: cxfwolfkings/EIM
        public void TraverseModelFeatures(ModelDoc2 swModel, long nLevel)
        {
            Feature swFeat;

            swFeat = (Feature)swModel.FirstFeature();

            TraverseFeatures(swFeat, nLevel);
        }
예제 #5
0
        private void GetBendsInfo(string config)
        {
            var swPart = (IPartDoc)_swModel;

            _swFeat = (Feature)_swModel.FirstFeature();
            while ((_swFeat != null))
            {
                if (IsSheetFeature(_swFeat.GetTypeName()))
                {
                    var parentFeatureName = _swFeat.Name;
                    var stateOfEdgeFlange = IsSuppressedEdgeFlange(parentFeatureName);
                    _swSubFeat = _swFeat.IGetFirstSubFeature();

                    while ((_swSubFeat != null))
                    {
                        if (_swSubFeat.GetTypeName() == "OneBend" || _swSubFeat.GetTypeName() == "SketchBend")
                        {
                            PartBendInfos.Add(new PartBendInfo
                            {
                                Config      = config,
                                EdgeFlange  = parentFeatureName,
                                OneBend     = _swSubFeat.Name,
                                IsSupressed = stateOfEdgeFlange
                            });

                            _swSubFeat.Select(false);

                            if (stateOfEdgeFlange)
                            {
                                swPart.EditSuppress();
                            }
                            else
                            {
                                swPart.EditUnsuppress();
                            }

                            _swSubFeat.DeSelect();
                        }
                        _swSubFeat = (Feature)_swSubFeat.GetNextSubFeature();
                    }
                }
                _swFeat = (Feature)_swFeat.GetNextFeature();
            }
        }
예제 #6
0
        private void GetBendsInfo(string config)
        {
            var swPart  = (IPartDoc)modelDoc;
            var _swFeat = (Feature)modelDoc.FirstFeature();

            while ((_swFeat != null))
            {
                //   MessageObserver.Instance.SetMessage("Got feature " + _swFeat.Name);
                if (IsSheetFeature(_swFeat.GetTypeName()))
                {
                    var parentFeatureName = _swFeat.Name;
                    var stateOfEdgeFlange = IsSuppressedEdgeFlange(parentFeatureName);
                    var _swSubFeat        = _swFeat.IGetFirstSubFeature();

                    while ((_swSubFeat != null))
                    {
                        if (_swSubFeat.GetTypeName() == "OneBend" || _swSubFeat.GetTypeName() == "SketchBend")
                        {
                            partBendInfo.Config      = config;
                            partBendInfo.EdgeFlange  = parentFeatureName;
                            partBendInfo.OneBend     = _swSubFeat.Name;
                            partBendInfo.IsSupressed = stateOfEdgeFlange;

                            _swSubFeat.Select(false);

                            if (stateOfEdgeFlange)
                            {
                                swPart.EditSuppress();
                            }
                            else
                            {
                                swPart.EditUnsuppress();
                            }

                            _swSubFeat.DeSelect();
                        }
                        _swSubFeat = (Feature)_swSubFeat.GetNextSubFeature();
                    }
                }
                _swFeat = (Feature)_swFeat.GetNextFeature();
            }
        }
예제 #7
0
        public void DeleteBom()
        {
            SldWorks  swapp   = default(SldWorks);
            ModelDoc2 swmodel = default(ModelDoc2);

            swapp   = (SldWorks)Marshal.GetActiveObject("SldWorks.Application");
            swmodel = swapp.ActiveDoc;
            Feature swFeat = swmodel.FirstFeature();

            while ((swFeat != null))
            {
                if (swFeat.GetTypeName() == "BomFeat")
                {
                    swFeat.Select(true);
                    swmodel.EditDelete();
                    swFeat = swmodel.FirstFeature();
                }
                swFeat = swFeat.GetNextFeature();
            }
        }
예제 #8
0
        private void ExportButtonClick(object sender, EventArgs e)
        {
            swModelDoc    = swApp.ActiveDoc;
            swModelDocExt = swModelDoc.Extension;
            swAssDoc      = swApp.ActiveDoc as AssemblyDoc;
            swFeat        = (Feature)swModelDoc.FirstFeature();
            swFeatMgr     = (FeatureManager)swModelDoc.FeatureManager;
            while ((swFeat != null))
            {
                sFeatType = swFeat.GetTypeName();

                if (sFeatType == "CommentsFolder")
                {
                    swCommentFolder = (CommentFolder)swFeat.GetSpecificFeature2();

                    nbrComments = swCommentFolder.GetCommentCount();
                    vComments   = (object[])swCommentFolder.GetComments();
                    for (i = 0; i <= (nbrComments - 1); i++)
                    {
                        swComment = (Comment)vComments[i];
                        string     name = swComment.Name;
                        Component2 comp = swAssDoc.GetComponentByName(name);
                        swModelDocExt.SelectByID2(comp.GetSelectByIDString(), "COMPONENT", 0, 0, 0, false, 0, null, 0);
                        swAssDoc.HideComponent();
                    }

                    for (i = 0; i <= (nbrComments - 1); i++)
                    {
                        swComment = (Comment)vComments[i];
                        string     name = swComment.Name;
                        Component2 comp = swAssDoc.GetComponentByName(name);
                        swModelDocExt.SelectByID2(comp.GetSelectByIDString(), "COMPONENT", 0, 0, 0, false, 0, null, 0);
                        swAssDoc.ShowComponent();
                        swModelDocExt.SetUserPreferenceString((int)swUserPreferenceStringValue_e.swFileSaveAsCoordinateSystem, (int)swUserPreferenceOption_e.swDetailingNoOptionSpecified, "CoordinateSystem");
                        swModelDocExt.SaveAs("C:/Users/Izmar/Documents/vmpc_models/jan2018/stlexport/" + swComment.Text + ".STL", (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, 0, ref errors, ref warnings);
                        swAssDoc.HideComponent();
                    }
                    for (i = 0; i <= (nbrComments - 1); i++)
                    {
                        swComment = (Comment)vComments[i];
                        string     name = swComment.Name;
                        Component2 comp = swAssDoc.GetComponentByName(name);
                        swModelDocExt.SelectByID2(comp.GetSelectByIDString(), "COMPONENT", 0, 0, 0, false, 0, null, 0);
                        swAssDoc.ShowComponent();
                    }
                }

                // Get next feature in FeatureManager design tree
                swFeat = (Feature)swFeat.GetNextFeature();
            }
        }
예제 #9
0
        private static BomFeature GetBOM(ModelDoc2 swModel)
        {
            BomFeature swBomFeat;
            Feature    swFeat = swModel.FirstFeature();

            while (swFeat != null)
            {
                if ("BomFeat" == swFeat.GetTypeName())
                {
                    swBomFeat = swFeat.GetSpecificFeature2();
                    return(swBomFeat);
                }
                swFeat = swFeat.GetNextFeature();
            }
            return(null);
        }
예제 #10
0
        public static Feature GetFeatureByTypeName(this ModelDoc2 model, string featureName)
        {
            var feature = model.FirstFeature() as Feature;

            while (feature != null)
            {
                if (feature.GetTypeName() == featureName)
                {
                    return(feature);
                }

                feature = feature.GetNextFeature() as Feature;
            }

            return(null);
        }
예제 #11
0
        public static List <Feature> GetAllFeaturesByTypeName(this ModelDoc2 model, string featureName)
        {
            var feature = model.FirstFeature() as Feature;
            var list    = new List <Feature>();

            while (feature != null)
            {
                var name = feature.GetTypeName();

                if (name == featureName)
                {
                    list.Add(feature);
                }

                feature = feature.GetNextFeature() as Feature;
            }

            return(list);
        }
예제 #12
0
        /// <summary>
        /// Creates a StorageModel for reading and writing data on the given Model
        /// </summary>
        /// <param name="model">Model to read and write data keys from</param>
        public StorageModel(ModelDoc2 model)
        {
            this.model = model;
            data = new Dictionary<string, LinkedList<IAttribute>>();
            //storedDoubles = new Dictionary<string,List<double>>();
            storedObjects = new Dictionary<string,object>();
            //storedStrings = new Dictionary<string,List<string>>();
            Feature feat = model.FirstFeature(); //Start scan of robot attribute's sub-features
            IAttribute attr;
            nextID = 0;
            int id;
            string path;
            int stopindex;
            LinkedList<IAttribute> newlist;

            while (feat != null)  //Scan robot attribute's sub-features
            {
                if (feat.GetTypeName().Equals("Attribute"))
                {
                    attr = (IAttribute)feat.GetSpecificFeature2();
                    if (attr.GetName().StartsWith("gsim"))
                    {
                        stopindex = attr.GetName().IndexOf("_");
                        id = Convert.ToInt32(attr.GetName().Substring(4, stopindex-4));
                        if (id >= nextID)
                            nextID = id + 1;
                        path = ((IParameter)attr.GetParameter("name")).GetStringValue();
                        if (!data.ContainsKey(path))
                        {
                            newlist = new LinkedList<IAttribute>();
                            newlist.AddLast(attr);
                            data.Add(path, newlist);
                        }
                        else
                            data[path].AddLast(attr);
                    }
                }
                feat = feat.GetNextFeature();
            }
        }
예제 #13
0
        internal static void drwChangeConfig(string cfgName)
        {
            ModelDoc2  swModel = iSwApp.ActiveDoc;
            DrawingDoc swDraw;
            bool       retVal;

            SolidWorks.Interop.sldworks.View swView;

            swDraw = (DrawingDoc)swModel;
            swView = swDraw.GetFirstView() as SolidWorks.Interop.sldworks.View;

            //Traverse the drawing views, select each view, and set the referenced configuration to the coice selected on frmDrawConfigSwitch
            while (swView != null)
            {
                retVal = swModel.Extension.SelectByID2(swView.Name, "DRAWINGVIEW", 0, 0, 0, false, 0, null, 0);
                swView.ReferencedConfiguration = cfgName;
                swView = swView.GetNextView();
            }

            //Insert logic to determine if there is a BOM table associated with this drawing. Not entirely needed, but would help
            //speed up the process by not having to loop the features below.

            BomFeature swBOMFeat;
            Feature    swFeat = swModel.FirstFeature();

            while (swFeat != null)
            {
                if (swFeat.GetTypeName2() == "BomFeat")
                {
                    string bomName = swFeat.Name;
                    swBOMFeat = swFeat.GetSpecificFeature2();
                    int cfgCount = swBOMFeat.GetConfigurationCount(true);
                    swBOMFeat.ISetConfigurations(true, cfgCount, true, cfgName);
                }
                swFeat = swFeat.GetNextFeature();
            }

            swModel.ClearSelection2(true);
            swDraw.ForceRebuild();
        }
예제 #14
0
        public static Feature GetFeatureInPrt(this ModelDoc2 swDoc, string name)
        {
            Feature feature     = null;
            string  featureName = "";

            feature = swDoc.FirstFeature();

            while (feature != null)
            {
                featureName = feature.Name;
                if (featureName == name)
                {
                    return(feature);
                }
                else
                {
                    feature = feature.GetNextFeature();
                }
            }

            return(null);
        }
예제 #15
0
        /// <summary>
        /// 获取根组件的配合(MATE)
        /// </summary>
        /// <param name="rootComponent"></param>
        /// <returns></returns>
        private static List <Mate2> GetMatesOfRootComponent(Component2 rootComponent)
        {
            if (rootComponent == null)
            {
                return(null);
            }

            Feature      feature = null;
            ModelDoc2    doc     = rootComponent.GetModelDoc2();
            List <Mate2> mates   = new List <Mate2>();
            Mate2        pMate   = null;

            //获得配合组(MateGroup)
            feature = doc.FirstFeature();
            while (feature != null)
            {
                if (feature.GetTypeName2() == "MateGroup")
                {
                    break;
                }
                feature = feature.GetNextFeature();
            }

            // 从配合组的子特征中提取配合
            if (feature != null)
            {
                feature = feature.GetFirstSubFeature();
                while (feature != null)
                {
                    pMate = feature.GetSpecificFeature2();
                    mates.Add(pMate);
                    feature = feature.GetNextSubFeature();
                }
            }

            return(mates);
        }
예제 #16
0
        /// <summary>
        /// Returns sheet metal cut list  by configuration name
        /// </summary>
        /// <param name="configuratuinName"></param>
        /// <param name="SwModel"></param>
        /// <returns></returns>
        public static DataToExport GetDataToExport(ModelDoc2 swModel)
        {
            solidWorksDocument = swModel;
            DataToExport dataToExport = new DataToExport();
            string       valOut;
            const string BoundingBoxLengthRu    = @"Длина граничной рамки"; // rename, change number to eng/rus
            const string BoundingBoxLengthEng   = @"Bounding Box Length";
            const string BoundingBoxWidthRu     = @"Ширина граничной рамки";
            const string BoundingBoxWidthEng    = @"Bounding Box Width";
            const string SheetMetalThicknessRu  = @"Толщина листового металла";
            const string SheetMetalThicknessEng = @"Sheet Metal Thickness";
            const string BendsRu  = @"Сгибы";
            const string BendsEng = @"Bends";
            Feature      swFeat2  = solidWorksDocument.FirstFeature();

            while (swFeat2 != null)
            {
                if (swFeat2.GetTypeName2() == "SolidBodyFolder")
                {
                    BodyFolder swBodyFolder = swFeat2.GetSpecificFeature2();
                    swFeat2.Select2(false, -1);
                    swBodyFolder.SetAutomaticCutList(true);
                    swBodyFolder.UpdateCutList();
                    Feature swSubFeat = swFeat2.GetFirstSubFeature();
                    while (swSubFeat != null)
                    {
                        if (swSubFeat.GetTypeName2() == "CutListFolder")
                        {
                            //MessageObserver.Instance.SetMessage("GetTypeName2: " + swSubFeat.GetTypeName2() + "; swSubFeat.Name " + swSubFeat.Name);
                            BodyFolder bodyFolder = swSubFeat.GetSpecificFeature2();

                            if (bodyFolder.GetCutListType() != (int)swCutListType_e.swSheetmetalCutlist)
                            {
                                goto m1;
                            }
                            swSubFeat.Select2(false, -1);
                            bodyFolder.SetAutomaticCutList(true);
                            bodyFolder.UpdateCutList();
                            var    swCustProp = swSubFeat.CustomPropertyManager;
                            string tempOutBoundingBoxLength;
                            swCustProp.Get4(BoundingBoxLengthRu, true, out valOut, out tempOutBoundingBoxLength);
                            if (string.IsNullOrEmpty(tempOutBoundingBoxLength))
                            {
                                swCustProp.Get4(BoundingBoxLengthEng, true, out valOut, out tempOutBoundingBoxLength);
                            }

                            dataToExport.WorkpieceX = SafeConvertToDecemal(tempOutBoundingBoxLength);//Convert.ToDecimal(tempOutBoundingBoxLength.Replace(".", ","));

                            string ширинаГраничнойРамки;
                            swCustProp.Get4(BoundingBoxWidthRu, true, out valOut,
                                            out ширинаГраничнойРамки);
                            if (string.IsNullOrEmpty(ширинаГраничнойРамки))
                            {
                                swCustProp.Get4(BoundingBoxWidthEng, true, out valOut,
                                                out ширинаГраничнойРамки);
                            }

                            dataToExport.WorkpieceY = SafeConvertToDecemal(ширинаГраничнойРамки);//Convert.ToDecimal(ширинаГраничнойРамки.Replace(".", ","));

                            string толщинаЛистовогоМеталла;
                            swCustProp.Get4(SheetMetalThicknessRu, true, out valOut,
                                            out толщинаЛистовогоМеталла);
                            if (string.IsNullOrEmpty(толщинаЛистовогоМеталла))
                            {
                                swCustProp.Get4(SheetMetalThicknessEng, true, out valOut,
                                                out толщинаЛистовогоМеталла);
                            }
                            dataToExport.Thickness = SafeConvertToDecemal(толщинаЛистовогоМеталла);//Convert.ToDecimal(толщинаЛистовогоМеталла.Replace(".", ","), );

                            string сгибы;
                            swCustProp.Get4(BendsRu, true, out valOut, out сгибы);
                            if (string.IsNullOrEmpty(сгибы))
                            {
                                swCustProp.Get4(BendsEng, true, out valOut, out сгибы);
                            }
                            //  swCustProp.Set(BendsRu, сгибы);
                            dataToExport.Bend = Convert.ToInt32(сгибы);

                            dataToExport.PaintX      = GetDimentions()[0];
                            dataToExport.PaintY      = GetDimentions()[1];
                            dataToExport.PaintZ      = GetDimentions()[2];
                            dataToExport.SurfaceArea = GetSurfaceArea();
                        }
m1:
                        swSubFeat = swSubFeat.GetNextFeature();
                    }
                }
                swFeat2 = swFeat2.GetNextFeature();
            }
            solidWorksDocument = null;
            return(dataToExport);
        }
예제 #17
0
        static void Main(string[] args)
        {
            SldWorks.SldWorks swApp;
            swApp = new SldWorks.SldWorks();

            ModelDoc2   swModel = default(ModelDoc2);
            Component2  swComponent;
            AssemblyDoc swAssembly;

            object[]    Components       = null;
            object[]    swMateEntityList = null;
            MateEntity2 swMateEntity;
            Mate2       swMate;
            MateInPlace swMateInPlace;
            int         numMateEntities = 0;
            int         i = 0;
            dynamic     temp;
            Component2  temp2;

            Feature swFeat = default(Feature);
            Feature swSubFeat;
            string  Filename = null;
            int     errors   = 0;
            int     warnings = 0;

            Filename = "F:\\solidWorksAPI\\TEST_20180105\\Assembly_20180105.sldasm";

            // Open document
            swApp.OpenDoc6(Filename, (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);
            swModel    = (ModelDoc2)swApp.ActiveDoc;
            swAssembly = (AssemblyDoc)swModel;

            /*           // Iterate through parts document and list concentric mate. Would Get repeating ones.
             *          Components = (Object[])swAssembly.GetComponents(false);
             *          foreach (Object SingleComponent in Components)
             *          {
             *              swComponent = (Component2)SingleComponent;
             *              Console.WriteLine("Name of component: " + swComponent.Name2);
             *              Mates = (Object[])swComponent.GetMates();
             *              if (Mates != null)
             *              {
             *                  foreach (Object SingleMate in Mates)
             *                  {
             *                      if (SingleMate is SolidWorks.Interop.sldworks.Mate2)
             *                      {
             *                          swMate = (Mate2)SingleMate;
             *                          if (swMate.Type == 1)
             *                              Console.WriteLine("Found one concentric mate.");
             *
             *                      }
             *
             *
             *                      if (SingleMate is SolidWorks.Interop.sldworks.MateInPlace)
             *
             *                      {
             *
             *                          swMateInPlace = (MateInPlace)SingleMate;
             *
             *                          numMateEntities = swMateInPlace.GetMateEntityCount();
             *
             *                          for (i = 0; i <= numMateEntities - 1; i++)
             *
             *                          {
             *
             *                              Console.WriteLine(" Mate component name: " + swMateInPlace.get_MateComponentName(i));
             *
             *                              Console.WriteLine(" Type of mate inplace: " + swMateInPlace.get_MateEntityType(i));
             *
             *                          }
             *                      }
             *                  }
             *
             *              }
             *          }
             *
             */
            // Get first feature in swModel
            swFeat = (Feature)swModel.FirstFeature();
            // Iterate over features in this part document in
            // FeatureManager design tree

            while ((swFeat != null))
            {
                // Write the name of the feature and its
                // creator to the Immediate window
                Console.WriteLine("  Feature " + swFeat.Name + " created by " + swFeat.GetTypeName());

                if (swFeat.GetTypeName() == "MateGroup")
                {
                    // Get first mate, which is a subfeature
                    swSubFeat = (Feature)swFeat.GetFirstSubFeature();

                    while (swSubFeat != null)
                    {
                        swMate = swSubFeat.GetSpecificFeature2();
                        // Go further analysis if swMate is of concentric type
                        if (swMate != null & swMate.Type == (int)swMateType_e.swMateCONCENTRIC)
                        {
                            Console.WriteLine(swSubFeat.Name);
                            Console.WriteLine("Num of Entity envolved: " + swMate.GetMateEntityCount());
                            //Console.WriteLine(swMate.MateEntity(2).GetEntityParamsSize());
                            for (i = 0; i <= 1; i++)
                            {
                                swMateEntity = swMate.MateEntity(i);
                                // Can't watch entity params in the watch window but works if setting a new variable.
                                temp = swMateEntity.EntityParams;
예제 #18
0
        /// <summary>
        /// Overgrown monster function that does everything. We need some refactoring here.
        /// </summary>
        public void ConnectSelection()
        {
            if (Properties.Settings.Default.IdiotLight)
            {
                if (PartSetup && mrb.IsDirty)
                {
                    if (System.Windows.Forms.MessageBox.Show(@"Save property changes?", @"Properties changed", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        Write();
                    }
                }
                if (DrawSetup && drb.IsDirty)
                {
                    if (System.Windows.Forms.MessageBox.Show(@"Save property changes?", @"Properties changed", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        Write();
                    }
                }
            }

            // Since I create objects and just toss them out liberally, I want to force garbage collection.
            // I think this leaves fewer GDI objects around. (This seems to be a good thing)
            System.GC.Collect(2, GCCollectionMode.Forced);
            prop.CutlistID = 0;
            if (Document != null)
            {
                // ignore clicks on the same object
                if (Document != md_last)
                {
                    // Blow out the propertyset so we can get new ones.
                    prop.Clear();

                    Enabled = true;
                    AddHash();

                    // what sort of doc is open?
                    swDocumentTypes_e docT     = swDocumentTypes_e.swDocNONE;
                    swDocumentTypes_e overDocT = swDocumentTypes_e.swDocNONE;
                    GetTypes(ref docT, ref overDocT);
                    switch (overDocT)
                    {
                    case swDocumentTypes_e.swDocASSEMBLY:
                        DisconnectAssemblyEvents();
                        SetupAssy((ModelDoc2)_swApp.ActiveDoc);
                        // a switch in a switch!
                        switch (docT)
                        {
                        case swDocumentTypes_e.swDocASSEMBLY:
                            regen_ok = true;
                            if (!PartSetup)
                            {
                                SetupPart();
                            }
                            if (!PartEventsAssigned)
                            {
                                ConnectPartEvents(prop.modeldoc);
                                PartSetup = true;
                            }
                            mrb.Update(ref prop);
                            break;

                        case swDocumentTypes_e.swDocDRAWING:
                            break;

                        case swDocumentTypes_e.swDocNONE:
                            break;

                        case swDocumentTypes_e.swDocPART:
                            regen_ok = true;
                            if (!PartSetup)
                            {
                                // ClearControls(this); // <-- redundant
                                // setup
                                SetupPart(prop.modeldoc);
                                // link
                                mrb.Update(ref prop);
                            }
                            else
                            {
                                DisconnectPartEvents();
                                ConnectPartEvents(prop.modeldoc);
                                PartSetup = true; // OK, this isn't how I meant to use this.
                                // or just link
                                mrb.Update(ref prop);
                            }
                            break;

                        case swDocumentTypes_e.swDocSDM:
                            break;

                        default:
                            break;
                        }
                        break;

                    case swDocumentTypes_e.swDocDRAWING:
                        regen_ok = false;
                        ClearControls(this);
                        SetupDrawing();
                        break;

                    case swDocumentTypes_e.swDocNONE:
                        SetupOther();
                        break;

                    case swDocumentTypes_e.swDocPART:
                        regen_ok = true;
                        if (!PartSetup)
                        {
                            // ClearControls(this); // <-- redundant
                            // setup
                            SetupPart(prop.modeldoc);
                            // link
                            mrb.Update(ref prop);
                        }
                        else
                        {
                            DisconnectPartEvents();
                            ConnectPartEvents(prop.modeldoc);
                            PartSetup = true; // OK, this isn't how I meant to use this.
                            // or just link
                            mrb.Update(ref prop);
                        }

                        break;

                    case swDocumentTypes_e.swDocSDM:
                        break;

                    default:
                        SetupOther();
                        break;
                    }
                }
                md_last = Document;
            }
            else
            {
                Enabled = false;
            }
#if EXPERIMENTAL
            if (Document != null)
            {
                Feature f        = (Feature)Document.FirstFeature();
                string  typeName = f.GetTypeName2();
                do
                {
                    f.GetNextSubFeature();
                    typeName = f.GetTypeName2();
                } while (typeName.ToUpper().Contains("FILE"));
                if (typeName != string.Empty)
                {
                    int res0 = SwApp.AddMenuPopupItem4(
                        (int)SolidWorks.Interop.swconst.swDocumentTypes_e.swDocASSEMBLY,
                        cookie,
                        typeName,
                        "Uaaaaaaaaaaaaaaaaa.........",
                        "donothing(1)",
                        "enablemethod(1)",
                        "pow",
                        "bip;bop"
                        );
                    int res1 = SwApp.AddMenuPopupItem4(
                        (int)SolidWorks.Interop.swconst.swDocumentTypes_e.swDocASSEMBLY,
                        cookie,
                        typeName,
                        "Ummmmmmmmmmmmmmm.........",
                        "donothing(2)",
                        "enablemethod(0)",
                        "pow",
                        "bip;bop"
                        );
                    int res2 = SwApp.AddMenuPopupItem(
                        (int)SolidWorks.Interop.swconst.swDocumentTypes_e.swDocASSEMBLY,
                        (int)SolidWorks.Interop.swconst.swSelectType_e.swSelBODYFEATURES,
                        typeName,
                        "donothing(2)",
                        "bip;bop"
                        );
                    (SwApp.Frame() as Frame).SetStatusBarText(
                        string.Format("Runtime Command IDs: {0}, {1}, {2} | Feature: {3}", res0, res1, res2, typeName)
                        );
                }
            }
#endif
        }
예제 #19
0
        /// <summary>
        /// 天花子装配导出DXF图纸
        /// </summary>
        /// <param name="swApp"></param>
        /// <param name="tree"></param>
        /// <param name="dxfPath"></param>
        /// <param name="userId"></param>
        public void CeilingAssyToDxf(SldWorks swApp, SubAssy subAssy, string dxfPath, int userId)
        {
            swApp.CommandInProgress = true;
            List <CeilingCutList> celingCutLists = new List <CeilingCutList>();
            string assyPath = subAssy.SubAssyPath;

            if (assyPath.Length == 0)
            {
                return;
            }
            try
            {
                //打开模型
                ModelDoc2 swModel = swApp.OpenDoc6(assyPath, (int)swDocumentTypes_e.swDocASSEMBLY,
                                                   (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings) as ModelDoc2;
                if (swModel == null)
                {
                    MessageBox.Show("模型不存在,请认真检查", "模型不存在");
                    return;
                }
                string modulePath = dxfPath + @"\" + subAssy.SubAssyName;
                if (!Directory.Exists(modulePath))
                {
                    Directory.CreateDirectory(modulePath);
                }
                swModel.ForceRebuild3(true);
                AssemblyDoc swAssy = swModel as AssemblyDoc;
                //获取所有零部件集合
                var compList = swAssy.GetComponents(false);
                //遍历集合中的所有零部件对象
                foreach (var swComp in compList)
                {
                    //判断零件是否被压缩,不显示,封套,零件名称不是以sldprt或SLDPRT结尾
                    if (swComp.Visible == 1 && !swComp.IsEnvelope() && !swComp.IsSuppressed() &&
                        (swComp.GetPathName().EndsWith(".sldprt") || swComp.GetPathName().EndsWith(".SLDPRT")))
                    {
                        Component2 swParentComp = swComp.GetParent();
                        //总装没有父装配体
                        if (swParentComp == null)
                        {
                            ConfigurationManager swConfigMgr = swModel.ConfigurationManager;
                            Configuration        swConfig2   = swConfigMgr.ActiveConfiguration;
                            swParentComp = swConfig2.GetRootComponent3(true);
                        }
                        //判断父装配体是否可视,并且不封套
                        if (swParentComp.Visible == 1 && !swParentComp.IsEnvelope() && !swComp.IsSuppressed())
                        {
                            PartDoc swPart = swComp.GetModelDoc2();
                            //获取文档中的额Body对象集合
                            var bodyList = swPart.GetBodies2(0, false);
                            //遍历集合中的所有Body对象,判断是否为钣金
                            foreach (var swBody in bodyList)
                            {
                                //如果是钣金则将零件地址添加到列表中
                                if (swBody.IsSheetMetal())
                                {
                                    if (sheetMetaDic.ContainsKey(swComp.GetPathName()))
                                    {
                                        sheetMetaDic[swComp.GetPathName()] += 1;
                                    }
                                    else
                                    {
                                        sheetMetaDic.Add(swComp.GetPathName(), 1);
                                    }
                                }
                            }
                        }
                    }
                }
                //关闭装配体零件
                swApp.CloseDoc(assyPath);
                //遍历钣金零件
                foreach (var sheetMeta in sheetMetaDic)
                {
                    //打开模型
                    ModelDoc2 swPart = swApp.OpenDoc6(sheetMeta.Key, (int)swDocumentTypes_e.swDocPART,
                                                      (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings) as ModelDoc2;
                    Feature        swFeat    = (Feature)swPart.FirstFeature();
                    CeilingCutList cutRecord = new CeilingCutList()
                    {
                        SubAssyId = subAssy.SubAssyId,
                        Quantity  = sheetMeta.Value,
                        UserId    = userId
                    };
                    while (swFeat != null)
                    {
                        var suppStatus = swFeat.IsSuppressed2((int)swInConfigurationOpts_e.swThisConfiguration, null);
                        if (suppStatus[0] == false && swFeat.GetTypeName() == "SolidBodyFolder")
                        {
                            BodyFolder swBodyFolder = (BodyFolder)swFeat.GetSpecificFeature2();
                            swBodyFolder.SetAutomaticCutList(true);
                            swBodyFolder.SetAutomaticUpdate(true);
                            Feature SubFeat = swFeat.GetFirstSubFeature();
                            if (SubFeat != null)
                            {
                                Feature    ownerFeature    = SubFeat.GetOwnerFeature();
                                BodyFolder swSubBodyFolder = ownerFeature.GetSpecificFeature2();
                                swSubBodyFolder.UpdateCutList();
                                string val         = string.Empty;
                                string valout      = string.Empty;
                                bool   wasResolved = false;
                                bool   linkToProp  = false;
                                SubFeat.CustomPropertyManager.Get4("Bounding Box Length", false, out val, out valout);
                                cutRecord.Length = Convert.ToDecimal(valout);
                                SubFeat.CustomPropertyManager.Get4("Bounding Box Width", false, out val, out valout);
                                cutRecord.Width = Convert.ToDecimal(valout);
                                SubFeat.CustomPropertyManager.Get4("Sheet Metal Thickness", false, out val, out valout);
                                cutRecord.Thickness = Convert.ToDecimal(valout);
                                SubFeat.CustomPropertyManager.Get4("Material", false, out val, out valout);
                                cutRecord.Materials = valout;
                                swPart.GetActiveConfiguration().CustomPropertyManager.Get6("Description", false, out valout, out val, out wasResolved, out linkToProp);
                                cutRecord.PartDescription = valout;
                                cutRecord.PartNo          = swPart.GetTitle().Substring(0, swPart.GetTitle().Length - 7);
                                celingCutLists.Add(cutRecord);//将信息添加到集合中
                            }
                        }
                        swFeat = swFeat.GetNextFeature();
                    }
                    PartToDxf(swApp, swPart, modulePath);
                    //关闭零件
                    swApp.CloseDoc(sheetMeta.Key);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(assyPath + "导图过程发生异常,详细:" + ex.Message);
            }
            finally
            {
                sheetMetaDic.Clear();
                swApp.CloseDoc(assyPath);        //关闭,很快
                swApp.CommandInProgress = false; //及时关闭外部命令调用,否则影响SolidWorks的使用
            }
            //基于事务ceilingCutLists提交SQLServer
            if (celingCutLists.Count == 0)
            {
                return;
            }
            try
            {
                if (objCeilingCutListService.ImportCutList(celingCutLists))
                {
                    celingCutLists.Clear();
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Cutlist导入数据库失败" + ex.Message);
            }
        }
예제 #20
0
        public bool RecalculateModel(ModelDoc2 inModel)
        {
            bool ret = false;

            try
            {
                OleDbConnection oleDb;

                if (OpenModelDatabase(inModel, out oleDb))
                {
                    var oleSchem = oleDb.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,
                                                             new object[] { null, null, null, "TABLE" });
                    if (oleSchem.Rows.Cast<DataRow>().Any(row => (string)row["TABLE_NAME"] == "objects"))
                    {
                        var cm = new OleDbCommand("SELECT source FROM objects GROUP BY source", oleDb);
                        OleDbDataReader rdSource = cm.ExecuteReader();

                        double strObjVal;
                        while (rdSource.Read())
                        {
                            if (rdSource["source"].ToString() != "")
                            {
                                cm = new OleDbCommand("SELECT * FROM objects WHERE ismaster=true " +
                                                      "AND source='" + rdSource["source"] + "' ORDER BY id", oleDb);
                                OleDbDataReader rdMaster = cm.ExecuteReader();

                                string strWhere = "";
                                string strOrder = "";

                                while (rdMaster.Read())
                                {
                                    string strObjName = rdMaster["name"].ToString();

                                    if (GetObjectValue(inModel, strObjName, (int)rdMaster["type"], out strObjVal))
                                    {
                                        if (strWhere != "") strWhere = strWhere + " AND ";
                                        strWhere = strWhere + "obj" + rdMaster["id"] + "<=" +
                                                   CorrectDecimalSymbol(strObjVal.ToString(), false, true);

                                        if (strOrder != "") strOrder = strOrder + ", ";
                                        strOrder = strOrder + "obj" + rdMaster["id"];
                                    }
                                }
                                rdMaster.Close();

                                if (strWhere != "") strWhere = " WHERE " + strWhere;
                                if (strOrder != "") strOrder = " ORDER BY " + strOrder + " DESC ";

                                cm = new OleDbCommand("SELECT * FROM " + rdSource["source"] + strWhere + strOrder, oleDb);
                                OleDbDataReader rdData = cm.ExecuteReader();

                                if (rdData.Read())
                                {
                                    for (int i = 0; i < rdData.FieldCount; i++)
                                    {
                                        string strFieldName = rdData.GetName(i);

                                        cm = new OleDbCommand("SELECT * FROM objects " + "WHERE id=" +
                                                              Strings.Right(strFieldName, strFieldName.Length - 3) +
                                                              " AND ismaster=false", oleDb);
                                        OleDbDataReader rdSlave = cm.ExecuteReader();

                                        if (rdSlave.Read())
                                        {
                                            double val = 0;
                                            switch ((int)rdSlave["type"])
                                            {
                                                case 14:
                                                    val = (double)rdData[i];
                                                    break;

                                                case 20:
                                                case 22:
                                                    val = (bool)rdData[i] ? 1 : 0;
                                                    break;
                                            }
                                            // bool? noArtIfSuppressed = rdSlave["noArtIfSuppressed"] as bool?;
                                            bool noArtIfSuppressed = false;

                                            try
                                            {
                                                if (rdSlave["noArtIfSuppressed"] as bool? != null)
                                                {
                                                    noArtIfSuppressed = (bool)rdSlave["noArtIfSuppressed"];
                                                }
                                            }
                                            catch (Exception)
                                            { }

                                            //MessageBox.Show(Path.GetFileNameWithoutExtension(inModel.GetPathName()) + " " + rdSlave["name"] + " " + val);
                                            SetObjectValue(inModel, rdSlave["name"].ToString(), (int)rdSlave["type"], val, (bool)noArtIfSuppressed);
                                        }
                                        rdSlave.Close();
                                    }
                                }
                                rdData.Close();

                            }
                        }
                        rdSource.Close();

                        if (oleSchem.Rows.Cast<DataRow>().Any(row => (string)row["TABLE_NAME"] == "equations"))
                        {
                            cm = new OleDbCommand("SELECT * FROM equations ORDER BY id", oleDb);
                            OleDbDataReader rdEqu = cm.ExecuteReader();

                            while (rdEqu.Read())
                            {
                                if (GetObjectValue(inModel, rdEqu["master"].ToString(), 14, out strObjVal))
                                {
                                    SetObjectValue(inModel, rdEqu["slave"].ToString(), 14, strObjVal);
                                }
                            }
                            rdEqu.Close();
                        }
                    }
                    oleDb.Close();

                    //�������������� ��������� ���������� � �������
                    Feature swSubFeature;
                    var swFeature = (Feature)inModel.FirstFeature();

                    bool isFeatureFound = false;

                    while (swFeature != null)
                    {
                        if (swFeature.GetTypeName2() == "MateGroup")
                        {
                            isFeatureFound = true;

                            swSubFeature = (Feature)swFeature.GetFirstSubFeature();
                            while (swSubFeature != null)
                            {
                                if (swSubFeature.GetErrorCode() != (int)swFeatureError_e.swFeatureErrorNone)
                                {
                                    swSubFeature.IsSuppressed2((int)swInConfigurationOpts_e.swThisConfiguration, null);
                                    swSubFeature.SetSuppression((int)swFeatureSuppressionAction_e.swSuppressFeature);
                                }
                                swSubFeature = (Feature)swSubFeature.GetNextSubFeature();
                            }
                        }
                        if (isFeatureFound) break;
                        swFeature = (Feature)swFeature.GetNextFeature();
                    }
                    ret = true;
                }

                _features.Clear();
                _comps.Clear();
            }

            catch (Exception e)
            {
                MessageBox.Show(e.Message, MyTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            return ret;
        }
예제 #21
0
        internal static bool GetFeatureByName(ModelDoc2 inModel, string inName, out Feature outFeature)
        {
            Feature swSubFeature;
            bool ret = false;

            outFeature = (Feature)inModel.FirstFeature();

            while (outFeature != null)
            {
                if (outFeature.Name == inName)
                {
                    ret = true;
                    break;
                }
                swSubFeature = (Feature)outFeature.GetFirstSubFeature();

                while (swSubFeature != null)
                {
                    if (swSubFeature.Name.ToLower() == inName.ToLower())
                    {
                        ret = true;
                        break;
                    }
                    swSubFeature = (Feature)swSubFeature.GetNextSubFeature();
                }
                if (ret) break;

                outFeature = (Feature)outFeature.GetNextFeature();
            }
            return ret;
        }
예제 #22
0
        private void FixOneBand(string config)
        {
            try
            {
                IPartDoc swPart = (IPartDoc)modelDoc;

                _swFeat = (Feature)modelDoc.FirstFeature();
                Feature flatPattern = null;

                while ((_swFeat != null))
                {
                    if (_swFeat.GetTypeName() == "FlatPattern")
                    {
                        flatPattern = _swFeat;
                        flatPattern.Select(true);
                        swPart.EditUnsuppress();
                        flatPattern.DeSelect();

                        _swSubFeat = (Feature)flatPattern.GetFirstSubFeature();

                        while ((_swSubFeat != null))
                        {
                            if (_swSubFeat.GetTypeName() == "UiBend")
                            {
                                object[] fisrtParent = _swSubFeat.GetParents();
                                if (fisrtParent != null)
                                {
                                    foreach (var item in fisrtParent)
                                    {
                                        Feature swFirstParentFeat    = (Feature)item;
                                        bool    SuppressedEdgeFlange = IsSuppressedEdgeFlange(swFirstParentFeat.GetOwnerFeature().Name);

                                        PartBendInfos.Add
                                        (
                                            new PartBendInfo
                                        {
                                            EdgeFlange  = _swSubFeat.Name,
                                            OneBend     = swFirstParentFeat.GetOwnerFeature().Name,
                                            IsSupressed = SuppressedEdgeFlange,
                                            Config      = config
                                        }
                                        );
                                    }
                                }
                            }
                            _swSubFeat = (Feature)_swSubFeat.GetNextSubFeature();
                        }
                    }

                    _swFeat = (Feature)_swFeat.GetNextFeature();

                    foreach (var item in PartBendInfos)
                    {
                        if (!item.IsSupressed)
                        {
                            modelDoc.Extension.SelectByID2(item.EdgeFlange, "BODYFEATURE", 0, 0, 0, false, 0, null, 0);
                            SelectionMgr swSelMgr = (SelectionMgr)modelDoc.SelectionManager;
                            Feature      swFeat   = (Feature)swSelMgr.GetSelectedObject6(1, -1);
                            swPart.EditUnsuppress();
                        }
                    }
                }
                //modelDoc.EditRebuild3();
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message + "\t StackTrace " + ex.StackTrace);
            }
        }
예제 #23
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;
            }
        }
예제 #24
0
        private Component2 CheckAllMates(ModelDoc2 model, Component2 originalComp, string[] linkedModels, double[] sBox, string axe, out bool isLeft)
        {
            int axeInt = 0;
            switch (axe.ToLower())
            {
                case "x":
                    axeInt = 3;
                    break;
                case "y":
                    axeInt = 4;
                    break;
                case "z":
                    axeInt = 5;
                    break;
            }
            if (axeInt == 0)
                throw new Exception("Не удалось растянуть деталь. В mdb ref_objects_axe не правильно указана ось (axe).");
            isLeft = false;
            //model.ClosestDistance(origPlane, nearestPlane, out point1, out point2);
            var swFeat = (Feature)model.FirstFeature();
            while (swFeat != null)
            {

                if (swFeat.GetTypeName2() == "MateGroup")
                {
                    var mate = swFeat.GetFirstSubFeature();
                    while (mate != null)
                    {
                        if (mate.GetTypeName() == "MateCoincident")
                        {

                            Mate2 spec = mate.GetSpecificFeature2();

                            if (spec.GetMateEntityCount() > 1)
                            {
                                var paramsArray = spec.MateEntity(0).EntityParams as double[];
                                double tst = 0;
                                if (paramsArray != null && paramsArray.Length > axeInt)
                                    tst = paramsArray[axeInt];
                                if (spec.MateEntity(0).ReferenceComponent.Name.Contains(originalComp.Name) && (tst == 1 || tst == -1))
                                {
                                    foreach (string modelName in linkedModels)
                                    {
                                        if (spec.MateEntity(1).ReferenceComponent.Name.Contains(modelName))
                                        {
                                            double avarageZ = (sBox[axeInt - 3] + sBox[axeInt]) / 2;
                                            double[] mateBox = spec.MateEntity(1).ReferenceComponent.GetBox(false, false);
                                            double mateAvarageZ = (mateBox[axeInt - 3] + mateBox[axeInt]) / 2;
                                            if (avarageZ > mateAvarageZ)
                                                isLeft = false;
                                            else
                                                isLeft = true;
                                            return spec.MateEntity(1).ReferenceComponent;
                                        }
                                    }
                                }
                                paramsArray = spec.MateEntity(1).EntityParams as double[];
                                tst = 0;
                                if (paramsArray != null && paramsArray.Length > axeInt)
                                    tst = paramsArray[axeInt];
                                if (spec.MateEntity(1).ReferenceComponent.Name.Contains(originalComp.Name) && (tst == 1 || tst == -1))
                                {
                                    foreach (string modelName in linkedModels)
                                    {
                                        if (spec.MateEntity(0).ReferenceComponent.Name.Contains(modelName))
                                        {
                                            double avarageZ = (sBox[axeInt - 3] + sBox[axeInt]) / 2;
                                            double[] mateBox = spec.MateEntity(0).ReferenceComponent.GetBox(false, false);
                                            double mateAvarageZ = (mateBox[axeInt - 3] + mateBox[axeInt]) / 2;
                                            if (avarageZ > mateAvarageZ)
                                                isLeft = false;
                                            else
                                                isLeft = true;
                                            return spec.MateEntity(0).ReferenceComponent;
                                        }
                                    }
                                }
                            }
                        }
                        mate = mate.GetNextSubFeature();
                    }
                }
                swFeat = (Feature)swFeat.GetNextFeature();
            }
            return null;
        }
예제 #25
0
        private void OpenAssemblyButtonClick(object sender, EventArgs e)
        {
            // display an open file dialog where user can select an assembly file
            OpenFileDialog openAssemblyFileDialog = new OpenFileDialog
            {
                InitialDirectory = "E:\\Files\\KPI\\macro",
                Filter           = "SolidWorks2014 assembly files|*.sldasm",
                Title            = "Select a SolidWorks Assembly File"
            };

            // show the dialog
            // if the user clicked OK in the dialog and
            // a file was selected, get name of the file
            if (openAssemblyFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                // get name of the assembly file
                string fileName = openAssemblyFileDialog.FileName;

                // start solidworks
                swApp = new SldWorks
                {
                    Visible = this.swVisible.Checked
                };

                // open assembly file
                swDoc = OpenAssembly(fileName);

                // activate opened document
                swApp.ActivateDoc2("sborka", false, 0);

                // get active document
                swDoc = (ModelDoc2)swApp.ActiveDoc;

                // get assembly object
                swAsm = (AssemblyDoc)swDoc;

                // get first feature in the doc
                feature = swDoc.FirstFeature();

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

                while (feature != null)
                {
                    featureNames.Add("Feature: " + feature.GetTypeName2());
                    if (feature.GetTypeName2() == "MateGroup")
                    {
                        // get first sub feature in the mate group
                        subFeature = feature.GetFirstSubFeature();

                        // for all sub features get all dimesions
                        while (subFeature != null)
                        {
                            featureNames.Add("-> SubFeature: " + subFeature.GetTypeName2());

                            displayDimension = subFeature.GetFirstDisplayDimension();

                            // for all display dimensions show their dimension
                            while (displayDimension != null)
                            {
                                dimension        = displayDimension.GetDimension2(0);
                                displayDimension = subFeature.GetNextDisplayDimension(displayDimension);
                            }

                            subFeature = subFeature.GetNextSubFeature();
                        }
                    }
                    else
                    {
                        subFeature = feature.GetFirstSubFeature();

                        while (subFeature != null)
                        {
                            featureNames.Add("-> SubFeature: " + subFeature.GetTypeName2());

                            subFeature = subFeature.GetNextSubFeature();
                        }
                    }
                    feature = feature.GetNextFeature();
                }
                this.textBox.AppendText("\n====== Start ======\n");
                this.textBox.AppendText("File path: " + fileName + "\n");
                this.textBox.AppendText(String.Join("\n", featureNames));
                this.textBox.AppendText("\n====== End ======\n");
            }

            swApp.ExitApp();
        }
예제 #26
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]);
                }
            }
        }
예제 #27
0
        internal static bool processModel(SldWorks swApp, string file, string targetFile, string calcFile, CancellationToken cancellationToken)
        {
            // Initiate variables
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");
            StreamWriter toFile = new StreamWriter(targetFile);

            toFile.AutoFlush = true;
            StreamWriter toCalc = new StreamWriter(calcFile);

            toCalc.AutoFlush = true;
            MathUtility swMathUtil = default(MathUtility);
            ModelDoc2   swModel    = default(ModelDoc2);
            Feature     swFeat     = default(Feature);
            Feature     swMateFeat = null;
            Feature     swSubFeat  = default(Feature);
            Mate2       swMate     = default(Mate2);
            Component2  swComp     = default(Component2);

            MateEntity2[] swMateEnt  = new MateEntity2[3];
            MathTransform swTrans    = default(MathTransform);
            MathPoint     swOrig     = default(MathPoint);
            AssemblyDoc   swAssembly = default(AssemblyDoc);

            double[] corners   = new double[6];
            int[]    swAssyDir = new int[6];
            double[] nPt       = new double[3];
            object   vPt       = null;
            double   height    = 0;
            double   width     = 0;
            double   depth     = 0;
            int      Warning   = 0;
            int      Error     = 0;
            int      i         = 0;

            double[] entityParameters = new double[8];
            // Start function
            try
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    return(false);
                }
                string extention = Path.GetExtension(file);
                int    type      = 0;
                if (extention.ToLower().Contains("sldprt"))
                {
                    type = (int)swDocumentTypes_e.swDocPART;
                }
                else
                {
                    type = (int)swDocumentTypes_e.swDocASSEMBLY;
                }
                // Get assembly model
                swModel = swApp.OpenDoc6(file, type, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref Error, ref Warning) as ModelDoc2;
                if (Error != 0)
                {
                    return(false);
                }
                if (swModel == null)
                {
                    return(false);
                }
                swModel.Visible = true;
                // Get first assembly feature
                swFeat = (Feature)swModel.FirstFeature();
                // Iterate over features in FeatureManager design tree
                while ((swFeat != null))
                {
                    if ("MateGroup" == swFeat.GetTypeName())
                    {
                        swMateFeat = swFeat;
                        break;
                    }
                    swFeat = swFeat = swFeat.GetNextFeature();
                }
                toFile.WriteLine(" " + swMateFeat.Name);
                toFile.WriteLine("");
                // Get first mate, which is a subfeature
                swSubFeat = (Feature)swMateFeat.GetFirstSubFeature();
                while ((swSubFeat != null))
                {
                    swMate = (Mate2)swSubFeat.GetSpecificFeature2();
                    if ((swMate != null))
                    {
                        for (i = 0; i <= 1; i++)
                        {
                            swMateEnt[i] = swMate.MateEntity(i);
                            swComp       = swMateEnt[i].ReferenceComponent;
                            // Initate point
                            nPt[0] = 0.0;
                            nPt[1] = 0.0;
                            nPt[2] = 0.0;
                            vPt    = nPt;
                            // Get component origin point
                            swTrans    = swComp.Transform2;
                            swMathUtil = (MathUtility)swApp.GetMathUtility();
                            swOrig     = (MathPoint)swMathUtil.CreatePoint(vPt);
                            swOrig     = (MathPoint)swOrig.MultiplyTransform(swTrans);
                            // Write parameters to readable ASCII file
                            toFile.WriteLine("    " + swSubFeat.Name);
                            toFile.WriteLine("      Type              = " + swMate.Type);
                            toFile.WriteLine("      Alignment         = " + swMate.Alignment);
                            toFile.WriteLine("      Can be flipped    = " + swMate.CanBeFlipped);
                            toFile.WriteLine("");
                            toFile.WriteLine("      Component         = " + swComp.Name2);
                            toFile.WriteLine("      Origin            = (" + ((double[])swOrig.ArrayData)[0] * 1000.0 + ", " + ((double[])swOrig.ArrayData)[1] * 1000.0 + ", " + ((double[])swOrig.ArrayData)[2] * 1000.0 + ")");
                            toFile.WriteLine("      Mate enity type   = " + swMateEnt[i].ReferenceType);
                            entityParameters = (double[])swMateEnt[i].EntityParams;
                            toFile.WriteLine("      (x,y,z)           = (" + entityParameters[0] * 1000 + ", " + entityParameters[1] * 1000 + ", " + entityParameters[2] * 1000 + ")");
                            toFile.WriteLine("      (i,j,k)           = (" + entityParameters[3] + ", " + entityParameters[4] + ", " + entityParameters[5] + ")");
                            toFile.WriteLine("      Radius 1          = " + entityParameters[6] * 1000);
                            toFile.WriteLine("      Radius 2          = " + entityParameters[7] * 1000);
                            toFile.WriteLine("");
                            // Write parameters to a simplified ASCII file for computation
                            toCalc.Write(swSubFeat.Name);
                            toCalc.Write(" " + swMate.Type);
                            toCalc.Write(" " + swMate.Alignment);
                            toCalc.Write(" " + swMate.CanBeFlipped);
                            toCalc.Write(" " + swComp.Name2);
                            toCalc.Write(" " + ((double[])swOrig.ArrayData)[0] * 1000.0 + "," + ((double[])swOrig.ArrayData)[1] * 1000.0 + "," + ((double[])swOrig.ArrayData)[2] * 1000.0);
                            toCalc.Write(" " + swMateEnt[i].ReferenceType);
                            toCalc.Write(" " + entityParameters[0] * 1000.0 + "," + entityParameters[1] * 1000.0 + "," + entityParameters[2] * 1000.0);
                            toCalc.Write(" " + entityParameters[3] + "," + entityParameters[4] + "," + entityParameters[5]);
                            toCalc.Write(" " + entityParameters[6] * 1000.0);
                            toCalc.WriteLine(" " + entityParameters[7] * 1000.0);
                        }
                        toFile.WriteLine(" ");
                    }
                    // Get the next mate in MateGroup
                    swSubFeat = (Feature)swSubFeat.GetNextSubFeature();
                }
                // Get bounding box around assembly
                swAssembly = (AssemblyDoc)swModel;
                corners    = swAssembly.GetBox(1);
                height     = (corners[4] - corners[1]) * 1000.0;
                width      = (corners[3] - corners[0]) * 1000.0;
                depth      = (corners[5] - corners[2]) * 1000.0;
                // Write to file
                toFile.WriteLine("Aprx. assembly dimensions");
                toFile.WriteLine("(Height, Width, Depth) = (" + height + ", " + width + ", " + depth + ")");
                toFile.WriteLine(" ");
                toCalc.WriteLine("dims(hwd) " + height + " " + width + " " + depth);
                // Get Possible Assembly Directions with interferenceDir function
                interference inter = new interference();
                swAssyDir = inter.interferenceDir(swApp, swModel, swMateFeat, swMateEnt);
                // Write swAssyDir to file
                toFile.WriteLine("(x+, x-, y+, y-, z+, z-) = (" + swAssyDir[0] + ", " + swAssyDir[1] + ", " + swAssyDir[2] + ", " + swAssyDir[3] + ", " + swAssyDir[4] + ", " + swAssyDir[5] + ") ");
                toFile.WriteLine("1 is possible, 0 is not possible");
                toFile.WriteLine("");
                toFile.WriteLine("All dimensions are in mm");
                toCalc.Write("dir " + swAssyDir[0] + " " + swAssyDir[1] + " " + swAssyDir[2] + " " + swAssyDir[3] + " " + swAssyDir[4] + " " + swAssyDir[5]);
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
예제 #28
0
        public PartEventHandler(ModelDoc2 modDoc, SwAddin addin)
            : base(modDoc, addin)
        {
            doc = (PartDoc)document;


            string partName = modDoc.GetPathName().Substring(
                modDoc.GetPathName().LastIndexOf('\\') + 1);

            GlobalCache.Instance.ComponetName = partName;

            this.partName = partName;

            pfr = new ProcessFileRoutingContext(DbConfig.Connection);


            List <ProcessFileRouting> qlist = null;

            try
            {
                qlist = (from p in pfr.ProcessFileRoutings
                         where p.ProcessFileName == partName
                         select p).ToList <ProcessFileRouting>();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }


            Dictionary <string, bool> featureDic = new Dictionary <string, bool>();
            Feature           feature            = modDoc.FirstFeature();
            ModelDocExtension swModelExt         = modDoc.Extension;

            while (feature != null)
            {
                string featureTypeName = feature.GetTypeName();
                string featureName     = feature.Name;

                if (featureTypeName == "ProfileFeature")
                {
                    if (!featureDic.ContainsKey(featureName))
                    {
                        featureDic.Add(featureName, false);
                    }
                }

                feature = (Feature)feature.GetNextFeature();
            }
            GlobalCache.Instance.SketchStatusDic = featureDic;


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

            foreach (var q in qlist)
            {
                routingIdList.Add(q.RoutingId);
            }

            this.routingIdList = routingIdList;


            if (routingIdList.Count > 0)
            {
                ///Exist the correlation component to  routing
                Routing(modDoc, iSwApp, routingIdList);
            }
        }