Exemplo n.º 1
0
        public virtual void Dispose()
        {
            // Do not cleanup Revit elements if we are shutting down Dynamo.
            if (DisposeLogic.IsShuttingDown)
            {
                return;
            }

            bool didRevitDelete = ElementIDLifecycleManager <int> .GetInstance().IsRevitDeleted(this.Id);



            var elementManager = ElementIDLifecycleManager <int> .GetInstance();

            int remainingBindings = elementManager.UnRegisterAssociation(this.Id, this);

            // Do not delete Revit owned elements
            if (!IsRevitOwned && remainingBindings == 0 && !didRevitDelete)
            {
                DocumentManager.Instance.DeleteElement(this.InternalElementId);
            }
            else
            {
                //This element has gone
                //but there was something else holding onto the Revit object so don't purge it

                internalId = null;
            }
        }
Exemplo n.º 2
0
        public virtual void Dispose()
        {
            // Do not cleanup Revit elements if we are shutting down Dynamo or
            // closing homeworkspace or the element itself is frozen.
            if (DisposeLogic.IsShuttingDown || DisposeLogic.IsClosingHomeworkspace || IsFrozen)
            {
                return;
            }

            bool didRevitDelete = ElementIDLifecycleManager <int> .GetInstance().IsRevitDeleted(Id);

            var elementManager = ElementIDLifecycleManager <int> .GetInstance();

            int remainingBindings = elementManager.UnRegisterAssociation(Id, this);

            // Do not delete Revit owned elements
            if (!IsRevitOwned && remainingBindings == 0 && !didRevitDelete)
            {
                DocumentManager.Instance.DeleteElement(new ElementUUID(InternalUniqueId));
            }
            else
            {
                //This element has gone
                //but there was something else holding onto the Revit object so don't purge it

                internalId = null;
            }
        }
Exemplo n.º 3
0
 public void WatcherMethodForDelete(Document document, IEnumerable <ElementId> deleted)
 {
     foreach (ElementId id in deleted)
     {
         Delete(document, id);
         ElementIDLifecycleManager <int> .GetInstance().NotifyOfRevitDeletion(id.IntegerValue);
     }
 }
Exemplo n.º 4
0
        public override void OnEvaluationCompleted(object sender, EvaluationCompletedEventArgs e)
        {
            Debug.WriteLine(ElementIDLifecycleManager <int> .GetInstance());

            // finally close the transaction!
            TransactionManager.Instance.ForceCloseTransaction();

            base.OnEvaluationCompleted(sender, e);
        }
Exemplo n.º 5
0
        public static object GetParameterValue(Autodesk.Revit.DB.Parameter param)
        {
            object result;

            switch (param.StorageType)
            {
            case StorageType.ElementId:
                int valueId = param.AsElementId().IntegerValue;
                if (valueId > 0)
                {
                    // When the element is obtained here, to convert it to our element wrapper, it
                    // need to be figured out whether this element is created by us. Here the existing
                    // element wrappers will be checked. If there is one, its property to specify
                    // whether it is created by us will be followed. If there is none, it means the
                    // element is not created by us.
                    var elem = ElementIDLifecycleManager <int> .GetInstance().GetFirstWrapper(valueId) as Element;

                    result = ElementSelector.ByElementId(valueId, elem == null ? true : elem.IsRevitOwned);
                }
                else
                {
                    int paramId = param.Id.IntegerValue;
                    if (paramId == (int)BuiltInParameter.ELEM_CATEGORY_PARAM || paramId == (int)BuiltInParameter.ELEM_CATEGORY_PARAM_MT)
                    {
                        var categories = DocumentManager.Instance.CurrentDBDocument.Settings.Categories;
                        result = new Category(categories.get_Item((BuiltInCategory)valueId));
                    }
                    else
                    {
                        // For other cases, return a localized string
                        result = param.AsValueString();
                    }
                }
                break;

            case StorageType.String:
                result = param.AsString();
                break;

            case StorageType.Integer:
                result = param.AsInteger();
                break;

            case StorageType.Double:
                result = param.AsDouble() * Revit.GeometryConversion.UnitConverter.HostToDynamoFactor(param.Definition.UnitType);
                break;

            default:
                throw new Exception(string.Format(Properties.Resources.ParameterWithoutStorageType, param));
            }

            return(result);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Get the value of one of the element's parameters.
        /// </summary>
        /// <param name="parameterName">The name of the parameter whose value you want to obtain.</param>
        /// <returns></returns>
        public object GetParameterValueByName(string parameterName)
        {
            object result;

            var param = InternalElement.Parameters.Cast <Autodesk.Revit.DB.Parameter>().FirstOrDefault(x => x.Definition.Name == parameterName);

            if (param == null || !param.HasValue)
            {
                return(string.Empty);
            }

            switch (param.StorageType)
            {
            case StorageType.ElementId:
                int id = param.AsElementId().IntegerValue;
                // When the element is obtained here, to convert it to our element wrapper, it
                // need to be figured out whether this element is created by us. Here the existing
                // element wrappers will be checked. If there is one, its property to specify
                // whether it is created by us will be followed. If there is none, it means the
                // element is not created by us.
                var ele = ElementIDLifecycleManager <int> .GetInstance().GetFirstWrapper(id) as Element;

                result = ElementSelector.ByElementId(id, ele == null ? true : ele.IsRevitOwned);
                break;

            case StorageType.String:
                result = param.AsString();
                break;

            case StorageType.Integer:
                result = param.AsInteger();
                break;

            case StorageType.Double:
                var paramType = param.Definition.ParameterType;
                if (IsConvertableParameterType(paramType))
                {
                    result = param.AsDouble() * UnitConverter.HostToDynamoFactor(
                        ParameterTypeToUnitType(paramType));
                }
                else
                {
                    result = param.AsDouble();
                }
                break;

            default:
                throw new Exception(string.Format("Parameter {0} has no storage type.", param));
            }

            return(result);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Construct a new Revit PathOfTravel in a floor plan view between the specified start point and end point
        /// </summary>
        /// <param name="rvtView"></param>
        /// <param name="startPoints"></param>
        /// <param name="endPoints"></param>
        /// <returns></returns>
        private static PathOfTravel[] InternalByViewEndPoints(Rvt.View rvtView, IEnumerable <XYZ> startPoints, IEnumerable <XYZ> endPoints)
        {
            List <PathOfTravel> pathsOfTravel = new List <PathOfTravel>();

            TransactionManager.Instance.EnsureInTransaction(Document);

            try
            {
                // get previously created elements
                IEnumerable <RvtAnalysis.PathOfTravel> existingRvtElements = ElementBinder.GetElementsFromTrace <RvtAnalysis.PathOfTravel>(Document);

                // update elements that can be reused
                IList <PathOfTravel> updatedPathsOfTravel = UpdateReusedElements(existingRvtElements, startPoints, endPoints);
                pathsOfTravel.AddRange(updatedPathsOfTravel);

                // delete elements that are not needed anymore
                DeleteExtraElements(existingRvtElements, startPoints, endPoints);

                // create additional elements
                IList <PathOfTravel> newPathsOfTravel = CreateAdditionalElements(rvtView, existingRvtElements, startPoints, endPoints);
                pathsOfTravel.AddRange(newPathsOfTravel);

                ElementBinder.SetElementsForTrace(pathsOfTravel.Where(x => x != null).Select(x => x.InternalElement));
            }
            catch (Exception e)
            {
                // unregister the elements from the element life cycle manager and delete the elements
                var elementManager = ElementIDLifecycleManager <int> .GetInstance();

                if (pathsOfTravel != null)
                {
                    foreach (var path in pathsOfTravel)
                    {
                        if (path != null)
                        {
                            elementManager.UnRegisterAssociation(path.InternalElementId.IntegerValue, path);
                            Document.Delete(path.InternalElementId);
                        }
                    }
                }

                throw e;
            }
            finally
            {
                TransactionManager.Instance.TransactionTaskDone();
            }

            return(pathsOfTravel.ToArray());
        }
Exemplo n.º 8
0
        public override void OnEvaluationCompleted(object sender, EvaluationCompletedEventArgs e)
        {
            Debug.WriteLine(ElementIDLifecycleManager <int> .GetInstance());

            if (historicalElementData.ContainsKey(CurrentWorkspace.Guid))
            {
                ReconcileHistoricalElements();
            }

            // finally close the transaction!
            TransactionManager.Instance.ForceCloseTransaction();

            base.OnEvaluationCompleted(sender, e);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Handling exceptions when calling the initializing function
        /// </summary>
        /// <param name="init"></param>
        protected void SafeInit(Action init)
        {
            TransactionManager.Instance.EnsureInTransaction(DocumentManager.Instance.CurrentDBDocument);

            var elementManager = ElementIDLifecycleManager <int> .GetInstance();

            var element = ElementBinder.GetElementFromTrace <Autodesk.Revit.DB.Element>(Document);
            int count   = 0;
            int id      = 0;

            if (null != element)
            {
                id    = element.Id.IntegerValue;
                count = elementManager.GetRegisteredCount(id);
            }
            try
            {
                init();
            }
            catch (Exception e)
            {
                //If the element is newly created and bound but the creation is aborted because
                //of an exception, it need to be unregistered.
                if (element == null && InternalElementId != null)
                {
                    elementManager.UnRegisterAssociation(Id, this);
                    internalId = null;
                    throw e;
                }
                else if (element != null)
                {
                    //If the internal element has already been bound, and if the registered count has increased,
                    //it need to be unregistered.
                    if (elementManager.GetRegisteredCount(id) == count + 1)
                    {
                        elementManager.UnRegisterAssociation(Id, this);
                        internalId = null;
                    }

                    //It means that the updating operation failed, an attemption of making a new element is made.
                    ElementBinder.SetRawDataForTrace(null);
                    SafeInit(init);
                }
                else
                {
                    throw e;
                }
            }
        }
Exemplo n.º 10
0
 public void WatcherMethodForDelete(Document document, IEnumerable <ElementId> deleted)
 {
     Debug.WriteLine(string.Format("{0} elements deleted from Revit.", deleted.Count()));
     foreach (ElementId id in deleted)
     {
         try
         {
             Delete(document, id);
             ElementIDLifecycleManager <int> .GetInstance()
             .NotifyOfRevitDeletion(id.IntegerValue);
         }
         catch
         { }
     }
 }
Exemplo n.º 11
0
        protected override void ShutDownCore(bool shutDownHost)
        {
            DisposeLogic.IsShuttingDown = true;

            base.ShutDownCore(shutDownHost);

            // unsubscribe events
            RevitServicesUpdater.Instance.UnRegisterAllChangeHooks();

            UnsubscribeApplicationEvents(externalCommandData);
            UnsubscribeDocumentManagerEvents();
            UnsubscribeRevitServicesUpdaterEvents();
            UnsubscribeTransactionManagerEvents();

            ElementIDLifecycleManager <int> .DisposeInstance();
        }
Exemplo n.º 12
0
        /// <summary>
        /// Create a list of adaptive components from two-dimensional array of points
        /// </summary>
        /// <param name="points">a two-dimensional array of points</param>
        /// <param name="familyType">a family type to use to create the adaptive components</param>
        /// <returns></returns>
        private static AdaptiveComponent[] InternalByPoints(Point[][] points, FamilyType familyType)
        {
            var oldInstances        = ElementBinder.GetElementsFromTrace <Autodesk.Revit.DB.FamilyInstance>(Document);
            int countToBeCreated    = points.Count();
            int countOfOldInstances = 0;

            if (oldInstances != null)
            {
                countOfOldInstances = oldInstances.Count();
            }
            int reusableCount = Math.Min(countToBeCreated, countOfOldInstances);

            TransactionManager.Instance.EnsureInTransaction(Document);

            List <Autodesk.Revit.DB.FamilyInstance> instances = new List <Autodesk.Revit.DB.FamilyInstance>();
            List <AdaptiveComponent> components = new List <AdaptiveComponent>();

            try
            {
                // Reuse the adaptive components that can be reused if possible
                for (int i = 0; i < reusableCount; i++)
                {
                    var fi   = oldInstances.ElementAt(i);
                    var comp = new AdaptiveComponent(fi);
                    components.Add(comp);

                    //Update the family symbol
                    if (familyType.InternalFamilySymbol.Id != fi.Symbol.Id)
                    {
                        fi.Symbol = familyType.InternalFamilySymbol;
                    }

                    UpdatePlacementPoints(fi, points[i].ToXyzs());
                    instances.Add(fi);
                }

                // Delete the redundant adaptive components if any
                for (int i = reusableCount; i < countOfOldInstances; i++)
                {
                    var fi = oldInstances.ElementAt(i);
                    Document.Delete(fi.Id);
                }

                // Create new adaptive components
                if (countToBeCreated > countOfOldInstances)
                {
                    var remainingPoints = points.Skip(reusableCount).ToArray();
                    // Prepare the creation data for batch processing
                    int numOfComponents = remainingPoints.Count();
                    List <FamilyInstanceCreationData> creationDatas = new List <FamilyInstanceCreationData>(numOfComponents);
                    for (int i = 0; i < numOfComponents; ++i)
                    {
                        int numOfPoints = remainingPoints[i].Length;
                        var aPoints     = remainingPoints[i].ToXyzs();

                        var creationData = DocumentManager.Instance.CurrentUIApplication.Application.Create.
                                           NewFamilyInstanceCreationData(familyType.InternalFamilySymbol, aPoints);

                        if (creationData != null)
                        {
                            creationDatas.Add(creationData);
                        }
                    }

                    // Create elements based on the creation data in a batch
                    ICollection <ElementId> elements;
                    if (creationDatas.Count > 0)
                    {
                        if (Document.IsFamilyDocument)
                        {
                            elements = DocumentManager.Instance.CurrentDBDocument.FamilyCreate.NewFamilyInstances2(creationDatas);
                        }
                        else
                        {
                            elements = DocumentManager.Instance.CurrentDBDocument.Create.NewFamilyInstances2(creationDatas);
                        }

                        foreach (var id in elements)
                        {
                            Autodesk.Revit.DB.FamilyInstance instance;
                            if (ElementUtils.TryGetElement <Autodesk.Revit.DB.FamilyInstance>(
                                    DocumentManager.Instance.CurrentDBDocument, id, out instance))
                            {
                                instances.Add(instance);
                                components.Add(new AdaptiveComponent(instance));
                            }
                        }
                    }
                }

                ElementBinder.SetElementsForTrace(instances);
            }
            catch (Exception e)
            {
                // Unregister the elements from the element life cycle manager and delete the elements
                var elementManager = ElementIDLifecycleManager <int> .GetInstance();

                foreach (var component in components)
                {
                    elementManager.UnRegisterAssociation(component.InternalElementId.IntegerValue, component);
                }
                foreach (var instance in instances)
                {
                    Document.Delete(instance.Id);
                }

                if (e is Autodesk.Revit.Exceptions.ArgumentException)
                {
                    throw new ArgumentException("The arguments have issues", e);
                }
                else
                {
                    throw e;
                }
            }
            finally
            {
                TransactionManager.Instance.TransactionTaskDone();
            }

            return(components.ToArray());
        }
Exemplo n.º 13
0
        /// <summary>
        /// [INTERNAL]: Calculates the longest Path of Travel of all shortest paths from rooms in the floor plan to given exit points.
        /// </summary>
        /// <param name="rvtView">Floor plan view for which rooms will be used to retrieve longest paths to the given exit points.</param>
        /// <param name="endPoints">List of end (exit) points.</param>
        /// <returns>List of Path of Travel elements corresponding to the longest of shortest exit paths from rooms.</returns>
        ///
        private static PathOfTravel[] InternalLongestOfShortestExitPaths(Rvt.View rvtView, IEnumerable <XYZ> endPoints)
        {
            List <PathOfTravel> pathsOfTravel = new List <PathOfTravel>();

            TransactionManager.Instance.EnsureInTransaction(Document);

            try
            {
                IList <XYZ> startsOfLongestPathsFromRooms = RvtAnalysis.PathOfTravel.FindStartsOfLongestPathsFromRooms(
                    rvtView,
                    endPoints.ToList());

                if (startsOfLongestPathsFromRooms.Count() != 0)
                {
                    IList <XYZ> endsOfShortestPaths = RvtAnalysis.PathOfTravel.FindEndsOfShortestPaths(
                        rvtView,
                        endPoints.ToList(),
                        startsOfLongestPathsFromRooms);

                    IList <RvtAnalysis.PathOfTravel> newRvtPathOfTravels = RvtAnalysis.PathOfTravel.CreateMultiple(
                        rvtView,
                        startsOfLongestPathsFromRooms.ToList(),
                        endsOfShortestPaths.ToList());

                    foreach (RvtAnalysis.PathOfTravel rvtPathOfTravel in newRvtPathOfTravels)
                    {
                        if (rvtPathOfTravel != null)
                        {
                            pathsOfTravel.Add(new PathOfTravel(rvtPathOfTravel));
                        }
                    }

                    ElementBinder.SetElementsForTrace(pathsOfTravel.Where(x => x != null).Select(x => x.InternalElement));
                }
            }
            catch (Exception e)
            {
                //unregister the elements from the element life cycle manager and delete the elements
                var elementManager = ElementIDLifecycleManager <int> .GetInstance();

                if (pathsOfTravel != null)
                {
                    foreach (var path in pathsOfTravel)
                    {
                        if (path != null)
                        {
                            elementManager.UnRegisterAssociation(path.InternalElementId.IntegerValue, path);
                            Document.Delete(path.InternalElementId);
                        }
                    }
                }

                throw e;
            }
            finally
            {
                TransactionManager.Instance.TransactionTaskDone();
            }

            return(pathsOfTravel.ToArray());
        }
Exemplo n.º 14
0
        /// <summary>
        /// Get the value of one of the element's parameters.
        /// </summary>
        /// <param name="parameterName">The name of the parameter whose value you want to obtain.</param>
        /// <returns></returns>
        public object GetParameterValueByName(string parameterName)
        {
            object result;

            var param =
                // We don't use Element.GetOrderedParameters(), it only returns ordered parameters
                // as show in the UI
                InternalElement.Parameters.Cast <Autodesk.Revit.DB.Parameter>()
                // Element.Parameters returns a differently ordered list on every invocation.
                // We must sort it to get sensible results.
                .OrderBy(x => x.Id.IntegerValue)
                .FirstOrDefault(x => x.Definition.Name == parameterName);

            if (param == null || !param.HasValue)
            {
                return(string.Empty);
            }

            switch (param.StorageType)
            {
            case StorageType.ElementId:
                int valueId = param.AsElementId().IntegerValue;
                if (valueId > 0)
                {
                    // When the element is obtained here, to convert it to our element wrapper, it
                    // need to be figured out whether this element is created by us. Here the existing
                    // element wrappers will be checked. If there is one, its property to specify
                    // whether it is created by us will be followed. If there is none, it means the
                    // element is not created by us.
                    var elem = ElementIDLifecycleManager <int> .GetInstance().GetFirstWrapper(valueId) as Element;

                    result = ElementSelector.ByElementId(valueId, elem == null ? true : elem.IsRevitOwned);
                }
                else
                {
                    int paramId = param.Id.IntegerValue;
                    if (paramId == (int)BuiltInParameter.ELEM_CATEGORY_PARAM || paramId == (int)BuiltInParameter.ELEM_CATEGORY_PARAM_MT)
                    {
                        var categories = DocumentManager.Instance.CurrentDBDocument.Settings.Categories;
                        result = new Category(categories.get_Item((BuiltInCategory)valueId));
                    }
                    else
                    {
                        // For other cases, return a localized string
                        result = param.AsValueString();
                    }
                }
                break;

            case StorageType.String:
                result = param.AsString();
                break;

            case StorageType.Integer:
                result = param.AsInteger();
                break;

            case StorageType.Double:
                var paramType = param.Definition.ParameterType;
                if (IsConvertableParameterType(paramType))
                {
                    result = param.AsDouble() * UnitConverter.HostToDynamoFactor(
                        ParameterTypeToUnitType(paramType));
                }
                else
                {
                    result = param.AsDouble();
                }
                break;

            default:
                throw new Exception(string.Format(Properties.Resources.ParameterWithoutStorageType, param));
            }

            return(result);
        }