Пример #1
0
        public void SelectElementsASTGeneration()
        {
            var refPoints = new List <ReferencePoint>();

            using (var trans = new Transaction(DocumentManager.Instance.CurrentDBDocument, "Create some ReferencePoints"))
            {
                trans.Start();

                FailureHandlingOptions fails = trans.GetFailureHandlingOptions();
                fails.SetClearAfterRollback(true);
                trans.SetFailureHandlingOptions(fails);

                refPoints.Add(DocumentManager.Instance.CurrentDBDocument.FamilyCreate.NewReferencePoint(new XYZ(0, 0, 0)));
                refPoints.Add(DocumentManager.Instance.CurrentDBDocument.FamilyCreate.NewReferencePoint(new XYZ(0, 0, 1)));
                refPoints.Add(DocumentManager.Instance.CurrentDBDocument.FamilyCreate.NewReferencePoint(new XYZ(0, 0, 2)));

                trans.Commit();
            }

            var sel = new DSModelElementsSelection {
                SelectedElement = refPoints.Cast <Element>().Select(x => x.UniqueId).ToList()
            };

            var buildOutput = sel.BuildOutputAst(new List <AssociativeNode>());
            var funCall     = (ExprListNode)((BinaryExpressionNode)buildOutput.First()).RightNode;

            Assert.AreEqual(funCall.list.Count, 3);
            Assert.Inconclusive("Need more robust testing here.");
        }
Пример #2
0
        private void CreateFloor(Level targetLevel, List <List <LINE> > NewBeamGroup, FloorType floor_type)
        {
            List <CurveArray> floorCurves = new List <CurveArray>();

            foreach (List <LINE> Beams in NewBeamGroup)
            {
                CurveArray curveArray = new CurveArray();
                //floorCurves.Add(curveArray);

                try
                {
                    foreach (LINE beam in Beams)
                    {
                        curveArray.Append(Line.CreateBound(beam.GetStartPoint(), beam.GetEndPoint()));
                    }

                    using (Transaction trans = new Transaction(this.revitDoc))
                    {
                        FailureHandlingOptions failureHandlingOptions = trans.GetFailureHandlingOptions();
                        FailureHandler         failureHandler         = new FailureHandler();
                        failureHandlingOptions.SetFailuresPreprocessor(failureHandler);
                        failureHandlingOptions.SetClearAfterRollback(false);
                        trans.SetFailureHandlingOptions(failureHandlingOptions);
                        trans.Start("Create Floors");
                        this.revitDoc.Create.NewFloor(curveArray, floor_type, targetLevel, false);
                        trans.Commit();
                    }
                }
                catch (Exception)
                {
                }
            }
        }
        public void CopyText(Document doc, List <ElementId> ids, View source, List <View> Taggets)
        {
            ProgressbarWPF progressbarWPF = new ProgressbarWPF(Taggets.Count, "Copy Text");

            progressbarWPF.Show();
            foreach (var Tagget in Taggets)
            {
                if (progressbarWPF.iscontinue == false)
                {
                    break;
                }
                using (Transaction t = new Transaction(doc, "Copy Text"))
                {
                    t.Start();
                    FailureHandlingOptions options       = t.GetFailureHandlingOptions();
                    MyPreProcessor         ignoreProcess = new MyPreProcessor();
                    options.SetClearAfterRollback(true);
                    options.SetFailuresPreprocessor(ignoreProcess);
                    t.SetFailureHandlingOptions(options);
                    try
                    {
                        ElementTransformUtils.CopyElements(source, ids, Tagget, Transform.Identity, new CopyPasteOptions());
                    }
                    catch
                    {
                    }
                    t.Commit();
                }
            }
            progressbarWPF.Close();
        }
Пример #4
0
        public static void ProcessFailure(object sender, FailuresProcessingEventArgs args)
        {
            try
            {
                if (isElementModified && null != currentDoc)
                {
                    FailuresAccessor fa = args.GetFailuresAccessor();

                    DTMWindow dtmWindow = new DTMWindow(currentDoc, elementModified);
                    if ((bool)dtmWindow.ShowDialog())
                    {
                        args.SetProcessingResult(FailureProcessingResult.ProceedWithRollBack);
                        FailureHandlingOptions option = fa.GetFailureHandlingOptions();
                        option.SetClearAfterRollback(true);
                        fa.SetFailureHandlingOptions(option);
                    }
                    isElementModified = false;
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message;
                LogUtil.AppendLog("DTMFailure-ProcessFailure:" + ex.Message);
            }
        }
Пример #5
0
        private void CheckElementWarning(object sender, FailuresProcessingEventArgs args)
        {
            try
            {
                if (isElementChanged)
                {
                    FailuresAccessor fa = args.GetFailuresAccessor();

                    WarningWindow warningWindow = new WarningWindow(reportingInfo);
                    if ((bool)warningWindow.ShowDialog())
                    {
                        args.SetProcessingResult(FailureProcessingResult.ProceedWithRollBack);
                        FailureHandlingOptions option = fa.GetFailureHandlingOptions();
                        option.SetClearAfterRollback(true);
                        fa.SetFailureHandlingOptions(option);
                    }
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message;
                MessageBox.Show("Failed to promt users for a warning message.\n" + ex.Message, "Check Element Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            finally
            {
                isElementChanged = false;
            }
        }
        /// <summary>
        /// Executes on type to instance change
        /// </summary>
        /// <param name="uiapp"></param>
        /// <param name="text"></param>
        /// <param name="values"></param>
        private void ExecuteParameterChange(UIApplication uiapp, String text, List <string> values, string type)
        {
            UIDocument uidoc = uiapp.ActiveUIDocument;
            Document   doc   = uidoc.Document;

            if (!doc.IsFamilyDocument)
            {
                Command.global_message =
                    "Please run this command in a family document.";
                TaskDialog.Show("Message", Command.global_message);
            }

            if ((uidoc != null))
            {
                using (TransactionGroup tg = new TransactionGroup(doc, "Parameter Type To Instance"))
                {
                    tg.Start();
                    using (Transaction trans = new Transaction(uidoc.Document))
                    {
                        FailureHandlingOptions failureHandlingOptions = trans.GetFailureHandlingOptions();
                        FailureHandler         failureHandler         = new FailureHandler();
                        failureHandlingOptions.SetFailuresPreprocessor(failureHandler);
                        failureHandlingOptions.SetClearAfterRollback(true);
                        trans.SetFailureHandlingOptions(failureHandlingOptions);
                        // Since we'll modify the document, we need a transaction
                        // It's best if a transaction is scoped by a 'using' block
                        // The name of the transaction was given as an argument
                        if (trans.Start(text) == TransactionStatus.Started)
                        {
                            FamilyManager mgr = doc.FamilyManager;
                            foreach (var value in values)
                            {
                                FamilyParameter fp = mgr.get_Parameter(value);
                                if (fp.IsInstance)
                                {
                                    mgr.MakeType(fp);
                                }
                                else
                                {
                                    mgr.MakeInstance(fp);
                                };
                            }
                        }
                        doc.Regenerate();
                        trans.Commit();
                        uidoc.RefreshActiveView();
                        if (failureHandler.ErrorMessage != "")
                        {
                            if (EncounteredError != null)
                            {
                                EncounteredError(this, null);
                            }
                        }
                    }
                    tg.Assimilate();
                }
            }
        }
Пример #7
0
        public XYZ GetReferenceDirection(Reference ref1, Document doc)
        // returns the direction perpendicular to reference
        // returns XYZ.Zero on error;
        {
            XYZ res             = XYZ.Zero;
            XYZ workPlaneNormal = doc.ActiveView.SketchPlane.GetPlane().Normal;

            if (ref1.ElementId == ElementId.InvalidElementId)
            {
                return(res);
            }
            Element elem = doc.GetElement(ref1.ElementId);

            if (elem == null)
            {
                return(res);
            }
            if (ref1.ElementReferenceType == ElementReferenceType.REFERENCE_TYPE_SURFACE || ref1.ElementReferenceType == ElementReferenceType.REFERENCE_TYPE_LINEAR)
            {
                // make a dimension to a point for direction

                XYZ            bEnd   = new XYZ(10, 10, 10);
                ReferenceArray refArr = new ReferenceArray();
                refArr.Append(ref1);
                Dimension dim = null;
                using (Transaction t = new Transaction(doc, "test"))
                {
                    FailureHandlingOptions failureHandlingOptions = t.GetFailureHandlingOptions();
                    FailureHandler         failureHandler         = new FailureHandler();
                    failureHandlingOptions.SetFailuresPreprocessor(failureHandler);
                    failureHandlingOptions.SetClearAfterRollback(true);
                    t.SetFailureHandlingOptions(failureHandlingOptions);

                    t.Start();
                    using (SubTransaction st = new SubTransaction(doc))
                    {
                        st.Start();
                        ReferencePlane refPlane = doc.Create.NewReferencePlane(XYZ.Zero, bEnd, bEnd.CrossProduct(XYZ.BasisZ).Normalize(), doc.ActiveView);
                        ModelCurve     mc       = doc.Create.NewModelCurve(Line.CreateBound(XYZ.Zero, new XYZ(10, 10, 10)), SketchPlane.Create(doc, refPlane.Id));
                        refArr.Append(mc.GeometryCurve.GetEndPointReference(0));
                        dim = doc.Create.NewDimension(doc.ActiveView, Line.CreateBound(XYZ.Zero, new XYZ(10, 0, 0)), refArr);
                        ElementTransformUtils.MoveElement(doc, dim.Id, new XYZ(0, 0.1, 0));
                        st.Commit();
                    }
                    if (dim != null)
                    {
                        Curve cv = dim.Curve;
                        cv.MakeBound(0, 1);
                        XYZ pt1 = cv.GetEndPoint(0);
                        XYZ pt2 = cv.GetEndPoint(1);
                        res = pt2.Subtract(pt1).Normalize();
                    }
                    t.RollBack();
                }
            }
            return(res);
        }
Пример #8
0
        private void InitializeOpenTransaction(string name)
        {
            m_Transaction.Start(Resources.IFCOpenReferenceFile);

            FailureHandlingOptions options = m_Transaction.GetFailureHandlingOptions();

            //options.SetFailuresPreprocessor(Log);
            options.SetForcedModalHandling(true);
            options.SetClearAfterRollback(true);
        }
Пример #9
0
        //----------------------------------------------------------
        public void PurgeUnusedType(Document doc)
        {
            var           allElementsInView = new FilteredElementCollector(doc, doc.ActiveView.Id).ToElements();
            List <string> typesName         = new List <string>();
            List <string> familysName       = new List <string>();

            foreach (Element ele in allElementsInView)
            {
                typesName.Add(ele.Name);
                string familyName = ele.get_Parameter(BuiltInParameter.ELEM_FAMILY_PARAM).AsValueString();
                familysName.Add(familyName);
            }

            List <string> typesName_Unique   = typesName.Distinct().ToList();
            List <string> familysName_Unique = familysName.Distinct().ToList();

            var elementType           = new FilteredElementCollector(doc).OfClass(typeof(ElementType)).ToList();
            var elementType1          = new FilteredElementCollector(doc).OfClass(typeof(FamilySymbol)).ToList();
            List <ElementId> idDelete = new List <ElementId>();

            foreach (ElementType type in elementType)
            {
                if (DocumentValidation.CanDeleteElement(doc, type.Id) && typesName_Unique.Contains(type.Name) == false && familysName_Unique.Contains(type.FamilyName))
                {
                    idDelete.Add(type.Id);
                }
            }
            foreach (FamilySymbol type in elementType1)
            {
                if (DocumentValidation.CanDeleteElement(doc, type.Id) && typesName_Unique.Contains(type.Name) == false && familysName_Unique.Contains(type.FamilyName))
                {
                    idDelete.Add(type.Id);
                }
            }
            foreach (ElementId type in idDelete)
            {
                Transaction            transaction = new Transaction(doc);
                FailureHandlingOptions failure     = transaction.GetFailureHandlingOptions();
                failure.SetClearAfterRollback(true);
                failure.SetForcedModalHandling(false);
                failure.SetFailuresPreprocessor(new RollbackIfErrorOccurs());
                transaction.SetFailureHandlingOptions(failure);
                transaction.Start("PurgeUnusedType");
                try
                {
                    doc.Delete(type);
                    transaction.Commit();
                }
                catch (Exception)
                {
                    transaction.Dispose();
                }
            }
        }
Пример #10
0
        public static void commitTransaction(this Transaction transaction, WarningSwallower failuresPreprocessor)
        {
            FailureHandlingOptions failureOptions = transaction.GetFailureHandlingOptions();

            failureOptions.SetFailuresPreprocessor(failuresPreprocessor);
            failureOptions.SetDelayedMiniWarnings(true);
            failureOptions.SetClearAfterRollback(true);

            transaction.SetFailureHandlingOptions(failureOptions);
            transaction.Commit();
        }
        /// <summary>
        /// Restore all values
        /// </summary>
        /// <param name="uiapp"></param>
        /// <param name="text"></param>
        /// <param name="values"></param>
        public static void ExecuteParameterChange(UIApplication uiapp, String text, List <Tuple <string, string, double> > values)
        {
            UIDocument uidoc = uiapp.ActiveUIDocument;
            Document   doc   = uidoc.Document;

            if (!doc.IsFamilyDocument)
            {
                Command.global_message = "Please run this command in a family document.";
                TaskDialog.Show("Message", Command.global_message);
            }

            if ((uidoc != null))
            {
                using (TransactionGroup tg = new TransactionGroup(doc, "Parameter Change"))
                {
                    tg.Start();
                    foreach (var value in values)
                    {
                        using (Transaction trans = new Transaction(uidoc.Document))
                        {
                            FailureHandlingOptions failureHandlingOptions = trans.GetFailureHandlingOptions();
                            FailureHandler         failureHandler         = new FailureHandler();
                            failureHandlingOptions.SetFailuresPreprocessor(failureHandler);
                            failureHandlingOptions.SetClearAfterRollback(true);
                            trans.SetFailureHandlingOptions(failureHandlingOptions);

                            FamilyManager   mgr = doc.FamilyManager;
                            FamilyParameter fp  = mgr.get_Parameter(value.Item1);
                            // Since we'll modify the document, we need a transaction
                            // It's best if a transaction is scoped by a 'using' block
                            // The name of the transaction was given as an argument
                            if (trans.Start(text) == TransactionStatus.Started)
                            {
                                mgr.Set(fp, value.Item3);
                                //operation(mgr, fp);
                                doc.Regenerate();
                                if (!value.Item1.Equals(value.Item2))
                                {
                                    mgr.RenameParameter(fp, value.Item2);
                                }
                                trans.Commit();
                                uidoc.RefreshActiveView();
                            }
                            if (failureHandler.ErrorMessage != "")
                            {
                                RequestError.ErrorLog.Add(new Message(fp.Definition.Name, failureHandler.ErrorMessage));
                            }
                        }
                    }
                    tg.Assimilate();
                }
            }
        }
        /// <summary>
        /// Delete parameter
        /// </summary>
        /// <param name="uiapp"></param>
        /// <param name="text"></param>
        /// <param name="values"></param>
        public static void ExecuteParameterChange(UIApplication uiapp, String text, List <string> values)
        {
            UIDocument uidoc = uiapp.ActiveUIDocument;
            Document   doc   = uidoc.Document;

            if (!doc.IsFamilyDocument)
            {
                Command.global_message =
                    "Please run this command in a family document.";
                TaskDialog.Show("Message", Command.global_message);
            }

            if ((uidoc != null))
            {
                using (TransactionGroup tg = new TransactionGroup(doc, "Parameter Delete"))
                {
                    tg.Start();
                    using (Transaction trans = new Transaction(uidoc.Document))
                    {
                        FailureHandlingOptions failureHandlingOptions = trans.GetFailureHandlingOptions();
                        FailureHandler         failureHandler         = new FailureHandler();
                        failureHandlingOptions.SetFailuresPreprocessor(failureHandler);
                        failureHandlingOptions.SetClearAfterRollback(true);
                        trans.SetFailureHandlingOptions(failureHandlingOptions);
                        // Since we'll modify the document, we need a transaction
                        // It's best if a transaction is scoped by a 'using' block
                        // The name of the transaction was given as an argument
                        if (trans.Start(text) == TransactionStatus.Started)
                        {
                            FamilyManager mgr = doc.FamilyManager;
                            foreach (var value in values)
                            {
                                FamilyParameter fp = mgr.get_Parameter(value);
                                mgr.RemoveParameter(fp);
                            }
                        }
                        doc.Regenerate();
                        trans.Commit();
                        uidoc.RefreshActiveView();
                        if (failureHandler.ErrorMessage != "")
                        {
                            RequestError.ErrorLog.Add(new Message("", failureHandler.ErrorMessage));
                        }
                        else
                        {
                            RequestError.NotifyLog += $"Successfully purged {values.Count.ToString()} unused parameters.";
                        }
                    }
                    tg.Assimilate();
                }
            }
        }
Пример #13
0
        public void SelectReferenceASTGeneration()
        {
            Form extrude;

            using (var trans = new Transaction(DocumentManager.Instance.CurrentDBDocument, "Create an extrusion Form"))
            {
                trans.Start();

                FailureHandlingOptions fails = trans.GetFailureHandlingOptions();
                fails.SetClearAfterRollback(true);
                trans.SetFailureHandlingOptions(fails);

                var p   = new Plane(new XYZ(0, 0, 1), new XYZ());
                var arc = Arc.Create(p, 2, 0, System.Math.PI);
                var sp  = SketchPlane.Create(DocumentManager.Instance.CurrentDBDocument, p);
                var mc  = DocumentManager.Instance.CurrentDBDocument.FamilyCreate.NewModelCurve(arc, sp);

                var profiles = new ReferenceArray();
                profiles.Append(mc.GeometryCurve.Reference);
                extrude = DocumentManager.Instance.CurrentDBDocument.FamilyCreate.NewExtrusionForm(false, profiles, new XYZ(0, 0, 1));
                trans.Commit();
            }

            var geom = extrude.get_Geometry(new Options()
            {
                ComputeReferences        = true,
                DetailLevel              = ViewDetailLevel.Medium,
                IncludeNonVisibleObjects = true
            });

            var solid = geom.FirstOrDefault(x => x is Solid) as Solid;
            var face  = solid.Faces.get_Item(0);

            Assert.Greater(solid.Faces.Size, 0);

            var sel = new DSFaceSelection()
            {
                SelectedElement = face.Reference
            };

            var buildOutput = sel.BuildOutputAst(new List <AssociativeNode>());

            var funCall = (FunctionCallNode)((IdentifierListNode)((BinaryExpressionNode)buildOutput.First()).RightNode).RightNode;

            Assert.IsInstanceOf <IdentifierNode>(funCall.Function);
            Assert.AreEqual(1, funCall.FormalArguments.Count);
            Assert.IsInstanceOf <StringNode>(funCall.FormalArguments[0]);

            var stableRef = face.Reference.ConvertToStableRepresentation(DocumentManager.Instance.CurrentDBDocument);

            Assert.AreEqual(stableRef, ((StringNode)funCall.FormalArguments[0]).value);
        }
 public void Transferviewtemplate(Document source, Document target, List <ElementId> elementIds)
 {
     using (Transaction tran = new Transaction(target, "Ivention EXT: Transfer view template"))
     {
         tran.Start();
         FailureHandlingOptions options       = tran.GetFailureHandlingOptions();
         IgnoreProcess          ignoreProcess = new IgnoreProcess();
         options.SetClearAfterRollback(true);
         options.SetFailuresPreprocessor(ignoreProcess);
         tran.SetFailureHandlingOptions(options);
         CopyPasteOptions coptions = new CopyPasteOptions();
         coptions.SetDuplicateTypeNamesHandler(new CopyHandler());
         ICollection <ElementId> litstrans = ElementTransformUtils.CopyElements(source, elementIds, target, null, coptions);
         tran.Commit(options);
     }
 }
        /// <summary>
        /// Change Parameter
        /// </summary>
        /// <param name="uiapp"></param>
        /// <param name="text"></param>
        /// <param name="values"></param>
        public static void ExecuteParameterChange(UIApplication uiapp, String text, Tuple <string, double> value)
        {
            UIDocument uidoc = uiapp.ActiveUIDocument;
            Document   doc   = uidoc.Document;

            if (!doc.IsFamilyDocument)
            {
                Command.global_message = "Please run this command in a family document.";
                TaskDialog.Show("Message", Command.global_message);
            }

            if ((uidoc != null))
            {
                using (Transaction trans = new Transaction(uidoc.Document, "Change Parameter Value"))
                {
                    FailureHandlingOptions failureHandlingOptions = trans.GetFailureHandlingOptions();
                    FailureHandler         failureHandler         = new FailureHandler();
                    failureHandlingOptions.SetFailuresPreprocessor(failureHandler);
                    failureHandlingOptions.SetClearAfterRollback(true);
                    trans.SetFailureHandlingOptions(failureHandlingOptions);

                    FamilyManager   mgr = doc.FamilyManager;
                    FamilyParameter fp  = mgr.get_Parameter(value.Item1);
                    // Since we'll modify the document, we need a transaction
                    // It's best if a transaction is scoped by a 'using' block
                    // The name of the transaction was given as an argument
                    if (trans.Start(text) == TransactionStatus.Started)
                    {
                        if (fp.IsDeterminedByFormula || fp.IsReporting)
                        {
                            trans.RollBack();  //Cannot change parameters driven by formulas, cannot change reporting parameters
                            return;
                        }

                        mgr.Set(fp, value.Item2);
                        doc.Regenerate();
                        trans.Commit();
                        uidoc.RefreshActiveView();
                        if (failureHandler.ErrorMessage != "")
                        {
                            RequestError.ErrorLog.Add(new Message(fp.Definition.Name, failureHandler.ErrorMessage));
                        }
                    }
                }
            }
        }
Пример #16
0
 public void Copyelement(Document Source, Document Target, ICollection <ElementId> elementIds)
 {
     using (Transaction t = new Transaction(Target, "Copy Model"))
     {
         t.Start();
         FailureHandlingOptions options       = t.GetFailureHandlingOptions();
         MyPreProcessor         ignoreProcess = new MyPreProcessor();
         options.SetClearAfterRollback(true);
         options.SetFailuresPreprocessor(ignoreProcess);
         t.SetFailureHandlingOptions(options);
         try
         {
             ElementTransformUtils.CopyElements(Source, elementIds, Target, Transform.Identity, new CopyPasteOptions());
         }
         catch
         {
         }
         t.Commit();
     }
 }
Пример #17
0
        public void SelectElementASTGeneration()
        {
            ReferencePoint refPoint;

            using (var trans = new Transaction(DocumentManager.Instance.CurrentDBDocument, "CreateAndDeleteAreReferencePoint"))
            {
                trans.Start();

                FailureHandlingOptions fails = trans.GetFailureHandlingOptions();
                fails.SetClearAfterRollback(true);
                trans.SetFailureHandlingOptions(fails);

                refPoint = DocumentManager.Instance.CurrentDBDocument.FamilyCreate.NewReferencePoint(new XYZ());

                trans.Commit();
            }

            var sel = new DSModelElementSelection {
                SelectedElement = refPoint.Id
            };

            var buildOutput = sel.BuildOutputAst(new List <AssociativeNode>());

            //function call node builds this

            /*return new IdentifierListNode
             * {
             *  LeftNode = new IdentifierNode(className),
             *  RightNode = AstFactory.BuildFunctionCall(functionName, arguments)
             * };*/

            var funCall = (FunctionCallNode)(((IdentifierListNode)((BinaryExpressionNode)buildOutput.First()).RightNode)).RightNode;

            Assert.IsInstanceOf <IdentifierNode>(funCall.Function);
            Assert.AreEqual(1, funCall.FormalArguments.Count);
            Assert.IsInstanceOf <IntNode>(funCall.FormalArguments[0]);

            Assert.AreEqual(refPoint.Id.IntegerValue, ((IntNode)funCall.FormalArguments[0]).Value);
        }
Пример #18
0
        public void CanCreateAndDeleteAReferencePoint()
        {
            using (_trans = _trans = new Transaction(dynRevitSettings.Doc.Document, "CreateAndDeleteAreReferencePoint"))
            {
                _trans.Start();

                FailureHandlingOptions fails = _trans.GetFailureHandlingOptions();
                fails.SetClearAfterRollback(true);
                _trans.SetFailureHandlingOptions(fails);

                ReferencePoint rp = dynRevitSettings.Doc.Document.FamilyCreate.NewReferencePoint(new XYZ());

                //make a filter for reference points.
                ElementClassFilter       ef  = new ElementClassFilter(typeof(ReferencePoint));
                FilteredElementCollector fec = new FilteredElementCollector(dynRevitSettings.Doc.Document);
                fec.WherePasses(ef);
                Assert.AreEqual(1, fec.ToElements().Count());

                dynRevitSettings.Doc.Document.Delete(rp);
                _trans.Commit();
            }
        }
Пример #19
0
        public void CanCreateAndDeleteAReferencePoint()
        {
            using (var trans = new Transaction(DocumentManager.Instance.CurrentDBDocument, "CreateAndDeleteAreReferencePoint"))
            {
                trans.Start();

                FailureHandlingOptions fails = trans.GetFailureHandlingOptions();
                fails.SetClearAfterRollback(true);
                trans.SetFailureHandlingOptions(fails);

                ReferencePoint rp = DocumentManager.Instance.CurrentUIDocument.Document.FamilyCreate.NewReferencePoint(new XYZ());

                //make a filter for reference points.
                ElementClassFilter       ef  = new ElementClassFilter(typeof(ReferencePoint));
                FilteredElementCollector fec = new FilteredElementCollector(DocumentManager.Instance.CurrentUIDocument.Document);
                fec.WherePasses(ef);
                Assert.AreEqual(1, fec.ToElements().Count());

                DocumentManager.Instance.CurrentDBDocument.Delete(rp.Id);

                trans.Commit();
            }
        }
Пример #20
0
        public static void ProcessFailure(object sender, FailuresProcessingEventArgs args)
        {
            try
            {
                if (isDoorFailed)
                {
                    FailuresAccessor fa = args.GetFailuresAccessor();
                    IList <FailureMessageAccessor> failList = new List <FailureMessageAccessor>();
                    failList = fa.GetFailureMessages();
                    bool foundFailingElement = false;
                    foreach (FailureMessageAccessor failure in failList)
                    {
                        foreach (ElementId id in failure.GetFailingElementIds())
                        {
                            if (failingDoorId.IntegerValue == id.IntegerValue)
                            {
                                foundFailingElement = true;
                            }
                        }
                    }
                    if (foundFailingElement)
                    {
                        args.SetProcessingResult(FailureProcessingResult.ProceedWithRollBack);
                        FailureHandlingOptions option = fa.GetFailureHandlingOptions();
                        option.SetClearAfterRollback(true);
                        fa.SetFailureHandlingOptions(option);
                    }

                    isDoorFailed = false;
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message;
                LogUtil.AppendLog("DoorFailure-ProcessFailure:" + ex.Message);
            }
        }
Пример #21
0
        public void CopyElements(Document doc, FamilyInstance familyInstance, List <FamilyInstance> listinstance, ICollection <ElementId> elementIds)
        {
            ICollection <ElementId> newlist         = new List <ElementId>();
            CopyPasteOptions        option          = new CopyPasteOptions();
            ProgressBarform         progressBarform = new ProgressBarform(listinstance.Count, "Loading...");

            progressBarform.Show();
            foreach (FamilyInstance source in listinstance)
            {
                progressBarform.giatri();
                if (progressBarform.iscontinue == false)
                {
                    break;
                }
                Transform transform  = TransformToCopy(source, familyInstance);
                Transform transform1 = Transform.CreateTranslation(transform.Origin);
                using (Transaction tran = new Transaction(doc, "copy"))
                {
                    tran.Start();
                    FailureHandlingOptions options       = tran.GetFailureHandlingOptions();
                    IgnoreProcess          ignoreProcess = new IgnoreProcess();
                    options.SetClearAfterRollback(true);
                    options.SetFailuresPreprocessor(ignoreProcess);
                    tran.SetFailureHandlingOptions(options);
                    try
                    {
                        newlist = ElementTransformUtils.CopyElements(doc, elementIds, doc, transform, option);
                        Remove_product(doc, newlist);
                    }
                    catch (Exception)
                    {
                    }
                    tran.Commit();
                }
            }
            progressBarform.Close();
        }
        /// <summary>
        /// Implementation of the command binding event for the IFC export command.
        /// </summary>
        /// <param name="sender">The event sender (Revit UIApplication).</param>
        /// <param name="args">The arguments (command binding).</param>
        public void OnIFCExport(object sender, CommandEventArgs args)
        {
            try
            {
                // Prepare basic objects
                UIApplication uiApp     = sender as UIApplication;
                UIDocument    uiDoc     = uiApp.ActiveUIDocument;
                Document      activeDoc = uiDoc.Document;

                TheDocument = activeDoc;

                // Note that when exporting multiple documents, we are still going to use the configurations from the
                // active document.
                IFCExportConfigurationsMap configurationsMap = new IFCExportConfigurationsMap();
                configurationsMap.Add(IFCExportConfiguration.GetInSession());
                configurationsMap.AddBuiltInConfigurations();
                configurationsMap.AddSavedConfigurations();

                String mruSelection = null;
                if (m_mruConfiguration != null && configurationsMap.HasName(m_mruConfiguration))
                {
                    mruSelection = m_mruConfiguration;
                }

                PotentiallyUpdatedConfigurations = false;
                IFCExport mainWindow = new IFCExport(uiApp, configurationsMap, mruSelection);

                mainWindow.ShowDialog();

                // If user chose to continue
                if (mainWindow.Result == IFCExportResult.ExportAndSaveSettings)
                {
                    int docsToExport = mainWindow.DocumentsToExport.Count;

                    // This shouldn't happen, but just to be safe.
                    if (docsToExport == 0)
                    {
                        return;
                    }

                    bool multipleFiles = docsToExport > 1;

                    // If user chooses to continue


                    // change options
                    IFCExportConfiguration selectedConfig = mainWindow.GetSelectedConfiguration();

                    // Prompt the user for the file location and path
                    string defaultExt = mainWindow.DefaultExt;
                    String fullName   = mainWindow.ExportFilePathName;
                    String path       = Path.GetDirectoryName(fullName);
                    String fileName   = multipleFiles ? Properties.Resources.MultipleFiles : Path.GetFileName(fullName);


                    // This option should be rarely used, and is only for consistency with old files.  As such, it is set by environment variable only.
                    String use2009GUID = Environment.GetEnvironmentVariable("Assign2009GUIDToBuildingStoriesOnIFCExport");
                    bool   use2009BuildingStoreyGUIDs = (use2009GUID != null && use2009GUID == "1");

                    string unsuccesfulExports = string.Empty;

                    // In rare occasions, there may be two projects loaded into Revit with the same name.  This isn't supposed to be allowed, but can happen if,
                    // e.g., a user creates a new project, exports it to IFC, and then calls Open IFC.  In this case, if we export both projects, we will overwrite
                    // one of the exports.  Prevent that by keeping track of the exported file names.
                    ISet <string> exportedFileNames = new HashSet <string>();

                    foreach (Document document in mainWindow.DocumentsToExport)
                    {
                        TheDocument = document;

                        // Call this before the Export IFC transaction starts, as it has its own transaction.
                        IFCClassificationMgr.DeleteObsoleteSchemas(document);

                        Transaction transaction = new Transaction(document, "Export IFC");
                        transaction.Start();

                        FailureHandlingOptions failureOptions = transaction.GetFailureHandlingOptions();
                        failureOptions.SetClearAfterRollback(false);
                        transaction.SetFailureHandlingOptions(failureOptions);

                        // Normally the transaction will be rolled back, but there are cases where we do update the document.
                        // There is no UI option for this, but these two options can be useful for debugging/investigating
                        // issues in specific file export.  The first one supports export of only one element
                        //exportOptions.AddOption("SingleElement", "174245");
                        // The second one supports export only of a list of elements
                        //exportOptions.AddOption("ElementsForExport", "174245;205427");

                        if (multipleFiles)
                        {
                            fileName = IFCUISettings.GenerateFileNameFromDocument(document, exportedFileNames) + "." + defaultExt;
                            fullName = path + "\\" + fileName;
                        }

                        // Prepare the export options
                        IFCExportOptions exportOptions = new IFCExportOptions();

                        ElementId activeViewId = GenerateActiveViewIdFromDocument(document);
                        selectedConfig.ActiveViewId = selectedConfig.UseActiveViewGeometry ? activeViewId.IntegerValue : -1;
                        selectedConfig.UpdateOptions(exportOptions, activeViewId);

                        bool result = document.Export(path, fileName, exportOptions);

                        Dictionary <ElementId, string> linksGUIDsCache = new Dictionary <ElementId, string>();
                        if (result)
                        {
                            // Cache for links guids
                            if (selectedConfig.ExportLinkedFiles == true)
                            {
                                Autodesk.Revit.DB.FilteredElementCollector collector = new FilteredElementCollector(document);
                                collector.WhereElementIsNotElementType().OfCategory(BuiltInCategory.OST_RvtLinks);
                                System.Collections.Generic.ICollection <ElementId> rvtLinkInstanceIds = collector.ToElementIds();
                                foreach (ElementId linkId in rvtLinkInstanceIds)
                                {
                                    Element linkInstance = document.GetElement(linkId);
                                    if (linkInstance == null)
                                    {
                                        continue;
                                    }
                                    Parameter parameter = linkInstance.get_Parameter(BuiltInParameter.IFC_GUID);
                                    if (parameter != null && parameter.HasValue && parameter.StorageType == StorageType.String)
                                    {
                                        String sGUID = parameter.AsString(), sGUIDlower = sGUID.ToLower();
                                        foreach (KeyValuePair <ElementId, string> value in linksGUIDsCache)
                                        {
                                            if (value.Value.ToLower().IndexOf(sGUIDlower) == 0)
                                            {
                                                sGUID += "-";
                                            }
                                        }
                                        linksGUIDsCache.Add(linkInstance.Id, sGUID);
                                    }
                                }
                            }
                        }
                        else
                        {
                            unsuccesfulExports += fullName + "\n";
                        }

                        // Roll back the transaction started earlier, unless certain options are set.
                        if (result && (use2009BuildingStoreyGUIDs || selectedConfig.StoreIFCGUID))
                        {
                            transaction.Commit();
                        }
                        else
                        {
                            transaction.RollBack();
                        }

                        // Export links
                        if (selectedConfig.ExportLinkedFiles == true)
                        {
                            exportOptions.AddOption("ExportingLinks", true.ToString());
                            ExportLinkedDocuments(document, fullName, linksGUIDsCache, exportOptions);
                            exportOptions.AddOption("ExportingLinks", false.ToString());
                        }
                    }

                    if (!string.IsNullOrWhiteSpace(unsuccesfulExports))
                    {
                        using (TaskDialog taskDialog = new TaskDialog(Properties.Resources.IFCExport))
                        {
                            taskDialog.MainInstruction = string.Format(Properties.Resources.IFCExportProcessError, unsuccesfulExports);
                            taskDialog.MainIcon        = TaskDialogIcon.TaskDialogIconWarning;
                            TaskDialogResult taskDialogResult = taskDialog.Show();
                        }
                    }

                    // Remember last successful export location
                    m_mruExportPath = path;
                }

                // The cancel button should cancel the export, not any "OK"ed setup changes.
                if (mainWindow.Result == IFCExportResult.ExportAndSaveSettings || mainWindow.Result == IFCExportResult.Cancel)
                {
                    if (PotentiallyUpdatedConfigurations)
                    {
                        configurationsMap = mainWindow.GetModifiedConfigurations();
                        configurationsMap.UpdateSavedConfigurations();
                    }

                    // Remember last selected configuration
                    m_mruConfiguration = mainWindow.GetSelectedConfiguration().Name;
                }
            }
            catch (Exception e)
            {
                using (TaskDialog taskDialog = new TaskDialog(Properties.Resources.IFCExport))
                {
                    taskDialog.MainInstruction = Properties.Resources.IFCExportProcessGenericError;
                    taskDialog.MainIcon        = TaskDialogIcon.TaskDialogIconWarning;
                    taskDialog.ExpandedContent = e.ToString();
                    TaskDialogResult result = taskDialog.Show();
                }
            }
        }
        /// <summary>
        /// 創建樓板
        /// </summary>
        /// <param name="targetLevel"></param>
        /// <param name="NewBeamGroup"></param>
        /// <param name="floor_type"></param>
        private void CreateFloor(Level targetLevel, List <List <LINE> > NewBeamGroup, FloorType floor_type)
        {
            List <CurveArray> floorCurves = new List <CurveArray>();

            foreach (List <LINE> Beams in NewBeamGroup)
            {
                try
                {
                    List <LINE> newBeam_  = AdjustCreatedFloorEdge(Beams);
                    List <LINE> newBeam_2 = AdjustCreatedFloorEdge(newBeam_);
                    List <LINE> newBeam_3 = new List <LINE>();
                    foreach (LINE item in newBeam_2)
                    {
                        if (item.GetLength() > 0.01)
                        {
                            newBeam_3.Add(item);
                        }
                    }

                    List <LINE> newBeam = new List <LINE>();
                    newBeam_3.Add(newBeam_3[0]);
                    for (int i = 0; i < newBeam_3.Count - 1; i++)
                    {
                        if (IsSamePoint(newBeam_3[i].GetStartPoint(), newBeam_3[i + 1].GetStartPoint()) &&
                            IsSamePoint(newBeam_3[i].GetEndPoint(), newBeam_3[i + 1].GetEndPoint()))
                        {
                        }
                        else if (IsSamePoint(newBeam_3[i].GetStartPoint(), newBeam_3[i + 1].GetEndPoint()) &&
                                 IsSamePoint(newBeam_3[i].GetEndPoint(), newBeam_3[i + 1].GetStartPoint()))
                        {
                        }
                        else
                        {
                            newBeam.Add(newBeam_3[i]);
                        }
                    }


                    // SaveTmp(new List<List<LINE>> { newBeam });

                    CurveArray curveArray = new CurveArray();
                    //floorCurves.Add(curveArray);
                    foreach (LINE beam in newBeam)
                    {
                        curveArray.Append(Line.CreateBound(beam.GetStartPoint(), beam.GetEndPoint()));
                    }

                    using (Transaction trans = new Transaction(this.revitDoc))
                    {
                        FailureHandlingOptions failureHandlingOptions = trans.GetFailureHandlingOptions();
                        FailureHandler         failureHandler         = new FailureHandler();
                        failureHandlingOptions.SetFailuresPreprocessor(failureHandler);
                        failureHandlingOptions.SetClearAfterRollback(false);
                        trans.SetFailureHandlingOptions(failureHandlingOptions);
                        trans.Start("Create Floors");
                        this.revitDoc.Create.NewFloor(curveArray, floor_type, targetLevel, false);
                        trans.Commit();
                    }
                }
                catch (Exception)
                {
                }
            }
        }
Пример #24
0
        public void ExportLinkedDocuments(Autodesk.Revit.DB.Document document, string fileName, Dictionary <ElementId, string> linksGUIDsCache, IFCExportOptions exportOptions)
        {
            // get the extension
            int index = fileName.LastIndexOf('.');

            if (index <= 0)
            {
                return;
            }
            string sExtension = fileName.Substring(index);

            fileName = fileName.Substring(0, index);

            // get all the revit link instances
            FilteredElementCollector collector        = new FilteredElementCollector(document);
            ElementFilter            elementFilter    = new ElementClassFilter(typeof(RevitLinkInstance));
            List <RevitLinkInstance> rvtLinkInstances = collector.WherePasses(elementFilter).Cast <RevitLinkInstance>().ToList();

            IDictionary <String, int> rvtLinkNamesDict = new Dictionary <String, int>();
            IDictionary <String, List <RevitLinkInstance> > rvtLinkNamesToInstancesDict = new Dictionary <String, List <RevitLinkInstance> >();

            try
            {
                // get the link types
                foreach (RevitLinkInstance rvtLinkInstance in rvtLinkInstances)
                {
                    // get the instance
                    if (rvtLinkInstance == null)
                    {
                        continue;
                    }

                    // check the cache
                    if (linksGUIDsCache.Keys.Contains(rvtLinkInstance.Id) == false)
                    {
                        continue;
                    }

                    // get the link document
                    Document linkDocument = rvtLinkInstance.GetLinkDocument();
                    if (linkDocument == null)
                    {
                        continue;
                    }

                    // get the link file path and name
                    String    linkPathName          = "";
                    Parameter originalFileNameParam = linkDocument.ProjectInformation.get_Parameter("Original IFC File Name");
                    if (originalFileNameParam != null && originalFileNameParam.StorageType == StorageType.String)
                    {
                        linkPathName = originalFileNameParam.AsString();
                    }
                    else
                    {
                        linkPathName = linkDocument.PathName;
                    }

                    // get the link file name
                    String linkFileName = "";
                    index = linkPathName.LastIndexOf("\\");
                    if (index > 0)
                    {
                        linkFileName = linkPathName.Substring(index + 1);
                    }
                    else
                    {
                        linkFileName = linkDocument.Title;
                    }

                    // remove the extension
                    index = linkFileName.LastIndexOf('.');
                    if (index > 0)
                    {
                        linkFileName = linkFileName.Substring(0, index);
                    }

                    // add to names count dictionary
                    if (!rvtLinkNamesDict.Keys.Contains(linkFileName))
                    {
                        rvtLinkNamesDict.Add(linkFileName, 0);
                    }
                    rvtLinkNamesDict[linkFileName]++;

                    // add to names instances dictionary
                    if (!rvtLinkNamesToInstancesDict.Keys.Contains(linkPathName))
                    {
                        rvtLinkNamesToInstancesDict.Add(linkPathName, new List <RevitLinkInstance>());
                    }
                    rvtLinkNamesToInstancesDict[linkPathName].Add(rvtLinkInstance);
                }
            }
            catch
            {
            }

            // get the link instances
            // We will keep track of the instances we can't export.
            // Reasons we can't export:
            // 1. The path for the linked instance doesn't exist.
            // 2. Couldn't create a temporary document for exporting the linked instance.
            // 3. The document for the linked instance can't be found.
            // 4. The linked instance is mirrored, non-conformal, or scaled.
            IList <string>    pathDoesntExist   = new List <string>();
            IList <string>    noTempDoc         = new List <string>();
            IList <ElementId> cantFindDoc       = new List <ElementId>();
            IList <ElementId> nonConformalInst  = new List <ElementId>();
            IList <ElementId> scaledInst        = new List <ElementId>();
            IList <ElementId> instHasReflection = new List <ElementId>();

            foreach (String linkPathName in rvtLinkNamesToInstancesDict.Keys)
            {
                // get the name of the copy
                String linkPathNameCopy = System.IO.Path.GetTempPath();
                index = linkPathName.LastIndexOf("\\");
                if (index > 0)
                {
                    linkPathNameCopy += linkPathName.Substring(index + 1);
                }
                else
                {
                    linkPathNameCopy += linkPathName;
                }
                index = linkPathNameCopy.LastIndexOf('.');
                if (index <= 0)
                {
                    index = linkPathNameCopy.Length;
                }
                linkPathNameCopy = linkPathNameCopy.Insert(index, " - Copy");
                int i = 1;
                while (File.Exists(linkPathNameCopy))
                {
                    linkPathNameCopy = linkPathNameCopy.Insert(index, "(" + (++i).ToString() + ")");
                }

                // copy the file
                File.Copy(linkPathName, linkPathNameCopy);
                if (!File.Exists(linkPathNameCopy))
                {
                    pathDoesntExist.Add(linkPathName);
                    continue;
                }

                // open the document
                Document documentCopy = null;
                try
                {
                    if ((linkPathName.Length >= 4 && linkPathName.Substring(linkPathName.Length - 4).ToLower() == ".ifc") ||
                        (linkPathName.Length >= 7 && linkPathName.Substring(linkPathName.Length - 7).ToLower() == ".ifcxml") ||
                        (linkPathName.Length >= 7 && linkPathName.Substring(linkPathName.Length - 7).ToLower() == ".ifczip"))
                    {
                        documentCopy = document.Application.OpenIFCDocument(linkPathNameCopy);
                    }
                    else
                    {
                        documentCopy = document.Application.OpenDocumentFile(linkPathNameCopy);
                    }
                }
                catch
                {
                    documentCopy = null;
                }

                if (documentCopy == null)
                {
                    noTempDoc.Add(linkPathName);
                    continue;
                }

                // get the link document unit scale
                DisplayUnitType dutLink = documentCopy.GetUnits().GetFormatOptions(UnitType.UT_Length).DisplayUnits;
                double          lengthScaleFactorLink = UnitUtils.ConvertFromInternalUnits(1.0, dutLink);

                // get the link instances
                List <RevitLinkInstance> currRvtLinkInstances = rvtLinkNamesToInstancesDict[linkPathName];
                IList <string>           serTransforms        = new List <string>();
                IList <string>           linkFileNames        = new List <string>();

                foreach (RevitLinkInstance currRvtLinkInstance in currRvtLinkInstances)
                {
                    // Nothing to report if the element itself is null.
                    if (currRvtLinkInstance == null)
                    {
                        continue;
                    }

                    // get the link document
                    Document linkDocument = currRvtLinkInstance.GetLinkDocument();
                    if (linkDocument == null)
                    {
                        cantFindDoc.Add(currRvtLinkInstance.Id);
                        continue;
                    }

                    // get the link transform
                    Transform tr = currRvtLinkInstance.GetTransform();

                    // We can't handle non-conformal, scaled, or mirrored transforms.
                    if (!tr.IsConformal)
                    {
                        nonConformalInst.Add(currRvtLinkInstance.Id);
                        continue;
                    }

                    if (tr.HasReflection)
                    {
                        instHasReflection.Add(currRvtLinkInstance.Id);
                        continue;
                    }

                    if (!MathUtil.IsAlmostEqual(tr.Determinant, 1.0))
                    {
                        scaledInst.Add(currRvtLinkInstance.Id);
                        continue;
                    }

                    // get the link file path and name
                    String linkFileName = "";
                    index = linkPathName.LastIndexOf("\\");
                    if (index > 0)
                    {
                        linkFileName = linkPathName.Substring(index + 1);
                    }
                    else
                    {
                        linkFileName = linkDocument.Title;
                    }

                    // remove the extension
                    index = linkFileName.LastIndexOf('.');
                    if (index > 0)
                    {
                        linkFileName = linkFileName.Substring(0, index);
                    }

                    //if link was an IFC file then make a different formating to the file name
                    if ((linkPathName.Length >= 4 && linkPathName.Substring(linkPathName.Length - 4).ToLower() == ".ifc") ||
                        (linkPathName.Length >= 7 && linkPathName.Substring(linkPathName.Length - 7).ToLower() == ".ifcxml") ||
                        (linkPathName.Length >= 7 && linkPathName.Substring(linkPathName.Length - 7).ToLower() == ".ifczip"))
                    {
                        String fName = fileName;

                        //get output path and add to the new file name
                        index = fName.LastIndexOf("\\");
                        if (index > 0)
                        {
                            fName = fName.Substring(0, index + 1);
                        }
                        else
                        {
                            fName = "";
                        }

                        //construct IFC file name
                        linkFileName = fName + linkFileName + "-";

                        //add guid
                        linkFileName += linksGUIDsCache[currRvtLinkInstance.Id];
                    }
                    else
                    {
                        // check if there are multiple instances with the same name
                        bool bMultiple = (rvtLinkNamesDict[linkFileName] > 1);

                        // add the path
                        linkFileName = fileName + "-" + linkFileName;

                        // add the guid
                        if (bMultiple)
                        {
                            linkFileName += "-";
                            linkFileName += linksGUIDsCache[currRvtLinkInstance.Id];
                        }
                    }

                    // add the extension
                    linkFileName += sExtension;

                    linkFileNames.Add(linkFileName);

                    // scale the transform origin
                    tr.Origin *= lengthScaleFactorLink;

                    // serialize transform
                    serTransforms.Add(SerializeTransform(tr));
                }

                // IFC export requires an open transaction, although no changes should be made
                Transaction transaction = new Transaction(documentCopy, "Export IFC Link");
                transaction.Start();
                FailureHandlingOptions failureOptions = transaction.GetFailureHandlingOptions();
                failureOptions.SetClearAfterRollback(false);
                transaction.SetFailureHandlingOptions(failureOptions);

                // export
                try
                {
                    int numLinkInstancesToExport = linkFileNames.Count;
                    exportOptions.AddOption("NumberOfExportedLinkInstances", numLinkInstancesToExport.ToString());

                    for (int ii = 0; ii < numLinkInstancesToExport; ii++)
                    {
                        string optionName = (ii == 0) ? "ExportLinkInstanceTransform" : "ExportLinkInstanceTransform" + (ii + 1).ToString();
                        exportOptions.AddOption(optionName, serTransforms[ii]);

                        // Don't pass in file name for the first link instance.
                        if (ii == 0)
                        {
                            continue;
                        }

                        optionName = "ExportLinkInstanceFileName" + (ii + 1).ToString();
                        exportOptions.AddOption(optionName, linkFileNames[ii]);
                    }

                    // Pass in the first value; the rest will  be in the options.
                    String path_     = Path.GetDirectoryName(linkFileNames[0]);
                    String fileName_ = Path.GetFileName(linkFileNames[0]);
                    bool   result    = documentCopy.Export(path_, fileName_, exportOptions); // pass in the options here
                }
                catch
                {
                }

                // rollback the transaction
                transaction.RollBack();

                // close the document
                documentCopy.Close(false);

                // delete the copy
                try
                {
                    File.Delete(linkPathNameCopy);
                }
                catch
                {
                }

                // Show user errors, if any.
                int numBadInstances = pathDoesntExist.Count + noTempDoc.Count + cantFindDoc.Count + nonConformalInst.Count
                                      + scaledInst.Count + instHasReflection.Count;
                if (numBadInstances > 0)
                {
                    using (TaskDialog taskDialog = new TaskDialog(Properties.Resources.IFCExport))
                    {
                        taskDialog.MainInstruction = string.Format(Properties.Resources.LinkInstanceExportErrorMain, numBadInstances);
                        taskDialog.MainIcon        = TaskDialogIcon.TaskDialogIconWarning;
                        taskDialog.TitleAutoPrefix = false;

                        string expandedContent = "";
                        AddExpandedStringContent(ref expandedContent, Properties.Resources.LinkInstanceExportErrorPath, pathDoesntExist);
                        AddExpandedStringContent(ref expandedContent, Properties.Resources.LinkInstanceExportCantCreateDoc, noTempDoc);
                        AddExpandedElementIdContent(ref expandedContent, Properties.Resources.LinkInstanceExportCantFindDoc, cantFindDoc);
                        AddExpandedElementIdContent(ref expandedContent, Properties.Resources.LinkInstanceExportNonConformal, nonConformalInst);
                        AddExpandedElementIdContent(ref expandedContent, Properties.Resources.LinkInstanceExportScaled, scaledInst);
                        AddExpandedElementIdContent(ref expandedContent, Properties.Resources.LinkInstanceExportHasReflection, instHasReflection);

                        taskDialog.ExpandedContent = expandedContent;
                        TaskDialogResult result = taskDialog.Show();
                    }
                }
            }
        }
Пример #25
0
        /// <summary>
        /// Implementation of the command binding event for the IFC export command.
        /// </summary>
        /// <param name="sender">The event sender (Revit UIApplication).</param>
        /// <param name="args">The arguments (command binding).</param>
        public void OnIFCExport(object sender, CommandEventArgs args)
        {
            try
            {
                // Prepare basic objects
                UIApplication uiApp = sender as UIApplication;
                UIDocument    uiDoc = uiApp.ActiveUIDocument;
                Document      doc   = uiDoc.Document;

                TheDocument = doc;

                IFCExportConfigurationsMap configurationsMap = new IFCExportConfigurationsMap();
                configurationsMap.Add(IFCExportConfiguration.GetInSession());
                configurationsMap.AddBuiltInConfigurations();
                configurationsMap.AddSavedConfigurations();

                String mruSelection = null;
                if (m_mruConfiguration != null && configurationsMap.HasName(m_mruConfiguration))
                {
                    mruSelection = m_mruConfiguration;
                }

                PotentiallyUpdatedConfigurations = false;

                IFCExport mainWindow = new IFCExport(doc, configurationsMap, mruSelection);
                mainWindow.ShowDialog();

                // If user chose to continue
                if (mainWindow.Result == IFCExportResult.ExportAndSaveSettings)
                {
                    // change options
                    IFCExportConfiguration selectedConfig = mainWindow.GetSelectedConfiguration();

                    // Prepare the export options
                    IFCExportOptions exportOptions = new IFCExportOptions();
                    selectedConfig.UpdateOptions(exportOptions, uiDoc.ActiveView.Id);

                    // prompt for the file name
                    SaveFileDialog fileDialog = new SaveFileDialog();
                    fileDialog.AddExtension = true;

                    String defaultDirectory = m_mruExportPath != null ? m_mruExportPath : null;

                    if (defaultDirectory == null)
                    {
                        String revitFilePath = doc.PathName;
                        if (!String.IsNullOrEmpty(revitFilePath))
                        {
                            defaultDirectory = Path.GetDirectoryName(revitFilePath);
                        }
                    }

                    if (defaultDirectory == null)
                    {
                        defaultDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                    }

                    String defaultFileName = doc.Title;
                    if (String.IsNullOrEmpty(defaultFileName))
                    {
                        defaultFileName = "Project";
                    }
                    else
                    {
                        defaultFileName = Path.GetFileNameWithoutExtension(defaultFileName);
                    }
                    String defaultExtension = mainWindow.GetFileExtension();

                    fileDialog.FileName         = defaultFileName;
                    fileDialog.DefaultExt       = defaultExtension;
                    fileDialog.Filter           = mainWindow.GetFileFilter();
                    fileDialog.InitialDirectory = defaultDirectory;
                    bool?fileDialogResult = fileDialog.ShowDialog();

                    // If user chose to continue
                    if (fileDialogResult.HasValue && fileDialogResult.Value)
                    {
                        // Prompt the user for the file location and path
                        String fullName = fileDialog.FileName;
                        String path     = Path.GetDirectoryName(fullName);
                        String fileName = Path.GetFileName(fullName);

                        // Call this before the Export IFC transaction starts, as it has its own transaction.
                        IFCClassificationMgr.DeleteObsoleteSchemas(doc);

                        // IFC export requires an open transaction, although no changes should be made
                        Transaction transaction = new Transaction(doc, "Export IFC");
                        transaction.Start();
                        FailureHandlingOptions failureOptions = transaction.GetFailureHandlingOptions();
                        failureOptions.SetClearAfterRollback(false);
                        transaction.SetFailureHandlingOptions(failureOptions);

                        // There is no UI option for this, but these two options can be useful for debugging/investigating
                        // issues in specific file export.  The first one supports export of only one element
                        //exportOptions.AddOption("SingleElement", "174245");
                        // The second one supports export only of a list of elements
                        //exportOptions.AddOption("ElementsForExport", "174245;205427");

                        bool result = doc.Export(path, fileName, exportOptions); // pass in the options here

                        if (!result)
                        {
                            using (TaskDialog taskDialog = new TaskDialog(Properties.Resources.IFCExport))
                            {
                                taskDialog.MainInstruction = Properties.Resources.IFCExportProcessError;
                                taskDialog.MainIcon        = TaskDialogIcon.TaskDialogIconWarning;
                                TaskDialogResult taskDialogResult = taskDialog.Show();
                            }
                        }

                        // This option should be rarely used, and is only for consistency with old files.  As such, it is set by environment variable only.
                        String use2009GUID = Environment.GetEnvironmentVariable("Assign2009GUIDToBuildingStoriesOnIFCExport");
                        bool   use2009BuildingStoreyGUIDs = (use2009GUID != null && use2009GUID == "1");

                        // Cache for links guids
                        Dictionary <ElementId, string> linksGUIDsCache = new Dictionary <ElementId, string>();
                        if (selectedConfig.ExportLinkedFiles == true)
                        {
                            Autodesk.Revit.DB.FilteredElementCollector collector = new FilteredElementCollector(doc);
                            collector.WhereElementIsNotElementType().OfCategory(BuiltInCategory.OST_RvtLinks);
                            System.Collections.Generic.ICollection <ElementId> rvtLinkInstanceIds = collector.ToElementIds();
                            foreach (ElementId linkId in rvtLinkInstanceIds)
                            {
                                Element linkInstance = doc.GetElement(linkId);
                                if (linkInstance == null)
                                {
                                    continue;
                                }
                                Parameter parameter = linkInstance.get_Parameter(BuiltInParameter.IFC_GUID);
                                if (parameter != null && parameter.HasValue && parameter.StorageType == StorageType.String)
                                {
                                    String sGUID = parameter.AsString(), sGUIDlower = sGUID.ToLower();
                                    foreach (KeyValuePair <ElementId, string> value in linksGUIDsCache)
                                    {
                                        if (value.Value.ToLower().IndexOf(sGUIDlower) == 0)
                                        {
                                            sGUID += "-";
                                        }
                                    }
                                    linksGUIDsCache.Add(linkInstance.Id, sGUID);
                                }
                            }
                        }

                        // Roll back the transaction started earlier, unless certain options are set.
                        if (use2009BuildingStoreyGUIDs || selectedConfig.StoreIFCGUID)
                        {
                            transaction.Commit();
                        }
                        else
                        {
                            transaction.RollBack();
                        }

                        // Export links
                        if (selectedConfig.ExportLinkedFiles == true)
                        {
                            exportOptions.AddOption("ExportingLinks", true.ToString());
                            ExportLinkedDocuments(doc, fullName, linksGUIDsCache, exportOptions);
                            exportOptions.AddOption("ExportingLinks", false.ToString());
                        }

                        // Remember last successful export location
                        m_mruExportPath = path;
                    }
                }

                // The cancel button should cancel the export, not any "OK"ed setup changes.
                if (mainWindow.Result == IFCExportResult.ExportAndSaveSettings || mainWindow.Result == IFCExportResult.Cancel)
                {
                    if (PotentiallyUpdatedConfigurations)
                    {
                        configurationsMap = mainWindow.GetModifiedConfigurations();
                        configurationsMap.UpdateSavedConfigurations();
                    }

                    // Remember last selected configuration
                    m_mruConfiguration = mainWindow.GetSelectedConfiguration().Name;
                }
            }
            catch (Exception e)
            {
                using (TaskDialog taskDialog = new TaskDialog(Properties.Resources.IFCExport))
                {
                    taskDialog.MainInstruction = Properties.Resources.IFCExportProcessError;
                    taskDialog.MainIcon        = TaskDialogIcon.TaskDialogIconWarning;
                    taskDialog.ExpandedContent = e.ToString();
                    TaskDialogResult result = taskDialog.Show();
                }
            }
        }
        /// <summary>
        /// Implementation of the command binding event for the IFC export command.
        /// </summary>
        /// <param name="sender">The event sender (Revit UIApplication).</param>
        /// <param name="args">The arguments (command binding).</param>
        public void OnIFCExport(object sender, CommandEventArgs args)
        {
            try
            {
                // Prepare basic objects
                UIApplication uiApp = sender as UIApplication;
                UIDocument    uiDoc = uiApp.ActiveUIDocument;
                Document      doc   = uiDoc.Document;

                TheDocument = doc;

                IFCExportConfigurationsMap configurationsMap = new IFCExportConfigurationsMap();
                configurationsMap.Add(IFCExportConfiguration.GetInSession());
                configurationsMap.AddBuiltInConfigurations();
                configurationsMap.AddSavedConfigurations();

                String mruSelection = null;
                if (m_mruConfiguration != null && configurationsMap.HasName(m_mruConfiguration))
                {
                    mruSelection = m_mruConfiguration;
                }

                PotentiallyUpdatedConfigurations = false;

                IFCExport mainWindow = new IFCExport(doc, configurationsMap, mruSelection);
                mainWindow.ShowDialog();

                // If user chose to continue
                if (mainWindow.Result == IFCExportResult.ExportAndSaveSettings)
                {
                    // change options
                    IFCExportConfiguration selectedConfig = mainWindow.GetSelectedConfiguration();

                    // Prepare the export options
                    IFCExportOptions exportOptions = new IFCExportOptions();
                    selectedConfig.UpdateOptions(exportOptions, uiDoc.ActiveView.Id);

                    // prompt for the file name
                    SaveFileDialog fileDialog = new SaveFileDialog();
                    fileDialog.AddExtension = true;

                    String defaultDirectory = m_mruExportPath != null ? m_mruExportPath : null;

                    if (defaultDirectory == null)
                    {
                        String revitFilePath = doc.PathName;
                        if (!String.IsNullOrEmpty(revitFilePath))
                        {
                            defaultDirectory = Path.GetDirectoryName(revitFilePath);
                        }
                    }

                    if (defaultDirectory == null)
                    {
                        defaultDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                    }

                    String defaultFileName = doc.Title;
                    if (String.IsNullOrEmpty(defaultFileName))
                    {
                        defaultFileName = "Project";
                    }
                    else
                    {
                        defaultFileName = Path.GetFileNameWithoutExtension(defaultFileName);
                    }
                    String defaultExtension = mainWindow.GetFileExtension();

                    fileDialog.FileName         = defaultFileName;
                    fileDialog.DefaultExt       = defaultExtension;
                    fileDialog.Filter           = mainWindow.GetFileFilter();
                    fileDialog.InitialDirectory = defaultDirectory;
                    bool?fileDialogResult = fileDialog.ShowDialog();

                    // If user chose to continue
                    if (fileDialogResult.HasValue && fileDialogResult.Value)
                    {
                        // Prompt the user for the file location and path
                        String fullName = fileDialog.FileName;
                        String path     = Path.GetDirectoryName(fullName);
                        String fileName = Path.GetFileName(fullName);

                        // IFC export requires an open transaction, although no changes should be made
                        Transaction transaction = new Transaction(doc, "Export IFC");
                        transaction.Start();
                        FailureHandlingOptions failureOptions = transaction.GetFailureHandlingOptions();
                        failureOptions.SetClearAfterRollback(false);
                        transaction.SetFailureHandlingOptions(failureOptions);

                        // There is no UI option for this, but these two options can be useful for debugging/investigating
                        // issues in specific file export.  The first one supports export of only one element
                        //exportOptions.AddOption("SingleElement", "174245");
                        // The second one supports export only of a list of elements
                        //exportOptions.AddOption("ElementsForExport", "174245;205427");

                        // This option should be rarely used, and is only for consistency with old files.  As such, it is set by environment variable only.
                        String use2009GUID = Environment.GetEnvironmentVariable("Assign2009GUIDToBuildingStoriesOnIFCExport");
                        bool   use2009BuildingStoreyGUIDs = (use2009GUID != null && use2009GUID == "1");

                        // Roll back the transaction started earlier, unless certain options are set.
                        bool commitTransaction = (use2009BuildingStoreyGUIDs || selectedConfig.StoreIFCGUID);

                        if (commitTransaction)
                        {
                            IFCStoredGUID.Clear();
                        }

                        bool result = doc.Export(path, fileName, exportOptions); // pass in the options here

                        if (!result)
                        {
                            //TODO localization
                            TaskDialog taskDialog = new TaskDialog("Error exporting IFC file");
                            taskDialog.MainInstruction = "The IFC export process encountered an error.";
                            taskDialog.MainIcon        = TaskDialogIcon.TaskDialogIconWarning;
                            taskDialog.Show();
                        }

                        // Roll back the transaction started earlier, unless certain options are set.
                        if (commitTransaction)
                        {
                            foreach (KeyValuePair <ElementId, string> elementIdToGUID in IFCStoredGUID.ElementIdToGUID)
                            {
                                Element element = doc.GetElement(elementIdToGUID.Key);
                                if (element == null)
                                {
                                    continue;
                                }

                                BuiltInParameter builtInParameter = (element is ElementType) ? BuiltInParameter.IFC_TYPE_GUID : BuiltInParameter.IFC_GUID;
                                SetGUIDParameter(element, builtInParameter, elementIdToGUID.Value);
                            }

                            ProjectInfo projectInfo = doc.ProjectInformation;
                            if (projectInfo != null)
                            {
                                foreach (KeyValuePair <BuiltInParameter, string> elementIdToGUID in IFCStoredGUID.ProjectInfoParameterGUID)
                                {
                                    SetGUIDParameter(projectInfo, elementIdToGUID.Key, elementIdToGUID.Value);
                                }
                            }

                            transaction.Commit();
                        }
                        else
                        {
                            transaction.RollBack();
                        }

                        // Remember last successful export location
                        m_mruExportPath = path;
                    }
                }

                // The cancel button should cancel the export, not any "OK"ed setup changes.
                if (mainWindow.Result == IFCExportResult.ExportAndSaveSettings || mainWindow.Result == IFCExportResult.Cancel)
                {
                    if (PotentiallyUpdatedConfigurations)
                    {
                        configurationsMap = mainWindow.GetModifiedConfigurations();
                        configurationsMap.UpdateSavedConfigurations();
                    }

                    // Remember last selected configuration
                    m_mruConfiguration = mainWindow.GetSelectedConfiguration().Name;
                }
            }
            catch (Exception e)
            {
                //TODO localization
                TaskDialog taskDialog = new TaskDialog("Error exporting IFC file");
                taskDialog.MainInstruction = "The IFC export process encountered an error.";
                taskDialog.MainIcon        = TaskDialogIcon.TaskDialogIconWarning;
                taskDialog.ExpandedContent = e.ToString();
                taskDialog.Show();
            }
        }
Пример #27
0
        public void CopyElementsFlatToWarped(Document doc, FamilyInstance familyInstance, ICollection <ElementId> elementIds, Selection sel)
        {
            ICollection <ElementId> newlist = new List <ElementId>();
            CopyPasteOptions        option  = new CopyPasteOptions();
            ElementtransformToCopy  tr      = new ElementtransformToCopy();
            FamilyInstance          flat    = tr.GetFlat(doc, familyInstance);
            List <PlanarFace>       list1   = FlFaces(flat);
            FamilyInstance          warped  = tr.GetWarped(doc, familyInstance);
            PlanarFace    face1             = Facemax(list1);
            Element       element1          = doc.GetElement(elementIds.First());
            LocationPoint loc      = element1.Location as LocationPoint;
            XYZ           pointorg = loc.Point;
            //double minspace = MinSpacePlanarFace(doc, familyInstance, face1, pointorg);
            Transform transform = TransformFlatWapred(doc, flat, warped);

            //Solid solid1 = Solidhelper.AllSolids(flat).First();
            //Solid solid2 = Solidhelper.AllSolids(warped).First();
            //Transform transform1 = solid1.GetBoundingBox().Transform;
            //Transform transform2 = solid2.GetBoundingBox().Transform;
            //Transform transform = transform1.Inverse.Multiply(transform2);
            using (Transaction tran = new Transaction(doc, "copy"))
            {
                tran.Start();
                FailureHandlingOptions options       = tran.GetFailureHandlingOptions();
                IgnoreProcess          ignoreProcess = new IgnoreProcess();
                options.SetClearAfterRollback(true);
                options.SetFailuresPreprocessor(ignoreProcess);
                tran.SetFailureHandlingOptions(options);
                try
                {
                    newlist = ElementTransformUtils.CopyElements(doc, elementIds, doc, transform, option);
                    Remove_product(doc, newlist);
                }
                catch (Exception)
                {
                }
                foreach (ElementId eleid in newlist)
                {
                    Element            ele      = doc.GetElement(eleid);
                    LocationPoint      locele   = ele.Location as LocationPoint;
                    XYZ                pointcon = locele.Point;
                    List <HermiteFace> list2    = WarpedFace(warped);
                    if (list2.Count != 0)
                    {
                        HermiteFace face2 = FacemaxWraped(list2);
                        //double distanceloc = kcpointtoHemiteFace(face2, pointcon);

                        double distanceloc = MinSpaceHermiteFace(doc, familyInstance, face2, pointcon);
                        var    xv1         = FIndpointonwraped(pointcon, new XYZ(0, 0, 1), distanceloc);
                        XYZ    point1      = pointcon - xv1;
                        ElementTransformUtils.MoveElement(doc, eleid, point1);
                    }
                    else
                    {
                        List <RevolvedFace> revolvedFaces = WarpedFaceRevolFace(warped);
                        RevolvedFace        face2         = FacemaxWrapedRevolFace(revolvedFaces);
                        //double distanceloc = kcpointtoHemiteFace(face2, pointcon);

                        double distanceloc = MinSpaceRevolFace(doc, familyInstance, face2, pointcon);
                        var    xv1         = FIndpointonwraped(pointcon, new XYZ(0, 0, 1), distanceloc);
                        XYZ    point1      = pointcon - xv1;
                        ElementTransformUtils.MoveElement(doc, eleid, point1);
                    }
                    //if (minspace > 0)
                    //{
                    //    var xv1 = FIndpointonwraped(pointcon,doc.ActiveView.UpDirection, distanceloc);
                    //    XYZ point1 = pointcon - xv1;
                    //    ElementTransformUtils.MoveElement(doc, eleid, point1);
                    //}
                    //else
                    //{
                    //    var xv1 = FIndpointonwraped(pointcon, doc.ActiveView.UpDirection, distanceloc);
                    //    XYZ point1 = xv1 - pointcon;
                    //    ElementTransformUtils.MoveElement(doc, eleid, point1);
                    //}
                }
                tran.Commit();
            }
        }
Пример #28
0
        public void CopyElementsConnFlangeDtee(Document doc, FamilyInstance familyInstance, List <FamilyInstance> listinstance, ICollection <ElementId> elementIds, bool valuekey)
        {
            ICollection <ElementId> newlist  = new List <ElementId>();
            Parameter        pa1             = familyInstance.LookupParameter("Flange_Edge_Offset_Right");
            double           Flange_Right1   = pa1.AsDouble();
            Parameter        pa2             = familyInstance.LookupParameter("Flange_Edge_Offset_Left");
            double           Flange_Left1    = pa2.AsDouble();
            Parameter        pal             = familyInstance.LookupParameter("DIM_LENGTH");
            double           dim_length      = pal.AsDouble();
            var              f1              = elementIds.First();
            double           kl              = Nut(doc, familyInstance, f1);
            CopyPasteOptions option          = new CopyPasteOptions();
            ProgressBarform  progressBarform = new ProgressBarform(listinstance.Count, "Loading...");

            progressBarform.Show();
            foreach (FamilyInstance source in listinstance)
            {
                if (source.Id != familyInstance.Id)
                {
                    using (Transaction tran = new Transaction(doc, "Copy"))
                    {
                        tran.Start();
                        Transform transform1   = source.GetTransform();
                        Parameter pa3          = source.LookupParameter("Flange_Edge_Offset_Right");
                        double    Flange_Right = pa3.AsDouble();
                        ElementId sourceid     = source.GetTypeId();
                        Element   sourcetype   = doc.GetElement(sourceid);
                        Parameter sourcepa     = sourcetype.LookupParameter("DT_Stem_Spacing_Form");
                        Parameter pa4          = source.LookupParameter("Flange_Edge_Offset_Left");
                        double    Flange_Left  = pa4.AsDouble();
                        double    val1         = Flange_Right1 - Flange_Right;
                        double    val2         = Flange_Left1 - Flange_Left;
                        progressBarform.giatri();
                        if (progressBarform.iscontinue == false)
                        {
                            break;
                        }
                        Transform transform                  = TransformToCopy(source, familyInstance);
                        FailureHandlingOptions options       = tran.GetFailureHandlingOptions();
                        IgnoreProcess          ignoreProcess = new IgnoreProcess();
                        options.SetClearAfterRollback(true);
                        options.SetFailuresPreprocessor(ignoreProcess);
                        tran.SetFailureHandlingOptions(options);
                        try
                        {
                            newlist = ElementTransformUtils.CopyElements(doc, elementIds, doc, transform, option);
                            Remove_product(doc, newlist);
                        }
                        catch (Exception)
                        {
                        }
                        if (valuekey == true)
                        {
                            if (sourcepa == null)
                            {
                                if (val1 != 0 || val2 != 0)
                                {
                                    FamilyInstance    flatsource        = GetFlat(doc, familyInstance);
                                    FamilyInstance    flattarget        = GetFlat(doc, source);
                                    List <PlanarFace> planarFacessource = FlFaces(flatsource);
                                    List <PlanarFace> planarFacetarget  = FlFaces(flattarget);
                                    Element           elesource         = doc.GetElement(elementIds.First());
                                    double            spatarget         = 0;
                                    foreach (ElementId i in newlist)
                                    {
                                        Element       eletarget      = doc.GetElement(i);
                                        LocationPoint locationPoint2 = eletarget.Location as LocationPoint;
                                        XYZ           pointtarget    = locationPoint2.Point;
                                        spatarget = DistanceToMin(doc, source, planarFacetarget, pointtarget, kl);
                                        if (spatarget != 0)
                                        {
                                            break;
                                        }
                                    }
                                    if (spatarget != 0)
                                    {
                                        foreach (ElementId i in newlist)
                                        {
                                            XYZ point1 = new XYZ(0, 0, 0);
                                            point1 = point1 + transform1.BasisX * -spatarget;
                                            ElementTransformUtils.MoveElement(doc, i, point1);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                if (val2 > 0)
                                {
                                    foreach (ElementId i in newlist)
                                    {
                                        XYZ point1 = new XYZ(0, 0, 0);
                                        point1 = point1 + transform1.BasisX * -val2;
                                        ElementTransformUtils.MoveElement(doc, i, point1);
                                    }
                                }
                                else
                                {
                                    foreach (ElementId i in newlist)
                                    {
                                        XYZ point1 = new XYZ(0, 0, 0);
                                        point1 = point1 + transform1.BasisX * -val2;
                                        ElementTransformUtils.MoveElement(doc, i, point1);
                                    }
                                }
                            }
                        }
                        if (valuekey == false)
                        {
                            if (sourcepa == null)
                            {
                                if (val1 != 0 || val2 != 0)
                                {
                                    FamilyInstance    flatsource        = GetFlat(doc, familyInstance);
                                    FamilyInstance    flattarget        = GetFlat(doc, source);
                                    List <PlanarFace> planarFacessource = FlFaces(flatsource);
                                    List <PlanarFace> planarFacetarget  = FlFaces(flattarget);
                                    Element           elesource         = doc.GetElement(elementIds.First());
                                    double            spatarget         = 0;
                                    foreach (ElementId i in newlist)
                                    {
                                        Element       eletarget      = doc.GetElement(i);
                                        LocationPoint locationPoint2 = eletarget.Location as LocationPoint;
                                        XYZ           pointtarget    = locationPoint2.Point;
                                        spatarget = DistanceToMin(doc, source, planarFacetarget, pointtarget, kl);
                                        if (spatarget != 0)
                                        {
                                            break;
                                        }
                                    }
                                    if (spatarget != 0)
                                    {
                                        foreach (ElementId i in newlist)
                                        {
                                            XYZ point1 = new XYZ(0, 0, 0);
                                            point1 = point1 + transform1.BasisX * spatarget;
                                            ElementTransformUtils.MoveElement(doc, i, point1);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                if (val1 > 0)
                                {
                                    foreach (ElementId i in newlist)
                                    {
                                        XYZ point1 = new XYZ(0, 0, 0);
                                        point1 = point1 + transform1.BasisX * (val1);
                                        ElementTransformUtils.MoveElement(doc, i, point1);
                                    }
                                }
                                else
                                {
                                    foreach (ElementId i in newlist)
                                    {
                                        XYZ point1 = new XYZ(0, 0, 0);
                                        point1 = point1 + transform1.BasisX * (-val1);
                                        ElementTransformUtils.MoveElement(doc, i, point1);
                                    }
                                }
                            }
                        }
                        tran.Commit();
                    }
                }
            }
            progressBarform.Close();
        }
Пример #29
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            string getPath = Path.Combine(startPath, "CAD_REVIT_DATA");

            revitDoc = commandData.Application.ActiveUIDocument.Document;
            uidoc    = commandData.Application.ActiveUIDocument;

            ElementId ele = null;


            Selection selection             = uidoc.Selection;
            ICollection <ElementId> element = selection.GetElementIds();

            foreach (ElementId eleID in element)
            {
                ele = eleID;
                break;
            }

            var FT2 = new FilteredElementCollector(revitDoc)
                      .OfClass(typeof(FloorType)).GetElementIterator();

            FloorType FT = new FilteredElementCollector(revitDoc)
                           .OfClass(typeof(FloorType))
                           .First <Element>(
                e => e.Name.Equals("160mm 混凝土與 50mm 金屬板"))
                           as FloorType;


            Transaction            transaction            = new Transaction(revitDoc);
            FailureHandlingOptions failureHandlingOptions = transaction.GetFailureHandlingOptions();
            FailureHandler         failureHandler         = new FailureHandler();

            failureHandlingOptions.SetFailuresPreprocessor(failureHandler);
            failureHandlingOptions.SetClearAfterRollback(false);
            transaction.SetFailureHandlingOptions(failureHandlingOptions);
            transaction.Start("Transaction Name");
            // Do something here that causes the error

            List <string> Height = new List <string>();
            List <XYZ>    Data   = LoadTest(ref Height, Path.Combine(getPath, "final.txt"));

            int kk = 0;

            foreach (var xyz in Data)
            {
                CreateFloor(xyz.X, xyz.Y, double.Parse(Height[kk]), xyz.Z, FT, ele);
                kk = kk + 1;
            }
            transaction.Commit();



            // The following is just illustrative.
            // In reality we would collect the errors
            // to show later.

            //if (failureHandler.ErrorMessage != "")
            //{
            //    System.Windows.Forms.MessageBox.Show(
            //      failureHandler.ErrorSeverity + " || "
            //      + failureHandler.ErrorMessage);
            //}

            return(Result.Succeeded);
        }
Пример #30
0
        public FamilyInstance CreateFamily(RoomProperties rp)
        {
            FamilyInstance familyInstance = null;

            try
            {
                string   currentAssembly = System.Reflection.Assembly.GetAssembly(this.GetType()).Location;
                string   massTemplate    = Path.GetDirectoryName(currentAssembly) + "/Resources/Mass.rfa";
                Document familyDoc       = null;
                using (Transaction trans = new Transaction(doc))
                {
                    trans.Start("Open Document");
                    familyDoc = m_app.OpenDocumentFile(massTemplate);
                    trans.Commit();
                }

                if (null != familyDoc)
                {
                    bool createdParam = false;
                    using (Transaction trans = new Transaction(familyDoc))
                    {
                        FailureHandlingOptions failureHandlingOptions = trans.GetFailureHandlingOptions();
                        FailureHandler         failureHandler         = new FailureHandler();
                        failureHandlingOptions.SetFailuresPreprocessor(failureHandler);
                        failureHandlingOptions.SetClearAfterRollback(true);
                        trans.SetFailureHandlingOptions(failureHandlingOptions);

                        trans.Start("Create Extrusion");
                        try
                        {
                            FamilyType newFamilyType = familyDoc.FamilyManager.NewType(rp.Name);

                            bool createdMass = CreateExtrusion(familyDoc, rp);

                            Dictionary <string, Parameter> parameters = new Dictionary <string, Parameter>();
                            parameters = rp.Parameters;
                            if (createdMass)
                            {
                                createdParam = CreateNewParameters(familyDoc, parameters);
                            }

                            if (failureHandler.FailureMessageInfoList.Count > 0)
                            {
                                failureMessage.AppendLine("[" + rp.ID + ": " + rp.Name + "] :" + failureHandler.FailureMessageInfoList[0].ErrorMessage);
                            }

                            trans.Commit();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Failed to create family.\n" + ex.Message, "MassCreator: CreateFamily", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            trans.RollBack();
                        }
                    }
                    if (createdParam)
                    {
                        SaveAsOptions opt = new SaveAsOptions();
                        opt.OverwriteExistingFile = true;
                        string fileName = Path.Combine(massFolder, rp.ID + ".rfa");
                        familyDoc.SaveAs(fileName, opt);
                        familyDoc.Close(true);
                        familyInstance = LoadMassFamily(fileName, rp.LevelObj);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to create family.\n" + ex.Message, "MassCreator: CreateFamily", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            return(familyInstance);
        }