public void VisualizePoint(SpatialAnalysis.Geometry.UV pnt, double size, double elevation) { //unit conversion SpatialAnalysis.Geometry.UV p = pnt.Copy(); unitConversion.Transform(p); //revit drawing XYZ p1 = new XYZ(p.U - size / 2, p.V - size / 2, elevation); XYZ p2 = new XYZ(p.U + size / 2, p.V + size / 2, elevation); XYZ q1 = new XYZ(p.U + size / 2, p.V - size / 2, elevation); XYZ q2 = new XYZ(p.U - size / 2, p.V + size / 2, elevation); using (Transaction t = new Transaction(OSM_FOR_REVIT.RevitDocument, "Show Point")) { t.Start(); FailureHandlingOptions failOpt = t.GetFailureHandlingOptions(); failOpt.SetFailuresPreprocessor(new CurveDrawingWarningSwallower()); t.SetFailureHandlingOptions(failOpt); Plane pln = Plane.CreateByNormalAndOrigin(XYZ.BasisZ, new XYZ(0, 0, elevation)); SketchPlane skp = SketchPlane.Create(OSM_FOR_REVIT.RevitDocument, pln); Line l1 = Line.CreateBound(p1, p2); Line l2 = Line.CreateBound(q1, q2); OSM_FOR_REVIT.RevitDocument.Create.NewModelCurve(l1, skp); OSM_FOR_REVIT.RevitDocument.Create.NewModelCurve(l2, skp); t.Commit(); } p1 = null; p2 = null; q1 = null; q2 = null; }
/// <summary> /// Gets a ReferenceArray representing the polygon /// </summary> /// <param name="document">The document in which the ReferenceArray is going to be generated</param> /// <param name="height">A desired plane that is determined by a Z value</param> /// <returns>Returns a ReferenceArray that might be null especifically the polygon is not closed</returns> public ReferenceArray Get_ReferenceArray(Document document, XYZ translation) { ReferenceArray refAr = null; using (Transaction createReferenceArray = new Transaction(document)) { FailureHandlingOptions failOpt = createReferenceArray.GetFailureHandlingOptions(); failOpt.SetFailuresPreprocessor(new WarningSwallower()); createReferenceArray.SetFailureHandlingOptions(failOpt); createReferenceArray.Start("Create ReferenceArray"); refAr = new ReferenceArray(); Plane p = new Plane(XYZ.BasisZ, new XYZ(this.processedPolygon[0].X, this.processedPolygon[0].Y, 0)); SketchPlane skp = SketchPlane.Create(document, p); try { for (int i = 0; i < this.processedPolygon.Count; i++) { int j = (i == this.processedPolygon.Count - 1) ? 0 : i + 1; XYZ ptA = this.processedPolygon[i] - translation; XYZ PtB = this.processedPolygon[j] - translation; Line l = Line.CreateBound(ptA, PtB); ModelCurve mCrv = document.FamilyCreate.NewModelCurve(l, skp); refAr.Append(mCrv.GeometryCurve.Reference); } } catch (Exception) { createReferenceArray.Commit(); return(null); } createReferenceArray.Commit(); } return(refAr); }
public void VisualizeOpenBoundary(List <SpatialAnalysis.Geometry.UV> points, double elevation) { //create a deep copy of the list var copy = new List <SpatialAnalysis.Geometry.UV>(); foreach (var item in points) { copy.Add(item.Copy()); } //transform units unitConversion.Transform(copy); //draw in revit using (Transaction t = new Transaction(OSM_FOR_REVIT.RevitDocument, "Draw Boundary")) { t.Start(); FailureHandlingOptions failOpt = t.GetFailureHandlingOptions(); failOpt.SetFailuresPreprocessor(new CurveDrawingWarningSwallower()); t.SetFailureHandlingOptions(failOpt); Plane p = Plane.CreateByNormalAndOrigin(XYZ.BasisZ, new XYZ(0, 0, elevation)); SketchPlane skp = SketchPlane.Create(OSM_FOR_REVIT.RevitDocument, p); for (int i = 0; i < copy.Count - 1; i++) { try { XYZ p1 = new XYZ(copy[i].U, copy[i].V, elevation); XYZ p2 = new XYZ(copy[i + 1].U, copy[i + 1].V, elevation); Line l = Line.CreateBound(p1, p2); OSM_FOR_REVIT.RevitDocument.Create.NewModelCurve(l, skp); } catch (Exception e) { MessageBox.Show(e.Report()); } } t.Commit(); } }
public void VisualizeLines(ICollection <UVLine> lines, double elevation) { using (Transaction t = new Transaction(OSM_FOR_REVIT.RevitDocument, "Draw lines")) { t.Start(); FailureHandlingOptions failOpt = t.GetFailureHandlingOptions(); failOpt.SetFailuresPreprocessor(new CurveDrawingWarningSwallower()); t.SetFailureHandlingOptions(failOpt); Plane p = Plane.CreateByNormalAndOrigin(XYZ.BasisZ, new XYZ(0, 0, elevation)); SketchPlane skp = SketchPlane.Create(OSM_FOR_REVIT.RevitDocument, p); foreach (UVLine item in lines) { //unit conversion SpatialAnalysis.Geometry.UV start = item.Start.Copy(); unitConversion.Transform(start); SpatialAnalysis.Geometry.UV end = item.End.Copy(); unitConversion.Transform(end); //revit drawing part try { XYZ p1 = new XYZ(start.U, start.V, elevation); XYZ p2 = new XYZ(end.U, end.V, elevation); Line l = Line.CreateBound(p1, p2); OSM_FOR_REVIT.RevitDocument.Create.NewModelCurve(l, skp); } catch (Exception e) { MessageBox.Show(e.Report()); } } t.Commit(); } }
/// <summary> /// Copies all view-specific elements from a source view to a target view. /// </summary> /// <remarks> /// The source and target views do not have to be in the same document. /// </remarks> /// <param name="fromView">The source view.</param> /// <param name="toView">The target view.</param> /// <returns>The number of new elements created during the copy operation.</returns> private static int DuplicateDetailingAcrossViews(View fromView, View toView) { // Collect view-specific elements in source view FilteredElementCollector collector = new FilteredElementCollector(fromView.Document, fromView.Id); // Skip elements which don't have a category. In testing, this was // the revision table and the extents element, which should not be copied as they will // be automatically created for the copied view. collector.WherePasses(new ElementCategoryFilter(ElementId.InvalidElementId, true)) .WherePasses(new ElementCategoryFilter(BuiltInCategory.OST_Viewers, true)); // Get collection of elements to copy for CopyElements() ICollection <ElementId> toCopy = collector.ToElementIds(); // Collect view-specific elements in source view FilteredElementCollector sectionsCollector = new FilteredElementCollector(fromView.Document, fromView.Id); // Skip elements which don't have a category. In testing, this was // the revision table and the extents element, which should not be copied as they will // be automatically created for the copied view. sectionsCollector.WherePasses(new ElementCategoryFilter(ElementId.InvalidElementId, true)) .WherePasses(new ElementCategoryFilter(BuiltInCategory.OST_Viewers)); // Get collection of elements to copy for CopyElements() ICollection <Element> sectionsToCopy = sectionsCollector.ToElements(); ICollection <ElementId> sectionsToCopyIds = sectionsCollector.ToElementIds(); // Return value int numberOfCopiedElements = 0; if (toCopy.Count > 0) { try { using (Transaction t2 = new Transaction(toView.Document, "Duplicate view detailing")) { t2.Start(); // Set handler to skip the duplicate types dialog CopyPasteOptions options = new CopyPasteOptions(); options.SetDuplicateTypeNamesHandler(new HideAndAcceptDuplicateTypeNamesHandler()); // Copy the elements using no transformation ICollection <ElementId> copiedElements = ElementTransformUtils.CopyElements(fromView, toCopy, toView, Transform.Identity, options); numberOfCopiedElements = copiedElements.Count; // Set failure handler to skip any duplicate types warnings that are posted. FailureHandlingOptions failureOptions = t2.GetFailureHandlingOptions(); failureOptions.SetFailuresPreprocessor(new HidePasteDuplicateTypesPreprocessor()); t2.Commit(failureOptions); } } catch { } } return(numberOfCopiedElements); }
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; } }
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 Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { Document doc = commandData.Application .ActiveUIDocument.Document; FilteredElementCollector collector = new FilteredElementCollector(doc); collector.OfClass(typeof(Level)); Level level = collector.FirstElement() as Level; Transaction t = new Transaction(doc); t.Start("Create unbounded room"); FailureHandlingOptions failOpt = t.GetFailureHandlingOptions(); failOpt.SetFailuresPreprocessor( new RoomWarningSwallower()); t.SetFailureHandlingOptions(failOpt); doc.Create.NewRoom(level, new UV(0, 0)); t.Commit(); return(Result.Succeeded); }
private void UpdateRFAinProject(Document doc) { //Load and update the family symbol instances present in the project //make changes to the documnet by modifying the family file //Open transaction using (Transaction updating_transaction = new Transaction(doc)) { //Start the transaction updating_transaction.Start("UPDATE THE PROJECT"); //FailureHandlingOptions will collect those warnings which occurs while importing the family file into the project and deletes those warning FailureHandlingOptions FH_options = updating_transaction.GetFailureHandlingOptions(); FH_options.SetFailuresPreprocessor(new Warning_Swallower()); updating_transaction.SetFailureHandlingOptions(FH_options); //Loads the new familysymbol FamilyLoadOptions FLO = new FamilyLoadOptions(); FamilySymbol new_FS = null; doc.LoadFamilySymbol(RFA_TEMP, "Chair", FLO, out new_FS); //project gets updated after loading the family file //Commit the transaction to save the changes updating_transaction.Commit(); } //save the project file in the same path after updating the project file //If the project file(.rvt) with same name already exists in the project path ,overwrite the already existing project file ModelPath Project_model_path = ModelPathUtils.ConvertUserVisiblePathToModelPath(RVT_OUTPUT); SaveAsOptions SAO = new SaveAsOptions(); SAO.OverwriteExistingFile = true; //Save the project file doc.SaveAs(Project_model_path, SAO); }
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); } }
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(); }
private static ViewDrafting DuplicateDraftingViews(PreviewMap previewMap) { ViewDrafting viewDrafting = null; try { Document fromDoc = previewMap.SourceModelInfo.Doc; Document toDoc = previewMap.RecipientModelInfo.Doc; ViewDrafting sourceView = previewMap.SourceViewProperties.ViewDraftingObj; ICollection <ElementId> referenceCalloutIds = sourceView.GetReferenceCallouts(); CopyPasteOptions options = new CopyPasteOptions(); options.SetDuplicateTypeNamesHandler(new HideAndAcceptDuplicateTypeNamesHandler()); ICollection <ElementId> copiedIds = null; using (Transaction transaction = new Transaction(toDoc, "Duplicate Draftingviews")) { transaction.Start(); try { List <ElementId> viewIds = new List <ElementId>(); viewIds.Add(sourceView.Id); //view-specific item copiedIds = ElementTransformUtils.CopyElements(fromDoc, viewIds, toDoc, Transform.Identity, options); FailureHandlingOptions failureOptions = transaction.GetFailureHandlingOptions(); failureOptions.SetFailuresPreprocessor(new HidePasteDuplicateTypesPreprocessor()); transaction.Commit(failureOptions); } catch (Exception ex) { string message = ex.Message; transaction.RollBack(); } } if (null != copiedIds) { ElementId viewId = copiedIds.First(); ViewDrafting copiedView = toDoc.GetElement(viewId) as ViewDrafting; if (null != copiedView) { int numOfCopied = DuplicateDetailingAcrossViews(sourceView, copiedView); } if (referenceCalloutIds.Count > 0) { bool placedCallout = DuplicateReferenceCallouts(sourceView, copiedView); } viewDrafting = copiedView; } } catch (Exception ex) { errorMessage.AppendLine(previewMap.SourceViewProperties.ViewName + ": errors in duplicating drafting views.\n" + ex.Message); //MessageBox.Show("Failed to duplicate drafintg views.\n" + ex.Message, "Duplicate DraftingViews", MessageBoxButton.OK, MessageBoxImage.Warning); } return(viewDrafting); }
public static void KhepriWarnings(Transaction t) { FailureHandlingOptions failOp = t.GetFailureHandlingOptions(); failOp.SetFailuresPreprocessor(WarningSwallower.forKhepri); t.SetFailureHandlingOptions(failOp); }
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."); }
private List <AnnotationElement> RetriveAnnotationElementsFromSelection(UIDocument UIDoc, Transaction tx) { ICollection <ElementId> elementIds = UIDoc.Selection.GetElementIds(); List <Element> elementList = new List <Element>(); List <AnnotationElement> annotationElementList = new List <AnnotationElement>(); tx.Start("Prepare tags"); using (IEnumerator <ElementId> enumerator = ((IEnumerable <ElementId>)elementIds).GetEnumerator()) { while (((IEnumerator)enumerator).MoveNext()) { ElementId current = enumerator.Current; Element element = UIDoc.get_Document().GetElement(current); if (((object)element).GetType() == typeof(IndependentTag)) { IndependentTag independentTag = element as IndependentTag; independentTag.set_LeaderEndCondition((LeaderEndCondition)1); if (independentTag.get_HasLeader()) { independentTag.set_LeaderEnd(independentTag.get_TagHeadPosition()); independentTag.set_LeaderElbow(independentTag.get_TagHeadPosition()); } elementList.Add(element); } else if (((object)element).GetType() == typeof(TextNote)) { (element as TextNote).RemoveLeaders(); elementList.Add(element); } else if (((object)element).GetType().IsSubclassOf(typeof(SpatialElementTag))) { SpatialElementTag spatialElementTag = element as SpatialElementTag; if (spatialElementTag.get_HasLeader()) { spatialElementTag.set_LeaderEnd(spatialElementTag.get_TagHeadPosition()); spatialElementTag.set_LeaderElbow(spatialElementTag.get_TagHeadPosition()); } elementList.Add(element); } else { elementList.Add(element); } } } FailureHandlingOptions failureHandlingOptions = tx.GetFailureHandlingOptions(); failureHandlingOptions.SetFailuresPreprocessor((IFailuresPreprocessor) new CommitPreprocessor()); tx.Commit(failureHandlingOptions); using (List <Element> .Enumerator enumerator = elementList.GetEnumerator()) { while (enumerator.MoveNext()) { Element current = enumerator.Current; annotationElementList.Add(new AnnotationElement(current)); } } return(annotationElementList); }
/// <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(); } } }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication application = commandData.get_Application(); Document document = application.get_ActiveUIDocument().get_Document(); Selection selection = application.get_ActiveUIDocument().get_Selection(); ICollection <ElementId> elementIds = selection.GetElementIds(); List <Element> list = new List <Element>(); foreach (ElementId item in elementIds) { Element element = document.GetElement(item); list.Add(element); } if (list.Count > 0) { GlobolVar.G_JoinWay = "Miter"; WF_StartEnd wF_StartEnd = new WF_StartEnd(); wF_StartEnd.ShowDialog(); if (GlobolVar.G_JoinStatus == -1) { return(0); } Transaction val = new Transaction(document); val.Start("Miter"); FailureHandlingOptions failureHandlingOptions = val.GetFailureHandlingOptions(); MyFailuresPreProcessor myFailuresPreProcessor = new MyFailuresPreProcessor(); failureHandlingOptions.SetFailuresPreprocessor(myFailuresPreProcessor); val.SetFailureHandlingOptions(failureHandlingOptions); foreach (Element item2 in list) { try { if (GlobolVar.G_JoinStatus == 0) { (item2.get_Location() as LocationCurve).set_JoinType(1, 1); (item2.get_Location() as LocationCurve).set_JoinType(0, 1); } else if (GlobolVar.G_JoinStatus == 1) { (item2.get_Location() as LocationCurve).set_JoinType(0, 1); } else if (GlobolVar.G_JoinStatus == 2) { (item2.get_Location() as LocationCurve).set_JoinType(1, 1); } } catch (Exception) { } } val.Commit(); } else { TaskDialog.Show("Result", "None Element Selected"); } return(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); }
private void InitializeOpenTransaction(string name) { m_Transaction.Start(Resources.IFCOpenReferenceFile); FailureHandlingOptions options = m_Transaction.GetFailureHandlingOptions(); //options.SetFailuresPreprocessor(Log); options.SetForcedModalHandling(true); options.SetClearAfterRollback(true); }
private static int DuplicateDetailingAcrossViews(View fromView, View toView) { int numberOfCopiedElements = 0; try { List <ElementId> elementIdsToExclude = new List <ElementId>(); ICollection <ElementId> referenceCalloutIds = fromView.GetReferenceCallouts(); elementIdsToExclude.AddRange(referenceCalloutIds); ICollection <ElementId> referenceElevationIds = fromView.GetReferenceElevations(); elementIdsToExclude.AddRange(referenceElevationIds); ICollection <ElementId> referenceSectionIds = fromView.GetReferenceSections(); elementIdsToExclude.AddRange(referenceSectionIds); FilteredElementCollector collector = new FilteredElementCollector(fromView.Document, fromView.Id); if (elementIdsToExclude.Count > 0) { collector.Excluding(elementIdsToExclude); } collector.WherePasses(new ElementCategoryFilter(ElementId.InvalidElementId, true)); ICollection <ElementId> toCopy = collector.ToElementIds(); CopyPasteOptions options = new CopyPasteOptions(); options.SetDuplicateTypeNamesHandler(new HideAndAcceptDuplicateTypeNamesHandler()); if (toCopy.Count > 0) { using (Transaction t2 = new Transaction(toView.Document, "Duplicate view detailing")) { t2.Start(); try { ICollection <ElementId> copiedElements = ElementTransformUtils.CopyElements(fromView, toCopy, toView, Transform.Identity, options); numberOfCopiedElements = copiedElements.Count; FailureHandlingOptions failureOptions = t2.GetFailureHandlingOptions(); failureOptions.SetFailuresPreprocessor(new HidePasteDuplicateTypesPreprocessor()); t2.Commit(failureOptions); } catch (Exception ex) { string message = ex.Message; t2.RollBack(); } } } } catch (Exception ex) { //MessageBox.Show("Failed to duplicate detialing across views.\n"+ex.Message, "Duplicate Detailing Across Views", MessageBoxButton.OK, MessageBoxImage.Warning); errorMessage.AppendLine(toView.Name + ": errors in duplicating detailing across views.\n" + ex.Message); } return(numberOfCopiedElements); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiApp = commandData.Application; Document doc = uiApp.ActiveUIDocument.Document; MessageDescriptionGatheringPreprocessor pp = new MessageDescriptionGatheringPreprocessor(); using (Transaction t = new Transaction(doc)) { FailureHandlingOptions ops = t.GetFailureHandlingOptions(); ops.SetFailuresPreprocessor(pp); t.SetFailureHandlingOptions(ops); t.Start("Marks"); // Generate a 'duplicate mark' warning message: IList <Element> specEqu = new FilteredElementCollector(doc) .OfCategory(BuiltInCategory.OST_SpecialityEquipment) .WhereElementIsNotElementType() .ToElements(); if (specEqu.Count >= 2) { for (int i = 0; i < 2; i++) { specEqu[i].get_Parameter( BuiltInParameter.ALL_MODEL_MARK).Set( "Duplicate Mark"); } } // Generate an 'duplicate wall' warning message: Element level = new FilteredElementCollector(doc) .OfClass(typeof(Level)) .FirstElement(); Line line = Line.CreateBound(XYZ.Zero, 10 * XYZ.BasisX); Wall wall1 = Wall.Create(doc, line, level.Id, false); Wall wall2 = Wall.Create(doc, line, level.Id, false); t.Commit(); } pp.ShowDialogue(); return(Result.Succeeded); }
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(); }
//---------------------------------------------------------- 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(); } } }
public void InitTransaction() { if (_trans == null || _trans.GetStatus() != TransactionStatus.Started) { _trans = new Autodesk.Revit.DB.Transaction(dynRevitSettings.Doc.Document, "Dynamo Script"); _trans.Start(); FailureHandlingOptions failOpt = _trans.GetFailureHandlingOptions(); failOpt.SetFailuresPreprocessor(new DynamoWarningPrinter()); _trans.SetFailureHandlingOptions(failOpt); } }
/// <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(); } } }
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); }
private void ProcesarFamiliasEnLaCarpeta(Document documentoActivo, string carpetaEnProceso, string carpetaDestino) { foreach (string pathArchivoFamilia in System.IO.Directory.GetFiles(carpetaEnProceso, "*.rfa")) { string pathArchivoImagen = System.IO.Path.Combine(carpetaDestino, System.IO.Path.GetFileName(System.IO.Path.ChangeExtension(pathArchivoFamilia, ".png"))); if (!(procesarSoloFamiliasSinImagen == true && System.IO.File.Exists(pathArchivoImagen)) || procesarTodasLasFamilias == true) { try { string nombreFamilia = System.IO.Path.GetFileNameWithoutExtension(pathArchivoFamilia); Family familia; using (Transaction trans = new Transaction(documentoActivo, "Load family for UCFamilyProcessor")) { trans.Start(); FailureHandlingOptions enCasoDeFalloOAviso = trans.GetFailureHandlingOptions(); enCasoDeFalloOAviso.SetFailuresPreprocessor(new ProcesadorDeWarnings()); trans.SetFailureHandlingOptions(enCasoDeFalloOAviso); documentoActivo.LoadFamily(pathArchivoFamilia, new OpcionesDeSobreescrituraDeFamiliasAnidadasYaExistentesEnElDocumento(), out familia); trans.Commit(); } ElementId idPrimerSimboloEnLaFamilia = familia.GetFamilySymbolIds().First(); FamilySymbol simbolo = (FamilySymbol)familia.Document.GetElement(idPrimerSimboloEnLaFamilia); System.Drawing.Bitmap thumbnail = simbolo.GetPreviewImage(new System.Drawing.Size(100, 100)); if (thumbnail != null) { thumbnail.Save(filename: pathArchivoImagen, format: System.Drawing.Imaging.ImageFormat.Png); } else { System.IO.File.Create(System.IO.Path.ChangeExtension(pathArchivoImagen, "dummy")); } } catch (Exception) { continue; } } } //Este bucle recursivo es una chapu para incorporar ANNOTATIONS y lo que se tercie... foreach (string subcarpeta in System.IO.Directory.GetDirectories(carpetaEnProceso)) { ProcesarFamiliasEnLaCarpeta(documentoActivo, subcarpeta, pathCarpetaDestino); } }
private void PostWarningAndResolveInFailurePreproccessor() { Transaction transaction = new Transaction(m_doc, "Warning_FailurePreproccessor"); FailureHandlingOptions options = transaction.GetFailureHandlingOptions(); FailurePreproccessor preproccessor = new FailurePreproccessor(); options.SetFailuresPreprocessor(preproccessor); transaction.SetFailureHandlingOptions(options); transaction.Start(); FailureMessage fm = new FailureMessage(m_idWarning); m_doc.PostFailure(fm); transaction.Commit(); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication application = commandData.get_Application(); Document document = application.get_ActiveUIDocument().get_Document(); Selection selection = application.get_ActiveUIDocument().get_Selection(); ICollection <ElementId> elementIds = selection.GetElementIds(); if (elementIds.Count != 0) { List <Element> list = Method.GeometryFilter(document, elementIds); int num = 0; if (list.Count > 1) { Combinations <Element> combinations = new Combinations <Element>(list, 2, GenerateOption.WithoutRepetition); Transaction val = new Transaction(document); val.Start("Merger Element"); FailureHandlingOptions failureHandlingOptions = val.GetFailureHandlingOptions(); MyFailuresPreProcessor myFailuresPreProcessor = new MyFailuresPreProcessor(); failureHandlingOptions.SetFailuresPreprocessor(myFailuresPreProcessor); val.SetFailureHandlingOptions(failureHandlingOptions); foreach (List <Element> item in combinations) { if (!JoinGeometryUtils.AreElementsJoined(document, item[0], item[1])) { try { JoinGeometryUtils.JoinGeometry(document, item[0], item[1]); num++; } catch { } } } MessageBox.Show(num.ToString() + " Pairs Elements Successfully Join.", "ElementMerger"); val.Commit(); } else if (list.Count == 1) { TaskDialog.Show("ElementMerger", "Only One Element Selected"); } } else { TaskDialog.Show("ElementMerger", "None Element Selected"); } return(0); }