public Wall DeteleAllGrids(Document doc, Wall curtainWall)
        {
            CurtainGrid grid = curtainWall.CurtainGrid;

            ICollection <ElementId> horizGrids = grid.GetUGridLineIds();
            ICollection <ElementId> vertGrids  = grid.GetVGridLineIds();

            foreach (ElementId eIdH in horizGrids)
            {
                Debug("Horiz Grid ID " + eIdH);
                CurtainGridLine cglH             = (CurtainGridLine)doc.GetElement(eIdH);
                Parameter       typeAssociationH = cglH.GetParameters("Type Association").FirstOrDefault();
                Debug($"Horiz Type Association {typeAssociationH?.AsValueString()}");
                Debug("Horiz Lock " + cglH.Lock);

                if (typeAssociationH?.AsInteger() == 1)
                {
                    typeAssociationH.Set(0);
                    Debug("Horiz Type Association Reset " + (typeAssociationH?.AsValueString() ?? "null"));
                    Debug("Horiz Type Association Element Id " + typeAssociationH.AsElementId());
                }

                if (cglH.Lock)
                {
                    cglH.Lock = false;
                    Debug("Horiz Lock Reset " + cglH.Lock);
                }

                doc.Delete(eIdH);
            }

            //deletes all vert grids
            foreach (ElementId eIdV in vertGrids)
            {
                Debug("Vert Grid ID " + eIdV);
                CurtainGridLine cglV             = (CurtainGridLine)doc.GetElement(eIdV);
                Parameter       typeAssociationV = cglV.GetParameters("Type Association").FirstOrDefault();
                Debug("Vert Type Association " + (typeAssociationV?.AsValueString() ?? "null"));
                Debug("Vert Lock " + cglV.Lock);

                if (typeAssociationV?.AsInteger() == 1)
                {
                    typeAssociationV.Set(0);
                    Debug("Vert Type Association Reset " + (typeAssociationV?.AsValueString() ?? "null"));
                    Debug("Vert Type Association Element Id " + typeAssociationV.AsElementId());
                }

                if (cglV.Lock)
                {
                    cglV.Lock = false;
                    Debug("Vert Lock Reset " + cglV.Lock);
                }

                doc.Delete(eIdV);
            }

            return(curtainWall);
        }
Exemplo n.º 2
0
        private string GetParameterValueById(Element element, ElementId paramId)
        {
            if (element == null)
            {
                return(string.Empty);
            }

            Parameter parameter = null;

            if (ParameterUtils.IsBuiltInParameter(paramId))
            {
                parameter = element.get_Parameter((BuiltInParameter)paramId.IntegerValue);
            }
            else
            {
                ParameterElement parameterElem = element.Document.GetElement(paramId) as ParameterElement;
                if (parameterElem == null)
                {
                    return(string.Empty);
                }
                parameter = element.get_Parameter(parameterElem.GetDefinition());
            }

            return(parameter?.AsValueString() ?? string.Empty);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Runtime is about O(n) * O(1): O(n)
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="fieldName"></param>
        /// <param name="fieldValue"></param>
        /// <returns></returns>
        private static Parameter SearchElementParametersByHash(Document doc, string fieldName, string fieldValue)
        {
            try
            {
                //var iter = new FilteredElementCollector(doc)
                //    .WhereElementIsNotElementType()
                //    .GetElementIterator();

                var iter = new FilteredElementCollector(doc)
                           .WhereElementIsViewIndependent()
                           .ToElements().ToArray();

                Parameter possible = null;

                Parallel.ForEach(iter, (elem) =>
                {
                    // skip any elements that don't have the parameter
                    var temp = TryGetParameter(elem, fieldName);

                    var val = possible?.AsValueString();

                    if (val == fieldValue)
                    {
                        possible = temp;
                    }
                });

                // store parameter name, paramter value and elementId
                //while (iter.MoveNext())
                //{
                //    var elem = iter.Current;

                //    // skip any elements that don't have the parameter
                //    var possible = TryGetParameter(elem, fieldName);

                //    if(possible == null)
                //        continue;

                //    var val = possible.AsValueString();

                //    if (val == fieldValue)
                //        return possible;
                //}

                if (possible != null)
                {
                    return(possible);
                }

                TaskDialog.Show("Doesn't exist", "The requested parameter does not exist in the model");
                throw new Exception("Could not find parameter");
            }

            catch (Exception e)
            {
                throw new Exception("Could not find parameter", e);
            }
        }
Exemplo n.º 4
0
        private static bool IsBeforeInOrder(this Parameter pivot, Parameter p)
        {
            try
            {
                if (p?.Definition?.Name == null)
                {
                    return(true);
                }

                var pivotP = (pivot?.Definition?.Name + pivot?.AsValueString()).ToLower();
                var checkP = (p?.Definition?.Name + p?.AsValueString()).ToLower();

                var isBefore = pivotP.IsLessThan(checkP);

                return(isBefore);
            }

            catch (Exception e)
            {
                throw new Exception("The parameter could no be processed", e);
            }
        }
Exemplo n.º 5
0
        private UpdateResult UpdateParameter(Parameter param, object paramValue)
        {
            UpdateResult result;

            try
            {
                bool flag  = param == null;
                bool flag2 = this.IsNullOrDBNull(paramValue);
                if (flag)
                {
                    if (flag2)
                    {
                        result = UpdateResult.Equals;
                    }
                    else
                    {
                        result = UpdateResult.ParameterNull;
                    }
                }
                else
                {
                    bool flag3 = this.IsParameterValueEmpty(param);
                    bool flag4 = this.IsValueEmpty(param.StorageType, paramValue);
                    if (flag3)
                    {
                        if (flag2 || flag4)
                        {
                            result = UpdateResult.Equals;
                        }
                        else if (param.IsReadOnly)
                        {
                            result = UpdateResult.ReadOnlyFailed;
                        }
                        else
                        {
                            result = (this.SetParameter(param, paramValue) ? UpdateResult.Success : UpdateResult.Failed);
                        }
                    }
                    else if (flag2 || flag4)
                    {
                        if (param.IsReadOnly)
                        {
                            result = UpdateResult.ReadOnlyFailed;
                        }
                        else
                        {
                            result = (this.SetParameterValueToEmpty(param) ? UpdateResult.Success : UpdateResult.Failed);
                        }
                    }
                    else
                    {
                        bool flag5 = false;
                        switch (param.StorageType)
                        {
                        case 0:
                        {
                            string text = param.AsValueString();
                            if (text == null)
                            {
                                flag5 = (paramValue == null || paramValue == System.DBNull.Value);
                                goto IL_343;
                            }
                            flag5 = text.Equals(paramValue.ToString());
                            goto IL_343;
                        }

                        case (StorageType)1:
                            flag5 = param.AsInteger().Equals(System.Convert.ToInt32(paramValue));
                            goto IL_343;

                        case (StorageType)2:
                        {
                            double num  = param.AsDouble();
                            double num2 = double.NaN;
                            try
                            {
                                num2 = Unit.CovertFromAPI(param.DisplayUnitType, num);
                                double left;
                                if (double.TryParse(paramValue.ToString(), out left))
                                {
                                    flag5 = Unit.DoubleEquals(left, num2);
                                }
                                goto IL_343;
                            }
                            catch (System.InvalidCastException ex)
                            {
                                Log.WriteLine(ex);
                                Log.WriteLine(string.Concat(new object[]
                                    {
                                        "Set (",
                                        param.Definition.Name,
                                        ") to (",
                                        paramValue,
                                        ")"
                                    }));
                                Log.WriteLine("\tparamValue = " + paramValue);
                                Log.WriteLine("\tparamValue Type = " + paramValue.GetType());
                                Log.WriteLine("\tparameter value = " + base.GetParameterDdValue(param));
                                Log.WriteLine("\tparameter StorageType = " + param.StorageType);
                                Log.WriteLine("\tunitValue = " + num2);
                                Log.WriteLine("\tunitValue Type = " + num2.GetType());
                                Log.WriteLine("unitValue.Equals((Double)paramValue)");
                                Log.WriteLine("{0}.Equals((Double){1})", new object[]
                                    {
                                        num2,
                                        paramValue
                                    });
                                Log.WriteLine("\tInner exeception:" + ex);
                                Log.WriteLine("doubleValue.Equals((Double)paramValue");
                                Log.WriteLine("{0}.Equals((Double){1})", new object[]
                                    {
                                        num,
                                        paramValue
                                    });
                                throw;
                            }
                            catch (System.Exception)
                            {
                                Log.WriteLine(string.Concat(new object[]
                                    {
                                        "Set (",
                                        param.Definition.Name,
                                        ") to (",
                                        paramValue,
                                        ")"
                                    }));
                                Log.WriteLine("Element Id: " + param.Element.Id);
                                throw;
                            }
                            break;
                        }

                        case (StorageType)3:
                        {
                            string text2 = param.AsString();
                            if (text2 == null)
                            {
                                flag5 = (paramValue == null || paramValue == System.DBNull.Value);
                                goto IL_343;
                            }
                            flag5 = text2.Equals(paramValue.ToString());
                            goto IL_343;
                        }

                        case (StorageType)4:
                            break;

                        default:
                            goto IL_343;
                        }
                        flag5 = param.AsElementId().IntegerValue.Equals(System.Convert.ToInt32(paramValue));
IL_343:
                        if (flag5)
                        {
                            result = UpdateResult.Equals;
                        }
                        else if (param.IsReadOnly)
                        {
                            result = UpdateResult.ReadOnlyFailed;
                        }
                        else
                        {
                            bool flag6 = this.SetParameter(param, paramValue);
                            if (!flag6)
                            {
                                Log.WriteWarning(string.Concat(new object[]
                                {
                                    "Update Failed: Set (",
                                    param.Definition.Name,
                                    ") to (",
                                    paramValue,
                                    ")"
                                }));
                            }
                            result = (flag6 ? UpdateResult.Success : UpdateResult.Failed);
                        }
                    }
                }
            }
            catch (System.Exception arg)
            {
                Log.WriteLine("\tOutside Exception: " + arg);
                Log.WriteLine("=======");
                result = UpdateResult.Exception;
            }
            return(result);
        }
        /// <summary>
        /// Returns a string value corresponding to an ElementId Parameter.
        /// </summary>
        /// <param name="parameter">The parameter.</param>
        /// <returns>The string.</returns>
        public static string ElementIdParameterAsString(Parameter parameter)
        {
            ElementId value = parameter.AsElementId();
            if (value == ElementId.InvalidElementId)
                return null;

            string valueString = null;
            // All real elements in Revit have non-negative ids.
            if (value.IntegerValue >= 0)
            {
                // Get the family and element name.
                Element paramElement = ExporterCacheManager.Document.GetElement(value);
                valueString = (paramElement != null) ? paramElement.Name : null;
                if (!string.IsNullOrEmpty(valueString))
                {
                    ElementType paramElementType = paramElement is ElementType ? paramElement as ElementType :
                        ExporterCacheManager.Document.GetElement(paramElement.GetTypeId()) as ElementType;
                    string paramElementTypeName = (paramElementType != null) ? ExporterIFCUtils.GetFamilyName(paramElementType) : null;
                    if (!string.IsNullOrEmpty(paramElementTypeName))
                        valueString = paramElementTypeName + ": " + valueString;
                }
            }
            else 
            {
                valueString = parameter.AsValueString();
            }

            if (string.IsNullOrEmpty(valueString))
                valueString = value.ToString();

            return valueString;
        }
Exemplo n.º 7
0
        /// <summary>
        /// Extract the parameter information.
        /// By Dan Tartaglia.
        /// </summary>
        public string GetParameterInformation(
            Parameter para,
            Document doc)
        {
            string defName = "";

              // Use different method to get parameter
              // data according to the storage type

              switch( para.StorageType )
              {
            // Determine the parameter type

            case StorageType.Double:

              // Convert the number into Metric

              defName = para.AsValueString();
              break;

            case StorageType.ElementId:

              // Find out the name of the element

              Autodesk.Revit.DB.ElementId id
            = para.AsElementId();

              defName = ( id.IntegerValue >= 0 )
            ? doc.GetElement( id ).Name
            : id.IntegerValue.ToString();

              break;

            case StorageType.Integer:
              if( ParameterType.YesNo
            == para.Definition.ParameterType )
              {
            if( para.AsInteger() == 0 )
            {
              defName = "False";
            }
            else
            {
              defName = "True";
            }
              }
              else
              {
            defName = para.AsInteger().ToString();
              }
              break;

            case StorageType.String:
              defName = para.AsString();
              break;

            default:
              defName = "Unexposed parameter";
              break;
              }
              return defName;
        }
Exemplo n.º 8
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            #region TEST_1
            #if TEST_1
              //
              // you cannot create your own parameter, because the
              // constuctor is for internal use only. This is due
              // to the fact that a parameter cannot live on its own,
              // it is linked to a definition and needs to be hooked
              // up properly in the Revit database system to work
              // ... case 1245614 [Formatting units strings]:
              //
              bool iReallyWantToCrash = false;
              if( iReallyWantToCrash )
              {
            Parameter p = new Parameter();
            p.Set( 1.0 );
            string s = p.AsDouble().ToString();
            string t = p.AsValueString();
            Debug.WriteLine( "Value " + s );
            Debug.WriteLine( "Value string " + t );
              }
            #endif // TEST
              #endregion // TEST_1

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

              // Loop through all pre-selected elements:

              foreach( ElementId id in uidoc.Selection.GetElementIds() )
              {
            Element e = doc.GetElement( id );

            string s = string.Empty;

            // set this variable to false to analyse the element's own parameters,
            // i.e. instance parameters for a family instance, and set it to true
            // to analyse a family instance's type parameters:

            bool analyseTypeParameters = false;

            if( analyseTypeParameters )
            {
              if( e is FamilyInstance )
              {
            FamilyInstance inst = e as FamilyInstance;
            if( null != inst.Symbol )
            {
              e = inst.Symbol;
              s = " type";
            }
              }
              else if( e is Wall )
              {
            Wall wall = e as Wall;
            if( null != wall.WallType )
            {
              e = wall.WallType;
              s = " type";
            }
              }
              // ... add support for other types if desired ...
            }

            // Loop through and list all UI-visible element parameters

            List<string> a = new List<string>();

            #region 4.1.a Iterate over element parameters and retrieve their name, type and value:

            foreach( Parameter p in e.Parameters )
            {
              string name = p.Definition.Name;
              string type = p.StorageType.ToString();
              string value = LabUtils.GetParameterValue2( p, uidoc.Document );
              //bool read_only = p.Definition.IsReadOnly; // 2013
              bool read_only = p.IsReadOnly; // 2014
              a.Add( string.Format(
            "Name={0}; Type={1}; Value={2}; ValueString={3}; read-{4}",
            name, type, value, p.AsValueString(),
            ( read_only ? "only" : "write" ) ) );
            }

            #endregion // 4.1.a

            string what = e.Category.Name
              + " (" + e.Id.IntegerValue.ToString() + ")";

            LabUtils.InfoMsg( what + " has {0} parameter{1}{2}", a );

            // If we know which param we are looking for, then:
            // A) If a standard parameter, we can get it via BuiltInParam
            // signature of Parameter method:

            try
            {

              #region 4.1.b Retrieve a specific built-in parameter:

              Parameter p = e.get_Parameter(
            BuiltInParameter.FAMILY_BASE_LEVEL_OFFSET_PARAM );

              #endregion // 4.1.b

              if( null == p )
              {
            LabUtils.InfoMsg( "FAMILY_BASE_LEVEL_OFFSET_PARAM is NOT available for this element." );
              }
              else
              {
            string name = p.Definition.Name;
            string type = p.StorageType.ToString();
            string value = LabUtils.GetParameterValue2( p, doc );
            LabUtils.InfoMsg( "FAMILY_BASE_LEVEL_OFFSET_PARAM: Name=" + name
              + "; Type=" + type + "; Value=" + value );
              }
            }
            catch( Exception )
            {
              LabUtils.InfoMsg( "FAMILY_BASE_LEVEL_OFFSET_PARAM is NOT available for this element." );
            }

            // B) For a shared parameter, we can get it via "GUID" signature
            // of Parameter method  ... this will be shown later in Labs 4 ...

            // C) or we can get the parameter by name:
            // alternatively, loop through all parameters and
            // search for the name (this works for either
            // standard or shared). Note that the same name
            // may occur multiple times:

            const string paramName = "Base Offset";

            //Parameter parByName = e.get_Parameter( paramName ); // 2014

            IList<Parameter> paramsByName = e.GetParameters( paramName ); // 2015

            if( 0 == paramsByName.Count )
            {
              LabUtils.InfoMsg( paramName + " is NOT available for this element." );
            }
            else foreach( Parameter p in paramsByName )
              {
            string parByNameName = p.Definition.Name;
            string parByNameType = p.StorageType.ToString();
            string parByNameValue = LabUtils.GetParameterValue2( p, doc );
            LabUtils.InfoMsg( paramName + ": Name=" + parByNameName
              + "; Type=" + parByNameType + "; Value=" + parByNameValue );
              }

            #region TEST_2
            #if TEST_2
            List<string> a = GetParameters( doc, e );
            foreach( string s2 in a )
            {
              Debug.WriteLine( s2 );
            }
            #endif // TEST_2
            #endregion // TEST_2

              }
              return Result.Failed;
        }
Exemplo n.º 9
0
        public Result ExecuteObsolete(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app   = commandData.Application;
            UIDocument    uidoc = app.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            BindingMap bindings = doc.ParameterBindings;
            //Dictionary<string, Guid> guids = new Dictionary<string, Guid>();
            Dictionary <Definition, object> mapDefToGuid = new Dictionary <Definition, object>();

            int n = bindings.Size;

            Debug.Print("{0} shared parementer{1} defined{2}",
                        n, Util.PluralSuffix(n), Util.DotOrColon(n));

            if (0 < n)
            {
                DefinitionBindingMapIterator it
                    = bindings.ForwardIterator();

                while (it.MoveNext())
                {
                    Definition d = it.Key as Definition;
                    Binding    b = it.Current as Binding;
                    if (d is ExternalDefinition)
                    {
                        Guid g = ((ExternalDefinition)d).GUID;
                        Debug.Print(d.Name + ": " + g.ToString());
                        mapDefToGuid.Add(d, g);
                    }
                    else
                    {
                        Debug.Assert(d is InternalDefinition);

                        // this built-in parameter is INVALID:

                        BuiltInParameter bip = ((InternalDefinition)d).BuiltInParameter;
                        Debug.Print(d.Name + ": " + bip.ToString());

                        // if have a definition file and group name, we can still determine the GUID:

                        //Guid g = SharedParamGuid( app, "Identity data", d.Name );

                        mapDefToGuid.Add(d, null);
                    }
                }
            }

            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.";
            }
            else
            {
                //List<string> keys = new List<string>( mapDefToGuid.Keys );
                //keys.Sort();

                foreach (Wall wall in walls)
                {
                    Debug.Print(Util.ElementDescription(wall));

                    foreach (Definition d in mapDefToGuid.Keys)
                    {
                        object o = mapDefToGuid[d];

                        Parameter p = (null == o)
            ? wall.get_Parameter(d)
            : wall.get_Parameter((Guid)o);

                        string s = (null == p)
            ? "<null>"
            : p.AsValueString();

                        Debug.Print(d.Name + ": " + s);
                    }
                }
            }
            return(Result.Failed);
        }
Exemplo n.º 10
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIDocument uiDoc = commandData.Application.ActiveUIDocument;
            Document   doc   = uiDoc.Document;
            Selection  sel   = uiDoc.Selection;

            try {
                bool stay = true;
                while (stay)
                {
                    CeilingSelectionFilter cf = new CeilingSelectionFilter();
                    /// Unable to pick either an active file ceiling and linked file ceiling with PickObject
                    Reference pickedCeilingRef = sel.PickObject(ObjectType.LinkedElement, cf, "Selecting Linked Ceilings Only");

                    //#region Dealing with non linked picks
                    //Reference pickedCeilingRefNL = sel.PickObject(ObjectType.Element, cf, "Selecting Nonlinked Ceilings Only");
                    //Element firstCeilingElement = doc.GetElement(pickedCeilingRefNL.ElementId);
                    //#endregion

                    #region Dealing with Linked picks
                    if (pickedCeilingRef == null)
                    {
                        return(Result.Failed);
                    }
                    // we need to get the linked document and then get the element that was picked from the LinkedElementId
                    RevitLinkInstance linkInstance        = doc.GetElement(pickedCeilingRef) as RevitLinkInstance;
                    Document          linkedDoc           = linkInstance.GetLinkDocument();
                    Element           firstCeilingElement = linkedDoc.GetElement(pickedCeilingRef.LinkedElementId);
                    #endregion

                    string daRmName     = "";
                    string daHT         = "";
                    string daLV         = "";
                    string daPhsCreated = "";
                    string daPhsDemo    = "";

                    switch (firstCeilingElement.GetType().ToString())
                    {
                    case "Autodesk.Revit.DB.Architecture.Room":
                        Room thisPickRm = firstCeilingElement as Room;
                        if (thisPickRm != null)
                        {
                            daRmName = thisPickRm.Name.ToString();
                            Phase phCR = linkedDoc.GetElement(thisPickRm.CreatedPhaseId) as Phase;
                            if (phCR != null)
                            {
                                daPhsCreated = phCR.ToString();
                            }
                            Level itsLevelRm = thisPickRm.Level;
                            if (itsLevelRm != null)
                            {
                                daLV = itsLevelRm.Name.ToString();
                            }
                        }
                        break;

                    case "Autodesk.Revit.DB.Ceiling":
                        Ceiling   thisPickCl   = firstCeilingElement as Ceiling;
                        Parameter itsRoomparam = thisPickCl.get_Parameter(BuiltInParameter.ROOM_NAME);
                        if (itsRoomparam != null)
                        {
                            daRmName = itsRoomparam.AsValueString();
                        }
                        Parameter daHTparam = thisPickCl.get_Parameter(BuiltInParameter.CEILING_HEIGHTABOVELEVEL_PARAM);
                        if (daHTparam != null)
                        {
                            daHT = daHTparam.AsValueString();
                        }
                        Parameter itsLevelCl = thisPickCl.get_Parameter(BuiltInParameter.LEVEL_PARAM);
                        if (itsLevelCl != null)
                        {
                            daLV = itsLevelCl.AsValueString();
                        }
                        Parameter whenCreated = thisPickCl.get_Parameter(BuiltInParameter.PHASE_CREATED);
                        if (whenCreated != null)
                        {
                            daPhsCreated = whenCreated.AsValueString();
                        }
                        break;

                    default:
                        break;
                    }

                    TaskDialog thisDialog = new TaskDialog("Ceiling Pick-O-Matic");
                    thisDialog.TitleAutoPrefix = false;
                    thisDialog.MainIcon        = TaskDialogIcon.TaskDialogIconNone;
                    thisDialog.CommonButtons   = TaskDialogCommonButtons.Close | TaskDialogCommonButtons.Retry;
                    thisDialog.DefaultButton   = TaskDialogResult.Retry;
                    thisDialog.FooterText      = "Hitting Escape allows picking again.";

                    //TaskDialog.Show("Ceiling Picker Says",
                    //                 firstCeilingElement.Category.Name + "\n" + firstCeilingElement.Name + "\n" +
                    //                 daHT);
                    string msg = firstCeilingElement.Name + "\n" + daHT + " from " + daLV;
                    msg = msg + "\n" + daPhsCreated + " that is " + daPhsDemo + "\n" + "Room Name: " + daRmName;

                    thisDialog.MainInstruction = msg;
                    thisDialog.MainContent     = "";
                    TaskDialogResult tResult = thisDialog.Show();

                    if (TaskDialogResult.Close == tResult)
                    {
                        stay = false;
                    }
                }
                return(Result.Succeeded);
            } catch (Autodesk.Revit.Exceptions.OperationCanceledException) {
                //TaskDialog.Show("Cancelled", "User cancelled");
                return(Result.Cancelled);
            }
            //Catch other errors
            catch (Exception ex) {
                TaskDialog.Show("Error", ex.Message);
                return(Result.Failed);
            }
        }
Exemplo n.º 11
0
        /***************************************************/

        public static bool SetParameter(this Parameter parameter, object value, Document document = null)
        {
            // Skip null and read-only parameters
            if (parameter == null || parameter.IsReadOnly)
            {
                return(false);
            }

            // Workset parameters
            // Filter for worksets
            if (parameter.Id.IntegerValue == (int)BuiltInParameter.ELEM_PARTITION_PARAM)
            {
                // Find an existing workset with a specified name if it exists
                string  worksetName = value as string;
                Workset workset     = document.Workset(worksetName);

                // Set the "Workset" parameter to the specified existing workset
                // Ensure the Query method hasn't returned a null, which can happen if the document is not workshared or the workset name is empty
                if (workset != null)
                {
                    // Set the parameter to a workset with the specified name if it exists
                    return(parameter.Set(workset.Id.IntegerValue));
                }
                else
                {
                    // A workset with the specified name doesn't exist
                    BH.Engine.Reflection.Compute.RecordWarning("Cannot set the Workset parameter because a workset with the specified name doesn't exist.");
                    return(false);
                }
            }

            switch (parameter.StorageType)
            {
            case StorageType.Double:
            {
                double dbl = double.NaN;

                if (value is double)
                {
                    dbl = (double)value;
                }
                else if (value is int || value is byte || value is float || value is long)
                {
                    dbl = System.Convert.ToDouble(value);
                }
                else if (value is bool)
                {
                    if ((bool)value)
                    {
                        dbl = 1.0;
                    }
                    else
                    {
                        dbl = 0.0;
                    }
                }
                else if (value is string)
                {
                    if (!double.TryParse((string)value, out dbl))
                    {
                        dbl = double.NaN;
                    }
                }

                if (!double.IsNaN(dbl))
                {
                    try
                    {
                        dbl = Convert.FromSI(dbl, parameter.Definition.UnitType);
                    }
                    catch
                    {
                        dbl = double.NaN;
                    }

                    if (!double.IsNaN(dbl))
                    {
                        if (parameter.Id.IntegerValue == (int)BuiltInParameter.STRUCTURAL_BEND_DIR_ANGLE)
                        {
                            dbl = dbl.NormalizeAngleDomain();
                        }

                        return(parameter.Set(dbl));
                    }
                }
                break;
            }

            case StorageType.ElementId:
            {
                ElementId elementID = null;

                if (value is int)
                {
                    elementID = new ElementId((int)value);
                }
                else if (value is string)
                {
                    int num;
                    if (int.TryParse((string)value, out num))
                    {
                        elementID = new ElementId(num);
                    }
                }
                else if (value is IBHoMObject)
                {
                    elementID = (value as IBHoMObject).ElementId();
                }
                else if (value != null)
                {
                    int num;
                    if (int.TryParse(value.ToString(), out num))
                    {
                        elementID = new ElementId(num);
                    }
                }

                if (elementID != null)
                {
                    bool exists = false;
                    if (elementID == ElementId.InvalidElementId)
                    {
                        exists = true;
                    }

                    if (!exists)
                    {
                        if (document == null)
                        {
                            exists = true;
                        }
                        else
                        {
                            Element element = document.GetElement(elementID);
                            exists = element != null;
                        }
                    }

                    if (exists)
                    {
                        return(parameter.Set(elementID));
                    }
                }
                break;
            }

            case StorageType.Integer:
            {
                if (value is int)
                {
                    return(parameter.Set((int)value));
                }
                else if (value is sbyte || value is byte || value is short || value is ushort || value is int || value is uint || value is long || value is ulong || value is float || value is double || value is decimal)
                {
                    parameter.Set(System.Convert.ToInt32(value));
                }
                else if (value is bool)
                {
                    if ((bool)value)
                    {
                        return(parameter.Set(1));
                    }
                    else
                    {
                        return(parameter.Set(0));
                    }
                }
                else if (value is string)
                {
                    string valueString = (string)value;
                    int    num         = 0;
                    if (int.TryParse(valueString, out num))
                    {
                        return(parameter.Set(num));
                    }

                    if (parameter.HasValue && parameter.Definition.ParameterType == ParameterType.Invalid)
                    {
                        string val = parameter.AsValueString();
                        if (val == valueString)
                        {
                            break;
                        }

                        int current = parameter.AsInteger();
                        int k       = 0;

                        string before = null;
                        while (before != val)
                        {
                            if (k == current)
                            {
                                k++;
                                continue;
                            }

                            try
                            {
                                before = val;

                                parameter.Set(k);
                                val = parameter.AsValueString();
                                if (val == valueString)
                                {
                                    return(true);
                                }

                                k++;
                            }
                            catch
                            {
                                break;
                            }
                        }

                        parameter.Set(current);
                    }
                }
                break;
            }

            case StorageType.String:
            {
                if (value == null)
                {
                    return(parameter.Set(value as string));
                }
                else if (value is string)
                {
                    return(parameter.Set((string)value));
                }
                else
                {
                    return(parameter.Set(value.ToString()));
                }
            }
            }

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

            FilteredElementCollector collector = new FilteredElementCollector(doc);
            ElementCategoryFilter    filter    = new ElementCategoryFilter(BuiltInCategory.OST_Rebar);
            IList <Element>          bars      = collector.WherePasses(filter).WhereElementIsNotElementType().ToElements();

            try
            {
                //check
                if (bars.Count == 0)
                {
                    TaskDialog.Show("Warning!", "No bars in the current document!");
                    return(Result.Cancelled);
                }
                else
                {
                    foreach (Element e in bars)
                    {
                        Parameter len  = e.LookupParameter("L");
                        Parameter dia  = e.LookupParameter("ØАрматуры");
                        Parameter name = e.LookupParameter("Наименование");

                        using (Transaction trans = new Transaction(doc, "Set Valid Names"))
                        {
                            trans.Start();
                            name.Set(string.Format("Ø{0}, L={1}", dia.AsValueString(), len.AsValueString()));
                            trans.Commit();
                        }
                    }
                    TaskDialog.Show("Assign names in Document.",
                                    string.Format("{0} bars found in the current document. Valid names assigned.", bars.Count));

                    return(Result.Succeeded);
                }
            }
            catch (Exception e)
            {
                message = e.Message;
                return(Result.Failed);
            }
        }
Exemplo n.º 13
0
        private void UpdatePluntData(List <FamilyInstance> allPlunts, ref List <FamilyInstance> failedPlunts)
        {
            const int upperZoneHeight = 1800;

            UI.ProgressBar pBar = new UI.ProgressBar("Назначение расхода", allPlunts.Count);
            foreach (FamilyInstance plunt in allPlunts)
            {
                try
                {
                    // Параметр номера помещения
                    Parameter spaceNumberParam = plunt.LookupParameter(spaceNumberParameterName);
                    // Параметр Расход воздуха
                    Parameter airflowParam = plunt.LookupParameter(airflowParameterName);
                    // Параметр "Классификация системы"
                    BuiltInParameter sysTypeBuiltIn  = BuiltInParameter.RBS_DUCT_SYSTEM_TYPE_PARAM;
                    Parameter        systemTypeParam = plunt.get_Parameter(sysTypeBuiltIn);
                    string           systemType      = systemTypeParam.AsValueString();
                    // Считаем количество диффузоров одной системы на пространство
                    int countUpperZone = (from d in allPlunts
                                          where d.LookupParameter(spaceNumberParameterName).AsString() == spaceNumberParam.AsString() &&
                                          d.get_Parameter(sysTypeBuiltIn).AsValueString() == systemType &&
                                          UnitUtils.ConvertFromInternalUnits(d.get_Parameter(BuiltInParameter.INSTANCE_FREE_HOST_OFFSET_PARAM).AsDouble(), DisplayUnitType.DUT_MILLIMETERS) >= upperZoneHeight
                                          select d).Count();
                    int countBottomZone = (from d in allPlunts
                                           where d.LookupParameter(spaceNumberParameterName).AsString() == spaceNumberParam.AsString() &&
                                           d.get_Parameter(sysTypeBuiltIn).AsValueString() == systemType &&
                                           UnitUtils.ConvertFromInternalUnits(d.get_Parameter(BuiltInParameter.INSTANCE_FREE_HOST_OFFSET_PARAM).AsDouble(), DisplayUnitType.DUT_MILLIMETERS) < upperZoneHeight
                                           select d).Count();
                    // Смещение
                    bool isInUpperZone = UnitUtils.ConvertFromInternalUnits(plunt.get_Parameter(BuiltInParameter.INSTANCE_FREE_HOST_OFFSET_PARAM).AsDouble(), DisplayUnitType.DUT_MILLIMETERS) >= upperZoneHeight;

                    // Находим пространство, в котором находится диффузор и достаем нужные значения
                    Space space = GetSpaceOfPlant(plunt);
                    if (space != null)
                    {
                        // Задаем расход диффузорам
                        double value = 0;
                        if (systemType == suplySystemTypeName)
                        {
                            value = space.get_Parameter(BuiltInParameter.ROOM_DESIGN_SUPPLY_AIRFLOW_PARAM).AsDouble();
                        }
                        else if (systemType == exhaustSystemTypeName)
                        {
                            value = space.get_Parameter(BuiltInParameter.ROOM_DESIGN_EXHAUST_AIRFLOW_PARAM).AsDouble();
                        }

                        // делим на количество диффузоров нужной системы, расположенных в одной вертикальной зоне
                        if (countUpperZone == 0 || countBottomZone == 0)
                        {
                            value = countUpperZone != 0 ? value / countUpperZone : value / countBottomZone;
                        }
                        else
                        {
                            value = isInUpperZone ? value / countUpperZone : value / countBottomZone;
                        }
                        airflowParam.Set(value);
                    }
                }
                catch
                {
                    failedPlunts.Add(plunt);
                }
                finally
                {
                    pBar.StepUp();
                }
            }
            pBar.Close();
        }
Exemplo n.º 14
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document   doc   = commandData.Application.ActiveUIDocument.Document;

            //get activeview
            View activeview = uidoc.ActiveView;

            if (!(activeview is ViewPlan))
            {
                TaskDialog.Show("wrong", "仅支持在平面内运行"); return(Result.Failed);
            }

            //get type
            FilteredElementCollector typecollector = new FilteredElementCollector(doc);

            typecollector.OfClass(typeof(SpotDimensionType));
            SpotDimensionType type = null;

            foreach (Element ele in typecollector)
            {
                SpotDimensionType tmp = ele as SpotDimensionType;
                if (tmp == null)
                {
                    continue;
                }
                if (tmp.Name == "A-LEVL-SLAB-2.5")
                {
                    type = tmp; break;
                }
            }
            if (type == null)
            {
                TaskDialog.Show("GOA", "未找到<A-LEVL-SLAB-2.5>类型."); return(Result.Failed);
            }

            List <SpotDimension> allsds = new List <SpotDimension>();
            string report = " ";

            //transaction
            using (Transaction transaction1 = new Transaction(doc))
            {
                transaction1.Start("creat elevation");
                //get floor
                FilteredElementCollector collector = new FilteredElementCollector(doc, activeview.Id);
                collector.OfCategory(BuiltInCategory.OST_Floors).WhereElementIsNotElementType();
                List <ElementId> floorids = collector.ToElementIds().ToList();
                allsds.AddRange(CreatSpotDimensionOnFloor(floorids, activeview, doc, ref report));
                transaction1.Commit();
            }

            using (Transaction transaction2 = new Transaction(doc))
            {
                transaction2.Start("creat elevation in link");
                FilteredElementCollector linkcollector = new FilteredElementCollector(doc);
                linkcollector.OfCategory(BuiltInCategory.OST_RvtLinks).WhereElementIsNotElementType();
                if (linkcollector != null && linkcollector.Count() != 0)
                {
                    foreach (RevitLinkInstance rli in linkcollector)
                    {
                        if (rli == null)
                        {
                            continue;
                        }
                        FilteredElementCollector floorcollector = new FilteredElementCollector(rli.GetLinkDocument());
                        floorcollector.OfCategory(BuiltInCategory.OST_Floors).WhereElementIsNotElementType();
                        if (floorcollector == null || floorcollector.Count() == 0)
                        {
                            continue;
                        }
                        List <ElementId> floorids = floorcollector.ToElementIds().ToList();
                        allsds.AddRange(CreatSpotDimensionOnFloorInLink(floorids, activeview, doc, rli, ref report));
                    }
                }
                transaction2.Commit();
            }

            using (Transaction transaction3 = new Transaction(doc))
            {
                transaction3.Start("±");
                foreach (SpotDimension sd in allsds)
                {
                    //set type and ±
                    sd.ChangeTypeId(type.Id);
                    Parameter para  = sd.get_Parameter(BuiltInParameter.SPOT_ELEV_SINGLE_OR_UPPER_VALUE);
                    Parameter para2 = sd.get_Parameter(BuiltInParameter.SPOT_ELEV_SINGLE_OR_UPPER_PREFIX);
                    if (para.AsValueString() == "0")
                    {
                        para2.Set("±");
                    }
                    Parameter para3 = sd.get_Parameter(BuiltInParameter.SPOT_ELEV_DISPLAY_ELEVATIONS);
                    para3.Set(3);
                }
                uidoc.RefreshActiveView();
                transaction3.Commit();
            }

            TaskDialog.Show("report", report);
            return(Result.Succeeded);
        }
Exemplo n.º 15
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Debug.Listeners.Clear();
            Debug.Listeners.Add(new RbsLogger.Logger("PropertiesCopy"));

            Document  doc = commandData.Application.ActiveUIDocument.Document;
            Selection sel = commandData.Application.ActiveUIDocument.Selection;
            Element   firstElem;

            List <ElementId> selIds = sel.GetElementIds().ToList();

            Debug.WriteLine("Selected elements: " + selIds.Count.ToString());
            if (selIds.Count > 0)
            {
                firstElem = doc.GetElement(selIds.First());
            }
            else
            {
                Reference r1;
                try
                {
                    r1 = sel.PickObject(ObjectType.Element, "Выберите элемент, с которого нужно скопировать свойства");
                }
                catch
                {
                    return(Result.Cancelled);
                }

                firstElem = doc.GetElement(r1.ElementId);
                Debug.WriteLine("First elem id: " + firstElem.Id.IntegerValue.ToString());
            }

            if (firstElem == null)
            {
                message += "Что-то не получилось. Сохраняйте спокойствие и порядок!";
                Debug.WriteLine("First elem is null");
                return(Result.Failed);
            }

            ParameterMap parameters = firstElem.ParametersMap;

            Debug.WriteLine("Parameters found: " + parameters.Size.ToString());

            while (true)
            {
                try
                {
                    SelectionFilter selFilter = new SelectionFilter(firstElem);
                    Reference       r         = sel.PickObject(ObjectType.Element, selFilter, "Выберите элементы для копирования свойств");
                    if (r == null)
                    {
                        continue;
                    }
                    ElementId curId = r.ElementId;
                    if (curId == null || curId == ElementId.InvalidElementId)
                    {
                        continue;
                    }
                    Element curElem = doc.GetElement(curId);
                    if (curElem == null)
                    {
                        continue;
                    }
                    Debug.WriteLine("Cur element id: " + curId.IntegerValue.ToString());

                    try
                    {
                        ElementId firstTypeId = firstElem.GetTypeId();
                        ElementId curTypeId   = curElem.GetTypeId();
                        if (firstTypeId != curTypeId)
                        {
                            using (Transaction t1 = new Transaction(doc))
                            {
                                t1.Start("Назначение типа");

                                curElem.get_Parameter(BuiltInParameter.ELEM_TYPE_PARAM).Set(firstTypeId);

                                t1.Commit();
                                Debug.WriteLine("Type of element is changed");
                            }
                        }
                    }
                    catch { }


                    using (Transaction t = new Transaction(doc))
                    {
                        t.Start("Копирование свойств");

                        foreach (Parameter param in parameters)
                        {
                            if (param == null)
                            {
                                continue;
                            }
                            if (!param.HasValue)
                            {
                                continue;
                            }
                            try
                            {
                                Parameter curParam = curElem.get_Parameter(param.Definition);

                                switch (param.StorageType)
                                {
                                case StorageType.None:
                                    break;

                                case StorageType.Integer:
                                    curParam.Set(param.AsInteger());
                                    break;

                                case StorageType.Double:
                                    curParam.Set(param.AsDouble());
                                    break;

                                case StorageType.String:
                                    curParam.Set(param.AsString());
                                    break;

                                case StorageType.ElementId:
                                    curParam.Set(param.AsElementId());
                                    break;

                                default:
                                    break;
                                }
                                Debug.WriteLine("Param value is written: " + curParam.Definition.Name + " = " + curParam.AsValueString());
                            }
                            catch (Exception ex)
                            {
                                Debug.WriteLine(ex.Message);
                                continue;
                            }
                        }
                        t.Commit();
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                    return(Result.Succeeded);
                }
            }
            Debug.WriteLine("All done");
        }
Exemplo n.º 16
0
        public void Execute(UpdaterData data)
        {
            try
            {
                Document            doc          = data.GetDocument();
                MonitorProjectSetup projectSetup = ProjectSetupDataStroageUtil.GetProjectSetup(doc);
                if (data.GetModifiedElementIds().Count > 0)
                {
                    ElementId      doorId       = data.GetModifiedElementIds().First();
                    FamilyInstance doorInstance = doc.GetElement(doorId) as FamilyInstance;
                    if (null != doorInstance)
                    {
#if RELEASE2013 || RELEASE2014
                        Parameter pushParameter = doorInstance.get_Parameter(pushParamName);
#elif RELEASE2015 || RELEASE2016 || RELEASE2017
                        Parameter pushParameter = doorInstance.LookupParameter(pushParamName);
#endif

                        if (null != pushParameter)
                        {
                            if (data.IsChangeTriggered(doorId, Element.GetChangeTypeParameter(pushParameter)))
                            {
                                string pushValue = pushParameter.AsValueString();
                                if (!pushValue.Contains("Approach"))
                                {
                                    AppCommand.Instance.IsDoorFail    = true;
                                    AppCommand.Instance.FailingDoorId = doorId;
                                    DialogResult dr = MessageBox.Show(pushValue + " is not a correct value for the parameter " + pushParamName, "Invalid Door Parameter.", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                }
                            }
                        }
#if RELEASE2013 || RELEASE2014
                        Parameter pullParameter = doorInstance.get_Parameter(pullParamName);
#elif RELEASE2015 || RELEASE2016 || RELEASE2017
                        Parameter pullParameter = doorInstance.LookupParameter(pullParamName);
#endif

                        if (null != pullParameter)
                        {
                            if (data.IsChangeTriggered(doorId, Element.GetChangeTypeParameter(pullParameter)))
                            {
                                string pullValue = pullParameter.AsValueString();
                                if (!pullValue.Contains("Approach"))
                                {
                                    AppCommand.Instance.IsDoorFail    = true;
                                    AppCommand.Instance.FailingDoorId = doorId;
                                    DialogResult dr = MessageBox.Show(pullValue + " is not a correct value for the parameter " + pullParamName, "Invalid Door Parameter.", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                }
                            }
                        }

#if RELEASE2013 || RELEASE2014
                        Parameter caParameter = doorInstance.get_Parameter(stateCAParamName);
#elif RELEASE2015 || RELEASE2016 || RELEASE2017
                        Parameter caParameter = doorInstance.LookupParameter(stateCAParamName);
#endif
                        if (null != caParameter)
                        {
                            if (data.IsChangeTriggered(doorId, Element.GetChangeTypeParameter(caParameter)))
                            {
                                int caValue    = caParameter.AsInteger();
                                int projectVal = Convert.ToInt32(projectSetup.IsStateCA);
                                if (caValue != projectVal)
                                {
                                    caParameter.Set(projectVal);
                                }
                            }
                        }
                    }
                }
                else if (data.GetAddedElementIds().Count > 0)
                {
                    ElementId      doorId       = data.GetAddedElementIds().First();
                    FamilyInstance doorInstance = doc.GetElement(doorId) as FamilyInstance;
                    if (null != doorInstance)
                    {
#if RELEASE2013 || RELEASE2014
                        Parameter caParameter = doorInstance.get_Parameter(stateCAParamName);
#elif RELEASE2015 || RELEASE2016 || RELEASE2017
                        Parameter caParameter = doorInstance.LookupParameter(stateCAParamName);
#endif
                        if (null != caParameter)
                        {
                            int caValue    = caParameter.AsInteger();
                            int projectVal = Convert.ToInt32(projectSetup.IsStateCA);
                            if (caValue != projectVal)
                            {
                                caParameter.Set(projectVal);//default value 1
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to execute the door updater.\n" + ex.Message, "DoorUpdater:Execute", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        private void btn_flash_Click(object sender, EventArgs e)
        {
            //this.dataGridView1.Rows.Clear();
            //this.dgv_FamilyAndXls.Rows.Clear();
            this.dataGridView1.DataSource = null;
            //codt = null;

            string SearchCondition = txt_condition.Text;    //实例名称筛选条件
            string paraCondition   = txt_paracond.Text;     //参数筛选条件

            string[] SearchConditions = null;
            string[] paraConditions   = null;

            #region 分割查找条件
            //分割实例名称查找条件
            if (SearchCondition.Contains(','))
            {
                SearchConditions = SearchCondition.Split(',');
            }
            else if (SearchCondition.Contains(','))
            {
                SearchConditions = SearchCondition.Split(',');
            }
            else
            {
                SearchConditions = SearchCondition.Split(' ');
            }
            //参数筛选条件
            if (paraCondition.Contains(','))
            {
                paraConditions = paraCondition.Split(',');
            }
            else if (paraCondition.Contains(','))
            {
                paraConditions = paraCondition.Split(',');
            }
            else
            {
                paraConditions = paraCondition.Split(' ');
            }

            #endregion

            //根据条件初始化dataset的列名
            codt.Columns.Add("实例名称", typeof(String));
            foreach (string cond in paraConditions)
            {
                codt.Columns.Add(cond, typeof(String));
            }

            //显示实例名称筛选的项
            //int codtCount = 0;
            for (int k = 0; k < fidt.Rows.Count; k++)
            {
                int cont = 0;
                foreach (string cond in SearchConditions)
                {
                    if (fidt.Rows[k]["实例名称"].ToString().Contains(cond))
                    {
                        cont++;
                    }
                    else
                    {
                        cont = 0;
                        break;
                    }
                }

                if (cont != 0)
                {
                    //codt.Rows.Add(fidt.Rows[k].ItemArray);

                    //DataRow row = codt.NewRow();
                    //row.ItemArray = fidt.Rows[k].ItemArray ;
                    //fidt.Rows.InsertAt(row, codtCount);
                    //codtCount++;
                    //codtCount++;
                    //codt.Rows.Add();
                    //codt.Rows[codtCount]["实例名称"] = fidt.Rows[k];
                    //codt.Rows[codtCount]["选定参数值"] = fidt.Rows[k];

                    //int index = this.dgv_FamilyAndXls.Rows.Add();
                    //this.dgv_FamilyAndXls.Rows[index].Cells["dgv_fName"].Value = fidt.Rows[k]["实例名称"];
                    //this.dgv_FamilyAndXls.Rows[index].Cells["dgv_fPath"].Value = fidt.Rows[k]["选定参数值"];
                    //this.dgv_FamilyAndXls.DataSource = fidt;

                    continue;
                }
                else if (cont == 0)
                {
                    fidt.Rows[k].Delete();
                    continue;
                }
            }
            fidt.AcceptChanges();

            int indexCodt = 0;
            for (int j = 0; j < fidt.Rows.Count; j++)
            {
                for (int ii = 0; ii < filteredList.Count(); ii++)
                {
                    if (fidt.Rows[j]["实例名称"].ToString() == filteredList[ii].Name)
                    {
                        codt.Rows.Add();
                        codt.Rows[indexCodt]["实例名称"] = filteredList[ii].Name;

                        foreach (string cond in paraConditions)
                        {
                            Parameter para = filteredList[ii].LookupParameter(cond);
                            if (para != null)
                            {
                                string parav = para.AsValueString();
                                codt.Rows[indexCodt][cond] = parav;
                            }
                            else
                            {
                                //codt.Rows[indexCodt][cond] = "0";
                            }
                        }
                        indexCodt++;
                    }
                }
            }

            //this.dgv_FamilyAndXls.DataSource = codt;
            this.dataGridView1.DataSource = codt;

            //foreach (string cond in paraConditions)
            //{
            //    this.listView1.Columns.Add(cond,50);
            //    var item = new ListViewItem();
            //    item.SubItems.Add(cond);
            //    item.SubItems[0].Text = dgvColumnSum(dataGridView1, cond).ToString();
            //    listView1.Items.Add(item);
            //}
            dataGridView2.Rows.Clear();
            foreach (string cond in paraConditions)
            {
                this.dataGridView2.Columns.Add(cond, cond);
                this.dataGridView2.Rows[0].Cells[cond].Value = dgvColumnSum(dataGridView1, cond).ToString();
            }

            //double sum = 0;
            //int indexR = this.dgv_FamilyAndXls.Rows.Add();
            //foreach (string cond in SearchConditions)
            //{
            //    decimal sumd = dgvColumnSum(dataGridView1, cond);
            //    this.dgv_FamilyAndXls.Rows[indexR].Cells[cond].Value = sumd.ToString();
            //}

            //for (int j = 0; j < codt.Rows.Count; j++)
            //{
            //    if (codt.Rows[j]["fiNamex"] != null)
            //    {
            //        sum = sum + Convert.ToDouble( codt.Rows[j]["fiNamex"] );
            //        sum = sum + Convert.ToDouble(this.dgv_FamilyAndXls.Rows[j].Cells["dgv_fPath"].Value);
            //    }
            //}

            //for (int j = 0; j < dgv_FamilyAndXls.Rows.Count; j++)
            //{
            //    if (this.dgv_FamilyAndXls.Rows[j].Cells["dgv_fPath"] != null)
            //    {
            //        //sum = sum + Convert.ToDouble(codt.Rows[j]["fiNamex"]);
            //        sum = sum + Convert.ToDouble(this.dgv_FamilyAndXls.Rows[j].Cells["dgv_fPath"].Value);
            //    }
            //}

            //lbl_all.Text = sum.ToString();
            //txt_all.Text = sum.ToString();
        }
Exemplo n.º 18
0
Arquivo: Para.cs Projeto: AMEE/revit
 // jeremy
 //public static Object GetParameterValue(Parameter parameter) // jeremy
 /// <summary>
 /// get parameter's value
 /// </summary>
 /// <param name="parameter">parameter of Element</param>
 /// <returns>parameter's value include unit if have</returns>
 public static string GetParameterValue(Parameter parameter)
 {
     switch (parameter.StorageType)
     {
         case StorageType.Double:
             //get value with unit, AsDouble() can get value without unit
             return parameter.AsValueString();
         case StorageType.ElementId:
             return parameter.AsElementId().IntegerValue.ToString();
         case StorageType.Integer:
             //get value with unit, AsInteger() can get value without unit
             return parameter.AsValueString();
         case StorageType.None:
             return parameter.AsValueString();
         case StorageType.String:
             return parameter.AsString();
         default:
             return "";
     }
 }
Exemplo n.º 19
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;

            try {
                StringBuilder sb = new StringBuilder();


                string inputFile = @"C:\Temp\RevitSettings.csv";

                Dictionary <string, List <string> > settings = Helpers.GetSettings(inputFile);


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

                ICollection <ViewSheet> selectedSheets = new List <ViewSheet>();

                foreach (var eid in selectedElementsId)
                {
                    selectedSheets.Add(doc.GetElement(eid) as ViewSheet);
                }

                TaskDialog.Show("r", selectedElementsId.Count.ToString() + " selected");

                uidoc.ActiveView = uidoc.ActiveGraphicalView;

                var sortedList = selectedSheets.OrderBy(pd => pd.SheetNumber);

                string headers = "Viewport Id, View type, View Name, Viewport Title, View PosX,View PosY,View PosZ,";


                foreach (ViewSheet vs in sortedList)
                {
                    ICollection <ElementId> viewports = vs.GetAllViewports();

                    foreach (var vpid in viewports)
                    {
                        Viewport vport = doc.GetElement(vpid) as Viewport;
                        View     view  = doc.GetElement(vport.ViewId) as View;

                        string viewType     = view.ViewType.ToString();
                        string viewName     = view.Name;
                        string viewPosition = vport.GetBoxCenter().ToString().Remove(0, 1).TrimEnd(')');
                        string type         = vport.Name;

                        string csvLine = $"{vpid},{viewType},{viewName},{type},{viewPosition},";

                        List <string> parameters = new List <string>();
                        if (settings.TryGetValue(vport.Category.Name, out parameters))
                        {
                            foreach (string s in parameters)
                            {
                                if (!headers.Contains(s))
                                {
                                    headers += s + ",";
                                }

                                string paramValue = "";

                                try
                                {
                                    Parameter p = vport.LookupParameter(s.Trim());

                                    StorageType parameterType = p.StorageType;

                                    if (StorageType.Double == parameterType)
                                    {
                                        paramValue = UnitUtils.ConvertFromInternalUnits(p.AsDouble(), DisplayUnitType.DUT_MILLIMETERS).ToString();
                                    }
                                    else if (StorageType.String == parameterType)
                                    {
                                        paramValue = p.AsString();
                                    }
                                    else if (StorageType.Integer == parameterType)
                                    {
                                        paramValue = p.AsInteger().ToString();
                                    }
                                    else if (StorageType.ElementId == parameterType)
                                    {
                                        paramValue = p.AsValueString();
                                    }
                                }
                                catch
                                {
                                    paramValue = s;
                                }
                                csvLine += paramValue + ",";
                            }
                        }

                        sb.AppendLine(String.Format("{0}", csvLine));
                    }
                }

                string outputFile = @"C:\Temp\ExportedData.csv";


                //			var sortedList = selectedSheets.OrderBy(pd => pd.SheetNumber);



                File.WriteAllText(outputFile, headers + "\n");


                File.AppendAllText(outputFile, sb.ToString());

                System.Diagnostics.Process process = new System.Diagnostics.Process();
                process.StartInfo.FileName = outputFile;
                process.Start();

                return(Result.Succeeded);
            }
            catch (Exception ex)
            {
                TaskDialog.Show("Error", ex.Message);
                return(Result.Failed);
            }

            #region Old Method
            //try
            //{
            //        ICollection<ElementId> selectedSheetsId = uidoc.Selection.GetElementIds();

            //        TaskDialog.Show("r", selectedSheetsId.Count.ToString() + " selected");

            //        ICollection<ViewSheet> selectedSheets = new List<ViewSheet>();

            //        foreach (var eid in selectedSheetsId)
            //        {
            //            selectedSheets.Add(doc.GetElement(eid) as ViewSheet);
            //        }

            //        uidoc.ActiveView = uidoc.ActiveGraphicalView;


            //        string outputFile = @"C:\Temp\ExportedData.csv";

            //        var sortedList = selectedSheets.OrderBy(pd => pd.SheetNumber);

            //        string headers = "ElementId, Sheet Number, Sheet Name, ARUP_BDR_TITLE1,ARUP_BDR_TITLE2,ARUP_BDR_TITLE3, View Type, View Name, View PosX, View PosY, View PosZ\n";

            //        StringBuilder sb = new StringBuilder();

            //        File.WriteAllText(outputFile, headers);


            //        foreach (ViewSheet vs in sortedList)
            //        {

            //            ICollection<ElementId> viewports = vs.GetAllViewports();
            //            foreach (var vpid in viewports)
            //            {
            //                Viewport vport = doc.GetElement(vpid) as Viewport;
            //                View view = doc.GetElement(vport.ViewId) as View;

            //                string viewId = vpid.ToString();
            //                string sheetNumber = vs.LookupParameter("Sheet Number").AsString();
            //                string sheetName = vs.LookupParameter("Sheet Name").AsString();
            //                string sheetTitle1 = vs.LookupParameter("ARUP_BDR_TITLE1").AsString();
            //                string sheetTitle2 = vs.LookupParameter("ARUP_BDR_TITLE2").AsString();
            //                string sheetTitle3 = vs.LookupParameter("ARUP_BDR_TITLE3").AsString();
            //                string viewType = view.ViewType.ToString();
            //                string viewName = view.Name;
            //                string viewPosition = vport.GetBoxCenter().ToString().Remove(0, 1).TrimEnd(')');
            //                sb.AppendLine(System.String.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8}",
            //                                            viewId, sheetNumber, sheetName, sheetTitle1, sheetTitle2, sheetTitle3,
            //                                            viewType, viewName, viewPosition));

            //            }
            //        }
            //        File.AppendAllText(outputFile, sb.ToString());

            //        System.Diagnostics.Process process = new System.Diagnostics.Process();
            //        process.StartInfo.FileName = outputFile;
            //        process.Start();


            //        return Result.Succeeded;

            //    }
            //    catch (Exception ex)
            //    {
            //        TaskDialog.Show("Error", ex.Message);
            //        return Result.Failed;
            //    //}

            #endregion
        }
Exemplo n.º 20
0
        public void Execute(UpdaterData data)
        {
            try
            {
                Document doc = data.GetDocument();
                if (data.GetModifiedElementIds().Count > 0)
                {
                    ElementId      doorId       = data.GetModifiedElementIds().First();
                    FamilyInstance doorInstance = doc.GetElement(doorId) as FamilyInstance;
                    if (null != doorInstance)
                    {
#if RELEASE2013 || RELEASE2014
                        Parameter pushParameter = doorInstance.get_Parameter(pushParamName);
#elif RELEASE2015 || RELEASE2016
                        Parameter pushParameter = doorInstance.LookupParameter(pushParamName);
#endif

                        if (null != pushParameter)
                        {
                            if (data.IsChangeTriggered(doorId, Element.GetChangeTypeParameter(pushParameter)))
                            {
                                string pushValue = pushParameter.AsValueString();
                                if (!pushValue.Contains("Approach"))
                                {
                                    DoorFailure.IsDoorFailed        = true;
                                    DoorFailure.FailingDoorId       = doorId;
                                    FailureProcessor.IsFailureFound = true;

                                    MessageBoxResult dr = MessageBox.Show(pushValue + " is not a correct value for the parameter " + pushParamName, "Invalid Door Parameter.", MessageBoxButton.OK, MessageBoxImage.Information);
                                }
                            }
                        }
#if RELEASE2013 || RELEASE2014
                        Parameter pullParameter = doorInstance.get_Parameter(pullParamName);
#elif RELEASE2015 || RELEASE2016
                        Parameter pullParameter = doorInstance.LookupParameter(pullParamName);
#endif


                        if (null != pullParameter)
                        {
                            if (data.IsChangeTriggered(doorId, Element.GetChangeTypeParameter(pullParameter)))
                            {
                                string pullValue = pullParameter.AsValueString();
                                if (!pullValue.Contains("Approach"))
                                {
                                    DoorFailure.IsDoorFailed        = true;
                                    DoorFailure.FailingDoorId       = doorId;
                                    FailureProcessor.IsFailureFound = true;

                                    MessageBoxResult dr = MessageBox.Show(pullValue + " is not a correct value for the parameter " + pullParamName, "Invalid Door Parameter.", MessageBoxButton.OK, MessageBoxImage.Information);
                                }
                            }
                        }

#if RELEASE2013 || RELEASE2014
                        Parameter caParameter = doorInstance.get_Parameter(stateCAParamName);
#elif RELEASE2015 || RELEASE2016
                        Parameter caParameter = doorInstance.LookupParameter(stateCAParamName);
#endif
                        if (null != caParameter)
                        {
                            if (data.IsChangeTriggered(doorId, Element.GetChangeTypeParameter(caParameter)))
                            {
                                string centralPath = FileInfoUtil.GetCentralFilePath(doc);
                                if (AppCommand.Instance.ProjectDictionary.ContainsKey(centralPath))
                                {
                                    Project project = AppCommand.Instance.ProjectDictionary[centralPath];
                                    if (project.address.state == "CA")
                                    {
                                        caParameter.Set(1);
                                    }
                                    else
                                    {
                                        caParameter.Set(0);
                                    }
                                }
                            }
                        }
                    }
                }
                else if (data.GetAddedElementIds().Count > 0)
                {
                    ElementId      doorId       = data.GetAddedElementIds().First();
                    FamilyInstance doorInstance = doc.GetElement(doorId) as FamilyInstance;
                    if (null != doorInstance)
                    {
#if RELEASE2013 || RELEASE2014
                        Parameter caParameter = doorInstance.get_Parameter(stateCAParamName);
#elif RELEASE2015 || RELEASE2016
                        Parameter caParameter = doorInstance.LookupParameter(stateCAParamName);
#endif
                        if (null != caParameter)
                        {
                            string centralPath = FileInfoUtil.GetCentralFilePath(doc);
                            if (AppCommand.Instance.ProjectDictionary.ContainsKey(centralPath))
                            {
                                Project project = AppCommand.Instance.ProjectDictionary[centralPath];
                                if (project.address.state == "CA")
                                {
                                    caParameter.Set(1);
                                }
                                else
                                {
                                    caParameter.Set(0);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogUtil.AppendLog("DoorUpdater-Execute:" + ex.Message);
            }
        }
Exemplo n.º 21
0
        public List <Element> CheckRebars(Document doc)
        {
            List <ParameterElement> paramsCheck = new FilteredElementCollector(doc)
                                                  .OfClass(typeof(ParameterElement))
                                                  .Cast <ParameterElement>()
                                                  .Where(p => p.Name == "RebarImage")
                                                  .ToList();

            if (paramsCheck.Count == 0)
            {
                return(null);
            }

            List <Element> rebars = new FilteredElementCollector(doc)
                                    .WhereElementIsNotElementType()
                                    .OfCategoryId(new ElementId(BuiltInCategory.OST_Rebar))
                                    .ToList();

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

            foreach (Element rebar in rebars)
            {
                Parameter imageParam = rebar.LookupParameter("RebarImage");
                if (imageParam == null)
                {
                    continue;
                }
                if (imageParam.HasValue == false)
                {
                    continue;
                }
                bool isCorrect = true;

                string   line1 = imageParam.AsValueString();
                string   line  = line1.Substring(0, line1.Length - 4);
                string[] data  = line.Split('#');
                if (data.Length < 2)
                {
                    continue;
                }

                string scheduleId = data[0];
                for (int i = 1; i < data.Length; i++)
                {
                    string paramBlock = data[i];
                    if (!paramBlock.Contains("~"))
                    {
                        isCorrect = false;
                        break;
                    }

                    string val     = paramBlock.Split('~').Last();
                    double length1 = double.Parse(val);

                    string    paramName = paramBlock.Split('~').First();
                    Parameter param     = rebar.LookupParameter(paramName);
                    if (param == null)
                    {
                        isCorrect = false;
                        break;
                    }

                    double l       = param.AsDouble() * 304.8;
                    double length2 = SupportSettings.lengthAccuracy * Math.Round(l / SupportSettings.lengthAccuracy);

                    if (length1 != length2)
                    {
                        isCorrect = false;
                        break;
                    }
                }

                if (!isCorrect)
                {
                    errorRebars.Add(rebar);
                }
            }

            return(errorRebars);
        }
Exemplo n.º 22
0
        public MyParameter(Parameter param, bool UseValue)
        {
            InternalDefinition def = param.Definition as InternalDefinition;

            Name = def.Name;

            if (param.IsShared)
            {
                ParamType = MyParameterType.Shared;
            }
            else
            {
                if (def.BuiltInParameter == BuiltInParameter.INVALID)
                {
                    ParamType = MyParameterType.Family;
                }
                else
                {
                    ParamType = MyParameterType.Builtin;
                }
            }

            Units = Enum.GetName(typeof(Autodesk.Revit.DB.UnitType), param.Definition.UnitType);

            if (!UseValue || !param.HasValue)
            {
                Value = "NO VALUE";
            }
            else if (def.ParameterType == ParameterType.YesNo)
            {
                int intval = param.AsInteger();
                Value = "false";
                if (intval == 1)
                {
                    Value = "true";
                }
            }
            else
            {
                switch (param.StorageType)
                {
                case StorageType.None:
                    Value = "NONE STORAGE TYPE";
                    break;

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

                case StorageType.Double:
                    Value = param.AsDouble().ToString("G");
                    break;

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

                case StorageType.ElementId:
                    Value = param.AsValueString();
                    break;

                default:
                    break;
                }
            }
        }
Exemplo n.º 23
0
        /// <summary>
        /// get a datatable contains parameters' information of certain element
        /// </summary>
        /// <param name="o">Revit element</param>
        /// <param name="substanceKind">the material type of this element</param>
        /// <returns>datatable contains parameters' names and values</returns>
        public DataTable GetParameterTable(object o, StructuralAssetClass substanceKind)
        {
            //create an empty datatable
            DataTable parameterTable = CreateTable();

            //if failed to convert object
            Autodesk.Revit.DB.Material material = o as Autodesk.Revit.DB.Material;
            if (material == null)
            {
                return(parameterTable);
            }

            Parameter temporaryAttribute = null;        // hold each parameter
            string    temporaryValue     = "";          // hold each value

            #region Get all material element parameters

            //- Behavior
            temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_BEHAVIOR);
            switch (temporaryAttribute.AsInteger())
            {
            case 0:
                AddDataRow(temporaryAttribute.Definition.Name, "Isotropic", parameterTable);
                break;

            case 1:
                AddDataRow(temporaryAttribute.Definition.Name, "Orthotropic", parameterTable);
                break;

            default:
                AddDataRow(temporaryAttribute.Definition.Name, "None", parameterTable);
                break;
            }
            //- Young's Modulus
            temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_YOUNG_MOD1);
            temporaryValue     = temporaryAttribute.AsValueString();
            AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable);
            temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_YOUNG_MOD2);
            temporaryValue     = temporaryAttribute.AsValueString();
            AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable);
            temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_YOUNG_MOD3);
            temporaryValue     = temporaryAttribute.AsValueString();
            AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable);

            // - Poisson Modulus
            temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_POISSON_MOD1);
            temporaryValue     = temporaryAttribute.AsValueString();
            AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable);
            temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_POISSON_MOD2);
            temporaryValue     = temporaryAttribute.AsValueString();
            AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable);
            temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_POISSON_MOD3);
            temporaryValue     = temporaryAttribute.AsValueString();
            AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable);

            // - Shear Modulus
            temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_SHEAR_MOD1);
            temporaryValue     = temporaryAttribute.AsValueString();
            AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable);
            temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_SHEAR_MOD2);
            temporaryValue     = temporaryAttribute.AsValueString();
            AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable);
            temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_SHEAR_MOD3);
            temporaryValue     = temporaryAttribute.AsValueString();
            AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable);

            //- Thermal Expansion Coefficient
            temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_EXP_COEFF1);
            temporaryValue     = temporaryAttribute.AsValueString();
            AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable);
            temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_EXP_COEFF2);
            temporaryValue     = temporaryAttribute.AsValueString();
            AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable);
            temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_EXP_COEFF3);
            temporaryValue     = temporaryAttribute.AsValueString();
            AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable);

            //- Unit Weight
            temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_UNIT_WEIGHT);
            temporaryValue     = temporaryAttribute.AsValueString();
            AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable);

            //- Damping Ratio
            temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_DAMPING_RATIO);
            temporaryValue     = temporaryAttribute.AsValueString();
            AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable);

            //- Bending Reinforcement
            temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_BENDING_REINFORCEMENT);
            if (null != temporaryAttribute)
            {
                temporaryValue = temporaryAttribute.AsValueString();
                AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable);
            }

            //- Shear Reinforcement
            temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_SHEAR_REINFORCEMENT);
            if (null != temporaryAttribute)
            {
                temporaryValue = temporaryAttribute.AsValueString();
                AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable);
            }

            //- Resistance Calc Strength
            temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_RESISTANCE_CALC_STRENGTH);
            if (null != temporaryAttribute)
            {
                temporaryValue = temporaryAttribute.AsValueString();
                AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable);
            }

            // For Steel only:
            if (StructuralAssetClass.Metal == substanceKind)
            {
                //- Minimum Yield Stress
                temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_MINIMUM_YIELD_STRESS);
                temporaryValue     = temporaryAttribute.AsValueString();
                AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable);

                //- Minimum Tensile Strength
                temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_MINIMUM_TENSILE_STRENGTH);
                temporaryValue     = temporaryAttribute.AsValueString();
                AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable);

                //- Reduction Factor
                temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_REDUCTION_FACTOR);
                temporaryValue     = temporaryAttribute.AsValueString();
                AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable);
            }

            // For Concrete only:
            if (StructuralAssetClass.Concrete == substanceKind)
            {
                //- Concrete Compression
                temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_CONCRETE_COMPRESSION);
                temporaryValue     = temporaryAttribute.AsValueString();
                AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable);

                //- Lightweight
                temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_LIGHT_WEIGHT);
                temporaryValue     = temporaryAttribute.AsValueString();
                AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable);

                //- Shear Strength Reduction
                temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_SHEAR_STRENGTH_REDUCTION);
                temporaryValue     = temporaryAttribute.AsValueString();
                AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable);
            }
            #endregion
            return(parameterTable);
        }
Exemplo n.º 24
0
        private List <MonitorMessage> VerifyDoorParameters(MonitorProjectSetup projectSetup)
        {
            List <MonitorMessage> warningMessages = new List <MonitorMessage>();

            try
            {
                using (TransactionGroup transGroup = new TransactionGroup(m_doc))
                {
                    transGroup.Start("Verify Doors");
                    ElementFilter            catFilter     = new ElementCategoryFilter(BuiltInCategory.OST_Doors);
                    FilteredElementCollector collector     = new FilteredElementCollector(m_doc);
                    List <FamilyInstance>    doorInstances = collector.WherePasses(catFilter).WhereElementIsNotElementType().Cast <FamilyInstance>().ToList();

                    foreach (FamilyInstance doorInstance in doorInstances)
                    {
#if RELEASE2013 || RELEASE2014
                        Parameter pullParam = doorInstance.get_Parameter(pullParamName);
#elif RELEASE2015 || RELEASE2016 || RELEASE2017
                        Parameter pullParam = doorInstance.LookupParameter(pullParamName);
#endif
                        if (null != pullParam)
                        {
                            string pullValue = pullParam.AsValueString();
                            if (!pullValue.Contains("Approach"))
                            {
                                MonitorMessage message = new MonitorMessage(doorInstance, pullParamName, "Incorrect parameter value has been set.");
                                warningMessages.Add(message);
                            }
                        }


#if RELEASE2013 || RELEASE2014
                        Parameter pushParam = doorInstance.get_Parameter(pushParamName);
#elif RELEASE2015 || RELEASE2016 || RELEASE2017
                        Parameter pushParam = doorInstance.LookupParameter(pushParamName);
#endif
                        if (null != pushParam)
                        {
                            string pushValue = pushParam.AsValueString();
                            if (!pushValue.Contains("Approach"))
                            {
                                MonitorMessage message = new MonitorMessage(doorInstance, pushParamName, "Incorrect parameter value has been set.");
                                warningMessages.Add(message);
                            }
                        }

#if RELEASE2013 || RELEASE2014
                        Parameter caParam = doorInstance.get_Parameter(stateCAParamName);
#elif RELEASE2015 || RELEASE2016 || RELEASE2017
                        Parameter caParam = doorInstance.LookupParameter(stateCAParamName);
#endif
                        if (null != caParam)
                        {
                            int caVal      = caParam.AsInteger();
                            int projectVal = Convert.ToInt32(projectSetup.IsStateCA);
                            if (caVal != projectVal)
                            {
                                using (Transaction trans = new Transaction(m_doc))
                                {
                                    trans.Start("Set State Param");
                                    try
                                    {
                                        caParam.Set(projectVal);
                                        MonitorMessage message = new MonitorMessage(doorInstance, stateCAParamName, "Parameter Value has been changed. (solved) ");
                                        warningMessages.Add(message);
                                        trans.Commit();
                                    }
                                    catch (Exception ex)
                                    {
                                        string message = ex.Message;
                                        trans.RollBack();
                                    }
                                }
                            }
                        }
                    }
                    transGroup.Assimilate();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to verify door parameters.\n" + ex.Message, "Verify Door Parameters", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            return(warningMessages);
        }
        private string GetSampleViewName()
        {
            string viewName = "";

            try
            {
                string prefix           = toolSettings.PrefixText;
                string intermediateText = toolSettings.IntermediateText;
                string suffix           = toolSettings.SuffixText;

                if (null != sampleRoom)
                {
                    Parameter parameter = sampleRoom.LookupParameter(toolSettings.IntermediateText);
                    if (null != parameter)
                    {
                        if (parameter.StorageType == StorageType.String)
                        {
                            intermediateText = parameter.AsString();
                        }
                        else
                        {
                            intermediateText = parameter.AsValueString();
                        }
                    }

                    parameter = sampleRoom.LookupParameter(toolSettings.SuffixText);

                    if (null != parameter)
                    {
                        if (parameter.StorageType == StorageType.String)
                        {
                            suffix = parameter.AsString();
                        }
                        else
                        {
                            suffix = parameter.AsValueString();
                        }
                    }

                    if (toolSettings.PrefixSelected)
                    {
                        viewName = prefix;
                    }
                    if (toolSettings.IntermediateSelected)
                    {
                        viewName += intermediateText;
                    }

                    if (toolSettings.ElevationSelected)
                    {
                        if (!string.IsNullOrEmpty(viewName))
                        {
                            viewName += "-Elevation";
                        }
                        else
                        {
                            viewName += "Elevation";
                        }
                    }

                    if (toolSettings.ABCDSelected)
                    {
                        if (!string.IsNullOrEmpty(viewName))
                        {
                            viewName += "-A";
                        }
                        else
                        {
                            viewName += "A";
                        }
                    }

                    if (toolSettings.SuffixSelected)
                    {
                        if (!string.IsNullOrEmpty(viewName))
                        {
                            viewName += " (" + suffix + ")";
                        }
                        else
                        {
                            viewName += "(" + suffix + ")";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to get the example of the view name.\n" + ex.Message, "Elevation Creator: GetSampleViewName", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            return(viewName);
        }
Exemplo n.º 26
0
 public override object GetValue(object component) =>
 parameter.Element is object && parameter.Definition is object?
 (parameter.StorageType == StorageType.String ? parameter.AsString() :
  parameter.AsValueString()) : null;
Exemplo n.º 27
0
        Stream(ArrayList data, Parameter param)
        {
            data.Add(new Snoop.Data.ClassSeparator(typeof(Parameter)));

            data.Add(new Snoop.Data.Object("Definition", param.Definition));

            try {   // this only works for certain types of Parameters
                data.Add(new Snoop.Data.String("Display unit type", param.DisplayUnitType.ToString()));
            }
            catch (System.Exception) {
                data.Add(new Snoop.Data.String("Display unit type", "N/A"));
            }
            try
            {   // this only works for certain types of Parameters
                data.Add(new Snoop.Data.Object("Element", param.Element));
            }
            catch (System.Exception ex)
            {
                data.Add(new Snoop.Data.Exception("Element", ex));
            }
            try
            {   // this only works for certain types of Parameters
                data.Add(new Snoop.Data.String("GUID", param.GUID.ToString()));
            }
            catch (System.Exception ex)
            {
                data.Add(new Snoop.Data.Exception("GUID", ex));
            }
            try
            {   // this only works for certain types of Parameters
                data.Add(new Snoop.Data.Bool("HasValue", param.HasValue));
            }
            catch (System.Exception ex)
            {
                data.Add(new Snoop.Data.Exception("HasValue", ex));
            }
            try
            {   // this only works for certain types of Parameters
                data.Add(new Snoop.Data.ElementId("ID", param.Id, m_activeDoc));
            }
            catch (System.Exception ex)
            {
                data.Add(new Snoop.Data.Exception("ID", ex));
            }
            try
            {   // this only works for certain types of Parameters
                data.Add(new Snoop.Data.Bool("IsShared", param.IsShared));
            }
            catch (System.Exception ex)
            {
                data.Add(new Snoop.Data.Exception("IsShared", ex));
            }

            data.Add(new Snoop.Data.String("Storage type", param.StorageType.ToString()));

            if (param.StorageType == StorageType.Double)
            {
                data.Add(new Snoop.Data.Double("Value", param.AsDouble()));
            }
            else if (param.StorageType == StorageType.ElementId)
            {
                data.Add(new Snoop.Data.ElementId("Value", param.AsElementId(), m_app.ActiveUIDocument.Document));
            }
            else if (param.StorageType == StorageType.Integer)
            {
                data.Add(new Snoop.Data.Int("Value", param.AsInteger()));
            }
            else if (param.StorageType == StorageType.String)
            {
                data.Add(new Snoop.Data.String("Value", param.AsString()));
            }

            data.Add(new Snoop.Data.String("As value string", param.AsValueString()));
        }
Exemplo n.º 28
0
        public static List <MyParameter> GetParameterValues(Document doc, List <Element> elems, string ParamName, int startSymbols)
        {
            bool isTypeParam = false;

            if (ParamName == "Имя типа" || ParamName == "Имя типа")
            {
                isTypeParam = true;
            }

            HashSet <MyParameter> values = new HashSet <MyParameter>(); //список значений параметра

            foreach (Element elem in elems)
            {
                Parameter curParam = elem.LookupParameter(ParamName);

                if (curParam == null)
                {
                    ElementId typeElemId = elem.GetTypeId();
                    if (typeElemId == null)
                    {
                        continue;
                    }
                    if (typeElemId == ElementId.InvalidElementId)
                    {
                        continue;
                    }
                    Element typeElem = doc.GetElement(typeElemId);
                    curParam = typeElem.LookupParameter(ParamName);
                    if (curParam == null)
                    {
                        continue;
                    }
                }

                MyParameter mp = new MyParameter(curParam);
                if (!mp.HasValue && !isTypeParam)
                {
                    continue;
                }
                if (isTypeParam)
                {
                    Parameter typeParam = elem.get_Parameter(BuiltInParameter.ELEM_TYPE_PARAM);
                    if (!typeParam.HasValue)
                    {
                        continue;
                    }
                    string typeName = typeParam.AsValueString();
                    mp.Set(typeName);
                }

                if (startSymbols > 0)
                {
                    if (mp.RevitStorageType != StorageType.String)
                    {
                        throw new Exception("Критерий \"Начинается с\" доступен только для текстовых параметров");
                    }

                    string valTemp = mp.AsString();
                    string val     = "";
                    if (valTemp.Length < startSymbols)
                    {
                        val = valTemp;
                    }
                    else
                    {
                        val = valTemp.Substring(0, startSymbols);
                    }

                    mp.Set(val);
                }
                values.Add(mp);
            }


            List <MyParameter> listParams = values.ToList();

            listParams.Sort();
            return(listParams);
        }
Exemplo n.º 29
0
        private void Stream(ArrayList data, Parameter param)
        {
            data.Add(new Snoop.Data.ClassSeparator(typeof(Parameter)));

            data.Add(new Snoop.Data.Object("Definition", param.Definition));

            try {   // this only works for certain types of Parameters
                data.Add(new Snoop.Data.String("Display unit type", param.DisplayUnitType.ToString()));
            }
            catch (System.Exception) {
                data.Add(new Snoop.Data.String("Display unit type", "N/A"));
            }
            try
            {   // this only works for certain types of Parameters
              data.Add(new Snoop.Data.Object("Element", param.Element));
            }
            catch (System.Exception ex)
            {
              data.Add(new Snoop.Data.Exception("Element", ex));
            }
            try
            {   // this only works for certain types of Parameters
              data.Add(new Snoop.Data.String("GUID", param.GUID.ToString()));
            }
            catch (System.Exception ex)
            {
              data.Add(new Snoop.Data.Exception("GUID", ex));
            }
            try
            {   // this only works for certain types of Parameters
              data.Add(new Snoop.Data.Bool("HasValue", param.HasValue));
            }
            catch (System.Exception ex)
            {
              data.Add(new Snoop.Data.Exception("HasValue", ex));
            }
            try
            {   // this only works for certain types of Parameters
              data.Add(new Snoop.Data.ElementId("ID", param.Id,m_activeDoc));
            }
            catch (System.Exception ex)
            {
              data.Add(new Snoop.Data.Exception("ID", ex));
            }
            try
            {   // this only works for certain types of Parameters
              data.Add(new Snoop.Data.Bool("IsShared", param.IsShared));
            }
            catch (System.Exception ex)
            {
              data.Add(new Snoop.Data.Exception("IsShared", ex));
            }

            data.Add(new Snoop.Data.String("Storage type", param.StorageType.ToString()));

            if (param.StorageType == StorageType.Double)
                data.Add(new Snoop.Data.Double("Value", param.AsDouble()));
            else if (param.StorageType == StorageType.ElementId)
                data.Add(new Snoop.Data.ElementId("Value", param.AsElementId(), m_app.ActiveUIDocument.Document));
            else if (param.StorageType == StorageType.Integer)
                data.Add(new Snoop.Data.Int("Value", param.AsInteger()));
            else if (param.StorageType == StorageType.String)
                data.Add(new Snoop.Data.String("Value", param.AsString()));

            data.Add(new Snoop.Data.String("As value string", param.AsValueString()));
        }
Exemplo n.º 30
0
 public ParamControl(Parameter param)
 {
     parameter     = param;
     newParamValue = param.AsValueString();
 }
Exemplo n.º 31
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            #region TEST_1
#if TEST_1
            //
            // you cannot create your own parameter, because the
            // constuctor is for internal use only. This is due
            // to the fact that a parameter cannot live on its own,
            // it is linked to a definition and needs to be hooked
            // up properly in the Revit database system to work
            // ... case 1245614 [Formatting units strings]:
            //
            bool iReallyWantToCrash = false;
            if (iReallyWantToCrash)
            {
                Parameter p = new Parameter();
                p.Set(1.0);
                string s = p.AsDouble().ToString();
                string t = p.AsValueString();
                Debug.WriteLine("Value " + s);
                Debug.WriteLine("Value string " + t);
            }
#endif // TEST
            #endregion // TEST_1

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

            // Loop through all pre-selected elements:

            foreach (ElementId id in uidoc.Selection.GetElementIds())
            {
                Element e = doc.GetElement(id);

                string s = string.Empty;

                // set this variable to false to analyse the element's own parameters,
                // i.e. instance parameters for a family instance, and set it to true
                // to analyse a family instance's type parameters:

                bool analyseTypeParameters = false;

                if (analyseTypeParameters)
                {
                    if (e is FamilyInstance)
                    {
                        FamilyInstance inst = e as FamilyInstance;
                        if (null != inst.Symbol)
                        {
                            e = inst.Symbol;
                            s = " type";
                        }
                    }
                    else if (e is Wall)
                    {
                        Wall wall = e as Wall;
                        if (null != wall.WallType)
                        {
                            e = wall.WallType;
                            s = " type";
                        }
                    }
                    // ... add support for other types if desired ...
                }

                // Loop through and list all UI-visible element parameters

                List <string> a = new List <string>();

                #region 4.1.a Iterate over element parameters and retrieve their name, type and value:

                foreach (Parameter p in e.Parameters)
                {
                    string name  = p.Definition.Name;
                    string type  = p.StorageType.ToString();
                    string value = LabUtils.GetParameterValue2(p, uidoc.Document);
                    //bool read_only = p.Definition.IsReadOnly; // 2013
                    bool read_only = p.IsReadOnly; // 2014
                    a.Add(string.Format(
                              "Name={0}; Type={1}; Value={2}; ValueString={3}; read-{4}",
                              name, type, value, p.AsValueString(),
                              (read_only ? "only" : "write")));
                }

                #endregion // 4.1.a

                string what = e.Category.Name
                              + " (" + e.Id.IntegerValue.ToString() + ")";

                LabUtils.InfoMsg(what + " has {0} parameter{1}{2}", a);

                // If we know which param we are looking for, then:
                // A) If a standard parameter, we can get it via BuiltInParam
                // signature of Parameter method:

                try
                {
                    #region 4.1.b Retrieve a specific built-in parameter:

                    Parameter p = e.get_Parameter(
                        BuiltInParameter.FAMILY_BASE_LEVEL_OFFSET_PARAM);

                    #endregion // 4.1.b

                    if (null == p)
                    {
                        LabUtils.InfoMsg("FAMILY_BASE_LEVEL_OFFSET_PARAM is NOT available for this element.");
                    }
                    else
                    {
                        string name  = p.Definition.Name;
                        string type  = p.StorageType.ToString();
                        string value = LabUtils.GetParameterValue2(p, doc);
                        LabUtils.InfoMsg("FAMILY_BASE_LEVEL_OFFSET_PARAM: Name=" + name
                                         + "; Type=" + type + "; Value=" + value);
                    }
                }
                catch (Exception)
                {
                    LabUtils.InfoMsg("FAMILY_BASE_LEVEL_OFFSET_PARAM is NOT available for this element.");
                }

                // B) For a shared parameter, we can get it via "GUID" signature
                // of Parameter method  ... this will be shown later in Labs 4 ...

                // C) or we can get the parameter by name:
                // alternatively, loop through all parameters and
                // search for the name (this works for either
                // standard or shared). Note that the same name
                // may occur multiple times:

                const string paramName = "Base Offset";

                //Parameter parByName = e.get_Parameter( paramName ); // 2014

                IList <Parameter> paramsByName = e.GetParameters(paramName); // 2015

                if (0 == paramsByName.Count)
                {
                    LabUtils.InfoMsg(paramName + " is NOT available for this element.");
                }
                else
                {
                    foreach (Parameter p in paramsByName)
                    {
                        string parByNameName  = p.Definition.Name;
                        string parByNameType  = p.StorageType.ToString();
                        string parByNameValue = LabUtils.GetParameterValue2(p, doc);
                        LabUtils.InfoMsg(paramName + ": Name=" + parByNameName
                                         + "; Type=" + parByNameType + "; Value=" + parByNameValue);
                    }
                }

                #region TEST_2
#if TEST_2
                List <string> a = GetParameters(doc, e);
                foreach (string s2 in a)
                {
                    Debug.WriteLine(s2);
                }
#endif // TEST_2
                #endregion // TEST_2
            }
            return(Result.Failed);
        }
Exemplo n.º 32
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elementSet)
        {
            Document doc = commandData.Application.ActiveUIDocument.Document;

            List <string> liste = new List <string>();

            Form1 form             = new Form1(doc);
            bool  RoomName         = false;
            bool  RoomWalls        = false;
            bool  RoomFurniture    = false;
            bool  RoomDoors        = false;
            bool  RoomAddFurniture = false;
            bool  RoomFinishes     = false;

            if (form.DialogResult == System.Windows.Forms.DialogResult.Cancel)
            {
                return(Result.Cancelled);
            }

            if (DialogResult.OK == form.ShowDialog())
            {
                //Nom du paramètre de type "oui/non" permettant de détecter les locaux confidentiels
                string param = "G6_Confidentiel";
                //Nom des éléments pour le remplacement des familles
                string wall_type       = "XXXX";
                string door_type       = "XXXX_P:XXXX";
                string furniture_type  = "XXXX_M:XXXX";
                string plumbing_type   = "XXXX_S:XXXX";
                string furniture_param = "Dimension";
                string plumbing_param  = "Dimension";
                //Valeur attribuée aux paramètres cryptés
                string change = "XXXX";
                //Clé de décryptage
                List <string> key    = new List <string>();
                string        phase  = "Nouvelle construction";
                string        phase2 = "New Construction";

                ElementId    levelID       = null;
                FamilySymbol door_fs       = null;
                FamilySymbol furniture_fs  = null;
                FamilySymbol plumbing_fs   = null;
                ElementId    eid           = null;
                Line         newWallLine_2 = null;
                List <Curve> curves        = new List <Curve>();
                int          count         = 0;
                Random       rnd           = new Random();
                int          Offset        = rnd.Next(4, 6);
                double       random        = rnd.NextDouble() * Offset;
                //double random = Offset;

                using (Transaction t = new Transaction(doc, "Crypter la maquette"))
                {
                    t.Start();
                    RoomName         = form.RoomName();
                    RoomWalls        = form.RoomWalls();
                    RoomFurniture    = form.RoomFurniture();
                    RoomDoors        = form.RoomDoors();
                    RoomAddFurniture = form.RoomAddFurnitures();
                    RoomFinishes     = form.RoomFinishes();
                    //Sélection du type de porte de remplacement
                    FamilySymbol fs = (from element in new FilteredElementCollector(doc).OfClass(typeof(FamilySymbol)).OfCategory(BuiltInCategory.OST_Doors).Cast <FamilySymbol>()
                                       where element.Family.Name + ":" + element.Name == door_type
                                       select element).ToList <FamilySymbol>().First();
                    door_fs = fs;
                    //Sélection du type de mobilier de remplacement
                    FamilySymbol fs_furniture = (from element in new FilteredElementCollector(doc).OfClass(typeof(FamilySymbol)).OfCategory(BuiltInCategory.OST_Furniture).Cast <FamilySymbol>()
                                                 where element.Family.Name + ":" + element.Name == furniture_type
                                                 select element).ToList <FamilySymbol>().First();
                    furniture_fs = fs_furniture;
                    //Sélection du type de sanitaire de remplacement
                    FamilySymbol fs_plumbing = (from element in new FilteredElementCollector(doc).OfClass(typeof(FamilySymbol)).OfCategory(BuiltInCategory.OST_PlumbingFixtures).Cast <FamilySymbol>()
                                                where element.Family.Name + ":" + element.Name == plumbing_type
                                                select element).ToList <FamilySymbol>().First();
                    plumbing_fs = fs_plumbing;
                    //Sélection du type de mur de remplacement
                    WallType walltype = (from element in new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Walls).WhereElementIsElementType()
                                         where element.Name == wall_type
                                         select element).Cast <WallType>().ToList <WallType>().First();
                    eid = walltype.Id;
                    //Remplacement du mobilier
                    if (RoomFurniture == true)
                    {
                        foreach (FamilyInstance furniture_instance in new FilteredElementCollector(doc).OfClass(typeof(FamilyInstance)).OfCategory(BuiltInCategory.OST_Furniture).Cast <FamilyInstance>())
                        {
                            if (furniture_instance.Room != null && furniture_instance.Room.LookupParameter(param).AsInteger() == 1)
                            {
                                try
                                {
                                    string original = furniture_instance.Name;
                                    furniture_instance.Symbol = furniture_fs;
                                    Random rd = new Random();
                                    double random_dimension = 0.5 + rd.NextDouble();
                                    furniture_instance.LookupParameter(furniture_param).Set(UnitUtils.ConvertToInternalUnits(random_dimension, DisplayUnitType.DUT_METERS));
                                    key.Add("F;" + furniture_instance.Id.ToString() + ";" + original + ";" + furniture_instance.Room.Id.ToString() + ";" + furniture_instance.Room.Name);
                                }
                                catch
                                {
                                }
                            }
                        }
                        foreach (FamilyInstance plumbing_instance in new FilteredElementCollector(doc).OfClass(typeof(FamilyInstance)).OfCategory(BuiltInCategory.OST_PlumbingFixtures).Cast <FamilyInstance>())
                        {
                            if (plumbing_instance.Room != null && plumbing_instance.Room.LookupParameter(param).AsInteger() == 1)
                            {
                                string original = plumbing_instance.Name;
                                plumbing_instance.Symbol = plumbing_fs;
                                Random rd = new Random();
                                double random_dimension = 0.5 + rd.NextDouble();
                                plumbing_instance.LookupParameter(plumbing_param).Set(UnitUtils.ConvertToInternalUnits(random_dimension, DisplayUnitType.DUT_METERS));
                                key.Add("P;" + plumbing_instance.Id.ToString() + ";" + original + ";" + plumbing_instance.Room.Id.ToString() + ";" + plumbing_instance.Room.Name);
                            }
                        }
                    }
                    //Lister les pièces confidentielles et appartenant à la phase désignée
                    List <Room> rooms = (from element in new FilteredElementCollector(doc).OfClass(typeof(SpatialElement)).OfCategory(BuiltInCategory.OST_Rooms).Cast <Room>()
                                         where element.LookupParameter(param).AsInteger() == 1 &&
                                         (element.get_Parameter(BuiltInParameter.ROOM_PHASE).AsValueString() == phase || element.get_Parameter(BuiltInParameter.ROOM_PHASE).AsValueString() == phase2)
                                         select element).ToList <Room>();
                    //Première boucle sur les pièces confidentielles pour renseigner la clé
                    foreach (Room r in rooms)
                    {
                        Parameter     name   = r.get_Parameter(BuiltInParameter.ROOM_NAME);
                        Parameter     number = r.get_Parameter(BuiltInParameter.ROOM_NUMBER);
                        Parameter     floor  = r.get_Parameter(BuiltInParameter.ROOM_FINISH_FLOOR);
                        LocationPoint lp     = r.Location as LocationPoint;
                        XYZ           point  = lp.Point;
                        //Ajout des valeurs de paramètres initiaux à la clé de déchiffrement
                        key.Add("R;" + r.Id.ToString() + ";" + name.AsString() + ";" + number.AsString() + ";" + floor.AsString() + ";" + point.X + ";" + point.Y + ";" + point.Z);
                    }

                    //Deuxième boucle sur les pièces confidentielles pour modifier paramètres et géométrie
                    foreach (Room r in rooms)
                    {
                        Parameter     name   = r.get_Parameter(BuiltInParameter.ROOM_NAME);
                        Parameter     number = r.get_Parameter(BuiltInParameter.ROOM_NUMBER);
                        Parameter     floor  = r.get_Parameter(BuiltInParameter.ROOM_FINISH_FLOOR);
                        LocationPoint lp     = r.Location as LocationPoint;
                        XYZ           point  = lp.Point;
                        //Remplacement des valeurs de paramètres des pièces par le code
                        if (RoomName == true)
                        {
                            name.Set(change);
                            number.Set(change + count.ToString());
                        }
                        if (RoomFinishes == true)
                        {
                            floor.Set(change);
                        }
                        //Incrémentation du nombre de pièces cryptées
                        count += 1;
                        //Retrouver les limites des pièces
                        IList <IList <Autodesk.Revit.DB.BoundarySegment> > segments = r.GetBoundarySegments(new SpatialElementBoundaryOptions());
                        int             segments_number   = 0;
                        int             boundaries_number = 0;
                        BoundarySegment bd0 = null;
                        BoundarySegment bd1 = null;
                        BoundarySegment bd2 = null;

                        if (null != segments)  //la pièce peut ne pas être fermée
                        {
                            foreach (IList <Autodesk.Revit.DB.BoundarySegment> segmentList in segments)
                            {
                                segments_number += 1;
                                foreach (Autodesk.Revit.DB.BoundarySegment boundarySegment in segmentList)
                                {
                                    boundaries_number += 1;
                                    if (boundaries_number == 1)
                                    {
                                        bd0 = boundarySegment;
                                    }
                                    if (boundaries_number == 3)
                                    {
                                        bd1 = boundarySegment;
                                    }
                                    if (boundaries_number == 4)
                                    {
                                        bd2 = boundarySegment;
                                    }
                                    //Retrouver l'élément qui forme la limite de pièce
                                    Element elt = r.Document.GetElement(boundarySegment.ElementId);
                                    //Déterminer si cet élément est un mur
                                    bool isWall = false;
                                    if (elt as Wall != null)
                                    {
                                        isWall = true;
                                    }
                                    //Si c'est un mur, continuer
                                    if (isWall == true)
                                    {
                                        Wall      wall     = elt as Wall;
                                        Parameter function = wall.WallType.get_Parameter(BuiltInParameter.FUNCTION_PARAM);
                                        //Ne traiter que les murs intérieurs
                                        if (function.AsValueString() == "Interior" || function.AsValueString() == "Intérieur")
                                        {
                                            if (RoomDoors == true)
                                            {
                                                //Changer les types de portes
                                                IList <ElementId> inserts = (wall as HostObject).FindInserts(true, true, true, true);
                                                foreach (ElementId id in inserts)
                                                {
                                                    Element e = doc.GetElement(id);
                                                    try
                                                    {
                                                        FamilyInstance fi = e as FamilyInstance;
                                                        if (fi.get_Parameter(BuiltInParameter.PHASE_CREATED).AsValueString() == phase || fi.get_Parameter(BuiltInParameter.PHASE_CREATED).AsValueString() == phase2)
                                                        {
                                                            string original = fi.Name;
                                                            fi.Symbol = door_fs;
                                                            LocationPoint doorPoint = fi.Location as LocationPoint;
                                                            XYZ           pt        = doorPoint.Point;
                                                            key.Add("D;" + fi.Id.ToString() + ";" + original + ";" + pt.X + ";" + pt.Y + ";" + pt.Z);
                                                        }
                                                    }
                                                    catch
                                                    {
                                                    }
                                                }
                                            }
                                            //Récupérer les points de départ et d'extrémité des murs
                                            LocationCurve wallLine  = wall.Location as LocationCurve;
                                            XYZ           endPoint0 = wallLine.Curve.GetEndPoint(0);
                                            XYZ           endPoint1 = wallLine.Curve.GetEndPoint(1);
                                            //Ajout des coordonnées initiales des murs à la clé de déchiffrement
                                            key.Add("W;" + wall.Id.ToString() + ";" + wall.WallType.Name + ";" + endPoint0.X.ToString() + ";" + endPoint0.Y.ToString() + ";" + endPoint1.X.ToString() + ";" + endPoint1.Y.ToString());
                                            levelID = wall.LevelId;
                                            //Changer le type des murs
                                            if (RoomWalls == true)
                                            {
                                                wall.ChangeTypeId(eid);
                                            }
                                        }
                                    }
                                }
                            }

                            if (RoomAddFurniture == true && r.Area > UnitUtils.ConvertToInternalUnits(7, DisplayUnitType.DUT_SQUARE_METERS))
                            {
                                //Créer de nouveaux meubles de façon aléatoire dans les pièces confidentielles
                                Random rd        = new Random();
                                int    offset    = rnd.Next(0, 10);
                                XYZ    new_point = new XYZ(point.X + offset * 0.5, point.Y + offset * 0.3, point.Z);
                                if (offset > 1 && offset < 9)
                                {
                                    FamilyInstance nf = doc.Create.NewFamilyInstance(new_point, furniture_fs, r.Level, StructuralType.NonStructural);
                                    key.Add("NF;" + nf.Id.ToString());
                                }
                            }
                        }
                    }

                    SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                    saveFileDialog1.Title            = "Choisir le chemin du fichier de chiffrement";
                    saveFileDialog1.Filter           = "Fichier texte (*.txt)|*.txt";
                    saveFileDialog1.RestoreDirectory = true;

                    DialogResult result = saveFileDialog1.ShowDialog();
                    if (result == System.Windows.Forms.DialogResult.OK)
                    {
                        string txt_filename = saveFileDialog1.FileName;
                        if (File.Exists(txt_filename))
                        {
                            File.Delete(txt_filename);
                        }
                        //Ecrire dans le fichier clé
                        using (StreamWriter sw = new StreamWriter(txt_filename))
                        {
                            foreach (string s in key)
                            {
                                sw.WriteLine(s);
                            }
                        }
                        //Process.Start(txt_filename);
                    }
                    t.Commit();
                    return(Result.Succeeded);
                }
            }
            return(Result.Succeeded);
        }
Exemplo n.º 33
0
        /// <summary>
        /// get the parameter value according given parameter name
        /// </summary>
        public string FindParameter(string parameterName, FamilyInstance familyInstanceName)
        {
            ParameterSetIterator i = familyInstanceName.Parameters.ForwardIterator();

            i.Reset();
            string valueOfParameter = null;
            bool   iMoreAttribute   = i.MoveNext();

            while (iMoreAttribute)
            {
                bool      isFound         = false;
                object    o               = i.Current;
                Parameter familyAttribute = o as Parameter;
                if (familyAttribute.Definition.Name == parameterName)
                {
                    //find the parameter whose name is same to the given parameter name
                    Autodesk.Revit.DB.StorageType st = familyAttribute.StorageType;
                    switch (st)
                    {
                    //get the storage type
                    case StorageType.Double:
                        if (parameterName.Equals(AngleDefinitionName))
                        {
                            //make conversion between degrees and radians
                            Double temp = familyAttribute.AsDouble();
                            valueOfParameter = Math.Round(temp * 180 / (Math.PI), 3).ToString();
                        }
                        else
                        {
                            valueOfParameter = familyAttribute.AsDouble().ToString();
                        }
                        break;

                    case StorageType.ElementId:
                        //get Autodesk.Revit.DB.ElementId as string
                        valueOfParameter = familyAttribute.AsElementId().IntegerValue.ToString();
                        break;

                    case StorageType.Integer:
                        //get Integer as string
                        valueOfParameter = familyAttribute.AsInteger().ToString();
                        break;

                    case StorageType.String:
                        //get string
                        valueOfParameter = familyAttribute.AsString();
                        break;

                    case StorageType.None:
                        valueOfParameter = familyAttribute.AsValueString();
                        break;

                    default:
                        break;
                    }
                    isFound = true;
                }
                if (isFound)
                {
                    break;
                }
                iMoreAttribute = i.MoveNext();
            }
            //return the value.
            return(valueOfParameter);
        }
Exemplo n.º 34
0
        private string ParameterValue(Parameter p)
        {
            test.p = p;

            string storageType = p.StorageType.ToString();
            string result      = (p.AsValueString() ?? "").Trim();

            if (string.IsNullOrWhiteSpace(result))
            {
                switch (p.StorageType)
                {
                case StorageType.Double:
                {
                    storageType = "double";
                    result      = p.AsValueString();
                    break;
                }

                case StorageType.ElementId:
                {
                    storageType = "element id";
                    ElementId id = new ElementId(p.AsElementId().IntegerValue);
                    Element   e  = _doc.GetElement(id);

                    result = e?.Name ?? "Null Element";
                    break;
                }

                case StorageType.Integer:
                {
                    storageType = "integer";
                    result      = p.AsInteger().ToString();
                    break;
                }

                case StorageType.None:
                {
                    storageType = "none";
                    result      = p.AsValueString();
                    break;
                }

                case StorageType.String:
                {
                    storageType = "string";
                    result      = p.AsString();
                    break;
                }
                }
            }


            if (p.StorageType == StorageType.ElementId && !firstPass[firstPassItem])
            {
                ElementArray ea = GetSimilarForElement(p.AsElementId());

                ElementType et = _doc.GetElement(p.AsElementId()) as ElementType;

                if (ea != null)
                {
                    firstPass[firstPassItem++] = true;

                    logMsgDbLn2("getting similar", et.Name + " :: " + et.FamilyName);

                    foreach (Element e in ea)
                    {
                        logMsgDbLn2("type", e.Name);
                    }
                }
            }

            UnitType      u  = UnitType.UT_Undefined;
            ParameterType pt = ParameterType.Acceleration;


            result  = result.PadRight(18);
            result += " :: " + storageType.ToString().PadRight(PAD_RIGHT);


            //not valid info
            result += " :: " + p.IsReadOnly.ToString().PadRight(PAD_RIGHT);

            // not valid info
            //			result += " :: " + p.UserModifiable.ToString().PadRight(PAD_RIGHT);

            // valid info
            //			result += " :: " + p.HasValue.ToString().PadRight(PAD_RIGHT);

            result += " :: " + p.Definition.ParameterType.ToString().PadRight(PAD_RIGHT);
            result += " :: " + p.Definition.UnitType.ToString().PadRight(PAD_RIGHT);


            try
            {
                result += " :: " + p.DisplayUnitType.ToString().PadRight(PAD_RIGHT + 6);
            }
            catch
            {
                result += " :: " + "(no unit type)".PadRight(PAD_RIGHT + 6);
            }

            result += " :: " + p.Definition.ParameterGroup.ToString().PadRight(PAD_RIGHT);


            return(result);
        }