public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app   = commandData.Application;
            UIDocument    uidoc = app.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            string msg = string.Empty;

            //Selection sel = uidoc.Selection; // 2014
            //foreach( Element e in sel.Elements ) // 2014

            List <Element> walls = new List <Element>();

            if (Util.GetSelectedElementsOrAll(walls, uidoc, typeof(Wall)))
            {
                foreach (Wall wall in walls)
                {
                    msg += ProcessWall(wall);
                }
            }

            if (0 == msg.Length)
            {
                msg = "Please select some walls.";
            }

            Util.InfoMsg(msg);

            return(Result.Succeeded);
        }
예제 #2
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app   = commandData.Application;
            UIDocument    uidoc = app.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            Selection sel = uidoc.Selection;
            string    msg = string.Empty;

            foreach (Element e in sel.Elements)
            {
                Wall wall = e as Wall;
                if (null != wall)
                {
                    msg += ProcessWall(wall);
                }
            }
            if (0 == msg.Length)
            {
                msg = "Please select some walls.";
            }
            Util.InfoMsg(msg);
            return(Result.Succeeded);
        }
예제 #3
0
        public Result Execute(
            ExternalCommandData revit,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = revit.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            string path = doc.PathName;

            BasicFileInfo info = BasicFileInfo.Extract(
                path);

            DocumentVersion v = info.GetDocumentVersion();

            int n = v.NumberOfSaves;

            Util.InfoMsg(string.Format(
                             "Document '{0}' has GUID {1} and {2} save{3}.",
                             path, v.VersionGUID, n,
                             Util.PluralSuffix(n)));

            return(Result.Succeeded);
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app   = commandData.Application;
            UIDocument    uidoc = app.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            // retrieve selected walls, or all walls,
            // if nothing is selected:

            List <Element> walls = new List <Element>();

            if (!Util.GetSelectedElementsOrAll(
                    walls, uidoc, typeof(Wall)))
            {
                Selection sel = uidoc.Selection;
                message = (0 < sel.GetElementIds().Count)
          ? "Please select some wall elements."
          : "No wall elements found.";
                return(Result.Failed);
            }


            // mapping of compound wall layers to total cumulated volume;
            // the key is "<wall type name> : <wall layer function>",
            // the value is its cumulated volume across all selected walls:

            MapLayerToVolume totalVolumes
                = new MapLayerToVolume();

            foreach (Wall wall in walls)
            {
                GetWallLayerVolumes(wall, ref totalVolumes);
            }

            string msg
                = "Compound wall layer volumes formatted as '"
                  + "wall type : layer function :"
                  + " volume in cubic meters':\n";

            List <string> keys = new List <string>(
                totalVolumes.Keys);

            keys.Sort();

            foreach (string key in keys)
            {
                msg += "\n" + key + " : "
                       + Util.RealString(
                    Util.CubicFootToCubicMeter(
                        totalVolumes[key]));
            }

            Util.InfoMsg(msg);

            return(Result.Cancelled);
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            Debug.Assert(false,
                         "setting the disallow join property was not possible prior to Revit 2012. "
                         + "In Revit 2012, you can use the WallUtils.DisallowWallJoinAtEnd method.");

            UIApplication app   = commandData.Application;
            UIDocument    uidoc = app.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            string s = "a wall, to retrieve its join types";

            Wall wall = Util.SelectSingleElementOfType(
                uidoc, typeof(Wall), s, false) as Wall;

            if (null == wall)
            {
                message = "Please select a wall.";
            }
            else
            {
                JoinType []     a1 = ( JoinType [] )Enum.GetValues(typeof(JoinType));
                List <JoinType> a  = new List <JoinType>((JoinType[])Enum.GetValues(typeof(JoinType)));
                int             n  = a.Count;

                LocationCurve lc = wall.Location as LocationCurve;

                s = Util.ElementDescription(wall) + ":\n";

                /*for( int i = 0; i < 2; ++i )
                 * {
                 * JoinType jt = lc.get_JoinType( i );
                 * int j = a.IndexOf( jt ) + 1;
                 * JoinType jtnew = a[ j < n ? j : 0];
                 * lc.set_JoinType( j, jtnew );
                 * s += string.Format(
                 *  "\nChanged join type at {0} from {1} to {2}.",
                 *  ( 0 == i ? "start" : "end" ), jt, jtnew );
                 * }
                 * // wall.Location = lc; // Property or indexer 'Autodesk.Revit.Element.Location' cannot be assigned to -- it is read only
                 */

                for (int i = 0; i < 2; ++i)
                {
                    JoinType jt    = ((LocationCurve)wall.Location).get_JoinType(i);
                    int      j     = a.IndexOf(jt) + 1;
                    JoinType jtnew = a[j < n ? j : 0];
                    ((LocationCurve)wall.Location).set_JoinType(j, jtnew);
                    s += string.Format(
                        "\nChanged join type at {0} from {1} to {2}.",
                        (0 == i ? "start" : "end"), jt, jtnew);
                }
            }
            Util.InfoMsg(s);
            return(Result.Succeeded);
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app = commandData.Application;
            Document      doc = app.ActiveUIDocument.Document;

            FilteredElementCollector levels = Util.GetElementsOfType(
                doc, typeof(Level), BuiltInCategory.OST_Levels);

            Level level = levels.FirstElement() as Level;

            PlanTopology pt = doc.get_PlanTopology(level);

            // Collect some data on each room in the circuit

            string output = "Rooms on "
                            + level.Name + ":"
                            + "\n  Name and Number : Area";

            //foreach( Room r in pt.Rooms ) // 2012

            foreach (ElementId id in pt.GetRoomIds()) // 2013
            {
                Room r = doc.GetElement(id) as Room;

                output += "\n  " + r.Name + " : "
                          + Util.RealString(r.Area) + " sqf";
            }
            Util.InfoMsg(output);

            output = "Circuits without rooms:"
                     + "\n  Number of Sides : Area";

            using (Transaction t = new Transaction(doc))
            {
                t.Start("Create New Rooms");

                foreach (PlanCircuit pc in pt.Circuits)
                {
                    if (!pc.IsRoomLocated) // this circuit has no room, create one
                    {
                        output += "\n  " + pc.SideNum + " : "
                                  + Util.RealString(pc.Area) + " sqf";

                        // Pass null to create a new room;
                        // to place an existing unplaced room,
                        // pass it in instead of null:

                        Room r = doc.Create.NewRoom(null, pc);
                    }
                }
                t.Commit();
            }
            Util.InfoMsg(output);

            return(Result.Succeeded);
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            Application app = commandData.Application.Application;

            string reg_path_product
                = RegPathForFlavour(
                      app.Product, app.VersionNumber);

            string product_code
                = GetRevitProductCode(reg_path_product);

            string install_location
                = GetRevitInstallLocation(product_code);

            string msg = FormatData(
                "Running application",
                app.VersionName,
                product_code,
                install_location);

            foreach (ProductType p in
                     Enum.GetValues(typeof(ProductType)))
            {
                try
                {
                    reg_path_product = RegPathForFlavour(
                        p, app.VersionNumber);

                    product_code = GetRevitProductCode(
                        reg_path_product);

                    install_location = GetRevitInstallLocation(
                        product_code);

                    msg += FormatData(
                        "\n\nInstalled product",
                        p.ToString(),
                        product_code,
                        install_location);
                }
                catch (Exception)
                {
                }
            }

            Util.InfoMsg(msg);

            return(Result.Failed);
        }
예제 #8
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app   = commandData.Application;
            UIDocument    uidoc = app.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            string s = "a wall, to retrieve its bottom face";

            Wall wall = Util.SelectSingleElementOfType(
                uidoc, typeof(Wall), s, false) as Wall;

            if (null == wall)
            {
                message = "Please select a wall.";
            }
            else
            {
                Options         opt = app.Application.Create.NewGeometryOptions();
                GeometryElement e   = wall.get_Geometry(opt);

                //foreach( GeometryObject obj in e.Objects ) // 2012

                foreach (GeometryObject obj in e) // 2013
                {
                    Solid solid = obj as Solid;
                    if (null != solid)
                    {
                        foreach (Face face in solid.Faces)
                        {
                            PlanarFace pf = face as PlanarFace;
                            if (null != pf)
                            {
                                if (Util.IsVertical(pf.Normal, _tolerance) &&
                                    pf.Normal.Z < 0)
                                {
                                    Util.InfoMsg(string.Format(
                                                     "The bottom face area is {0},"
                                                     + " and its origin is at {1}.",
                                                     Util.RealString(pf.Area),
                                                     Util.PointString(pf.Origin)));
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            return(Result.Failed);
        }
        void Report(FilteredElementCollector a)
        {
            int    n = 0;
            string s = _msg;

            foreach (Element e in a)
            {
                ++n;
                s += string.Format("\r\n  {0}",
                                   Util.ElementDescription(e));
            }
            s = string.Format(s, n, Util.PluralSuffix(n));

            Util.InfoMsg(s);
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Document      doc   = uidoc.Document;
            Result        rslt  = Result.Failed;

            string name = "TrackChanges_project_identifier";
            Guid   named_guid;

            bool rc = JtNamedGuidStorage.Get(doc,
                                             name, out named_guid, false);

            if (rc)
            {
                Util.InfoMsg(string.Format(
                                 "This document already has a project "
                                 + "identifier: {0} = {1}",
                                 name, named_guid.ToString()));

                rslt = Result.Succeeded;
            }
            else
            {
                rc = JtNamedGuidStorage.Get(doc,
                                            name, out named_guid, true);

                if (rc)
                {
                    Util.InfoMsg(string.Format(
                                     "Created a new project identifier "
                                     + "for this document: {0} = {1}",
                                     name, named_guid.ToString()));

                    rslt = Result.Succeeded;
                }
                else
                {
                    Util.ErrorMsg("Something went wrong");
                }
            }
            return(rslt);
        }
예제 #11
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            Element e = null;

            while (true)
            {
                try
                {
                    e = Util.SelectSingleElementOfType(
                        uidoc, typeof(Element), "an element", true);
                }
                catch (Autodesk.Revit.Exceptions.OperationCanceledException)
                {
                    message = "No element selected";
                    break;
                }
                if (null == e)
                {
                    break;
                }

                Util.InfoMsg(string.Format(
                                 //"{0} is {1} {2} ({3})",
                                 "{0} is {1} ({2})",
                                 Util.ElementDescription(e),
                                 //MepElementShapeVersion3.GetElementShape( e ),
                                 MepElementShapeVersion2.GetElementShape(e),
                                 MepElementShapeV1.GetElementShape(e)));
            }
            return(Result.Succeeded);
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            using (Transaction tx = new Transaction(doc))
            {
                tx.Start("Mirror and List Added");
                //Line line = app.Create.NewLine(
                //  XYZ.Zero, XYZ.BasisX, true ); // 2011

                //ElementSet els = uidoc.Selection.Elements; // 2011

                //Plane plane = new Plane( XYZ.BasisY, XYZ.Zero ); // added in 2012, used until 2016

                Plane plane = Plane.CreateByNormalAndOrigin(XYZ.BasisY, XYZ.Zero); // 2017

                ICollection <ElementId> elementIds
                    = uidoc.Selection.GetElementIds(); // 2012

                using (SubTransaction t = new SubTransaction(doc))
                {
                    // determine newly added elements relying on the
                    // element sequence as returned by the filtered collector.
                    // this approach works in both Revit 2010 and 2011:

                    t.Start();

                    int n = GetElementCount(doc);

                    //doc.Mirror( els, line ); // 2011

                    //ElementTransformUtils.MirrorElements(
                    //  doc, elementIds, plane ); // 2012-2015

                    ElementTransformUtils.MirrorElements(
                        doc, elementIds, plane, true); // 2016

                    List <Element> a = GetElementsAfter(n, doc);

                    t.RollBack();
                }

                using (SubTransaction t = new SubTransaction(doc))
                {
                    // here is an idea for a new approach in 2011:
                    // determine newly added elements relying on
                    // monotonously increasing element id values:

                    t.Start();

                    FilteredElementCollector a = GetElements(doc);
                    int       i     = a.Max <Element>(e => e.Id.IntegerValue);
                    ElementId maxId = new ElementId(i);

                    // doc.Mirror( els, line ); // 2011

                    //ElementTransformUtils.MirrorElements(
                    //  doc, elementIds, plane ); // 2012-2015

                    ElementTransformUtils.MirrorElements(
                        doc, elementIds, plane, true); // 2016

                    // get all elements in document with an
                    // element id greater than maxId:

                    a = GetElementsAfter(doc, maxId);

                    Report(a);

                    t.RollBack();
                }

                using (SubTransaction t = new SubTransaction(doc))
                {
                    // similar to the above approach relying on
                    // monotonously increasing element id values,
                    // but apply a quick filter first:

                    t.Start();

                    FilteredElementCollector a = GetElements(doc);
                    int       i     = a.Max <Element>(e => e.Id.IntegerValue);
                    ElementId maxId = new ElementId(i);

                    //doc.Mirror( els, line ); // 2011

                    //ElementTransformUtils.MirrorElements(
                    //  doc, elementIds, plane ); // 2012-2015

                    ElementTransformUtils.MirrorElements(
                        doc, elementIds, plane, true); // 2016

                    // only look at non-ElementType elements
                    // instead of all document elements:

                    a = GetElements(doc);
                    a = GetElementsAfter(a, maxId);

                    Report(a);

                    t.RollBack();
                }

                using (SubTransaction t = new SubTransaction(doc))
                {
                    // use a local and temporary DocumentChanged event
                    // handler to directly obtain a list of all newly
                    // created elements.
                    // unfortunately, this canot be tested in this isolated form,
                    // since the DocumentChanged event is only triggered when the
                    // real outermost Revit transaction is committed, i.e. our
                    // local sub-transaction makes no difference. since we abort
                    // the sub-transaction before the command terminates and no
                    // elements are really added to the database, our event
                    // handler is never called:

                    t.Start();

                    app.DocumentChanged
                        += new EventHandler <DocumentChangedEventArgs>(
                               app_DocumentChanged);

                    //doc.Mirror( els, line ); // 2011

                    //ElementTransformUtils.MirrorElements(
                    //  doc, elementIds, plane ); // 2012-2015

                    ElementTransformUtils.MirrorElements(
                        doc, elementIds, plane, true); // 2016

                    app.DocumentChanged
                        -= new EventHandler <DocumentChangedEventArgs>(
                               app_DocumentChanged);

                    Debug.Assert(null == _addedElementIds,
                                 "never expected the event handler to be called");

                    if (null != _addedElementIds)
                    {
                        int n = _addedElementIds.Count;

                        string s = string.Format(_msg, n,
                                                 Util.PluralSuffix(n));

                        foreach (ElementId id in _addedElementIds)
                        {
                            Element e = doc.GetElement(id);

                            s += string.Format("\r\n  {0}",
                                               Util.ElementDescription(e));
                        }
                        Util.InfoMsg(s);
                    }

                    t.RollBack();
                }
                tx.RollBack();
            }
            return(Result.Succeeded);
        }
예제 #13
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app   = commandData.Application;
            UIDocument    uidoc = app.ActiveUIDocument;
            Document      doc   = app.ActiveUIDocument.Document;

            List <Element> walls = new List <Element>();

            if (!Util.GetSelectedElementsOrAll(
                    walls, uidoc, typeof(Wall)))
            {
                Selection sel = uidoc.Selection;
                message = (0 < sel.GetElementIds().Count)
          ? "Please select some wall elements."
          : "No wall elements found.";
                return(Result.Failed);
            }

            int    i, n;
            string desc, s = null;
            //List<Element> neighbours;
            ElementArray neighbours;

            foreach (Wall wall in walls)
            {
                desc = Util.ElementDescription(wall);

                LocationCurve c
                    = wall.Location as LocationCurve;

                if (null == c)
                {
                    s = desc + ": No wall curve found.";
                }
                else
                {
                    s = string.Empty;

                    for (i = 0; i < 2; ++i)
                    {
                        neighbours = c.get_ElementsAtJoin(i);
                        n          = neighbours.Size;

                        s += string.Format(
                            "\n\n{0} {1} point has {2} neighbour{3}{4}",
                            desc,
                            (0 == i ? "start" : "end"),
                            n,
                            Util.PluralSuffix(n),
                            Util.DotOrColon(n));

                        foreach (Wall nb in neighbours)
                        {
                            s += "\n  " +
                                 Util.ElementDescription(nb);
                        }
                    }
                }
                Util.InfoMsg(s);
            }
            return(Result.Failed);
        }
예제 #14
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;
            Selection     sel   = uidoc.Selection;

            Reference r = sel.PickObject(ObjectType.Element,
                                         "Please pick an element");

            // 'Autodesk.Revit.DB.Reference.Element' is
            // obsolete: Property will be removed. Use
            // Document.GetElement(Reference) instead.
            //Element e = r.Element; // 2011

            Element e = doc.GetElement(r); // 2012

            Transaction tx = new Transaction(doc);

            tx.Start(_caption);

            ICollection <ElementId> ids = doc.Delete(e.Id);

            tx.RollBack();

            bool showOnlySketchElements = true;

            /*
             * StringBuilder s = new StringBuilder(
             * _caption
             + " for host element "
             + Util.ElementDescription( e )
             + ": " );
             +
             + foreach( ElementId id in ids )
             + {
             + Element e = doc.GetElement( id );
             +
             + if( !showOnlySketchElements
             || e is Sketch
             || e is SketchPlane )
             ||{
             || s.Append( Util.ElementDescription( e ) + ", " );
             ||}
             ||}
             */

            List <Element> a = new List <Element>(
                ids.Select(id => doc.GetElement(id)));

            string s = _caption
                       + " for host element "
                       + Util.ElementDescription(e)
                       + ": ";

            s += string.Join(", ",
                             a.Where(e2 => !showOnlySketchElements ||
                                     e2 is Sketch ||
                                     e2 is SketchPlane)
                             .Select(e2 => Util.ElementDescription(e2))
                             .ToArray());

            Util.InfoMsg(s);

            return(Result.Succeeded);
        }
예제 #15
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app   = commandData.Application;
            UIDocument    uidoc = app.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            #region Determine true north rotation

            Element projectInfoElement
                = new FilteredElementCollector(doc)
                  .OfCategory(BuiltInCategory.OST_ProjectBasePoint)
                  .FirstElement();

            BuiltInParameter bipAtn
                = BuiltInParameter.BASEPOINT_ANGLETON_PARAM;

            Parameter patn = projectInfoElement.get_Parameter(
                bipAtn);

            double atn = patn.AsDouble();

            Debug.Print(
                "Angle to north from project info: {0}",
                Util.AngleString(atn));

            #endregion // Determine true north rotation

            //ElementSet els = uidoc.Selection.Elements; // 2014

            ICollection <ElementId> ids = uidoc.Selection.GetElementIds(); // 2015

            if (1 != ids.Count)
            {
                message = "Please select a single element.";
            }
            else
            {
                //ElementSetIterator it = els.ForwardIterator();
                //it.MoveNext();
                //Element e = it.Current as Element; // 2014

                Element e = doc.GetElement(ids.First()); // 2015

                XYZ p;
                if (!Util.GetElementLocation(out p, e))
                {
                    message
                        = "Selected element has no location defined.";

                    Debug.Print(message);
                }
                else
                {
                    string msg
                        = "Selected element location: "
                          + Util.PointString(p);

                    XYZ    pnp;
                    double x, y, pna;

                    foreach (ProjectLocation location
                             in doc.ProjectLocations)
                    {
                        //ProjectPosition projectPosition
                        //  = location.get_ProjectPosition( XYZ.Zero ); // 2017

                        ProjectPosition projectPosition
                            = location.GetProjectPosition(XYZ.Zero); // 2018

                        x   = projectPosition.EastWest;
                        y   = projectPosition.NorthSouth;
                        pnp = new XYZ(x, y, 0.0);
                        pna = projectPosition.Angle;

                        msg +=
                            "\nAngle between project north and true north: "
                            + Util.AngleString(pna);

                        // Transform tr = Transform.get_Rotation( XYZ.Zero, XYZ.BasisZ, pna ); // 2013
                        Transform tr = Transform.CreateRotation(XYZ.BasisZ, pna); // 2014

                        //Transform tt = Transform.get_Translation( pnp ); // 2013
                        Transform tt = Transform.CreateTranslation(pnp); // 2014

                        Transform t = tt.Multiply(tr);

                        msg +=
                            "\nUnrotated element location: "
                            + Util.PointString(tr.OfPoint(p)) + " "
                            + Util.PointString(tt.OfPoint(p)) + " "
                            + Util.PointString(t.OfPoint(p));

                        Util.InfoMsg(msg);
                    }
                }
            }
            return(Result.Failed);
        }
        void MiroReloadLinks(IList <RevitLinkType> fecLinkTypes)
        {
            // Loop all RVT Links

            foreach (RevitLinkType typeLink in fecLinkTypes)
            {
                // ...

                // Skip1 - not IsFromRevitServer

                if (!typeLink.IsFromRevitServer())
                {
                    //…
                    continue;
                }

                // Skip2 - not ExternalFileReference
                // 99% it would already skip above as
                // RevitServer MUST be ExternalFileReference,
                // but leave just in case...

                ExternalFileReference er = typeLink.GetExternalFileReference();

                if (er == null)
                {
                    // ...

                    continue;
                }

                // If here, we can cache ModelPath related
                // info and show to user regardless if we skip
                // on next checks or not....

                ModelPath mp = er.GetPath();

                string userVisiblePath = ModelPathUtils
                                         .ConvertModelPathToUserVisiblePath(mp);

                // Skip3 - if ModelPath is NOT Server Path
                // 99% redundant as we already checked raw
                // RevitLinkType for this, but keep
                // just in case...

                if (!mp.ServerPath)
                {
                    // ...

                    continue;
                }

                // Skip4 - if NOT "NOT Found" problematic one
                // there is nothing to fix

                if (er.GetLinkedFileStatus()
                    != LinkedFileStatus.NotFound)
                {
                    // ...

                    continue;
                }

                // Skip5 - if Nested Link (can’t (re)load these!)

                if (typeLink.IsNestedLink)
                {
                    // ...

                    continue;
                }

                // If here, we MUST offer user to "Reload from..."

                // ...

                RevitLinkLoadResult res = null;

                try
                {
                    // This fails for problematic Server files
                    // since it also fails on "Reload" button in
                    // UI (due to the GUID issue in the answer)

                    //res = typeLink.Reload();

                    // This fails same as above :-(!

                    //res = typeLink.Load();

                    // This WORKS!
                    // Basically, this is the equivalent of UI
                    // "Reload from..." + browsing to the *same*
                    // Saved path showing in the manage Links
                    // dialogue.
                    // ToDo: Check if we need to do anything
                    // special with WorksetConfiguration?
                    // In tests, it works fine with the
                    // default c-tor.

                    ModelPath mpForReload = ModelPathUtils
                                            .ConvertUserVisiblePathToModelPath(
                        userVisiblePath);

                    res = typeLink.LoadFrom(mpForReload,
                                            new WorksetConfiguration());

                    Util.InfoMsg(string.Format(
                                     "Result = {0}", res.LoadResult));
                }
                catch (Exception ex)
                {
                    Debug.Print(ex.Message);
                }
            } // foreach typeLink
        }
예제 #17
0
        /// <summary>
        /// Sample file is at
        /// C:\a\j\adn\case\bsd\1242980\attach\mullion.rvt
        /// </summary>
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app   = commandData.Application;
            UIDocument    uidoc = app.ActiveUIDocument;
            Document      doc   = app.ActiveUIDocument.Document;
            Selection     sel   = uidoc.Selection;

            Options options = app.Application.Create.NewGeometryOptions();
            string  s, msg = string.Empty;
            int     n;

            foreach (ElementId id in sel.GetElementIds())
            {
                Mullion mullion = doc.GetElement(id)
                                  as Mullion;

                if (null != mullion)
                {
                    //Location location = mullion.AsFamilyInstance.Location; // seems to be uninitialised // 2011

                    Location location = mullion.Location; // 2012

                    LocationPoint lp
                        = mullion.Location
                          as LocationPoint;

                    Debug.Assert(null != lp,
                                 "expected a valid mullion location point");

                    Debug.Assert(null != mullion.LocationCurve,                                 // 2012
                                 "in Revit 2012, the mullion also has a valid location curve"); // 2012

                    GeometryElement geoElem
                        = mullion.get_Geometry(options);

                    //GeometryObjectArray objects = geoElem.Objects; // 2012
                    //n = objects.Size; // 2012

                    n = geoElem.Count <GeometryObject>(); // 2013

                    s = string.Format(
                        "Mullion <{0} {1}> at {2} rotation"
                        + " {3} has {4} geo object{5}:",
                        mullion.Name, mullion.Id.IntegerValue,
                        Util.PointString(lp.Point),
                        Util.RealString(lp.Rotation),
                        n, Util.PluralSuffix(n));

                    if (0 < msg.Length)
                    {
                        msg += "\n\n";
                    }
                    msg += s;

                    //foreach( GeometryObject obj in objects ) // 2012

                    foreach (GeometryObject obj in geoElem) // 2013
                    {
                        GeometryInstance inst = obj as GeometryInstance;
                        Transform        t    = inst.Transform;

                        s    = "  Transform " + Util.TransformString(t);
                        msg += "\n" + s;

                        GeometryElement elem2 = inst.SymbolGeometry;

                        //foreach( GeometryObject obj2 in elem2.Objects ) // 2012

                        foreach (GeometryObject obj2 in elem2) // 2013
                        {
                            Solid solid = obj2 as Solid;
                            if (null != solid)
                            {
                                FaceArray faces = solid.Faces;
                                n = faces.Size;

                                s = string.Format(
                                    "  {0} face{1}, face point > WCS point:",
                                    n, Util.PluralSuffix(n));

                                msg += "\n" + s;

                                foreach (Face face in solid.Faces)
                                {
                                    s = string.Empty;
                                    Mesh mesh = face.Triangulate();
                                    foreach (XYZ p in mesh.Vertices)
                                    {
                                        s += (0 == s.Length) ? "    " : ", ";
                                        s += string.Format("{0} > {1}",
                                                           Util.PointString(p),
                                                           Util.PointString(t.OfPoint(p)));
                                    }
                                    msg += "\n" + s;
                                }
                            }
                        }
                    }
                }
            }
            if (0 == msg.Length)
            {
                msg = "Please select some mullions.";
            }
            Util.InfoMsg(msg);
            return(Result.Failed);
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            // Construct a parameter filter to get only
            // unnamed reference planes, i.e. reference
            // planes whose name equals the empty string:

            BuiltInParameter bip
                = BuiltInParameter.DATUM_TEXT;

            ParameterValueProvider provider
                = new ParameterValueProvider(
                      new ElementId(bip));

            FilterStringRuleEvaluator evaluator
                = new FilterStringEquals();

            FilterStringRule rule = new FilterStringRule(
                provider, evaluator, "", false);

            ElementParameterFilter filter
                = new ElementParameterFilter(rule);

            FilteredElementCollector col
                = new FilteredElementCollector(doc)
                  .OfClass(typeof(ReferencePlane))
                  .WherePasses(filter);

            int n        = 0;
            int nDeleted = 0;

            // No need to cast ... this is pretty nifty,
            // I find ... grab the elements as ReferencePlane
            // instances, since the filter guarantees that
            // only ReferencePlane instances are selected.
            // In Revit 2014, this attempt to delete the
            // reference planes while iterating over the
            // filtered element collector throws an exception:
            // Autodesk.Revit.Exceptions.InvalidOperationException:
            // HResult=-2146233088
            // Message=The iterator cannot proceed due to
            // changes made to the Element table in Revit's
            // database (typically, This can be the result
            // of an Element deletion).
            //
            //foreach( ReferencePlane rp in col )
            //{
            //  ++n;
            //  nDeleted += DeleteIfNotHosting( rp ) ? 1 : 0;
            //}

            ICollection <ElementId> ids = col.ToElementIds();

            n = ids.Count();

            if (0 < n)
            {
                using (Transaction tx = new Transaction(doc))
                {
                    tx.Start(string.Format(
                                 "Delete {0} ReferencePlane{1}",
                                 n, Util.PluralSuffix(n)));

                    // This also causes the exception "One or more of
                    // the elementIds cannot be deleted. Parameter
                    // name: elementIds
                    //
                    //ICollection<ElementId> ids2 = doc.Delete(
                    //  ids );
                    //nDeleted = ids2.Count();

                    List <ElementId> ids2 = new List <ElementId>(
                        ids);

                    foreach (ElementId id in ids2)
                    {
                        try
                        {
                            ICollection <ElementId> ids3 = doc.Delete(
                                id);

                            nDeleted += ids3.Count;
                        }
                        catch (Autodesk.Revit.Exceptions.ArgumentException)
                        {
                        }
                    }

                    tx.Commit();
                }
            }

            Util.InfoMsg(string.Format(
                             "{0} unnamed reference plane{1} examined, "
                             + "{2} element{3} in total were deleted.",
                             n, Util.PluralSuffix(n),
                             nDeleted, Util.PluralSuffix(nDeleted)));

            return(Result.Succeeded);
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication           app   = commandData.Application;
            UIDocument              uidoc = app.ActiveUIDocument;
            Document                doc   = uidoc.Document;
            Selection               sel   = uidoc.Selection;
            ICollection <ElementId> ids   = sel.GetElementIds();
            Options  opt = app.Application.Create.NewGeometryOptions();
            Material mat;
            string   msg = string.Empty;
            int      i, n;

            foreach (ElementId id in ids)
            {
                Element e = doc.GetElement(id);

                // For 0310_ensure_material.htm:

                if (e is FamilyInstance)
                {
                    mat = GetMaterial(doc, e as FamilyInstance);

                    Util.InfoMsg(
                        "Family instance element material: "
                        + (null == mat ? "<null>" : mat.Name));
                }

                GeometryElement geo = e.get_Geometry(opt);

                // If you are not interested in duplicate
                // materials, you can define a class that
                // overloads the Add method to only insert
                // a new entry if its value is not already
                // present in the list, instead of using
                // the standard List<> class:

                List <string> materials = GetMaterials(doc, geo);

                msg += "\n" + Util.ElementDescription(e);

                n = materials.Count;

                if (0 == n)
                {
                    msg += " has no materials.";
                }
                else
                {
                    i = 0;

                    msg += string.Format(
                        " has {0} material{1}:",
                        n, Util.PluralSuffix(n));

                    foreach (string s in materials)
                    {
                        msg += string.Format(
                            "\n  {0} {1}", i++, s);
                    }
                }
            }

            if (0 == msg.Length)
            {
                msg = "Please select some elements.";
            }

            Util.InfoMsg(msg);

            return(Result.Succeeded);
        }
        /// <summary>
        /// External command mainline. Run in the
        /// sample model TestCrossFitting.rvt, e.g.
        /// </summary>
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app   = commandData.Application;
            UIDocument    uidoc = app.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            IList <Element> pipes = null;
            int             n     = 0;

            // Ensure that 2, 3 or 4 pipes are selected.

            while (n < 2 || 4 < n)
            {
                if (0 != n)
                {
                    Util.InfoMsg(string.Format(
                                     "You picked {0} pipe{1}. "
                                     + "Please only pick 2, 3 or 4.",
                                     n, Util.PluralSuffix(n)));
                }

                try
                {
                    Selection sel = app.ActiveUIDocument.Selection;

                    pipes = sel.PickElementsByRectangle(
                        new JtElementsOfClassSelectionFilter <Pipe>(),
                        "Please pick some pipes.");
                }
                catch (Autodesk.Revit.Exceptions
                       .InvalidOperationException)
                {
                    return(Result.Cancelled);
                }
                n = pipes.Count;
            }

            XYZ pt = null;

            using (Transaction tx = new Transaction(doc))
            {
                tx.Start("CreateConnector");
                if (pipes.Count() <= 1)
                {
                    return(Result.Cancelled);
                }

                Pipe pipe1 = pipes[0] as Pipe;
                Pipe pipe2 = pipes[1] as Pipe;

                Curve curve1 = pipe1.GetCurve();
                Curve curve2 = pipe2.GetCurve();

                XYZ p1 = curve1.GetEndPoint(0);
                XYZ q1 = curve1.GetEndPoint(1);

                XYZ p2 = curve2.GetEndPoint(0);
                XYZ q2 = curve2.GetEndPoint(1);

                if (q1.DistanceTo(p2) < 0.1)
                {
                    pt = (q1 + p2) * 0.5;
                }
                else if (q1.DistanceTo(q2) < 0.1)
                {
                    pt = (q1 + q2) * 0.5;
                }
                else if (p1.DistanceTo(p2) < 0.1)
                {
                    pt = (p1 + p2) * 0.5;
                }
                else if (p1.DistanceTo(q2) < 0.1)
                {
                    pt = (p1 + q2) * 0.5;
                }
                else
                {
                    message = "Please select two pipes "
                              + "with near-by endpoints.";

                    return(Result.Failed);
                }

                Connector c1 = Util.GetConnectorClosestTo(
                    pipe1, pt);

                Connector c2 = Util.GetConnectorClosestTo(
                    pipe2, pt);

                if (pipes.Count() == 2)
                {
                    if (IsPipeParallel(pipe1, pipe2) == true)
                    {
                        doc.Create.NewUnionFitting(c1, c2);
                    }
                    else
                    {
                        doc.Create.NewElbowFitting(c1, c2);
                    }
                }
                else if (pipes.Count() == 3)
                {
                    Pipe pipe3 = pipes[2] as Pipe;

                    XYZ v1 = GetPipeDirection(pipe1);
                    XYZ v2 = GetPipeDirection(pipe2);
                    XYZ v3 = GetPipeDirection(pipe3);

                    Connector c3 = Util.GetConnectorClosestTo(
                        pipe3, pt);

                    if (Math.Sin(v1.AngleTo(v2)) < 0.01) //平行
                    {
                        doc.Create.NewTeeFitting(c1, c2, c3);
                    }
                    else //v1, 和v2 垂直.
                    {
                        if (Math.Sin(v3.AngleTo(v1)) < 0.01) //v3, V1 平行
                        {
                            doc.Create.NewTeeFitting(c3, c1, c2);
                        }
                        else //v3, v2 平行
                        {
                            doc.Create.NewTeeFitting(c3, c2, c1);
                        }
                    }
                }
                else if (pipes.Count() == 4)
                {
                    Pipe pipe3 = pipes[2] as Pipe;
                    Pipe pipe4 = pipes[3] as Pipe;

                    Connector c3 = Util.GetConnectorClosestTo(
                        pipe3, pt);

                    Connector c4 = Util.GetConnectorClosestTo(
                        pipe4, pt);

                    //以从哪c1为入口.

                    // The required connection order for a cross
                    // fitting is main – main – side - side.

                    if (IsPipeParallel(pipe1, pipe2))
                    {
                        doc.Create.NewCrossFitting(
                            c1, c2, c3, c4);
                    }
                    else if (IsPipeParallel(pipe1, pipe3))
                    {
                        try
                        {
                            doc.Create.NewCrossFitting(
                                c1, c3, c2, c4);
                        }
                        catch (Exception ex)
                        {
                            TaskDialog.Show(
                                "Cannot insert cross fitting",
                                ex.Message);
                        }
                    }
                    else if (IsPipeParallel(pipe1, pipe4))
                    {
                        doc.Create.NewCrossFitting(
                            c1, c4, c2, c3);
                    }
                }
                tx.Commit();
            }
            return(Result.Succeeded);
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app = commandData.Application;
            Document      doc = app.ActiveUIDocument.Document;

            ICollection <ElementId> unusedTextNoteTypes
                = GetUnusedTextNoteTypes(doc);

            int n = unusedTextNoteTypes.Count;

            int nLoop = 100;

            Stopwatch sw = new Stopwatch();

            sw.Reset();
            sw.Start();

            for (int i = 0; i < nLoop; ++i)
            {
                unusedTextNoteTypes
                    = GetUnusedTextNoteTypes(doc);

                Debug.Assert(unusedTextNoteTypes.Count == n,
                             "expected same number of unused text note types");
            }

            sw.Stop();
            double ms = (double)sw.ElapsedMilliseconds
                        / (double)nLoop;

            sw.Reset();
            sw.Start();

            for (int i = 0; i < nLoop; ++i)
            {
                unusedTextNoteTypes
                    = GetUnusedTextNoteTypesExcluding(doc);

                Debug.Assert(unusedTextNoteTypes.Count == n,
                             "expected same number of unused texct note types");
            }

            sw.Stop();
            double msExcluding
                = (double)sw.ElapsedMilliseconds
                  / (double)nLoop;

            Transaction t = new Transaction(doc,
                                            "Purging unused text note types");

            t.Start();

            sw.Reset();
            sw.Start();

            doc.Delete(unusedTextNoteTypes);

            sw.Stop();
            double msDeleting
                = (double)sw.ElapsedMilliseconds
                  / (double)nLoop;

            t.Commit();

            Util.InfoMsg(string.Format(
                             "{0} text note type{1} purged. "
                             + "{2} ms to collect, {3} ms to collect "
                             + "excluding, {4} ms to delete.",
                             n, Util.PluralSuffix(n),
                             ms, msExcluding, msDeleting));

            return(Result.Succeeded);
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app   = commandData.Application;
            UIDocument    uidoc = app.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            Wall wall = Util.SelectSingleElementOfType(
                uidoc, typeof(Wall), "a wall", false)
                        as Wall;

            if (null == wall)
            {
                message
                    = "Please select a single wall element.";

                return(Result.Failed);
            }

            ICollection <ElementId> delIds = null;

            using (Transaction t = new Transaction(doc))
            {
                try
                {
                    t.Start("Temporary Wall Deletion");

                    delIds = doc.Delete(wall.Id);

                    t.RollBack();
                }
                catch (Exception ex)
                {
                    message = "Deletion failed: " + ex.Message;
                    t.RollBack();
                }
            }

            WallFoundation footing = null;

            foreach (ElementId id in delIds)
            {
                footing = doc.GetElement(id) as WallFoundation;

                if (null != footing)
                {
                    break;
                }
            }

            string s = Util.ElementDescription(wall);

            Util.InfoMsg((null == footing)
        ? string.Format("No footing found for {0}.", s)
        : string.Format("{0} has {1}.", s,
                        Util.ElementDescription(footing)));

            return(Result.Succeeded);
        }
예제 #23
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app   = commandData.Application;
            UIDocument    uidoc = app.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            Element e = Util.SelectSingleElement(
                uidoc, "an element");

            if (null == e)
            {
                message = "No element selected";
                return(Result.Failed);
            }

            // Trying to call this property returns the
            // compile time error: Property, indexer, or
            // event 'BoundingBox' is not supported by
            // the language; try directly calling
            // accessor method 'get_BoundingBox( View )'

            //BoundingBoxXYZ b = e.BoundingBox[null];

            View v = null;

            BoundingBoxXYZ b = e.get_BoundingBox(v);

            if (null == b)
            {
                v = commandData.View;
                b = e.get_BoundingBox(v);
            }

            if (null == b)
            {
                Util.InfoMsg(
                    Util.ElementDescription(e)
                    + " has no bounding box.");
            }
            else
            {
                using (Transaction tx = new Transaction(doc))
                {
                    tx.Start("Draw Model Line Bounding Box Outline");

                    Debug.Assert(b.Transform.IsIdentity,
                                 "expected identity bounding box transform");

                    string in_view = (null == v)
            ? "model space"
            : "view " + v.Name;

                    Util.InfoMsg(string.Format(
                                     "Element bounding box of {0} in "
                                     + "{1} extends from {2} to {3}.",
                                     Util.ElementDescription(e),
                                     in_view,
                                     Util.PointString(b.Min),
                                     Util.PointString(b.Max)));

                    Creator creator = new Creator(doc);

                    creator.DrawPolygon(new List <XYZ>(
                                            Util.GetBottomCorners(b)));

                    Transform rotation = Transform.CreateRotation(
                        XYZ.BasisZ, 60 * Math.PI / 180.0);

                    b = RotateBoundingBox(b, rotation);

                    Util.InfoMsg(string.Format(
                                     "Bounding box rotated by 60 degrees "
                                     + "extends from {0} to {1}.",
                                     Util.PointString(b.Min),
                                     Util.PointString(b.Max)));

                    creator.DrawPolygon(new List <XYZ>(
                                            Util.GetBottomCorners(b)));

                    tx.Commit();
                }
            }
            return(Result.Succeeded);
        }