Exemple #1
0
        private static string GetIdFromFragment(this IBHoMObject obj, Type fragmentType, string fragmentIdProperty)
        {
            if (!typeof(IFragment).IsAssignableFrom(fragmentType))
            {
                BH.Engine.Reflection.Compute.RecordError("The specified Type must be a fragment Type.");
                return(null);
            }

            // Check on fragmentIdProperty
            if (string.IsNullOrWhiteSpace(fragmentIdProperty))
            {
                BH.Engine.Reflection.Compute.RecordError($"Invalid {nameof(fragmentIdProperty)} provided.");
                return(null);
            }

            IFragment idFragm = obj.FindFragment <IFragment>(fragmentType);

            if (idFragm == null)
            {
                BH.Engine.Reflection.Compute.RecordWarning($"Object of type {obj.GetType()}, guid {obj.BHoM_Guid} does not contain a fragment of the provided Fragment type {fragmentType}.");
                return(null);
            }

            object value = BH.Engine.Reflection.Query.PropertyValue(idFragm, fragmentIdProperty);

            if (value == null)
            {
                BH.Engine.Reflection.Compute.RecordWarning($"The retrieved fragment for an object of type {obj.GetType()}, guid {obj.BHoM_Guid} has not any value under the property named {fragmentIdProperty}.");
                return(null);
            }

            return(value.ToString());
        }
Exemple #2
0
        public static IBHoMObject RemoveFragment(this IBHoMObject iBHoMObject, Type fragmentType = null)
        {
            if (fragmentType == null)
            {
                return(iBHoMObject);
            }
            if (iBHoMObject == null)
            {
                return(null);
            }
            IBHoMObject o = iBHoMObject.DeepClone();

            if (!typeof(IFragment).IsAssignableFrom(fragmentType))
            {
                Reflection.Compute.RecordError("Provided input in fragmentType is not a Fragment type (does not implement IFragment interface).");
                return(iBHoMObject);
            }

            if (!iBHoMObject.Fragments.Contains(fragmentType))
            {
                Reflection.Compute.RecordWarning($"{iBHoMObject.GetType().Name} does not contain any `{fragmentType.Name}` fragment.");
                return(iBHoMObject);
            }

            o.Fragments.Remove(fragmentType);

            return(o);
        }
Exemple #3
0
        /***************************************************/

        private static TestResult TestResultFromPushedObject(IBHoMObject obj)
        {
            return(new TestResult
            {
                Description = $"Test object of type {obj.GetType().Name} with name {obj.Name}",
                ID = obj.Hash(null, true),
            });
        }
Exemple #4
0
        /***************************************************/
        /****               Internal methods            ****/
        /***************************************************/

        internal static void NotConvertedError(this IBHoMObject obj)
        {
            string message = String.Format("BHoM object conversion to Revit failed.");

            if (obj != null)
            {
                message += string.Format(" BHoM object type: {0}, BHoM Guid: {1}", obj.GetType(), obj.BHoM_Guid);
            }

            BH.Engine.Reflection.Compute.RecordError(message);
        }
        /***************************************************/

        public static HashSet <BuiltInCategory> BuiltInCategories(this IBHoMObject bHoMObject, Document document, bool caseSensitive = true)
        {
            BuiltInCategory category = document.BuiltInCategory(bHoMObject.CategoryName(), caseSensitive);

            if (category != Autodesk.Revit.DB.BuiltInCategory.INVALID)
            {
                return new HashSet <BuiltInCategory> {
                           category
                }
            }
            ;

            return(bHoMObject.GetType().BuiltInCategories());
        }
Exemple #6
0
        /***************************************************/

        private static TestResult ComparePushedAndPulledObject(IBHoMObject pushedObj, IBHoMObject pulledObj, ComparisonConfig config)
        {
            TestResult result = TestResultFromPushedObject(pushedObj);

            try
            {
                var equalityResult = Engine.Test.Query.IsEqual(pushedObj, pulledObj, config);

                Type type = pushedObj.GetType();

                for (int i = 0; i < equalityResult.Item2.Count; i++)
                {
                    result.Information.Add(new PushPullObjectComparison
                    {
                        Message      = $"Difference found in {type.Name}. {equalityResult.Item2[i]} was {equalityResult.Item3[i]} on the pushed item and {equalityResult.Item4[i]} on the pulled item.",
                        ObjectType   = type,
                        PropertyID   = equalityResult.Item2[i],
                        PushedItem   = equalityResult.Item3[i],
                        ReturnedItem = equalityResult.Item4[i],
                        Status       = oM.Test.TestStatus.Warning
                    });
                }
            }
            catch (Exception e)
            {
                result.Status   = oM.Test.TestStatus.Error;
                result.Message  = "Failed to run the comparison of the Pushed and Pulled object." + Environment.NewLine;
                result.Message += $"Exception thrown: {e.Message}";
                return(result);
            }

            if (result.Information.Count == 0)
            {
                result.Status  = oM.Test.TestStatus.Pass;
                result.Message = "No differences found between the pushed and pulled object";
            }
            else
            {
                result.Status  = oM.Test.TestStatus.Warning;
                result.Message = "Differences found between the pushed and the pulled object.";
            }

            return(result);
        }
Exemple #7
0
        /***************************************************/

        private static Dictionary <string, Type> PropertyTypeDictionary(this IBHoMObject obj)
        {
            if (obj is CustomObject)
            {
                return(PropertyTypeDictionary(obj as CustomObject));
            }

            Dictionary <string, Type> dic = new Dictionary <string, Type>();

            foreach (var prop in obj.GetType().GetProperties())
            {
                if (!prop.CanRead || prop.GetMethod.GetParameters().Count() > 0)
                {
                    continue;
                }

                dic[prop.Name] = prop.PropertyType;
            }
            return(dic);
        }
Exemple #8
0
        public static IBHoMObject AddFragment(this IBHoMObject iBHoMObject, IFragment fragment, bool replace = false)
        {
            if (iBHoMObject == null || fragment == null)
            {
                return(null);
            }
            IBHoMObject o = iBHoMObject.DeepClone();

            // Give a warning if the fragment is supposed to be unique but is found on the object
            List <Type> currentFragmentTypes = iBHoMObject.Fragments.Select(x => x.GetType()).ToList();

            foreach (Type restriction in fragment.GetType().UniquenessRestrictions())
            {
                if (currentFragmentTypes.Any(x => restriction.IsAssignableFrom(x) && x != fragment.GetType()))
                {
                    Engine.Reflection.Compute.RecordWarning("There is already a fragment of type " + restriction + " on this object. \nThe Fragment will still be added but consider reviewing this task as fragments of that type are supposed to be unique.");
                }
            }

            // Make sure this fragment can be added to that object
            if (fragment.CanTarget(iBHoMObject))
            {
                if (!replace)
                {
                    o.Fragments.Add(fragment);
                }
                else
                {
                    o.Fragments.AddOrReplace(fragment);
                }
            }
            else
            {
                Engine.Reflection.Compute.RecordError("An object of type " + iBHoMObject.GetType() + " is not a valid target for a fragment of type " + fragment.GetType() + ". The fragment was not added.");
            }


            return(o);
        }
Exemple #9
0
        private static object GetValue(this IBHoMObject obj, string sourceName, bool errorIfNotFound = false)
        {
            IBHoMObject bhomObj = obj as IBHoMObject;
            object      value   = null;

            if (bhomObj.CustomData.ContainsKey(sourceName))
            {
                if (bhomObj.CustomData.TryGetValue(sourceName, out value))
                {
                    return(value);
                }
            }
            else if (sourceName.ToLower().Contains("customdata["))
            {
                string keyName = sourceName.Substring(sourceName.IndexOf('[') + 1, sourceName.IndexOf(']') - sourceName.IndexOf('[') - 1);
                bhomObj.CustomData.TryGetValue(keyName, out value);
                return(value);
            }
            else
            {
                if (sourceName.Contains("."))
                {
                    string[] props = sourceName.Split('.');

                    Type fragmentType = BH.Engine.Reflection.Create.Type(sourceName, true);

                    if (fragmentType != null)
                    {
                        List <IFragment> allFragmentsOfType = bhomObj.Fragments.Where(fr => fragmentType.IsAssignableFrom(fr.GetType())).ToList();
                        List <object>    values             = allFragmentsOfType.Select(f => ValueFromSource(f, string.Join(".", props.Skip(1)))).ToList();
                        value = values.Count == 1 ? values.First() : values;
                    }
                }
                else
                {
                    // Try extracting the property using an Extension method.
                    MethodInfo method = BH.Engine.Reflection.Query.ExtensionMethodToCall(obj, sourceName);
                    if (method != null)
                    {
                        value = BH.Engine.Reflection.Compute.RunExtensionMethod(obj, method);
                    }
                    else
                    if (errorIfNotFound)
                    {
                        BH.Engine.Reflection.Compute.RecordError($"No property, customData or ExtensionMethod found with name `{sourceName}` for this {obj.GetType().Name}.");
                    }
                }
            }

            return(value);
        }
Exemple #10
0
        // Note: setAssignedId is currently not exposed as an option
        //  -- waiting for Adapter refactoring LVL 04 to expose a new CRUDconfig input for the Push
        // CRUDconfig will become available to all CRUD methods
        protected bool CreateAnyObject(List <IObject> objects, bool setAssignedId = true)
        {
            /// Create the objects
            List <SpeckleObject> objs_serialized = SpeckleCore.Converter.Serialise(objects);

            SpeckleLayer.ObjectCount += objects.Count();
            SpeckleStream.Objects.AddRange(objs_serialized);

            /// Assign any other property to the objects before sending them
            var objList = objects.ToList();
            int i       = 0;

            foreach (var o in SpeckleStream.Objects)
            {
                IBHoMObject bhomObj = objList[i] as IBHoMObject;
                if (bhomObj != null)
                {
                    SpeckleStream.Objects[i].Name = string.IsNullOrEmpty(bhomObj.Name) ? bhomObj.GetType().ToString() : bhomObj.Name;
                    //SpeckleStream.Objects[i].Type = string.IsNullOrEmpty(bhomObj.Name) ? bhomObj.GetType().ToString() : bhomObj.Name;
                }
                i++;
            }

            /// Send the objects
            var updateResponse = SpeckleClient.StreamUpdateAsync(SpeckleStreamId, SpeckleStream).Result;

            SpeckleClient.BroadcastMessage("stream", SpeckleStreamId, new { eventType = "update-global" });



            /// Read the IBHoMobjects as exported in speckle
            /// so we can assign the Speckle-generated id into the BHoMobjects
            if (setAssignedId)
            {
                ResponseObject response = SpeckleClient.StreamGetObjectsAsync(SpeckleStreamId, "").Result;

                List <IBHoMObject>        bHoMObjects_inSpeckle = new List <IBHoMObject>();
                IEnumerable <IBHoMObject> iBhomObjsInSpeckle    = BH.Engine.Speckle.Convert.ToBHoM(response, true);

                VennDiagram <IBHoMObject> correspondenceDiagram = Engine.Data.Create.VennDiagram(objects.Where(o => o as IBHoMObject != null).Cast <IBHoMObject>(), iBhomObjsInSpeckle, new IBHoMGUIDComparer());

                if (correspondenceDiagram.Intersection.Count != objects.Count())
                {
                    var gna = 0;
                    //Engine.Reflection.Compute.RecordError("Push failed.\nNumber of objects created in Speckle do not correspond to the number of objects pushed.");
                    //return false;
                }

                correspondenceDiagram.Intersection.ForEach(o => o.Item1.CustomData[AdapterId] = o.Item2.CustomData[AdapterId]);
            }

            return(true);
        }
Exemple #11
0
        /***************************************************/

        internal static void ConvertBeforePushError(this IBHoMObject iBHoMObject, Type typeToConvert)
        {
            BH.Engine.Reflection.Compute.RecordError(string.Format("{0} has to be converted to {1} before pushing. BHoM object Guid: {2}", iBHoMObject.GetType().Name, typeToConvert.Name, iBHoMObject.BHoM_Guid));
        }
Exemple #12
0
        /***************************************************/

        public static bool SetLocation(this Element element, IBHoMObject bHoMObject, RevitSettings settings)
        {
            Type type = element.GetType();

            if (AbstractRevitTypes.All(x => !x.IsAssignableFrom(type)))
            {
                BH.Engine.Reflection.Compute.RecordError(String.Format("Unable to set location of Revit element of type {0} based on BHoM object of type {1} beacuse no suitable method could be found. Only parameters were updated. Revit ElementId: {2} BHoM_Guid: {3}", element.GetType(), bHoMObject.GetType(), element.Id, bHoMObject.BHoM_Guid));
            }

            return(false);
        }
Exemple #13
0
        /***************************************************/

        public static void CopyParameters(this Element element, IBHoMObject bHoMObject, RevitSettings settings = null)
        {
            if (bHoMObject == null || element == null)
            {
                return;
            }

            settings = settings.DefaultIfNull();

            RevitParametersToPush fragment = bHoMObject.Fragments.FirstOrDefault(x => x is RevitParametersToPush) as RevitParametersToPush;

            if (fragment == null)
            {
                return;
            }

            ElementType elementType = element.Document.GetElement(element.GetTypeId()) as ElementType;

            Type type = bHoMObject.GetType();

            BH.oM.Adapters.Revit.Parameters.ParameterMap parameterMap = settings?.ParameterSettings?.ParameterMap(type);

            IEnumerable <PropertyInfo> propertyInfos = type.MapPropertyInfos();

            if (propertyInfos != null)
            {
                propertyInfos = propertyInfos.Where(x => x.PropertyType != typeof(double)).Union(propertyInfos.Where(x => x.PropertyType == typeof(double)));
                foreach (PropertyInfo pInfo in propertyInfos)
                {
                    object value = pInfo.GetValue(bHoMObject);

                    HashSet <string> parameterNames = settings.ParameterSettings.ParameterNames(type, pInfo.Name, false);
                    if (parameterNames != null && element.SetParameters(parameterNames, value))
                    {
                        continue;
                    }

                    if (elementType == null)
                    {
                        continue;
                    }

                    parameterNames = settings.ParameterSettings.ParameterNames(type, pInfo.Name, true);
                    if (parameterNames != null)
                    {
                        element.SetParameters(parameterNames, value);
                    }
                }
            }

            // Sort the parameters so that doubles get assigned last, to make sure all reference levels etc. go first.
            foreach (RevitParameter param in fragment.Parameters.Where(x => !(x.Value is double)).Union(fragment.Parameters.Where(x => x.Value is double)))
            {
                IEnumerable <IParameterLink> parameterLinks = parameterMap.ParameterLinks(param.Name);
                if (parameterLinks != null)
                {
                    foreach (IParameterLink parameterLink in parameterLinks)
                    {
                        if (parameterLink is ElementParameterLink)
                        {
                            element.SetParameters(parameterLink.ParameterNames, param.Value);
                        }
                        else if (elementType != null)
                        {
                            elementType.SetParameters(parameterLink.ParameterNames, param.Value);
                        }
                    }
                }
                else
                {
                    element.SetParameters(param.Name, param.Value);
                }
            }

            element.Document.Regenerate();
        }
Exemple #14
0
        /***************************************************/
        /****              Public methods               ****/
        /***************************************************/

        public static void CopyParameters(this IBHoMObject bHoMObject, Element element, ParameterSettings settings = null)
        {
            if (bHoMObject == null || element == null)
            {
                return;
            }

            List <RevitParameter> parameters = new List <RevitParameter>();

            oM.Adapters.Revit.Parameters.ParameterMap parameterMap = settings?.ParameterMap(bHoMObject.GetType());
            IEnumerable <IParameterLink> parameterLinks            = null;

            if (parameterMap != null)
            {
                Element elementType = element.Document.GetElement(element.GetTypeId());
                IEnumerable <IParameterLink> typeParameterLinks = parameterMap.ParameterLinks.Where(x => x is ElementTypeParameterLink);
                if (elementType != null && typeParameterLinks.Count() != 0)
                {
                    foreach (Parameter parameter in elementType.ParametersMap)
                    {
                        RevitParameter bHoMParameter = parameter.ParameterFromRevit(typeParameterLinks, true);
                        if (bHoMParameter != null)
                        {
                            parameters.Add(bHoMParameter);
                        }
                    }
                }

                parameterLinks = parameterMap.ParameterLinks.Where(x => !(x is ElementTypeParameterLink));
            }

            IEnumerable elementParams = element.ParametersMap;

            if (((Autodesk.Revit.DB.ParameterMap)elementParams).IsEmpty)
            {
                elementParams = element.Parameters;
            }

            foreach (Parameter parameter in elementParams)
            {
                parameters.Add(parameter.ParameterFromRevit(parameterLinks, false));
            }

            bHoMObject.Fragments.Add(new RevitPulledParameters(parameters));
        }
Exemple #15
0
        /***************************************************/

        private bool CreateObject(IBHoMObject obj)
        {
            Engine.Base.Compute.RecordWarning($"Objects of type {obj.GetType()} are not supported by the ETABSAdapter.");
            return(false);
        }