Example #1
0
    public Result Execute(
      ExternalCommandData commandData,
      ref string message,
      ElementSet elements)
    {
        // Get application and document objects
        UIApplication uiApp = commandData.Application;
        Document doc = uiApp.ActiveUIDocument.Document;
        UIDocument uidoc = uiApp.ActiveUIDocument;

        try
        {
            using (Transaction trans = new Transaction(doc, "UpperCase Views on Sheets."))
            {
                // Delete all unnamed Reference Planes in the project
                // Create Filter to check for Name
                BuiltInParameter bip = BuiltInParameter.DATUM_TEXT;
                ParameterValueProvider provider = new ParameterValueProvider(new ElementId(bip));
                FilterStringEquals evaluator = new FilterStringEquals();
                FilterStringRule rule = new FilterStringRule(provider, evaluator, "", false);
                ElementParameterFilter filter = new ElementParameterFilter(rule);

                ICollection<ElementId> refPlanes = new FilteredElementCollector(doc)
                    .OfClass(typeof(ReferencePlane))
                    .WherePasses(filter)
                    .ToElementIds();

                int count = refPlanes.Count;
                try
                {
                    trans.Start();
                    doc.Delete(refPlanes);
                    trans.Commit();
                }
                catch (Exception x)
                {
                    message = x.Message;
                    return Result.Failed;
                }

                TaskDialog.Show("Delete Reference Planes", "You have successfully delete " + count.ToString() + " unnamed reference planes!");
                return Result.Succeeded;
            }
        }
        // Catch any Exceptions and display them.
        catch (Autodesk.Revit.Exceptions.OperationCanceledException)
        {
            return Result.Cancelled;
        }
        catch (Exception x)
        {
            message = x.Message;
            return Result.Failed;
        }
    }
        public Result Execute(ExternalCommandData commandData,
                              ref string message,
                              ElementSet elements)
        {
            try
            {
                uiApp = commandData.Application;
                uiDoc = uiApp.ActiveUIDocument;
                app = uiApp.Application;
                doc = uiDoc.Document;

                FilteredElementCollector refPlaneCollector = new FilteredElementCollector(doc);
                IList<Element> refPlanes = refPlaneCollector.OfClass(typeof(ReferencePlane)).ToElements();

                ElementId nameParamterId = new ElementId(BuiltInParameter.DATUM_TEXT);
                ParameterValueProvider pvp = new ParameterValueProvider(nameParamterId);
                FilterStringRuleEvaluator evaluator = new FilterStringEquals();
                FilterRule rule = new FilterStringRule(pvp, evaluator, "", false);
                ElementFilter filter = new ElementParameterFilter(rule);

                FilteredElementCollector unnamedRefPlaneCollector = new FilteredElementCollector(doc);
                unnamedRefPlaneCollector.OfClass(typeof(ReferencePlane));
                unnamedRefPlaneCollector.WherePasses(filter);
                IList<Element> unnamedRefPlanes = unnamedRefPlaneCollector.ToElements();

                Transaction transaction = new Transaction(doc);
                transaction.Start("Purging unnamed reference planes");

                foreach (Element refPlane in unnamedRefPlanes)
                     doc.Delete(refPlane.Id);

                transaction.Commit();

                TaskDialog.Show("Purge Unnamed Ref Planes",
                                String.Format("{0} reference planes found.\n{1} unnamed reference planes deleted.",
                                               refPlanes.Count.ToString(), unnamedRefPlanes.Count.ToString()));

                return Result.Succeeded;
            }
            catch (Exception e)
            {
                TaskDialog.Show("Revit Quick Tools", e.Message);
                return Result.Failed;
            }
        }
Example #3
0
 public void Execute(UpdaterData data)
 {
     if (!Paused)
     {
         Document         doc  = data.GetDocument();
         List <ElementId> list = data.GetAddedElementIds().ToList();
         list.AddRange(data.GetModifiedElementIds());
         IList <Element> list2 = (from ElementId id in list
                                  select doc.GetElement(id)).ToList();
         Definition                parameterDefinition = LODapp.GetParameterDefinition(doc, "Zone");
         ElementId                 val  = LODapp.GetLODparameter(doc, parameterDefinition).get_Id();
         ParameterValueProvider    val2 = new ParameterValueProvider(val);
         FilterStringRuleEvaluator val3 = new FilterStringContains();
         FilterStringRuleEvaluator val4 = new FilterStringEquals();
         FilterStringRuleEvaluator val5 = new FilterStringBeginsWith();
         foreach (Element item in list2)
         {
             string text = item.LookupParameter("Name").AsString();
             if (!string.IsNullOrWhiteSpace(text))
             {
                 FilterRule[] array = (FilterRule[])new FilterRule[3]
                 {
                     new FilterStringRule(val2, val4, text, true),
                     new FilterStringRule(val2, val5, text + ", ", true),
                     new FilterStringRule(val2, val3, ", " + text, true)
                 };
                 ElementParameterFilter      val6        = new ElementParameterFilter((IList <FilterRule>)array);
                 IList <Element>             list3       = new FilteredElementCollector(doc).WhereElementIsNotElementType().WherePasses(val6).ToElements();
                 BoundingBoxIntersectsFilter val7        = new BoundingBoxIntersectsFilter(ToOutline(item.get_BoundingBox(null)));
                 IList <Element>             list4       = new FilteredElementCollector(doc).WhereElementIsNotElementType().WherePasses(val7).ToElements();
                 IEnumerable <Element>       enumerable  = list3.Except(list4, new EqualUniqueId());
                 IEnumerable <Element>       enumerable2 = list4.Except(list3, new EqualUniqueId());
                 foreach (Element item2 in enumerable)
                 {
                     Parameter val8 = item2.get_Parameter(parameterDefinition);
                     if (val8 != null)
                     {
                         string text2 = val8.AsString() ?? string.Empty;
                         string text3;
                         if (text2.Length > text.Length)
                         {
                             int num = text2.IndexOf(text);
                             text3 = ((num < 2 || text2[num - 2] != ',') ? text2.Remove(num, text.Length + 2) : text2.Remove(num - 2, text.Length + 2));
                         }
                         else
                         {
                             text3 = string.Empty;
                         }
                         val8.Set(text3);
                     }
                 }
                 foreach (Element item3 in enumerable2)
                 {
                     Parameter val9  = item3.get_Parameter(parameterDefinition);
                     string    text4 = (((int)val9 != 0) ? val9.AsString() : null) ?? string.Empty;
                     string    text5 = (text4.Length <= 0) ? text : (text4 + ", " + text);
                     Parameter val10 = item3.get_Parameter(parameterDefinition);
                     if ((int)val10 != 0)
                     {
                         val10.Set(text5);
                     }
                 }
             }
         }
     }
 }
        /// <summary>
        /// Use a parameter filter to return the first element
        /// of the given type and with the specified string-valued
        /// built-in parameter matching the given name.
        /// </summary>
        Element GetFirstElementOfTypeWithBipString(
            Type type,
            BuiltInParameter bip,
            string name)
        {
            FilteredElementCollector a
            = GetElementsOfType( type );

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

              FilterStringRuleEvaluator evaluator
            = new FilterStringEquals();

              FilterRule rule = new FilterStringRule(
            provider, evaluator, name, true );

              ElementParameterFilter filter
            = new ElementParameterFilter( rule );

              return a.WherePasses( filter ).FirstElement();
        }
        /// <summary>
        /// The one and only method required by the IExternalCommand interface,
        /// the main entry point for every external command.
        /// </summary>
        /// <param name="commandData">Input argument providing access to the Revit application and its documents and their properties.</param>
        /// <param name="message">Return argument to display a message to the user in case of error if Result is not Succeeded.</param>
        /// <param name="elements">Return argument to highlight elements on the graphics screen if Result is not Succeeded.</param>
        /// <returns>Cancelled, Failed or Succeeded Result code.</returns>
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIDocument uidoc = commandData.Application.ActiveUIDocument;

            try
            {
                int roomNumber = 1;

                while (true)
                {
                    Reference selRef = uidoc.Selection.PickObject(
                        ObjectType.Element,
                        new MySelectionFilter(),
                        "Select a room");

                    Room room = (Room)selRef.Element;
                    // In 2012 it's better to use
                    // Room room = (Room)uidoc.Document.GetElement(selRef);

                    FilteredElementCollector collector = new FilteredElementCollector(uidoc.Document);

                    // either
                    // collector.OfClass(typeof(Enclosure));
                    // or
                    collector.WherePasses(new RoomFilter());

                    ParameterValueProvider provider = new ParameterValueProvider(
                        new ElementId(BuiltInParameter.ROOM_NUMBER));

                    FilterStringEquals evaluator = new FilterStringEquals();

                    FilterStringRule rule = new FilterStringRule(
                        provider,
                        evaluator,
                        roomNumber.ToString(),
                        false);

                    ElementParameterFilter filter = new ElementParameterFilter(rule);

                    collector.WherePasses(filter);

                    IList <Element> rooms = collector.ToElements();

                    if (rooms.Count > 0)
                    {
                        ((Room)rooms[0]).Number = room.Number;
                    }

                    room.Number = roomNumber.ToString();

                    uidoc.Document.Regenerate();

                    roomNumber++;
                }
            } catch (Autodesk.Revit.Exceptions.OperationCanceledException) {}

            //Must return some code
            return(Result.Succeeded);
        }
        /// <summary>
        /// Return all elements from the given collector
        /// whose element id is greater than 'lastId'.
        /// </summary>
        FilteredElementCollector GetElementsAfter(
            FilteredElementCollector input,
            ElementId lastId)
        {
            BuiltInParameter bip = BuiltInParameter.ID_PARAM;

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

              FilterNumericRuleEvaluator evaluator
            = new FilterNumericGreater();

              FilterRule rule = new FilterElementIdRule(
            provider, evaluator, lastId );

              ElementParameterFilter filter
            = new ElementParameterFilter( rule );

              return input.WherePasses( filter );
        }
    /// <summary>
    /// Optional - example of parameter filter. 
    /// Find walls whose length is longer than a certain length. e.g., 60 feet 
    ///     wall.parameter(length) > 60 feet 
    /// This could get more complex than looping through in terms of writing a code. 
    /// See page 87 of Developer guide. 
    /// </summary> 
    public IList<Element> FindLongWalls()
    {
      // Constant for this function. 
      const double kWallLength = 60.0;  // 60 feet. hard coding for simplicity. 

      // First, narrow down to the elements of the given type and category 
      var collector = new FilteredElementCollector(_doc).OfClass(typeof(Wall));

      // Define a filter by parameter 
      // 1st arg - value provider 
      BuiltInParameter lengthParam = BuiltInParameter.CURVE_ELEM_LENGTH;
      int iLengthParam = (int)lengthParam;
      var paramValueProvider = new ParameterValueProvider(new ElementId(iLengthParam));

      // 2nd - evaluator 
      FilterNumericGreater evaluator = new FilterNumericGreater();

      // 3rd - rule value 
      double ruleVal = kWallLength;

      // 4th - epsilon 
      const double eps = 1E-06;

      // Define a rule 
      var filterRule = new FilterDoubleRule(paramValueProvider, evaluator, ruleVal, eps);

      // Create a new filter 
      var paramFilter = new ElementParameterFilter(filterRule);

      // Go through the filter 
      IList<Element> elems = collector.WherePasses(paramFilter).ToElements();

      return elems;
    }
Example #8
0
        /// <summary>
        /// Return parameter data for all
        /// elements of all the given categories
        /// </summary>
        static void GetParamValuesForCats(
            Dictionary <string, Dictionary <string, List <string> > >
            map_cat_to_uid_to_param_values,
            Document doc,
            BuiltInCategory[] cats)
        {
            // One top level dictionary per category

            foreach (BuiltInCategory cat in cats)
            {
                map_cat_to_uid_to_param_values.Add(
                    cat.Description(),
                    new Dictionary <string,
                                    List <string> >());
            }

            // Collect all required elements

            // The FilterCategoryRule as used here seems to
            // have no filtering effect at all!
            // It passes every single element, afaict.

            List <ElementId> ids
                = new List <BuiltInCategory>(cats)
                  .ConvertAll <ElementId>(c
                                          => new ElementId((int)c));

            FilterCategoryRule r
                = new FilterCategoryRule(ids);

            ElementParameterFilter f
                = new ElementParameterFilter(r, true);

            // Use a logical OR of category filters

            IList <ElementFilter> a
                = new List <ElementFilter>(cats.Length);

            foreach (BuiltInCategory bic in cats)
            {
                a.Add(new ElementCategoryFilter(bic));
            }

            LogicalOrFilter categoryFilter
                = new LogicalOrFilter(a);

            // Run the collector

            FilteredElementCollector els
                = new FilteredElementCollector(doc)
                  .WhereElementIsNotElementType()
                  .WhereElementIsViewIndependent()
                  .WherePasses(categoryFilter);

            // Retrieve parameter data for each element

            foreach (Element e in els)
            {
                Category cat = e.Category;
                if (null == cat)
                {
                    Debug.Print(
                        "element {0} {1} has null category",
                        e.Id, e.Name);
                    continue;
                }
                List <string> param_values = GetParamValues(e);

                BuiltInCategory bic = (BuiltInCategory)
                                      (e.Category.Id.IntegerValue);

                string catkey = bic.Description();
                string uid    = e.UniqueId;

                map_cat_to_uid_to_param_values[catkey].Add(
                    uid, param_values);
            }
        }
Example #9
0
        public void processOlets(ExternalCommandData commandData)
        {
            Document doc = commandData.Application.ActiveUIDocument.Document;

            NumberFormatInfo nfi = new NumberFormatInfo();

            nfi.NumberDecimalSeparator = ",";

            //Collect and filter Olets
            ElementParameterFilter   epf = fi.ParameterValueGenericFilter(doc, "Olet", new Guid("e0baa750-22ba-4e60-9466-803137a0cba8"));
            FilteredElementCollector col = new FilteredElementCollector(doc);
            var olets = col.OfCategory(BuiltInCategory.OST_PipeFitting).OfClass(typeof(FamilyInstance)).WherePasses(epf).ToHashSet();

            foreach (Element olet in olets)
            {
                Cons      cons = mp.GetConnectors(olet);
                Connector prim = cons.Primary;
                //Test if Connector is connected
                if (prim.IsConnected)
                {
                    ConnectorSet refConSet = prim.AllRefs;
                    var          refCons   = mp.GetAllConnectorsFromConnectorSet(refConSet);
                    Connector    refCon    = refCons.Where(x => isPipe(x.Owner)).SingleOrDefault();
                    if (refCon == null)
                    {
                        refCon = refCons.Where(x => x.Owner.IsType <FamilyInstance>()).FirstOrDefault();
                    }
                    if (refCon == null)
                    {
                        throw new Exception($"Element {olet.Id.IntegerValue} refCon Owner cannot find a Pipe of FamilyInstance!");
                    }

                    double dia = 0;

                    switch (refCon.Owner)
                    {
                    case Pipe pipe:
                        dia = pipe.get_Parameter(BuiltInParameter.RBS_PIPE_OUTER_DIAMETER).AsDouble().FtToMm().Round(1);
                        break;

                    case FamilyInstance fis:
                        Element element = (Element)fis;
                        Cons    consFis = mp.GetConnectors(element);
                        dia = (consFis.Primary.Radius * 2).FtToMm().Round(1);
                        break;

                    default:
                        break;
                    }

                    //Pipe pipe = (Pipe)refCon.Owner;

                    Parameter weldsToPar = olet.get_Parameter(new Guid("c3401bb0-2e6c-4831-9917-73d6784a4a6f"));
                    weldsToPar.Set("ø" + dia.ToString(nfi));
                }
            }

            bool isPipe(Element elem)
            {
                switch (elem)
                {
                case Pipe pipe:
                    return(true);

                default:
                    return(false);
                }
            }
        }
        /// <summary>
        /// Return a list of all elements with the 
        /// specified value in their shared parameter with 
        /// the given name oand group. They are retrieved
        /// using a parameter filter, and the required 
        /// parameter id is found by temporarily adding 
        /// the shared parameter to the project info.
        /// </summary>
        static IList<Element> GetElementsMatchingParameter(
            Document doc,
            string paramName,
            string paramGroup,
            string paramValue)
        {
            IList<Element> elems = new List<Element>();

              // Determine if definition for parameter binding exists

              Definition definition = null;
              BindingMap bm = doc.ParameterBindings;
              DefinitionBindingMapIterator it = bm.ForwardIterator();
              while( it.MoveNext() )
              {
            Definition def = it.Key;
            if( def.Name.Equals( paramName ) )
            {
              definition = def;
              break;
            }
              }
              if( definition == null )
              {
            return elems; // parameter binding not defined
              }

              using( Transaction tx = new Transaction( doc ) )
              {
            tx.Start( "Set temporary parameter" );

            // Temporarily set project information element
            // parameter in order to determine param.Id

            FilteredElementCollector collectorPI
              = new FilteredElementCollector( doc );

            collectorPI.OfCategory(
              BuiltInCategory.OST_ProjectInformation );

            Element projInfoElem
              = collectorPI.FirstElement();

            // using http://thebuildingcoder.typepad.com/blog/2012/04/adding-a-category-to-a-shared-parameter-binding.html

            Parameter param = null;

            //param = HelperParams.GetOrCreateElemSharedParam(
            //     projInfoElem, paramName, paramGroup,
            //     ParameterType.Text, false, true );

            if( param != null )
            {
              ElementId paraId = param.Id;

              tx.RollBack(); // discard project element change

              ParameterValueProvider provider
            = new ParameterValueProvider( paraId );

              FilterRule rule = new FilterStringRule(
            provider, new FilterStringEquals(),
            paramValue, true );

              ElementParameterFilter filter
            = new ElementParameterFilter( rule );

              FilteredElementCollector collector
            = new FilteredElementCollector(
              doc, doc.ActiveView.Id );

              elems = collector.WherePasses( filter )
            .ToElements();
            }
              }
              return elems;
        }
Example #11
0
        Result IExternalCommand.Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;
            double        FT    = 0.3048;

            FamilySymbol neocube = new FilteredElementCollector(doc).OfClass(typeof(FamilySymbol)).Where(q => q.Name == "cube").First() as FamilySymbol;

            //FilterStringRuleEvaluator cubeEval = new FilterStringEquals();
            //FilterableValueProvider cubeProv = new ParameterValueProvider(new ElementId((int)BuiltInParameter.ALL_MODEL_TYPE_NAME));
            //FilterStringRule cubeRule = new FilterStringRule(cubeProv, cubeEval, "cube", false);
            ElementParameterFilter cubeFilter = new ElementParameterFilter(new FilterStringRule(new ParameterValueProvider(new ElementId((int)BuiltInParameter.ALL_MODEL_TYPE_NAME)), new FilterStringEquals(), "cube", false));
            List <FamilyInstance>  existCubes = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_GenericModel).WhereElementIsNotElementType().WherePasses(cubeFilter).Cast <FamilyInstance>().ToList();

            List <FamilyInstance> karkas = new FilteredElementCollector(doc)
                                           .OfCategory(BuiltInCategory.OST_StructuralFraming)
                                           .WhereElementIsNotElementType()
                                           .Cast <FamilyInstance>()
                                           .ToList();
            List <FamilyInstance> myKar = new List <FamilyInstance>();

            foreach (FamilyInstance i in karkas)
            {
                if (i.StructuralType.ToString() != "NonStructural")
                {
                    myKar.Add(i);
                }
            }

            List <FamilyInstance> kolon = new FilteredElementCollector(doc)
                                          .OfCategory(BuiltInCategory.OST_StructuralColumns)
                                          .WhereElementIsNotElementType()
                                          .Cast <FamilyInstance>()
                                          .ToList();



            using (Transaction tr = new Transaction(doc, "creating"))
            {
                tr.Start();

                foreach (FamilyInstance i in existCubes)
                {
                    doc.Delete(i.Id);
                }

                /*
                 * foreach (Element i in rooms)
                 * {
                 *
                 *      for (int ind = 0; ind < doors.Count; ind++)
                 *      {
                 *              FamilyInstance dr = doors[ind];
                 *              try
                 *              {
                 *                      if (dr.get_FromRoom(lastPhase).Id == i.Id | dr.get_ToRoom(lastPhase).Id == i.Id)
                 *                      {
                 *
                 *                              BoundingBoxXYZ bBox = i.get_BoundingBox(null);
                 *                              LocationPoint origin = (LocationPoint)i.Location;
                 *
                 *                              XYZ center = origin.Point;
                 *                              if (!neocube.IsActive)
                 *                                      neocube.Activate();
                 *                              FamilyInstance cubeIns = doc.Create.NewFamilyInstance(center, neocube, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
                 *                              cubeIns.LookupParameter("RoomNum").Set(i.get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString());
                 *                              cubeIns.LookupParameter("MainText").Set(dr.Symbol.LookupParameter("ADSK_Марка").AsString());
                 *                              cubeIns.setType();
                 *
                 *                              b.Append("ok");//dr.LookupParameter("ADSK_Марка").AsValueString());
                 *                              doors.Remove(dr);
                 *                              ind--;
                 *
                 *                      }
                 *              }
                 *              catch (Exception)
                 *              {
                 *
                 *              }
                 *
                 *      }
                 *
                 *      foreach (FamilyInstance dr in windows)
                 *      {
                 *              try
                 *              {
                 *                      if (dr.get_FromRoom(lastPhase).Id == i.Id)
                 *                      {
                 *
                 *
                 *                              LocationPoint origin = (LocationPoint)i.Location;
                 *
                 *                              XYZ center = origin.Point;
                 *                              if (!neocube.IsActive)
                 *                                      neocube.Activate();
                 *                              FamilyInstance cubeIns = doc.Create.NewFamilyInstance(center, neocube, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
                 *                              cubeIns.LookupParameter("RoomNum").Set(i.get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString());
                 *                              cubeIns.LookupParameter("MainText").Set(dr.Symbol.LookupParameter("ADSK_Марка").AsString());
                 *                              cubeIns.setType();
                 *
                 *
                 *                              FamilyInstance winOtkos = doc.Create.NewFamilyInstance(center, neocube, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
                 *                              winOtkos.LookupParameter("RoomNum").Set(i.get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString());
                 *                              winOtkos.LookupParameter("MainText").Set("Площадь откосов: ");
                 *                              winOtkos.LookupParameter("Area").Set(dr.LookupParameter("ADSK_Откосы_Глубина").AsDouble()
                 * (dr.LookupParameter("VIDNAL_Высота проема").AsDouble() * 2 + dr.LookupParameter("VIDNAL_Ширина проема").AsDouble()));
                 *                              winOtkos.setType("area");
                 *
                 *                              FamilyInstance winPodok = doc.Create.NewFamilyInstance(center, neocube, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
                 *                              winPodok.LookupParameter("RoomNum").Set(i.get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString());
                 *                              String output = String.Format("Подоконник {0:f2}x{1:f2}", dr.LookupParameter("VIDNAL_Ширина проема").AsDouble() * FT, dr.LookupParameter("ADSK_Откосы_Глубина").AsDouble() * FT);
                 *                              winPodok.LookupParameter("MainText").Set(output);
                 *                              winPodok.setType();
                 *
                 *                              FamilyInstance winUgol = doc.Create.NewFamilyInstance(center, neocube, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
                 *                              winUgol.LookupParameter("RoomNum").Set(i.get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString());
                 *                              winUgol.LookupParameter("MainText").Set("ПВХ уголок 60х60");
                 *                              winUgol.LookupParameter("dlina").Set(dr.LookupParameter("VIDNAL_Высота проема").AsDouble() * 2 + dr.LookupParameter("VIDNAL_Ширина проема").AsDouble());
                 *                              winUgol.setType("len");
                 *
                 *                      }
                 *              }
                 *              catch (Exception)
                 *              {
                 *
                 *              }
                 *      }
                 * }
                 * foreach (Element i in rooms)
                 * {
                 *      if (i.LookupParameter("ЗаменаПокрытияПола").AsInteger() == 1)
                 *      {
                 *
                 *              LocationPoint origin = (LocationPoint)i.Location;
                 *              XYZ center = origin.Point;
                 *              if (!neocube.IsActive)
                 *                      neocube.Activate();
                 *              FamilyInstance cubeIns = doc.Create.NewFamilyInstance(center, neocube, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
                 *              cubeIns.LookupParameter("RoomNum").Set(i.get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString());
                 *              cubeIns.LookupParameter("MainText").Set(i.LookupParameter("snosF").AsString());
                 *              cubeIns.LookupParameter("Area").Set(i.get_Parameter(BuiltInParameter.ROOM_AREA).AsDouble());
                 *              cubeIns.setType("area");
                 *              if (cubeIns.LookupParameter("MainText").AsString() == "")
                 *              {
                 *                      doc.Delete(cubeIns.Id);
                 *
                 *              }
                 *
                 *      }
                 *      if (i.LookupParameter("НоваяОтделка").AsInteger() == 1)
                 *      {
                 *
                 *              LocationPoint origin = (LocationPoint)i.Location;
                 *              XYZ center = origin.Point;
                 *              if (!neocube.IsActive)
                 *                      neocube.Activate();
                 *              FamilyInstance cubeIns = doc.Create.NewFamilyInstance(center, neocube, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
                 *              cubeIns.LookupParameter("RoomNum").Set(i.get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString());
                 *              cubeIns.LookupParameter("MainText").Set("Демонтаж штукатурки");
                 *              cubeIns.LookupParameter("Area").Set(i.LookupParameter("WallS").AsDouble());
                 *              cubeIns.setType("area");
                 *      }
                 *
                 * }
                 */
                tr.Commit();
            }

            return(Result.Succeeded);
        }
        /// <summary>
        /// Return the viewport on the given
        /// sheet displaying the given view.
        /// </summary>
        Element GetViewport( ViewSheet sheet, View view )
        {
            Document doc = sheet.Document;

              // filter for view name:

              BuiltInParameter bip
            = BuiltInParameter.VIEW_NAME;

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

              FilterStringRuleEvaluator evaluator
            = new FilterStringEquals();

              FilterRule rule = new FilterStringRule(
            provider, evaluator, view.Name, true );

              ElementParameterFilter name_filter
            = new ElementParameterFilter( rule );

              BuiltInCategory bic
            = BuiltInCategory.OST_Viewports;

              // retrieve the specific named viewport:

              //Element viewport
              //  = new FilteredElementCollector( doc )
              //    .OfCategory( bic )
              //    .WherePasses( name_filter )
              //    .FirstElement();
              //return viewport;

              // unfortunately, there are not just one,
              // but two candidate elements. apparently,
              // we can distibuish them using the
              // owner view id property:

              List<Element> viewports
            = new List<Element>(
              new FilteredElementCollector( doc )
            .OfCategory( bic )
            .WherePasses( name_filter )
            .ToElements() );

              Debug.Assert( viewports[0].OwnerViewId.Equals( ElementId.InvalidElementId ),
            "expected the first viewport to have an invalid owner view id" );

              Debug.Assert( !viewports[1].OwnerViewId.Equals( ElementId.InvalidElementId ),
            "expected the second viewport to have a valid owner view id" );

              int i = 1;

              return viewports[i];
        }
Example #13
0
        public static ElementFilter createParameterFilter(Document doc, ParameterData parameter, string operation, string ruleString)
        {
            ElementId parameterId              = parameter.Id;
            ParameterValueProvider fvp         = new ParameterValueProvider(parameterId);
            StorageType            storageType = parameter.StorageType;
            FilterRule             fRule       = null;
            FilterInverseRule      fInvRule    = null;
            ElementParameterFilter filter      = null;


            switch (storageType)
            {
            case StorageType.String:
            case StorageType.Integer:
                FilterStringRuleEvaluator fsre = null;
                switch (operation)
                {
                case "равно":
                    fsre   = new FilterStringEquals();
                    fRule  = new FilterStringRule(fvp, fsre, ruleString, true);
                    filter = new ElementParameterFilter(fRule);
                    break;

                case "не равно":
                    fsre     = new FilterStringEquals();
                    fRule    = new FilterStringRule(fvp, fsre, ruleString, true);
                    fInvRule = new FilterInverseRule(fRule);
                    filter   = new ElementParameterFilter(fInvRule);
                    break;

                case "содержит":
                    fsre   = new FilterStringContains();
                    fRule  = new FilterStringRule(fvp, fsre, ruleString, true);
                    filter = new ElementParameterFilter(fRule);
                    break;

                case "не содержит":
                    fsre     = new FilterStringContains();
                    fRule    = new FilterStringRule(fvp, fsre, ruleString, true);
                    fInvRule = new FilterInverseRule(fRule);
                    filter   = new ElementParameterFilter(fInvRule);
                    break;

                case "начинается с":
                    fsre   = new FilterStringBeginsWith();
                    fRule  = new FilterStringRule(fvp, fsre, ruleString, true);
                    filter = new ElementParameterFilter(fRule);
                    break;

                case "не начинается с":
                    fsre     = new FilterStringBeginsWith();
                    fRule    = new FilterStringRule(fvp, fsre, ruleString, true);
                    fInvRule = new FilterInverseRule(fRule);
                    filter   = new ElementParameterFilter(fInvRule);
                    break;

                case "заканчивается на":
                    fsre   = new FilterStringEndsWith();
                    fRule  = new FilterStringRule(fvp, fsre, ruleString, true);
                    filter = new ElementParameterFilter(fRule);
                    break;

                case "не заканчивается на":
                    fsre     = new FilterStringEndsWith();
                    fRule    = new FilterStringRule(fvp, fsre, ruleString, true);
                    fInvRule = new FilterInverseRule(fRule);
                    filter   = new ElementParameterFilter(fInvRule);
                    break;
                }
                break;

            case StorageType.Double:
                FilterNumericRuleEvaluator fnre = null;
                double ruleValue = Convert.ToDouble(ruleString);
                switch (operation)
                {
                case "равно":
                    fnre   = new FilterNumericEquals();
                    fRule  = new FilterDoubleRule(fvp, fnre, ruleValue, 0.0);
                    filter = new ElementParameterFilter(fRule);
                    break;

                case "не равно":
                    fnre     = new FilterNumericEquals();
                    fRule    = new FilterDoubleRule(fvp, fnre, ruleValue, 0.0);
                    fInvRule = new FilterInverseRule(fRule);
                    filter   = new ElementParameterFilter(fInvRule);
                    break;

                case "больше":
                    fnre   = new FilterNumericGreater();
                    fRule  = new FilterDoubleRule(fvp, fnre, ruleValue, 0.0);
                    filter = new ElementParameterFilter(fRule);
                    break;

                case "больше или равно":
                    fnre   = new FilterNumericGreaterOrEqual();
                    fRule  = new FilterDoubleRule(fvp, fnre, ruleValue, 0.0);
                    filter = new ElementParameterFilter(fRule);
                    break;

                case "меньше":
                    fnre   = new FilterNumericLess();
                    fRule  = new FilterDoubleRule(fvp, fnre, ruleValue, 0.0);
                    filter = new ElementParameterFilter(fRule);
                    break;

                case "меньше или равно":
                    fnre   = new FilterNumericLessOrEqual();
                    fRule  = new FilterDoubleRule(fvp, fnre, ruleValue, 0.0);
                    filter = new ElementParameterFilter(fRule);
                    break;
                }
                break;

            case StorageType.ElementId:

                var       levels = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Levels).ToElements();
                var       level  = levels.Where(i => i.Name == ruleString).FirstOrDefault();
                ElementId ruleId = level.Id;

                fnre = null;
                switch (operation)
                {
                case "равно":
                    fnre   = new FilterNumericEquals();
                    fRule  = new FilterElementIdRule(fvp, fnre, ruleId);
                    filter = new ElementParameterFilter(fRule);
                    break;

                case "не равно":
                    fnre     = new FilterNumericEquals();
                    fRule    = new FilterElementIdRule(fvp, fnre, ruleId);
                    fInvRule = new FilterInverseRule(fRule);
                    filter   = new ElementParameterFilter(fInvRule);
                    break;

                case "выше":
                    fnre   = new FilterNumericGreater();
                    fRule  = new FilterElementIdRule(fvp, fnre, ruleId);
                    filter = new ElementParameterFilter(fRule);
                    break;

                case "ровно или выше":
                    fnre   = new FilterNumericGreaterOrEqual();
                    fRule  = new FilterElementIdRule(fvp, fnre, ruleId);
                    filter = new ElementParameterFilter(fRule);
                    break;

                case "ниже":
                    fnre   = new FilterNumericLess();
                    fRule  = new FilterElementIdRule(fvp, fnre, ruleId);
                    filter = new ElementParameterFilter(fRule);
                    break;

                case "ровно или ниже":
                    fnre   = new FilterNumericLessOrEqual();
                    fRule  = new FilterElementIdRule(fvp, fnre, ruleId);
                    filter = new ElementParameterFilter(fRule);
                    break;
                }
                break;
            }
            return(filter);
        }
Example #14
0
        private bool DoWork(ExternalCommandData commandData,
                            ref String message, ElementSet elements)
        {
            if (null == commandData)
            {
                throw new ArgumentNullException(nameof(commandData));
            }

            if (null == message)
            {
                throw new ArgumentNullException(nameof(message));
            }

            if (null == elements)
            {
                throw new ArgumentNullException(nameof(elements));
            }

            ResourceManager res_mng     = new ResourceManager(GetType());
            ResourceManager def_res_mng = new ResourceManager(typeof(Properties.Resources));

            UIApplication ui_app    = commandData.Application;
            UIDocument    ui_doc    = ui_app?.ActiveUIDocument;
            Application   app       = ui_app?.Application;
            Document      doc       = ui_doc?.Document;
            Selection     selection = ui_doc?.Selection;

            var tr_name = res_mng.GetString("_transaction_name");

            try
            {
                using (var tr = new Transaction(doc, tr_name))
                {
                    if (TransactionStatus.Started == tr.Start()
                        )
                    {
                        ProjectSettingsStorage pStore = new ProjectSettingsStorage();
                        ProjectSettings        set    = pStore.ReadSettings(doc);

                        ICollection <ElementId> selectedIds = selection.GetElementIds();
                        ICollection <ElementId> panelIds    = new List <ElementId>();
                        IList <ElementId>       elems       = new List <ElementId>();
                        IList <bool>            check       = new List <bool>();


                        if (0 == selectedIds.Count)
                        {
                            // If no elements selected.
                            TaskDialog.Show("Revit", "You haven't selected any elements.");
                        }
                        else
                        {
                            int    totalCount   = 0;
                            int    currentCount = 0;
                            int    localTotal   = 10;
                            int    localCurrent = 0;
                            String info         = "The following assemblies have successfully been created: ";
                            foreach (ElementId id in selectedIds)
                            {
                                Element elem = ui_doc.Document.GetElement(id);
                                elem.LookupParameter("BIMSF_Container");
                                //foreach (Parameter pa in elem.Parameters)
                                //{
                                //if (pa.Definition.Name == "BIMSF_Container" && pa.AsString() != null && elem.get_Parameter(BuiltInParameter.ASSEMBLY_NAME) == null)
                                if (elem.LookupParameter("BIMSF_Container") != null && elem.get_Parameter(BuiltInParameter.ASSEMBLY_NAME) == null)
                                {
                                    panelIds.Add(id);
                                    totalCount += 1;
                                }
                                //}
                            }
                            ProgressForm pf           = new ProgressForm(String.Format("{0} of {1} panels processed", currentCount, totalCount), "Creating wall assembly...", (int)100 / totalCount, (int)100 / localTotal);
                            string       localString  = "Creating wall assembly...";
                            string       globalString =
                                String.Format("{0} of {1} panels processed", currentCount, totalCount);
                            pf.LabelSet(localString, false, false, globalString, false);

                            pf.Show();

                            foreach (ElementId id in panelIds)
                            {
                                Element elem = ui_doc.Document.GetElement(id);
                                //foreach (Parameter pa in elem.Parameters)
                                //{
                                Parameter pa = elem.LookupParameter("BIMSF_Container");
                                if (pa.Definition.Name == "BIMSF_Container" && pa.AsString() != null && elem.get_Parameter(BuiltInParameter.ASSEMBLY_NAME) == null)
                                {
                                    ElementId ida = new ElementId(pa.Id.IntegerValue);
                                    elems.Clear();

                                    ParameterValueProvider provider = new ParameterValueProvider(ida);

                                    FilterStringRuleEvaluator eval = new FilterStringEquals();

                                    FilterRule               rule   = new FilterStringRule(provider, eval, elem.get_Parameter(pa.Definition).AsString(), false);
                                    ElementParameterFilter   filter = new ElementParameterFilter(rule);
                                    FilteredElementCollector fec    = new FilteredElementCollector(ui_doc.Document).WhereElementIsNotElementType().WherePasses(filter);

                                    foreach (Element e in fec)
                                    {
                                        elems.Add(e.Id);
                                    }
                                    FilteredElementCollector fecC = new FilteredElementCollector(doc, elems).OfCategory(BuiltInCategory.OST_StructuralColumns);
                                    FilteredElementCollector fecF = new FilteredElementCollector(doc, elems).OfCategory(BuiltInCategory.OST_StructuralFraming);

                                    ElementId categoryId = doc.GetElement(elems.First()).Category.Id; // use category of one of the assembly elements
                                    if (AssemblyInstance.IsValidNamingCategory(doc, categoryId, elems))
                                    {
                                        TransactionStatus tStat = tr.HasStarted() ? tr.GetStatus() : tr.Start();

                                        pf.LabelSet(localString, true, false, globalString, false);

                                        //IList<Element> el = new List<Element>();
                                        //IList<Element> col = new List<Element>();
                                        ReferenceArray colArray  = new ReferenceArray();
                                        ReferenceArray framArray = new ReferenceArray();
                                        colArray.Clear();
                                        framArray.Clear();
                                        AssemblyInstance assemblyInstance = AssemblyInstance.Create(doc, elems, categoryId);
                                        XYZ pt1 = assemblyInstance.GetTransform().BasisZ;
                                        XYZ pt2 = assemblyInstance.GetCenter();

                                        /*el.Clear();
                                         * col.Clear();
                                         *
                                         * foreach (Element co in fecC)
                                         * {
                                         *  col.Add(co);
                                         * }*/

                                        foreach (Element fr in fecF)
                                        {
                                            //el.Add(fr);
                                            FamilyInstance fi = fr as FamilyInstance;
                                            framArray.Append(fi.GetReferenceByName("HardSide"));
                                        }

                                        /*foreach (ElementId item in elems)
                                         * {
                                         *  if (doc.GetElement(item).Category.Name == "Structural Framing")
                                         *  {
                                         *      el.Add(doc.GetElement(item));
                                         *      FamilyInstance fi = doc.GetElement(item) as FamilyInstance;
                                         *      framArray.Append(fi.GetReferenceByName("HardSide"));
                                         *  }else if (doc.GetElement(item).Category.Name == "Structural Columns")
                                         *  {
                                         *      col.Add(doc.GetElement(item));
                                         *  }
                                         * }*/
                                        //Element il = el.First();
                                        LocationCurve lc    = fecF.FirstElement().Location as LocationCurve;
                                        Curve         line  = lc.Curve;
                                        XYZ           start = line.GetEndPoint(0);
                                        XYZ           end   = line.GetEndPoint(1);
                                        XYZ           v     = (end - start);
                                        double        angle = v.AngleTo(XYZ.BasisX);

                                        foreach (Element column in fecC)
                                        {
                                            FamilyInstance fi       = column as FamilyInstance;
                                            LocationPoint  colLc    = column.Location as LocationPoint;
                                            double         colAngle = colLc.Rotation;
                                            if (Math.Round(colAngle, 2) == Math.Round(angle, 2) || Math.Round(colAngle, 2) == Math.Round(angle + Math.PI, 2) || Math.Round(colAngle, 2) == Math.Round(angle - Math.PI, 2))
                                            {
                                                colArray.Append(fi.GetReferenceByName("HardSide"));
                                                //TaskDialog.Show("HardSide", colAngle + "\n" + angle);
                                            }
                                            else
                                            {
                                                colArray.Append(fi.GetReferenceByName("LeftSide"));
                                                //TaskDialog.Show("Revit",colAngle + "\n" + angle);
                                            }
                                        }

                                        //TaskDialog.Show("Revit", angle.ToString());
                                        Transform trf = Transform.CreateRotationAtPoint(pt1, angle, pt2);
                                        assemblyInstance.SetTransform(trf);
                                        tr.Commit(); // commit the transaction that creates the assembly instance before modifying the instance's name
                                        localCurrent += 1;
                                        localString   = "Creating 3D view...";
                                        pf.LabelSet(localString, true, false, globalString, false);
                                        if (tr.GetStatus() == TransactionStatus.Committed)
                                        {
                                            tr.Start("Set Assembly Name");
                                            assemblyInstance.AssemblyTypeName = elem.get_Parameter(pa.Definition).AsString();
                                            info += "\n" + assemblyInstance.AssemblyTypeName;
                                            tr.Commit();
                                        }

                                        if (assemblyInstance.AllowsAssemblyViewCreation()) // create assembly views for this assembly instance
                                        {
                                            if (tr.GetStatus() == TransactionStatus.Committed)
                                            {
                                                tr.Start("View Creation");

                                                View3D view3D = AssemblyViewUtils.Create3DOrthographic(doc, assemblyInstance.Id);

                                                localCurrent += 1;
                                                localString   = "Creating elevation view...";
                                                pf.LabelSet(localString, true, false, globalString, false);

                                                View elView = AssemblyViewUtils.CreateDetailSection(doc, assemblyInstance.Id, AssemblyDetailViewOrientation.ElevationFront);

                                                localCurrent += 1;
                                                localString   = "Populating elevation view...";
                                                pf.LabelSet(localString, true, false, globalString, false);

                                                TagMode        tm      = TagMode.TM_ADDBY_CATEGORY;
                                                bool           addLead = false;
                                                XYZ            center;
                                                TagOrientation to;

                                                foreach (Element co in fecC)
                                                {
                                                    to = TagOrientation.Vertical;
                                                    LocationPoint cols  = co.Location as LocationPoint;
                                                    XYZ           colPt = cols.Point;
                                                    double        colX  = colPt.X;
                                                    double        colY  = colPt.Y;
                                                    ElementId     blId  = co.get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_PARAM).AsElementId();
                                                    Level         bl    = doc.GetElement(blId) as Level;
                                                    double        zb    = bl.Elevation;
                                                    double        blo   = co.get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_OFFSET_PARAM).AsDouble();
                                                    double        bot   = zb + blo;

                                                    ElementId tlId  = co.get_Parameter(BuiltInParameter.FAMILY_TOP_LEVEL_PARAM).AsElementId();
                                                    Level     tl    = doc.GetElement(tlId) as Level;
                                                    double    zt    = tl.Elevation;
                                                    double    tlo   = co.get_Parameter(BuiltInParameter.FAMILY_TOP_LEVEL_OFFSET_PARAM).AsDouble();
                                                    double    top   = zt + tlo;
                                                    double    zCent = (top + bot) / 2;

                                                    center = new XYZ(colX, colY, zCent);
                                                    Reference refer = new Reference(co);
                                                    IndependentTag.Create(doc, elView.Id, refer, addLead, tm, to, center);
                                                }

                                                foreach (Element fr in fecF)
                                                {
                                                    to = TagOrientation.Horizontal;
                                                    LocationCurve loc    = fr.Location as LocationCurve;
                                                    XYZ           start2 = loc.Curve.GetEndPoint(0);
                                                    XYZ           end2   = loc.Curve.GetEndPoint(1);
                                                    center = (start2 + end2) / 2;
                                                    Reference refer = new Reference(fr);
                                                    IndependentTag.Create(doc, elView.Id, refer, addLead, tm, to, center);
                                                }

                                                /*foreach (ElementId eI in elems)
                                                 * {
                                                 *  Element e = doc.GetElement(eI);
                                                 *
                                                 *  if ((BuiltInCategory)e.Category.Id.IntegerValue == BuiltInCategory.OST_StructuralColumns || (BuiltInCategory)e.Category.Id.IntegerValue == BuiltInCategory.OST_StructuralFraming)
                                                 *  {
                                                 *      XYZ center;
                                                 *      TagOrientation to;
                                                 *      if ((BuiltInCategory)e.Category.Id.IntegerValue == BuiltInCategory.OST_StructuralColumns)
                                                 *      {
                                                 *          to = TagOrientation.Vertical;
                                                 *          LocationPoint cols = e.Location as LocationPoint;
                                                 *          XYZ colPt = cols.Point;
                                                 *          double colX = colPt.X;
                                                 *          double colY = colPt.Y;
                                                 *          ElementId blId = e.get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_PARAM).AsElementId();
                                                 *          Level bl = doc.GetElement(blId) as Level;
                                                 *          double zb = bl.Elevation;
                                                 *          double blo = e.get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_OFFSET_PARAM).AsDouble();
                                                 *          double bot = zb + blo;
                                                 *
                                                 *          ElementId tlId = e.get_Parameter(BuiltInParameter.FAMILY_TOP_LEVEL_PARAM).AsElementId();
                                                 *          Level tl = doc.GetElement(tlId) as Level;
                                                 *          double zt = tl.Elevation;
                                                 *          double tlo = e.get_Parameter(BuiltInParameter.FAMILY_TOP_LEVEL_OFFSET_PARAM).AsDouble();
                                                 *          double top = zt + tlo;
                                                 *          double zCent = (top + bot) / 2;
                                                 *
                                                 *          center = new XYZ(colX,colY,zCent);
                                                 *      }
                                                 *      else
                                                 *      {
                                                 *          to = TagOrientation.Horizontal;
                                                 *          LocationCurve loc = e.Location as LocationCurve;
                                                 *          XYZ start2 = loc.Curve.GetEndPoint(0);
                                                 *          XYZ end2 = loc.Curve.GetEndPoint(1);
                                                 *          center = (start2 + end2) / 2;
                                                 *      }
                                                 *
                                                 *
                                                 *      Reference refer = new Reference(e);
                                                 *      IndependentTag.Create(doc, elView.Id, refer, addLead, tm, to, center);
                                                 *
                                                 *  }
                                                 *
                                                 * }*/

                                                try
                                                {
                                                    //LocationCurve framC = fecF.FirstElement().Location as LocationCurve;
                                                    FamilyInstance fi = fecC.FirstElement() as FamilyInstance;
                                                    //Transform fiP = fi.GetTransform();

                                                    LocationPoint col1 = fecC.FirstElement().Location as LocationPoint;
                                                    //XYZ test = fiP.OfPoint(col1.Point);

                                                    ElementId col1Bot = fecC.FirstElement().get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_PARAM).AsElementId();
                                                    Level     col1LB  = doc.GetElement(col1Bot) as Level;
                                                    double    bottom  = col1LB.Elevation;

                                                    ElementId col1Top = fecC.FirstElement().get_Parameter(BuiltInParameter.FAMILY_TOP_LEVEL_PARAM).AsElementId();
                                                    Level     col1LT  = doc.GetElement(col1Top) as Level;
                                                    double    top     = col1LT.Elevation;

                                                    //Line framT = framC.Curve as Line;
                                                    //XYZ framP = framT.Origin;
                                                    Line      framL = Line.CreateBound(new XYZ(col1.Point.X, col1.Point.Y, bottom), new XYZ(col1.Point.X, col1.Point.Y, top));
                                                    Dimension di    = doc.Create.NewDimension(elView, framL, framArray);
                                                    di.DimensionType = doc.GetElement(set.HorizontalDimFlr) as DimensionType;
                                                }
                                                catch (Exception e)
                                                {
                                                    TaskDialog.Show("Revit", e.Message + "\n" + e.Source);
                                                }

                                                try
                                                {
                                                    LocationCurve framC = fecF.FirstElement().Location as LocationCurve;

                                                    ElementId col1Bot = fecC.FirstElement().get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_PARAM).AsElementId();
                                                    Level     col1LB  = doc.GetElement(col1Bot) as Level;
                                                    double    bottom  = col1LB.Elevation;

                                                    Line framT = framC.Curve as Line;
                                                    XYZ  framS = framT.GetEndPoint(0);
                                                    XYZ  framE = framT.GetEndPoint(1);
                                                    //Line framL = framT.CreateOffset(-1, XYZ.BasisZ) as Line;
                                                    //XYZ framP = framT.Origin;
                                                    Line      framL = Line.CreateBound(new XYZ(framS.X, framS.Y, bottom - 1.5), new XYZ(framE.X, framE.Y, bottom - 1.5));
                                                    Dimension di    = doc.Create.NewDimension(elView, framL, colArray);
                                                    di.DimensionType = doc.GetElement(set.HeightDimWa) as DimensionType;
                                                    LocationPoint clp = fecC.FirstElement().Location as LocationPoint;
                                                }
                                                catch (Exception e)
                                                {
                                                    TaskDialog.Show("Revit", e.Message + "\n" + e.Source);
                                                }
                                                localCurrent += 1;
                                                localString   = "Creating plan view...";
                                                pf.LabelSet(localString, true, false, globalString, false);
                                                View plView = AssemblyViewUtils.CreateDetailSection(doc, assemblyInstance.Id, AssemblyDetailViewOrientation.ElevationTop);

                                                localCurrent += 1;
                                                localString   = "Creating material takeoff schedule...";
                                                pf.LabelSet(localString, true, false, globalString, false);
                                                ViewSchedule partList = AssemblyViewUtils.CreatePartList(doc, assemblyInstance.Id);

                                                XYZ pt3D = new XYZ(0.1, 0.45, 0);
                                                XYZ ptEl = new XYZ(0.5, 0.5, 0);
                                                XYZ ptPl = new XYZ(0.5, 0.5, 0);
                                                XYZ ptPa = new XYZ(0.03, 0.1, 0);

                                                if (set != null)
                                                {
                                                    view3D.ViewTemplateId = set.View3DTemplate;
                                                }

                                                if (set != null)
                                                {
                                                    elView.ViewTemplateId = set.ViewElTemplate;
                                                }

                                                if (set != null)
                                                {
                                                    plView.ViewTemplateId = set.ViewPlTemplate;
                                                }

                                                if (set != null)
                                                {
                                                    partList.ViewTemplateId = set.ViewPaTemplate;
                                                }
                                                if (set != null)
                                                {
                                                    try
                                                    {
                                                        localCurrent += 1;
                                                        localString   = "Creating spool sheet...";
                                                        pf.LabelSet(localString, true, false, globalString, false);
                                                        ElementType noTitle          = null;
                                                        FilteredElementCollector fen = new FilteredElementCollector(doc).OfClass(typeof(ElementType));
                                                        foreach (Element item in fen)
                                                        {
                                                            if (item.Name == "No Title")
                                                            {
                                                                noTitle = item as ElementType;
                                                            }
                                                        }

                                                        ViewSheet sheet = AssemblyViewUtils.CreateSheet(doc, assemblyInstance.Id, set.TemplateTemplate);
                                                        localCurrent += 1;
                                                        localString   = "Adding views to sheet...";
                                                        pf.LabelSet(localString, true, false, globalString, false);
                                                        Viewport v3D = AddViewToSheet(doc, sheet, noTitle, pt3D, view3D.Id);

                                                        Viewport       vEl  = AddViewToSheet(doc, sheet, noTitle, ptEl, elView.Id);
                                                        BoundingBoxXYZ bbEl = vEl.get_BoundingBox(sheet);


                                                        Viewport       vPl  = AddViewToSheet(doc, sheet, noTitle, ptPl, plView.Id);
                                                        BoundingBoxXYZ bbPl = vPl.get_BoundingBox(sheet);



                                                        ScheduleSheetInstance vPa = ScheduleSheetInstance.Create(doc, sheet.Id, partList.Id, ptPa);
                                                        localCurrent += 1;
                                                        localString   = "Cleaning up spool sheet...";
                                                        pf.LabelSet(localString, true, false, globalString, false);
                                                        BoundingBoxXYZ bb    = sheet.CropBox;
                                                        BoundingBoxXYZ bbvPa = vPa.get_BoundingBox(sheet);
                                                        double         minX  = bb.Min.X;
                                                        double         maxX  = bb.Max.X;
                                                        double         xLen  = maxX - minX;
                                                        //TaskDialog.Show("Revit",minX + ", " + maxX + "\n" +bbvPa.Min.Y + ", " + bbvPa.Max.Y +  "\n" + bbPl.Min.X + ", " + bbPl.Min.Y);
                                                        vPa.Point = new XYZ(vPa.Point.X, vPa.Point.Y - bbvPa.Min.Y, vPa.Point.Z);
                                                        double schedX  = bbvPa.Max.X + 0.03;
                                                        double centEl  = (bbEl.Max.X - bbEl.Min.X) / 2;
                                                        double centElY = (bbEl.Max.Y - bbEl.Min.Y) / 2;
                                                        double centPlY = (bbPl.Max.Y - bbPl.Min.Y) / 2;
                                                        vEl.SetBoxCenter(new XYZ(schedX + centEl, (centPlY + 0.05) * 2 + centElY, vEl.GetBoxCenter().Z));
                                                        vPl.SetBoxCenter(new XYZ(schedX + centEl, centPlY + 0.05, vPl.GetBoxCenter().Z));


                                                        sheet.SheetNumber = elem.get_Parameter(pa.Definition).AsString();
                                                        sheet.Name        = "Framing";
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        TaskDialog.Show("Error", ex.Message);
                                                        break;
                                                    }
                                                }

                                                localCurrent += 1;
                                                localString   = String.Format("Wall assembly {0} completed...",
                                                                              elem.get_Parameter(pa.Definition).AsString());
                                                pf.LabelSet(localString, true, false, globalString, false);
                                                tr.Commit();
                                                localCurrent = 0;
                                            }
                                        }
                                        currentCount += 1;
                                        globalString  = String.Format("{0} of {1} panels processed", currentCount, totalCount);
                                        pf.LabelSet(localString, false, true, globalString, true);
                                    }
                                    //info += "\n\t" + pa.Definition.Name + ": " + pa.AsString();
                                }
                                //}
                            }
                            pf.Close();
                            tr.Start();
                            doc.Regenerate();
                            tr.Commit();
                            TaskDialog.Show("Revit", info);
                        }

                        return(true);
                    }
                }
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }
            finally
            {
                res_mng.ReleaseAllResources();
                def_res_mng.ReleaseAllResources();
            }
            return(false);
        }
Example #15
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Document doc = commandData.Application.ActiveUIDocument.Document;

            // Door variables.
            string doorName = string.Empty;
            string itemType = string.Empty;
            string doorType = string.Empty;
            int    height   = 0;
            int    width    = 0;
            string props    = string.Empty;

            // Find the right door family.
            FilteredElementCollector collector =
                new FilteredElementCollector(doc);

            FilterRule famNameRule = ParameterFilterRuleFactory
                                     .CreateBeginsWithRule(
                new ElementId((int)BuiltInParameter.ALL_MODEL_FAMILY_NAME),
                "A-M3-ConceptualDoor", true);

            FilterRule typeNameRule = ParameterFilterRuleFactory
                                      .CreateEqualsRule(
                new ElementId((int)BuiltInParameter.ALL_MODEL_TYPE_NAME),
                "Default", true);

            ElementParameterFilter famNameFlt =
                new ElementParameterFilter(famNameRule);

            ElementParameterFilter typeNameFlt =
                new ElementParameterFilter(typeNameRule);

            LogicalAndFilter andFilter =
                new LogicalAndFilter(famNameFlt, typeNameFlt);

            Func <FamilySymbol, bool> singleLeaf =
                (fs) => fs.FamilyName == "A-M3-ConceptualDoorSingleLeaf-LOD2";

            Func <FamilySymbol, bool> doubleLeaf =
                (fs) => fs.FamilyName == "A-M3-ConceptualDoorDoubleLeaf-LOD2";

            IEnumerable <FamilySymbol> doors = collector
                                               .OfCategory(BuiltInCategory.OST_Doors)
                                               .WhereElementIsElementType()
                                               .WherePasses(andFilter)
                                               .Cast <FamilySymbol>();

            FamilySymbol singleLeafDoor = doors
                                          .Where(singleLeaf)
                                          .FirstOrDefault();

            FamilySymbol doubleLeafDoor = doors
                                          .Where(doubleLeaf)
                                          .FirstOrDefault();

            if (singleLeafDoor == null)
            {
                TaskDialog.Show("No door family",
                                "Please load the family: A-M3-ConceptualDoorSingleLeaf-LOD2");
                return(Result.Failed);
            }

            // Show the custom window
            RussianDoorWnd win = new RussianDoorWnd();

            win.btnCreate.Click += delegate(object sender, RoutedEventArgs e) {
                doorName = win.lbg6629.Content.ToString();

                itemType = ((ComboBoxItem)win.itemType.SelectedItem).Content.ToString();
                doorType = ((ComboBoxItem)win.doorType.SelectedItem).Content.ToString();
                height   = Int16.Parse((string)((ComboBoxItem)win.height.SelectedItem).Content) * 100;
                width    = Int16.Parse((string)((ComboBoxItem)win.width.SelectedItem).Content) * 100;
                props    = ((ComboBoxItem)win.props.SelectedItem).Content.ToString();

                win.Close();

                try {
                    using (TransactionGroup tg = new TransactionGroup(doc, "Create new type")) {
                        ElementType newType;

                        tg.Start();

                        using (Transaction t1 = new Transaction(doc, "Create new type")) {
                            t1.Start();
                            if (width <= 1200)
                            {
                                newType = singleLeafDoor.Duplicate(doorName);
                            }
                            else
                            {
                                newType = doubleLeafDoor.Duplicate(doorName);
                            }
                            t1.Commit();
                        }

                        using (Transaction t2 = new Transaction(doc, "Set params")) {
                            t2.Start();

                            switch (doorType)
                            {
                            case "Г":
                                newType.LookupParameter("Solid Leaf").Set(1);
                                newType.LookupParameter("Glazed Leaf").Set(0);
                                newType.LookupParameter("Leaf with Vent Grille").Set(0);
                                break;

                            case "О":
                                newType.LookupParameter("Solid Leaf").Set(0);
                                newType.LookupParameter("Glazed Leaf").Set(1);
                                newType.LookupParameter("Leaf with Vent Grille").Set(0);
                                break;
                            }

                            newType.LookupParameter("Door Leaf Height")
                            .Set(RvtCnvt.ConvertToInternalUnits((height - 100), DisplayUnitType.DUT_MILLIMETERS));

                            newType.LookupParameter("Door Leaf Width")
                            .Set(RvtCnvt.ConvertToInternalUnits((width - 100), DisplayUnitType.DUT_MILLIMETERS));

                            if (props.Contains('Л'))
                            {
                                newType.LookupParameter("RH").Set(0);
                            }
                            else
                            {
                                newType.LookupParameter("RH").Set(1);
                            }

                            if (props.Contains('П'))
                            {
                                newType.LookupParameter("Threshold").Set(1);
                            }
                            else
                            {
                                newType.LookupParameter("Threshold").Set(0);
                            }

                            t2.Commit();
                        }

                        tg.Assimilate();
                    }
                }
                catch (Autodesk.Revit.Exceptions.ArgumentException ex) {
                    if (ex.ParamName == "name")
                    {
                        TaskDialog.Show("ArgumentError",
                                        string.Format("This type already exists."));
                    }
                }
                catch (Exception ex) {
                    TaskDialog.Show("Exception", ex.StackTrace);
                }
            };

            win.ShowDialog();

            return(Result.Succeeded);
        }
        /// <summary>
        /// Retrieve all stairs on a given level.
        /// </summary>
        FilteredElementCollector GetStairsOnLevel(
            Document doc,
            Level level)
        {
            ElementId id = level.Id;

              BuiltInCategory bic
            = BuiltInCategory.OST_Stairs;

              FilteredElementCollector collector
            = new FilteredElementCollector( doc );

              collector.OfCategory( bic );

              // explicit iteration and manual
              // checking of a property:

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

              foreach( Element e in collector )
              {
            if( e.LevelId.Equals( id ) )
            {
              stairs.Add( e );
            }
              }

              // using LINQ:

              IEnumerable<Element> stairsOnLevelLinq =
            from e in collector
            where e.LevelId.Equals( id )
            select e;

              // using an anonymous method:

              IEnumerable<Element> stairsOnLevelAnon =
            collector.Where<Element>( e
              => e.LevelId.Equals( id ) );

              // using a parameter filter:

              BuiltInParameter bip
            = BuiltInParameter.STAIRS_BASE_LEVEL_PARAM;

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

              FilterNumericRuleEvaluator evaluator
            = new FilterNumericEquals();

              FilterRule rule = new FilterElementIdRule(
            provider, evaluator, id );

              ElementParameterFilter filter
            = new ElementParameterFilter( rule );

              return collector.WherePasses( filter );
        }
Example #17
0
        /// <summary>
        /// A function to number Family Instances
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="builtInCategory"></param>
        public static void numberFamilyInstance(Document doc,
                                                Phase phase,
                                                Boolean numeric,
                                                string separator,
                                                BuiltInCategory builtInCategory,
                                                ref int countInstances,
                                                Parameter parameter)
        {
            // Create dictionary to store window-room values
            Dictionary <FamilyInstance, string> instanceNumbers = new Dictionary <FamilyInstance, string>();
            // Create dictionary to store number of windows in room
            Dictionary <string, int> instancesInRoomCount = new Dictionary <string, int>();

            // Design option filter
            ElementDesignOptionFilter designOptionFilter = new ElementDesignOptionFilter(ElementId.InvalidElementId);

            // Select elements in phase
            ElementId idPhase = phase.Id;
            ParameterValueProvider     provider   = new ParameterValueProvider(new ElementId((int)BuiltInParameter.PHASE_CREATED));
            FilterNumericRuleEvaluator evaluator  = new FilterNumericEquals();
            FilterElementIdRule        rule       = new FilterElementIdRule(provider, evaluator, idPhase);
            ElementParameterFilter     paraFilter = new ElementParameterFilter(rule);

            // Collect all windows in project
            using (FilteredElementCollector instances = new FilteredElementCollector(doc).OfCategory(builtInCategory)
                                                        .WhereElementIsNotElementType().WherePasses(designOptionFilter).WherePasses(paraFilter))
            {
                string roomNumber = "";
                // Retrieve rooms from windows
                foreach (FamilyInstance inst in instances)
                {
                    if (builtInCategory == BuiltInCategory.OST_Doors)
                    {
                        if (inst.ToRoom != null)
                        {
                            roomNumber = inst.ToRoom.Number;
                        }
                        else if (inst.FromRoom != null)
                        {
                            roomNumber = inst.FromRoom.Number;
                        }
                    }
                    else
                    {
                        if (inst.FromRoom != null)
                        {
                            roomNumber = inst.FromRoom.Number;
                        }
                        else if (inst.ToRoom != null)
                        {
                            roomNumber = inst.ToRoom.Number;
                        }
                    }
                    if (numeric)
                    {
                        Helpers.InstanceFromToRoomNumber(instancesInRoomCount, roomNumber, separator, instanceNumbers, inst);
                    }
                    else
                    {
                        Helpers.InstanceFromToRoom(instancesInRoomCount, roomNumber, separator, instanceNumbers, inst);
                    }
                }
            }

            // Create transaction and make changes in Revit
            using (Transaction t = new Transaction(doc, "Number Instances"))
            {
                t.Start();

                // Empty Mark parameter to avoid duplicated values
                foreach (KeyValuePair <FamilyInstance, string> entry in instanceNumbers)
                {
                    Parameter instanceMark = entry.Key.LookupParameter(parameter.Definition.Name);
                    instanceMark.Set("");
                }

                // Populate Mark parameter
                foreach (KeyValuePair <FamilyInstance, string> entry in instanceNumbers)
                {
                    Parameter instanceMark = entry.Key.LookupParameter(parameter.Definition.Name);
                    if (entry.Value != "")
                    {
                        instanceMark.Set(entry.Value);
                        countInstances += 1;
                    }
                }

                t.Commit();
            }
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string messages,
            ElementSet elements)
        {
            UIApplication app = commandData.Application;
              Document doc = app.ActiveUIDocument.Document;

              Transaction tx = new Transaction( doc, "Test" );
              tx.Start();

              // use the view filter

              FilteredElementCollector collector
            = new FilteredElementCollector(
              doc, doc.ActiveView.Id );

              // use the parameter filter.
              // get the phase id "New construction"

              ElementId idPhase = GetPhaseId(
            "New Construction", doc );

              ParameterValueProvider provider
            = new ParameterValueProvider(
              new ElementId( (int)
            BuiltInParameter.PHASE_CREATED ) );

              FilterNumericRuleEvaluator evaluator
            = new FilterNumericEquals();

              FilterElementIdRule rule
            = new FilterElementIdRule(
              provider, evaluator, idPhase );

              ElementParameterFilter parafilter
            = new ElementParameterFilter( rule );

              collector.WherePasses( parafilter );

              TaskDialog.Show( "Element Count",
            "There are " + collector.Count().ToString()
            + " elements in the current view created"
            + " with phase New Construction" );

              tx.Commit();

              return Result.Succeeded;
        }
Example #19
0
        Result IExternalCommand.Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            //Application app = uiapp.Application;
            Document doc = uidoc.Document;

            PhaseArray xcom      = doc.Phases;
            Phase      lastPhase = xcom.get_Item(xcom.Size - 1);
            ElementId  idPhase   = lastPhase.Id;

            //ICollection<ElementId> selectedElementIds = uidoc.Selection.GetElementIds();
            //List<Element> selElem = selectedElementIds.Select(x => doc.GetElement(x)).ToList();
            //Element foundtype = doc.GetElement(selElem[0].GetTypeId());
            //List<string> parlist = new List<string>();
            //foreach (Parameter item in foundtype.Parameters)
            //{
            //    parlist.Add(item.Definition.Name);
            //}
            //int parvalue = foundtype.LookupParameter("шт/м/м2/м3").AsInteger();
            FilterableValueProvider valueProvider = new ParameterValueProvider(new ElementId(BuiltInParameter.PHASE_CREATED));

            FilterNumericRuleEvaluator evaluator = new FilterNumericEquals();
            ElementId ruleValue = idPhase;
            ElementParameterFilter stageFilter = new ElementParameterFilter(new FilterElementIdRule(valueProvider, evaluator, ruleValue));

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

            collectFromModel.Add(new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructuralFraming)
                                 .WhereElementIsNotElementType()
                                 .WherePasses(stageFilter)
                                 .Where(x => ((FamilyInstance)x).StructuralType.ToString() != "NonStructural")
                                 .Cast <Element>()
                                 .ToList());
            //collectFromModel.Add(karkas);

            collectFromModel.Add(new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructuralColumns)
                                 .WhereElementIsNotElementType()
                                 .WherePasses(stageFilter)
                                 .Cast <Element>()
                                 .ToList());

            collectFromModel.Add(new FilteredElementCollector(doc).OfClass(typeof(Rebar))
                                 .WherePasses(stageFilter)
                                 .ToElements().ToList());
            collectFromModel.Add(new FilteredElementCollector(doc).OfClass(typeof(RebarInSystem))
                                 .WherePasses(stageFilter)
                                 .ToElements().ToList());
            collectFromModel.Add(new FilteredElementCollector(doc).OfClass(typeof(Railing))
                                 .WhereElementIsNotElementType()
                                 .WherePasses(stageFilter)
                                 .ToElements()
                                 .ToList());
            collectFromModel.Add(new FilteredElementCollector(doc).OfClass(typeof(HostedSweep))
                                 .WhereElementIsNotElementType()
                                 .WherePasses(stageFilter)
                                 .ToElements()
                                 .ToList());
            collectFromModel.Add(new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Roofs)
                                 .WhereElementIsNotElementType()
                                 .WherePasses(stageFilter)
                                 .Cast <Element>()
                                 .ToList());
            collectFromModel.Add(new FilteredElementCollector(doc).OfClass(typeof(FabricSheet))
                                 .WhereElementIsNotElementType()
                                 .WherePasses(stageFilter)
                                 .ToElements()
                                 .ToList());
            collectFromModel.Add(new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructConnectionPlates)
                                 .WhereElementIsNotElementType()
                                 .WherePasses(stageFilter)
                                 .Cast <Element>()
                                 .ToList());
            collectFromModel.Add(new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructConnectionAnchors)
                                 .WhereElementIsNotElementType()
                                 .WherePasses(stageFilter)
                                 .Cast <Element>()
                                 .ToList());
            collectFromModel.Add(new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_GenericModel)
                                 .WhereElementIsNotElementType()
                                 .WherePasses(stageFilter)
                                 .Cast <Element>()
                                 .Where(x => x.Name != "cube")
                                 .ToList());


            List <Element> floors = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Floors)
                                    .WhereElementIsNotElementType()
                                    .WherePasses(stageFilter)
                                    .Cast <Element>()
                                    .ToList();
            List <Element> walls = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Walls)
                                   .WhereElementIsNotElementType()
                                   .WherePasses(stageFilter)
                                   .Cast <Element>()
                                   .ToList();
            List <Element> fundament = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructuralFoundation)
                                       .WhereElementIsNotElementType()
                                       .WherePasses(stageFilter)
                                       .Cast <Element>()
                                       .ToList();
            List <Element> lestnici = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Stairs)
                                      .WhereElementIsNotElementType()
                                      .WherePasses(stageFilter)
                                      .Cast <Element>()
                                      .ToList();
            List <string> ororo = fundament.Select(x => x.Name).ToList();

            //genModel = genModel.Where(x => x.Name != "cube").ToList();
            List <Cube> allCube = new List <Cube>();

            //List<Cube> someCube = new List<Cube>();

            foreach (Element f in floors)
            {
                foreach (ElementId m in f.GetMaterialIds(false))
                {
                    Cube abc = new Cube(doc.GetElement(m), f);
                    if (abc.out_Name != null)
                    {
                        allCube.Add(abc);
                    }
                }
            }

            foreach (Element w in walls)
            {
                foreach (ElementId m in w.GetMaterialIds(false))
                {
                    Cube abc = new Cube(doc.GetElement(m), w);
                    if (abc.out_Name != null)
                    {
                        allCube.Add(abc);
                    }
                }
            }

            foreach (Element f in fundament)
            {
                if (doc.GetElement(f.GetTypeId()).LookupParameter("шт/м/м2/м3") != null && doc.GetElement(f.GetTypeId()).LookupParameter("шт/м/м2/м3").AsInteger() == 0)
                {
                    Cube abc = new Cube(f);
                    if (abc.out_Name != null)
                    {
                        allCube.Add(abc);
                    }
                }
                else
                {
                    foreach (ElementId m in f.GetMaterialIds(false))
                    {
                        Cube abc = new Cube(doc.GetElement(m), f);
                        if (abc.out_Name != null)
                        {
                            allCube.Add(abc);
                        }
                    }
                }
            }
            foreach (Element f in lestnici)
            {
                foreach (ElementId m in f.GetMaterialIds(false))
                {
                    Cube abc = new Cube(doc.GetElement(m), f);
                    if (abc.out_Name != null)
                    {
                        allCube.Add(abc);
                    }
                }
            }
            foreach (List <Element> a in collectFromModel)
            {
                foreach (Element e in a)
                {
                    Cube abc = new Cube(e);
                    if (abc.out_Name == null)
                    {
                        abc.out_Name   = "Исключение: " + abc.typeName;
                        abc.DontSetPos = true;
                    }
                    allCube.Add(abc);
                }
            }
            List <List <Cube> > groupingCube = new List <List <Cube> >();

            //List<string> groupNum=allCube.Select(x => x.Group).Distinct().ToList();

            foreach (string eqGroup in allCube.Select(x => x.out_Group).Distinct())
            {
                if (eqGroup == "" | eqGroup == null)
                {
                    continue;
                }
                List <Cube> similarGroup = new List <Cube>();
                foreach (Cube c in allCube)
                {
                    if (c.out_Group == eqGroup)
                    {
                        similarGroup.Add(c);
                    }
                }
                groupingCube.Add(similarGroup);
            }

            List <Cube> outCube = new List <Cube>();

            foreach (List <Cube> item in groupingCube)
            {
                int a = 1;
                //int addpos = 1;
                foreach (myTypes mt in item.Select(x => x.mType).Distinct())
                {
                    foreach (string eqName in item.Select(x => x.out_Name).Distinct())
                    {
                        List <Cube> b = item
                                        .Where(x => x.mType == mt)
                                        .Where(y => y.out_Name == eqName)
                                        .ToList();
                        if (b.Count == 0)
                        {
                            continue;
                        }
                        (Cube addCube, int addpos) = Meta.forgeCube(b, a);
                        if (!addCube.DontSetPos)
                        {
                            a += addpos;
                        }


                        outCube.Add(addCube);
                    }
                }
            }

            List <List <Cube> > secondOutCube = new List <List <Cube> >();

            foreach (string eqGr in outCube.Select(x => x.out_Name).Distinct())
            {
                foreach (Cube cube in outCube)
                {
                }
            }
            //foreach (string eqGroup in outCube.Select(x => x.out_Group).Distinct())
            //{
            //    List<Cube> similarGroup = new List<Cube>();
            //    foreach (Cube c in allCube)
            //    {
            //        if (c.out_Group == eqGroup)
            //        {
            //            similarGroup.Add(c);
            //        }
            //    }
            //    int i = 1;
            //    similarGroup.OrderBy(x => x.Prior);
            //    foreach (var item in similarGroup)
            //    {
            //        item.out_Pos = i.ToString();
            //        i++;
            //        secondOutCube.Add(item);
            //    }

            //    //similarGroup.short
            //    //secondOutCube.Add(similarGroup.Select());
            //}
            //outCube = secondOutCube;



            ElementParameterFilter cubeFilter = new ElementParameterFilter(new FilterStringRule(new ParameterValueProvider(new ElementId((int)BuiltInParameter.ALL_MODEL_TYPE_NAME)), new FilterStringEquals(), "cube", false));
            List <FamilyInstance>  existCubes = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_GenericModel).WhereElementIsNotElementType().WherePasses(cubeFilter).Cast <FamilyInstance>().ToList();


            using (Transaction tr = new Transaction(doc, "ModelledSpec"))
            {
                tr.Start();
                foreach (FamilyInstance i in existCubes)
                {
                    doc.Delete(i.Id);
                }
                foreach (Cube i in outCube)
                {
                    if (i.posElements.Count != 0)
                    {
                        foreach (ElementExt e in i.posElements)
                        {
                            try
                            {
                                e.refElement.LookupParameter("СП_Позиция").Set(i.out_Pos);
                                e.refElement.LookupParameter("АН__Верх").Set(i.textUP);
                                e.refElement.LookupParameter("АН__Низ").Set(e.textDOWN);
                            }
                            catch
                            {
                            }
                        }
                    }

                    i.Create(doc);
                }

                tr.Commit();
            }

            TaskDialog msg = new TaskDialog("Info");

            msg.MainInstruction = outCube.Count.ToString();
            msg.Show();
            return(Result.Succeeded);
        }
        void f3( Document doc )
        {
            FilteredElementCollector collector
            = new FilteredElementCollector( doc );

              collector.OfClass( typeof( Level ) );
              ElementId id = new ElementId(
            BuiltInParameter.DATUM_TEXT );

              ParameterValueProvider provider
            = new ParameterValueProvider( id );

              FilterStringRuleEvaluator evaluator
            = new FilterStringContains();

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

              ElementParameterFilter filter
            = new ElementParameterFilter( rule );
        }
Example #21
0
        public static void ExtractElementConfiguration(DataSet dataSet, ElementSymbol es)
        {
            try
            {
                DataTableCollection dataTables = dataSet.Tables;
                DataTable           dataTable;

                //Handle all pipelines or separate configuration setting
                if (iv.ConfigureAll)
                {
                    dataTable = (from DataTable dt in dataTables
                                 where string.Equals(dt.TableName, "All pipelines")
                                 select dt).FirstOrDefault();
                }
                else
                {
                    dataTable = (from DataTable dt in dataTables
                                 where string.Equals(dt.TableName, es.PipelineReference)
                                 select dt).FirstOrDefault();
                }

                //query the element family and type is using the variables in the loop to query the dataset
                EnumerableRowCollection <string> query = from value in dataTable.AsEnumerable()
                                                         where value.Field <string>(0) == es.PipelineReference
                                                         select value.Field <string>(es.ElementType);

                string familyAndType = query.FirstOrDefault().ToString();
                FilteredElementCollector collector   = new FilteredElementCollector(PCF_Importer_form._doc);
                ElementParameterFilter   filter      = Filter.ParameterValueFilter(familyAndType, BuiltInParameter.SYMBOL_FAMILY_AND_TYPE_NAMES_PARAM);
                LogicalOrFilter          classFilter = Filter.FamSymbolsAndPipeTypes();
                Element familySymbol = collector.WherePasses(classFilter).WherePasses(filter).FirstOrDefault();

                if (es.ElementType == "PIPE")
                {
                    es.PipeType = (PipeType)familySymbol;
                }
                else
                {
                    es.FamilySymbol = (FamilySymbol)familySymbol;
                }

                //query the corresponding pipe family and type to add to the element symbol
                //This is because pipe type is needed to create certain fittings
                if (es.ElementType != "PIPE" || es.ElementType != "OLET") //Exclude olets -- they are handled next
                {
                    EnumerableRowCollection <string> queryPipeType = from value in dataTable.AsEnumerable()
                                                                     where value.Field <string>(0) == es.PipelineReference
                                                                     select value.Field <string>("PIPE");

                    string pipeTypeName = queryPipeType.FirstOrDefault();
                    FilteredElementCollector collectorPipeType  = new FilteredElementCollector(PCF_Importer_form._doc);
                    ElementParameterFilter   filterPipeTypeName = Filter.ParameterValueFilter(pipeTypeName, BuiltInParameter.SYMBOL_FAMILY_AND_TYPE_NAMES_PARAM);
                    Element pipeType = collectorPipeType.OfClass(typeof(PipeType)).WherePasses(filterPipeTypeName).FirstOrDefault();
                    es.PipeType = (PipeType)pipeType;
                }
                if (es.ElementType == "OLET") //Get the TAP pipetype for olets
                {
                    EnumerableRowCollection <string> queryPipeType = from value in dataTable.AsEnumerable()
                                                                     where value.Field <string>(0) == "Olet"
                                                                     select value.Field <string>("PIPE");

                    string pipeTypeName = queryPipeType.FirstOrDefault();
                    FilteredElementCollector collectorPipeType  = new FilteredElementCollector(PCF_Importer_form._doc);
                    ElementParameterFilter   filterPipeTypeName = Filter.ParameterValueFilter(pipeTypeName, BuiltInParameter.SYMBOL_FAMILY_AND_TYPE_NAMES_PARAM);
                    Element pipeType = collectorPipeType.OfClass(typeof(PipeType)).WherePasses(filterPipeTypeName).FirstOrDefault();
                    es.PipeType = (PipeType)pipeType;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Example #22
0
        private List <Element> GetLightingFixtures(Area area, out Room correlatedRoom)
        {
            correlatedRoom = null;
            var lightingFixtures = new List <Element>();

            try
            {
                var fromHost = new List <Element>();
                var fromLink = new List <Element>();

                var profiles = new CurveArrArray();
                var outline  = GetBoundingBox(area, out profiles);
                var topFace  = GetAreaFace(profiles);

                var intersectFilter = new BoundingBoxIntersectsFilter(outline);
                var insideFilter    = new BoundingBoxIsInsideFilter(outline);
                var orFilter        = new LogicalOrFilter(intersectFilter, insideFilter);

                var collector = new FilteredElementCollector(m_doc);
                collector.OfCategory(BuiltInCategory.OST_LightingFixtures);
                var elementIds = collector.WherePasses(orFilter).ToElementIds().ToList();

                var roomCollector = new FilteredElementCollector(m_doc);
                roomCollector.OfCategory(BuiltInCategory.OST_Rooms);
                var roomsFound = roomCollector.WherePasses(orFilter).ToElements().Cast <Room>().ToList();
                foreach (var room in roomsFound)
                {
                    if (area.LevelId.IntegerValue == room.LevelId.IntegerValue)
                    {
                        correlatedRoom = room; break;
                    }
                }

                var bltParam1 = BuiltInParameter.INSTANCE_SCHEDULE_ONLY_LEVEL_PARAM;
                var pvp1      = new ParameterValueProvider(new ElementId((int)bltParam1));
                var bltParam2 = BuiltInParameter.FAMILY_LEVEL_PARAM;
                var pvp2      = new ParameterValueProvider(new ElementId((int)bltParam2));

                FilterNumericRuleEvaluator fnrv = new FilterNumericEquals();
                var ruleValueId = new ElementId(area.LevelId.IntegerValue);

                FilterRule filterRule1 = new FilterElementIdRule(pvp1, fnrv, ruleValueId);
                FilterRule filterRule2 = new FilterElementIdRule(pvp2, fnrv, ruleValueId);

                var paramFilter1 = new ElementParameterFilter(filterRule1);
                var paramFilter2 = new ElementParameterFilter(filterRule2);
                var paramFilter  = new LogicalOrFilter(paramFilter1, paramFilter2);

                if (elementIds.Count > 0)
                {
                    collector = new FilteredElementCollector(m_doc, elementIds);
                    fromHost  = collector.WherePasses(paramFilter).ToElements().ToList();
                    fromHost  = GetPolygonIntersect(topFace, fromHost);
                }

                if (lightingSelection != ModelSelection.Host)
                {
                    if (linkedDocuments.Count > 0)
                    {
                        foreach (Document doc in m_app.Application.Documents)
                        {
                            if (linkedDocuments.Contains(doc.Title))
                            {
                                if (null == correlatedRoom)
                                {
                                    roomCollector = new FilteredElementCollector(doc);
                                    roomCollector.OfCategory(BuiltInCategory.OST_Rooms);
                                    roomsFound = roomCollector.WherePasses(orFilter).ToElements().Cast <Room>().ToList();
                                    foreach (var room in roomsFound)
                                    {
                                        if (area.LevelId.IntegerValue == room.LevelId.IntegerValue)
                                        {
                                            correlatedRoom = room; break;
                                        }
                                    }
                                }

                                collector = new FilteredElementCollector(doc);
                                collector.OfCategory(BuiltInCategory.OST_LightingFixtures);
                                elementIds = collector.WherePasses(orFilter).ToElementIds().ToList();
                                if (elementIds.Count > 0)
                                {
                                    collector = new FilteredElementCollector(doc, elementIds);
                                    var elements = collector.WherePasses(paramFilter).ToElements().ToList();
                                    elements = GetPolygonIntersect(topFace, elements);
                                    fromLink.AddRange(elements);
                                }
                            }
                        }
                    }
                }

                switch (lightingSelection)
                {
                case ModelSelection.Host:
                    lightingFixtures = fromHost;
                    break;

                case ModelSelection.Link:
                    lightingFixtures = fromLink;
                    break;

                case ModelSelection.Both:
                    lightingFixtures.AddRange(fromHost);
                    lightingFixtures.AddRange(fromLink);
                    break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to get lighting fixtures.\n" + ex.Message, "Get Lighting Fixtures", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            return(lightingFixtures);
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            // There is likely an easier way to do this using
            // an exclusion filter but this being my first foray
            // into filtering with Revit, I couldn't get that working.

            FilteredElementCollector filt   = new FilteredElementCollector(doc);
            List <ElementId>         refIDs = filt.OfClass(typeof(ReferencePlane)).ToElementIds().ToList();

            using (TransactionGroup tg = new TransactionGroup(doc))
            {
                tg.Start("Remove Un-Used Reference Planes");
                foreach (ElementId id in refIDs)
                {
                    var filt2 = new ElementClassFilter(typeof(FamilyInstance));

                    var filt3 = new ElementParameterFilter(new FilterElementIdRule(new ParameterValueProvider(new ElementId(BuiltInParameter.HOST_ID_PARAM)), new FilterNumericEquals(), id));
                    var filt4 = new LogicalAndFilter(filt2, filt3);

                    var thing = new FilteredElementCollector(doc);

                    using (Transaction t = new Transaction(doc))
                    {
                        // Check for hosted elements on the plane
                        if (thing.WherePasses(filt4).Count() == 0)
                        {
                            t.Start("Do The Thing");

#if Revit2018
                            if (doc.GetElement(id).GetDependentElements(new ElementClassFilter(typeof(FamilyInstance))).Count == 0)
                            {
                                doc.Delete(id);
                            }

                            t.Commit();
#else
                            // Make sure there is nothing measuring to the plane

                            if (doc.Delete(id).Count() > 1)
                            {
                                t.Dispose();
                                // Skipped
                            }
                            else
                            {
                                // Deleted
                                t.Commit();
                            }
#endif
                        }
                        else
                        {
                            // Skipped
                        }
                    }
                }
                tg.Assimilate();
            }
            return(Result.Succeeded);
        }
    private static void HostedFamilyInstanceOpenings(Wall wall,
        double minOpeningValue)
    {
      double wallOpeningArea = 0.0;
      double wallTotalOpeningArea = 0.0;

      // Filter all Family Instances where the HOST_ID_PARAM 
      // equals the wall ID
      // 
      // More information at
      // http://thebuildingcoder.typepad.com/
      //                 blog/2010/06/parameter-filter.html#4
      BuiltInParameter testParam =
          BuiltInParameter.HOST_ID_PARAM;
      ParameterValueProvider pvp =
          new ParameterValueProvider(
              new ElementId((int)testParam));

      FilterNumericRuleEvaluator fnrv = new FilterNumericEquals();
      ElementId ruleValId = wall.Id;

      FilterRule paramFr = new FilterElementIdRule
        (pvp, fnrv, ruleValId);
      ElementParameterFilter epf = 
        new ElementParameterFilter(paramFr);
      FilteredElementCollector collector =
          new FilteredElementCollector(wall.Document);

      collector.OfClass(typeof(FamilyInstance)).WherePasses(epf);
      IList<Element> hostedFamilyInstances = collector.ToElements();

      // Now iterate through the collected family instances
      Document doc = wall.Document;
      double previousArea = wall.get_Parameter(
          BuiltInParameter.HOST_AREA_COMPUTED).AsDouble();

      foreach (FamilyInstance instance in hostedFamilyInstances)
      {
        // Delete the hosted family instace and regenerate
        doc.Delete(instance);
        doc.Regenerate();

        // Get the new area to compare
        double newArea = wall.get_Parameter(
            BuiltInParameter.HOST_AREA_COMPUTED).AsDouble();

        // So the instance opening equals:
        double instanceAreaOnTheWall = 
          Math.Abs(newArea - previousArea);

        // The element area (on wall) is smaller than 
        // the minOpeningValue?
        if (instanceAreaOnTheWall <= minOpeningValue)
          wallOpeningArea += instanceAreaOnTheWall;
        else
          wallTotalOpeningArea += instanceAreaOnTheWall;

        if (System.Diagnostics.Debugger.IsAttached)
          TaskDialog.Show(
              "Wall opening (by inst) found (in sq feet)",
              string.Format("Area: {0}", instanceAreaOnTheWall));

        previousArea = newArea;
      }

      AddWallArea(wall.Id, wallOpeningArea, wallTotalOpeningArea);
    }
        /// <summary>
        /// Return the first wall type with the given name.
        /// </summary>
        static WallType GetFirstWallTypeNamed(
            Document doc,
            string name)
        {
            // built-in parameter storing this
              // wall type's name:

              BuiltInParameter bip
            = BuiltInParameter.SYMBOL_NAME_PARAM;

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

              FilterStringRuleEvaluator evaluator
            = new FilterStringEquals();

              FilterRule rule = new FilterStringRule(
            provider, evaluator, name, false );

              ElementParameterFilter filter
            = new ElementParameterFilter( rule );

              FilteredElementCollector collector
            = new FilteredElementCollector( doc )
              .OfClass( typeof( WallType ) )
              .WherePasses( filter );

              return collector.FirstElement() as WallType;
        }
        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;

              Reference r = uidoc.Selection.PickObject(
            ObjectType.Element );

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

              Wall wall = doc.GetElement( r ) as Wall; // 2012

              Parameter parameter = wall.get_Parameter(
            "Unconnected Height" );

              ParameterValueProvider pvp
            = new ParameterValueProvider( parameter.Id );

              FilterNumericRuleEvaluator fnrv
            = new FilterNumericGreater();

              FilterRule fRule
            = new FilterDoubleRule( pvp, fnrv, 20, 1E-6 );

              ElementParameterFilter filter
            = new ElementParameterFilter( fRule );

              FilteredElementCollector collector
            = new FilteredElementCollector( doc );

              // Find walls with unconnected height
              // less than or equal to 20:

              ElementParameterFilter lessOrEqualFilter
            = new ElementParameterFilter( fRule, true );

              IList<Element> lessOrEqualFounds
            = collector.WherePasses( lessOrEqualFilter )
              .OfCategory( BuiltInCategory.OST_Walls )
              .OfClass( typeof( Wall ) )
              .ToElements();

              TaskDialog.Show( "Revit", "Walls found: "
            + lessOrEqualFounds.Count );

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

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

              BuiltInParameter bip
            = BuiltInParameter.DATUM_TEXT;

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

              FilterStringRuleEvaluator evaluator
            = new FilterStringEquals();

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

              ElementParameterFilter filter
            = new ElementParameterFilter( rule );

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

              int n = 0;
              int nDeleted = 0;

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

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

              n = ids.Count();

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

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

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

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

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

              tx.Commit();
            }
              }

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

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

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

            BuiltInParameter bip
                = BuiltInParameter.DATUM_TEXT;

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

            FilterStringRuleEvaluator evaluator
                = new FilterStringEquals();

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

            ElementParameterFilter filter
                = new ElementParameterFilter(rule);

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

            int n        = 0;
            int nDeleted = 0;

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

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

            n = ids.Count();

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

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

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

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

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

                    tx.Commit();
                }
            }

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

            return(Result.Succeeded);
        }
Example #29
0
        internal Result ExecuteMyCommand(UIApplication uiApp, ref string msg)
        {
            // UIApplication uiApp = commandData.Application;
            //Test comment
            Document   doc   = uiApp.ActiveUIDocument.Document;
            UIDocument uidoc = uiApp.ActiveUIDocument;

            try
            {
                #region Declaration of variables
                // Instance a collector
                FilteredElementCollector collector = new FilteredElementCollector(doc);
                //FilteredElementCollector pipeTypeCollector = new FilteredElementCollector(doc); //Obsolete???

                // Define a Filter instance to filter by System Abbreviation
                ElementParameterFilter sysAbbr = Shared.Filter.ParameterValueGenericFilter(doc, InputVars.SysAbbr, InputVars.SysAbbrParam);

                // Declare pipeline grouping object
                IEnumerable <IGrouping <string, Element> > pipelineGroups;

                //Declare an object to hold collected elements from collector
                HashSet <Element> colElements = new HashSet <Element>();

                // Instance a collecting stringbuilder
                StringBuilder sbCollect = new StringBuilder();
                #endregion

                #region Compose preamble
                //Compose preamble
                Composer composer = new Composer();

                StringBuilder sbPreamble = composer.PreambleComposer();

                //Append preamble
                sbCollect.Append(sbPreamble);
                #endregion

                #region Element collectors
                //If user chooses to export a single pipeline get only elements in that pipeline and create grouping.
                //Grouping is necessary even tho theres only one group to be able to process by the same code as the all pipelines case

                //If user chooses to export all pipelines get all elements and create grouping
                if (InputVars.ExportAllOneFile)
                {
                    //Define a collector (Pipe OR FamInst) AND (Fitting OR Accessory OR Pipe).
                    //This is to eliminate FamilySymbols from collector which would throw an exception later on.
                    collector.WherePasses(new LogicalAndFilter(new List <ElementFilter>
                    {
                        new LogicalOrFilter(new List <ElementFilter>
                        {
                            new ElementCategoryFilter(BuiltInCategory.OST_PipeFitting),
                            new ElementCategoryFilter(BuiltInCategory.OST_PipeAccessory),
                            new ElementClassFilter(typeof(Pipe))
                        }),
                        new LogicalOrFilter(new List <ElementFilter>
                        {
                            new ElementClassFilter(typeof(Pipe)),
                            new ElementClassFilter(typeof(FamilyInstance))
                        })
                    }));

                    colElements = collector.ToElements().ToHashSet();
                }

                else if (InputVars.ExportAllSepFiles || InputVars.ExportSpecificPipeLine)
                {
                    //Define a collector with multiple filters to collect PipeFittings OR PipeAccessories OR Pipes + filter by System Abbreviation
                    //System Abbreviation filter also filters FamilySymbols out.
                    collector.WherePasses(
                        new LogicalOrFilter(
                            new List <ElementFilter>
                    {
                        new ElementCategoryFilter(BuiltInCategory.OST_PipeFitting),
                        new ElementCategoryFilter(BuiltInCategory.OST_PipeAccessory),
                        new ElementClassFilter(typeof(Pipe))
                    })).WherePasses(sysAbbr);
                    colElements = collector.ToElements().ToHashSet();
                }

                else if (InputVars.ExportSelection)
                {
                    ICollection <ElementId> selection = uiApp.ActiveUIDocument.Selection.GetElementIds();
                    colElements = selection.Select(s => doc.GetElement(s)).ToHashSet();
                }


                #region Sub: Filtering
                HashSet <Element> elements;
                try
                {
                    //DiameterLimit filter applied to ALL elements.
                    var filtering = from element in colElements where Filters.FilterDL(element) select element;

                    //Filter out EXCLUDED elements -> 0 means no checkmark
                    filtering = from element in filtering
                                where element.get_Parameter(new plst().PCF_ELEM_EXCL.Guid).AsInteger() == 0
                                select element;

                    //Filter out EXCLUDED pipelines -> 0 means no checkmark
                    filtering = filtering.Where(x => x.PipingSystemAllowed(doc) == true);

                    //Remove instrument pipes
                    filtering = filtering.ExceptWhere(x => x.get_Parameter(BuiltInParameter.RBS_DUCT_PIPE_SYSTEM_ABBREVIATION_PARAM)
                                                      .AsString() == "INSTR");

                    //Filter out elements with specified PCF_ELEM_SPEC string
                    if (InputVars.PCF_ELEM_SPEC_FILTER.IsNullOrEmpty() == false)
                    {
                        filtering = filtering.ExceptWhere(x => x.get_Parameter(new plst().PCF_ELEM_SPEC.Guid).AsString() == InputVars.PCF_ELEM_SPEC_FILTER);
                    }

                    //If exporting to ISO, remove some not needed elements
                    if (InputVars.ExportToIsogen)
                    {
                        //When exporting to Plant3D ISO creation, remove the group with the Piping System: Analysis Rigids (ARGD)
                        filtering = filtering
                                    .Where(x => !(x.get_Parameter(BuiltInParameter.RBS_DUCT_PIPE_SYSTEM_ABBREVIATION_PARAM).AsString() == "ARGD"));

                        ////Also remove anchor symbols -> not needed for ISO
                        ////Currently not removed -> used for floor symbols
                        //filtering = filtering.ExceptWhere(x => x
                        //    .get_Parameter(BuiltInParameter.ELEM_FAMILY_AND_TYPE_PARAM)
                        //    .AsValueString() == "Support Symbolic: ANC");
                    }

                    //Create a grouping of elements based on the Pipeline identifier (System Abbreviation)
                    pipelineGroups = from e in filtering
                                     group e by e.get_Parameter(BuiltInParameter.RBS_DUCT_PIPE_SYSTEM_ABBREVIATION_PARAM).AsString();

                    elements = filtering.ToHashSet();
                }
                catch (Exception ex)
                {
                    throw new Exception("Filtering in Main threw an exception:\n" + ex.Message +
                                        "\nTo fix:\n" +
                                        "1. See if parameter PCF_ELEM_EXCL exists, if not, rerun parameter import.");
                }
                #endregion
                #endregion

                #region Initialize Material Data
                //TEST: Do not write material data to elements with EXISTING-INCLUDE spec
                //HashSet<Element> existInclElements = elements.Where(x =>
                //    x.get_Parameter(new plst().PCF_ELEM_SPEC.Guid).AsString() == "EXISTING-INCLUDE").ToHashSet();
                ////Remember the clearing of previous run data in transaction below

                //elements = elements.ExceptWhere(x =>
                //    x.get_Parameter(new plst().PCF_ELEM_SPEC.Guid).AsString() == "EXISTING-INCLUDE").ToHashSet();

                //Set the start number to count the COMPID instances and MAT groups.
                int elementIdentificationNumber = 0;
                int materialGroupIdentifier     = 0;

                //Make sure that every element has PCF_MAT_DESCR filled out.
                foreach (Element e in elements)
                {
                    if (string.IsNullOrEmpty(e.get_Parameter(new plst().PCF_MAT_DESCR.Guid).AsString()))
                    {
                        uidoc.Selection.SetElementIds(new List <ElementId>(1)
                        {
                            e.Id
                        });
                        BuildingCoderUtilities.ErrorMsg("PCF_MAT_DESCR is empty for element " + e.Id + "! Please, correct this issue before exporting again.");
                        throw new Exception("PCF_MAT_DESCR is empty for element " + e.Id + "! Please, correct this issue before exporting again.");
                    }
                }

                //Initialize material group numbers on the elements
                IEnumerable <IGrouping <string, Element> > materialGroups = from e in elements group e by e.get_Parameter(new plst().PCF_MAT_DESCR.Guid).AsString();

                using (Transaction trans = new Transaction(doc, "Set PCF_ELEM_COMPID and PCF_MAT_ID"))
                {
                    trans.Start();
                    //Clear MTL data from previous runs for elements with EXISTING-INCLUDE spec
                    //foreach (Element e in existInclElements)
                    //{
                    //    e.get_Parameter(new plst().PCF_ELEM_COMPID.Guid).Set("");
                    //    e.get_Parameter(new plst().PCF_MAT_ID.Guid).Set("");
                    //}

                    //Access groups
                    foreach (IEnumerable <Element> group in materialGroups)
                    {
                        materialGroupIdentifier++;
                        //Access parameters
                        foreach (Element element in group)
                        {
                            elementIdentificationNumber++;
                            element.get_Parameter(new plst().PCF_ELEM_COMPID.Guid).Set(elementIdentificationNumber.ToString());
                            element.get_Parameter(new plst().PCF_MAT_ID.Guid).Set(materialGroupIdentifier.ToString());
                        }
                    }
                    trans.Commit();
                }

                //If turned on, write wall thickness of all components
                if (InputVars.WriteWallThickness)
                {
                    //Assign correct wall thickness to elements.
                    using (Transaction trans1 = new Transaction(doc))
                    {
                        trans1.Start("Set wall thickness for pipes!");
                        ParameterDataWriter.SetWallThicknessPipes(elements);
                        trans1.Commit();
                    }
                }

                #endregion

                using (TransactionGroup txGp = new TransactionGroup(doc))
                {
                    txGp.Start("Bogus transactionGroup for the break in hangers");
                    #region Pipeline management
                    foreach (IGrouping <string, Element> gp in pipelineGroups)
                    {
                        HashSet <Element> pipeList = (from element in gp
                                                      where element.Category.Id.IntegerValue == (int)BuiltInCategory.OST_PipeCurves
                                                      select element).ToHashSet();
                        HashSet <Element> fittingList = (from element in gp
                                                         where element.Category.Id.IntegerValue == (int)BuiltInCategory.OST_PipeFitting
                                                         select element).ToHashSet();
                        HashSet <Element> accessoryList = (from element in gp
                                                           where element.Category.Id.IntegerValue == (int)BuiltInCategory.OST_PipeAccessory
                                                           select element).ToHashSet();

                        StringBuilder sbPipeline           = new PCF_Pipeline.PCF_Pipeline_Export().Export(gp.Key, doc);
                        StringBuilder sbFilename           = PCF_Pipeline.Filename.BuildAndWriteFilename(doc);
                        StringBuilder sbEndsAndConnections = PCF_Pipeline.EndsAndConnections
                                                             .DetectAndWriteEndsAndConnections(gp.Key, pipeList, fittingList, accessoryList, doc);

                        #region BrokenPipes

                        //Here be code to handle break in accessories that act as supports
                        //Find the supports in current acessoryList and add to supportList
                        //Instantiate a brokenPipesGroup class

                        //Collect all Connectors from brokenPipesList and find the longest distance
                        //Create a temporary pipe from the Connectors with longest distance
                        //Copy PCF_ELEM parameter values to the temporary pipe
                        //Add the temporary pipe to the pipeList
                        //Roll back the TransactionGroup after the elements are sent to Export class' Export methods.

                        List <BrokenPipesGroup> bpgList = new List <BrokenPipesGroup>();

                        List <Element> supportsList = accessoryList.Where(x => x.ComponentClass1(doc) == "Pipe Support").ToList();

                        while (supportsList.Count > 0)
                        {
                            //Get an element to start traversing
                            Element seedElement = supportsList.FirstOrDefault();
                            if (seedElement == null)
                            {
                                throw new Exception("BrokenPipes: Seed element returned null! supportsList.Count is " + supportsList.Count);
                            }

                            //Instantiate the BrokenPipesGroup
                            BrokenPipesGroup bpg = new BrokenPipesGroup(seedElement, gp.Key);

                            //Traverse system
                            bpg.Traverse(doc);

                            //Remove the support Elements from the collection to keep track of the while loop
                            foreach (Element support in bpg.SupportsOnPipe)
                            {
                                supportsList = supportsList.ExceptWhere(x => x.Id.IntegerValue == support.Id.IntegerValue).ToList();
                            }

                            bpgList.Add(bpg);
                        }

                        using (Transaction tx = new Transaction(doc))
                        {
                            tx.Start("Create healed pipes");
                            foreach (BrokenPipesGroup bpg in bpgList)
                            {
                                //Remove the broken pipes from the pipeList
                                //If there's only one broken pipe, then there's no need to do anything
                                //If there's no broken pipes, then there's no need to do anything either
                                if (bpg.BrokenPipes.Count != 0 && bpg.BrokenPipes.Count != 1)
                                {
                                    foreach (Element pipe in bpg.BrokenPipes)
                                    {
                                        pipeList = pipeList.ExceptWhere(x => x.Id.IntegerValue == pipe.Id.IntegerValue).ToHashSet();
                                    }

                                    //Using the new IEqualityComparer for Connectors to get distinct connectors in the collection
                                    var brokenCons = MepUtils.GetALLConnectorsFromElements(bpg.BrokenPipes.ToHashSet(), new ConnectorXyzComparer(2.0.MmToFt()));
                                    //Create distinct pair combinations with distance from all broken connectors
                                    //https://stackoverflow.com/a/47003122/6073998
                                    List <(Connector c1, Connector c2, double dist)> pairs = brokenCons
                                                                                             .SelectMany
                                                                                             (
                                        (fst, i) => brokenCons.Skip(i + 1).Select(snd => (fst, snd, fst.Origin.DistanceTo(snd.Origin)))
                                                                                             )
                                                                                             .ToList();
                                    var  longest = pairs.MaxBy(x => x.dist).FirstOrDefault();
                                    Pipe dPipe   = (Pipe)longest.c1.Owner;
                                    bpg.HealedPipe = Pipe.Create(doc, dPipe.MEPSystem.GetTypeId(), dPipe.GetTypeId(),
                                                                 dPipe.ReferenceLevel.Id, longest.c1.Origin, longest.c2.Origin);

                                    Pipe donorPipe = (Pipe)bpg.BrokenPipes.FirstOrDefault();
                                    bpg.HealedPipe.get_Parameter(BuiltInParameter.RBS_PIPE_DIAMETER_PARAM).Set(donorPipe.Diameter);

                                    //Add the healed pipe to the pipeList for processing
                                    pipeList.Add(bpg.HealedPipe);
                                }
                            }
                            tx.Commit();
                        }

                        //Now the healed pipe must be populated by the parameters from a donorPipe
                        using (Transaction tx = new Transaction(doc))
                        {
                            //Gather all relevant parameter definitions
                            List <pdef> plist = new plst().LPAll.Where(x => x.Domain == "ELEM" && x.Usage == "U").ToList();
                            plist.Add(new plst().PCF_MAT_ID);

                            tx.Start("Populate the HealedPipe parameters!");
                            foreach (BrokenPipesGroup bpg in bpgList)
                            {
                                //Skip iteration if there's only 1 or no broken pipes
                                if (bpg.BrokenPipes.Count == 0 || bpg.BrokenPipes.Count == 1)
                                {
                                    continue;
                                }
                                Element donorPipe = bpg.BrokenPipes.FirstOrDefault();

                                foreach (pdef p in plist)
                                {
                                    Parameter donorParameter = donorPipe.get_Parameter(p.Guid);
                                    if (donorParameter == null)
                                    {
                                        continue;
                                    }
                                    switch (donorParameter.StorageType)
                                    {
                                    case StorageType.None:
                                        continue;

                                    case StorageType.Integer:
                                        int donorInt = donorParameter.AsInteger();
                                        if (donorInt == 0)
                                        {
                                            continue;
                                        }
                                        Parameter targetParInt = bpg.HealedPipe.get_Parameter(p.Guid);
                                        targetParInt.Set(donorInt);
                                        break;

                                    case StorageType.Double:
                                        continue;

                                    case StorageType.String:
                                        string donorStr = donorParameter.AsString();
                                        if (donorStr.IsNullOrEmpty())
                                        {
                                            continue;
                                        }
                                        Parameter targetParStr = bpg.HealedPipe.get_Parameter(p.Guid);
                                        targetParStr.Set(donorStr);
                                        break;

                                    case StorageType.ElementId:
                                        continue;

                                    default:
                                        continue;
                                    }
                                }
                            }
                            tx.Commit();
                        }

                        #endregion

                        StringBuilder sbPipes       = new PCF_Pipes.PCF_Pipes_Export().Export(gp.Key, pipeList, doc);
                        StringBuilder sbFittings    = new PCF_Fittings.PCF_Fittings_Export().Export(gp.Key, fittingList, doc);
                        StringBuilder sbAccessories = new PCF_Accessories.PCF_Accessories_Export().Export(gp.Key, accessoryList, doc);

                        sbCollect.Append(sbPipeline); sbCollect.Append(sbFilename); sbCollect.Append(sbEndsAndConnections);
                        sbCollect.Append(sbPipes); sbCollect.Append(sbFittings); sbCollect.Append(sbAccessories);
                    }
                    #endregion

                    txGp.RollBack(); //RollBack the temporary created elements
                }

                #region Materials
                StringBuilder sbMaterials = composer.MaterialsSection(materialGroups);
                sbCollect.Append(sbMaterials);
                #endregion

                #region Output
                // Output the processed data
                PCF_Output.Output output = new PCF_Output.Output();
                output.OutputWriter(sbCollect);
                #endregion
            }

            catch (Autodesk.Revit.Exceptions.OperationCanceledException)
            {
                return(Result.Cancelled);
            }

            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            return(Result.Succeeded);
        }
        /// <summary>
        /// Return the first wall found that
        /// uses the given wall type.
        /// </summary>
        static Wall GetFirstWallUsingType(
            Document doc,
            WallType wallType)
        {
            // built-in parameter storing this
              // wall's wall type element id:

              BuiltInParameter bip
            = BuiltInParameter.ELEM_TYPE_PARAM;

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

              FilterNumericRuleEvaluator evaluator
            = new FilterNumericEquals();

              FilterRule rule = new FilterElementIdRule(
            provider, evaluator, wallType.Id );

              ElementParameterFilter filter
            = new ElementParameterFilter( rule );

              FilteredElementCollector collector
            = new FilteredElementCollector( doc )
              .OfClass( typeof( Wall ) )
              .WherePasses( filter );

              return collector.FirstElement() as Wall;
        }
Example #31
0
        private void Application_DocumentOpened(object sender, Autodesk.Revit.DB.Events.DocumentOpenedEventArgs e)
        {
            Application   app   = sender as Application;
            UIApplication uiApp = new UIApplication(app);
            Document      doc   = uiApp.ActiveUIDocument.Document;

            Utilits.Doc = doc;
            //app.DocumentChanged += new EventHandler<DocumentChangedEventArgs>(OnDocumentChanged);

            //Создание словаря
            MapConnectorsToCircuits dicConnCirc = new MapConnectorsToCircuits();
            //Develop.dicConnectCirc = dicConnCirc;

            //Перебор всех коннекторов для заполнения коннекторов
            //ElementId idConnect = ElementId.InvalidElementId;
            //string idCircuits = "";

            List <ElementId> circuitsId = new List <ElementId>();

            FilteredElementCollector filtConnectors = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_TelephoneDevices).WhereElementIsNotElementType();

            foreach (var el in filtConnectors)
            {
                string strIdCirc = el.LookupParameter("ID_Circuits").AsString();
                //Проверка если в коннекторе нет цепей
                if (strIdCirc != null)
                {
                    string[] spl = strIdCirc.Split('?');
                    for (int i = 0; i < spl.Length; i++)
                    {
                        string strid = spl[i];
                        if (Int32.TryParse(strid, out int intId))
                        {
                            ElementId idCirc = new ElementId(Int32.Parse(strid));
                            dicConnCirc.Add(el.Id, idCirc);
                            circuitsId.Add(idCirc);
                        }
                    }
                }
            }

            Develop.dicConnectCirc = dicConnCirc;
            CircUpdater updater = new CircUpdater(uiApp.ActiveAddInId);

            Develop.updater = updater;
            //Регистрация апдатера
            if (!UpdaterRegistry.IsUpdaterRegistered(updater.GetUpdaterId()))
            {
                UpdaterRegistry.RegisterUpdater(updater);
            }

            if (circuitsId.Count != 0)
            {
                //Добавление триггера на электрические цепи

                Element   elem      = doc.GetElement(circuitsId.First());
                Parameter parNumber = elem.get_Parameter(BuiltInParameter.RBS_ELEC_CIRCUIT_NUMBER);
                //Parameter parIdConn = elem.GetParameters("IdConnectors").First();
                UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), doc, circuitsId, Element.GetChangeTypeParameter(parNumber));
                //UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), doc, circuitsId, Element.GetChangeTypeParameter(parIdConn));

                UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), doc, circuitsId, Element.GetChangeTypeElementDeletion());


                updater.dic = dicConnCirc;
            }
            if (filtConnectors.Count() != 0)
            {
                //добавление триггера на коннекторы
                //ElementCategoryFilter filt = new ElementCategoryFilter(BuiltInCategory.OST_TelephoneDevices);
                IList <FilterRule> ruls = new List <FilterRule>();
                FilterRule         rule = ParameterFilterRuleFactory.CreateEqualsRule(new ElementId(BuiltInParameter.ELEM_FAMILY_PARAM), "Эмуляция потребителя без нагрузки", false);
                ruls.Add(rule);
                rule = ParameterFilterRuleFactory.CreateEqualsRule(new ElementId(BuiltInCategory.OST_TelephoneDevices), (int)BuiltInCategory.OST_TelephoneDevices);
                ruls.Add(rule);
                ElementParameterFilter filter = new ElementParameterFilter(ruls);
                //FilteredElementCollector collector = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_TelephoneDevices).WherePasses(filter);

                //var fs = new FilteredElementCollector(doc).WhereElementIsNotElementType().Where(x => x.Name == "Bunch");
                UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), doc, filter, Element.GetChangeTypeElementDeletion());
            }
        }
        void f4( Document doc )
        {
            // Use numeric evaluator and integer rule to test ElementId parameter
              // Filter levels whose id is greater than specified id value

              BuiltInParameter testParam
            = BuiltInParameter.ID_PARAM;

              ParameterValueProvider pvp
            = new ParameterValueProvider(
              new ElementId( (int) testParam ) );

              FilterNumericRuleEvaluator fnrv
            = new FilterNumericGreater();

              // filter elements whose Id is greater than 99

              ElementId ruleValId = new ElementId( 99 );

              FilterRule paramFr = new FilterElementIdRule(
            pvp, fnrv, ruleValId );

              ElementParameterFilter epf
            = new ElementParameterFilter( paramFr );

              FilteredElementCollector collector
            = new FilteredElementCollector( doc );

              collector.OfClass( typeof( ViewPlan ) )
            .WherePasses( epf ); // only deal with ViewPlan

              // Use numeric evaluator and integer rule to test bool parameter
              // Filter levels whose crop view is false

              int ruleValInt = 0;

              testParam = BuiltInParameter.VIEWER_CROP_REGION;

              pvp = new ParameterValueProvider(
            new ElementId( (int) testParam ) );

              fnrv = new FilterNumericEquals();

              paramFr = new FilterIntegerRule(
            pvp, fnrv, ruleValInt );

              epf = new ElementParameterFilter( paramFr );

              collector = new FilteredElementCollector( doc );

              collector.OfClass( typeof( ViewPlan ) )
            .WherePasses( epf ); // only deal with ViewPlan

              // Use numeric evaluator and double rule to test double parameter
              // Filter levels whose top offset is greater than specified value

              double ruleValDb = 10;

              testParam =
            BuiltInParameter.VIEWER_BOUND_OFFSET_TOP;

              pvp = new ParameterValueProvider(
            new ElementId( (int) testParam ) );

              fnrv = new FilterNumericGreater();

              paramFr = new FilterDoubleRule(
            pvp, fnrv, ruleValDb, double.Epsilon );

              collector = new FilteredElementCollector( doc );

              collector.OfClass( typeof( ViewPlan ) )
            .WherePasses( epf ); // only deal with ViewPlan

              // Use string evaluator and string rule to test string parameter
              // Filter all elements whose view name contains level

              String ruleValStr = "Level";

              testParam = BuiltInParameter.VIEW_NAME;

              pvp = new ParameterValueProvider(
            new ElementId( (int) testParam ) );

              FilterStringRuleEvaluator fnrvStr
            = new FilterStringContains();

              paramFr = new FilterStringRule(
            pvp, fnrvStr, ruleValStr, false );

              collector = new FilteredElementCollector( doc );

              collector.OfClass( typeof( ViewPlan ) )
            .WherePasses( epf ); // only deal with ViewPlan
        }
Example #33
0
        Result IExternalCommand.Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp     = commandData.Application;
            UIDocument    uidoc     = uiapp.ActiveUIDocument;
            Application   app       = uiapp.Application;
            Document      doc       = uidoc.Document;
            PhaseArray    xcom      = doc.Phases;
            Phase         lastPhase = xcom.get_Item(xcom.Size - 1);
            ElementId     idPhase   = lastPhase.Id;
            FilterNumericRuleEvaluator evaluator = new FilterNumericEquals();

            GlobalParameter GlobePar2 = GlobalParametersManager.FindByName(doc, "FinData") != ElementId.InvalidElementId ?
                                        doc.GetElement(GlobalParametersManager.FindByName(doc, "FinData")) as GlobalParameter :null;
            FinishForm MainForm = new FinishForm(doc);

            MainForm.ShowDialog();
            using (Transaction tr = new Transaction(doc, "setGP"))
            {
                tr.Start();
                GlobalParameter GlobePar = GlobalParametersManager.FindByName(doc, "FinData") != ElementId.InvalidElementId ?
                                           doc.GetElement(GlobalParametersManager.FindByName(doc, "FinData")) as GlobalParameter :
                                           GlobalParameter.Create(doc, "FinData", ParameterType.Text);
                GlobePar.SetValue(new StringParameterValue(string.Join("|", MainForm.wTypeBoxes)));
                //int MoreThenOneLevel = ((IntegerParameterValue)GlobePar.GetValue()).Value;
                tr.Commit();
            }

            lastPhase = MainForm.retPhase;
            idPhase   = lastPhase.Id;

            List <SharedParameterElement> shParamElements = new FilteredElementCollector(doc)
                                                            .OfClass(typeof(SharedParameterElement))
                                                            .Cast <SharedParameterElement>()
                                                            .ToList();
            //Фильтр: Помещения на последней стадии
            FilterableValueProvider providerRoom = new ParameterValueProvider(new ElementId((int)BuiltInParameter.ROOM_PHASE_ID));
            FilterElementIdRule     rRule        = new FilterElementIdRule(providerRoom, evaluator, idPhase);
            ElementParameterFilter  room_filter  = new ElementParameterFilter(rRule);
            //FilterableValueProvider provRoomSchool = new ParameterValueProvider(shParam.Id);
            FilterStringRuleEvaluator StrEvaluator = new FilterStringEquals();
            IList <Element>           rooms        = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Rooms)
                                                     .WhereElementIsNotElementType()
                                                     .WherePasses(room_filter)
                                                     //.WherePasses(roomSc_filter)
                                                     .ToElements();

            //Фильтр: Стены созданные на последней стадии
            FilterableValueProvider provider    = new ParameterValueProvider(new ElementId((int)BuiltInParameter.PHASE_CREATED));
            FilterElementIdRule     fRule       = new FilterElementIdRule(provider, evaluator, idPhase);
            ElementParameterFilter  door_filter = new ElementParameterFilter(fRule);

            IList <Element> allWalls = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Walls)
                                       .WhereElementIsNotElementType()
                                       .WherePasses(door_filter)
                                       .ToElements();

            //Фильтр: экземпляры дверей
            List <FamilyInstance> doors = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Doors)
                                          .WhereElementIsNotElementType()
                                          .Cast <FamilyInstance>()
                                          .ToList();


            foreach (Element e in rooms)
            {
                RoomFinishing.Rooms.Add(new RoomFinishing(e));
            }
            RoomFinishing.Rooms = RoomFinishing.Rooms.OrderBy(x => x.Num).ToList();

            List <GhostWall> cWalls = new List <GhostWall>();

            foreach (Element wall in allWalls)
            {
                if (wall.LookupParameter("Помещение").AsString() != null & wall.LookupParameter("Помещение").AsString() != "")
                {
                    cWalls.Add(new GhostWall(wall, MainForm.LocType));
                }
            }

            foreach (GhostWall w in cWalls)
            {
                foreach (RoomFinishing r in RoomFinishing.Rooms)
                {
                    if (r.Num == w.Room)
                    {
                        if (w.typeName == MainForm.LocType.Name)
                        {
                            r.unitLocalWallVal += w.Area;
                            r.LocalWallText     = w.sostav;
                        }
                        else if (w.typeName == MainForm.ColType.Name)
                        {
                            r.unitKolonWallVal += w.Area;
                            r.KolonWallText     = w.sostav;
                        }
                        else
                        {
                            r.unitMainWallVal += w.Area;
                        }
                        if (w.countNewW)
                        {
                            r.unitNewWallVal += w.Area;
                        }
                    }
                }
            }


            //Плинтус
            foreach (FamilyInstance d in doors)
            {
                foreach (RoomFinishing r in RoomFinishing.Rooms)
                {
                    try
                    {
                        if (d.get_FromRoom(lastPhase).Id == r.Id | d.get_ToRoom(lastPhase).Id == r.Id)
                        {
                            r.Perimeter -= d.LookupParameter("сп_Ширина проёма").AsDouble();
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
            }

            RoomFinishing.makeFinish(MainForm);
            RoomFinishing.makeFloor(MainForm.splitLevel);
            using (Transaction tr = new Transaction(doc, "otdelka"))
            {
                tr.Start();
                GlobalParameter GlobePar = GlobalParametersManager.FindByName(doc, "НесколькоЭтажей") != ElementId.InvalidElementId ?
                                           doc.GetElement(GlobalParametersManager.FindByName(doc, "НесколькоЭтажей")) as GlobalParameter :
                                           GlobalParameter.Create(doc, "НесколькоЭтажей", ParameterType.YesNo);
                int MoreThenOneLevel = ((IntegerParameterValue)GlobePar.GetValue()).Value;

                int withNames = MainForm.withnames;
                MoreThenOneLevel = MainForm.levels;

                RoomFinishing.FinishTableCommit(doc, MainForm);
                RoomFinishing.FloorTableCommit(MoreThenOneLevel, withNames, doc);

                tr.Commit();
            }
            TaskDialog msg = new TaskDialog("Info");

            msg.MainInstruction = $"Выполнен расчет отделки для стадии \"{MainForm.retPhase.Name}\"";
            msg.Show();
            return(Result.Succeeded);
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
              UIDocument uidoc = uiapp.ActiveUIDocument;
              Application app = uiapp.Application;
              Document doc = uidoc.Document;

              Reference r = uidoc.Selection.PickObject(
            ObjectType.Element );

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

              Wall wall = doc.GetElement( r ) as Wall; // 2012

              //Parameter parameter = wall.get_Parameter( "Unconnected Height" ); // 2014, causes warning CS0618: 'Autodesk.Revit.DB.Element.get_Parameter(string)' is obsolete: 'This property is obsolete in Revit 2015, as more than one parameter can have the same name on a given element. Use Element.Parameters to obtain a complete list of parameters on this Element, or Element.GetParameters(String) to get a list of all parameters by name, or Element.LookupParameter(String) to return the first available parameter with the given name.'
              Parameter parameter = wall.get_Parameter( BuiltInParameter.WALL_USER_HEIGHT_PARAM ); // 2015, avoids warning, in language indepependent and more effective to look up

              ParameterValueProvider pvp
            = new ParameterValueProvider( parameter.Id );

              FilterNumericRuleEvaluator fnrv
            = new FilterNumericGreater();

              FilterRule fRule
            = new FilterDoubleRule( pvp, fnrv, 20, 1E-6 );

              ElementParameterFilter filter
            = new ElementParameterFilter( fRule );

              FilteredElementCollector collector
            = new FilteredElementCollector( doc );

              // Find walls with unconnected height
              // less than or equal to 20:

              ElementParameterFilter lessOrEqualFilter
            = new ElementParameterFilter( fRule, true );

              IList<Element> lessOrEqualFounds
            = collector.WherePasses( lessOrEqualFilter )
              .OfCategory( BuiltInCategory.OST_Walls )
              .OfClass( typeof( Wall ) )
              .ToElements();

              TaskDialog.Show( "Revit", "Walls found: "
            + lessOrEqualFounds.Count );

              return Result.Succeeded;
        }
Example #35
0
        public IEnumerable <CW_Category> Get(IEnumerable <string> documentTitles, string idOrName, bool mustContainElements, IEnumerable <CW_CategoryType> categoryTypes)
        {
            var result = new List <CW_Category>();

            foreach (var documentTitle in documentTitles)
            {
                var document = GetDocument(documentTitle);

                if (int.TryParse(idOrName, out int elementIdValue))
                {
                    var iterator = document.Settings.Categories.ForwardIterator();
                    while (iterator.MoveNext())
                    {
                        var category = iterator.Current as Category;
                        if (category.Id.IntegerValue == elementIdValue)
                        {
                            var cwCategory = RvtToCwElementConverter.SetCategoryData(new CW_Category(), category);
                            result.Add(cwCategory);
                            break;
                        }
                    }
                    break;
                }
                else if (idOrName != string.Empty)
                {
                    var category = document.Settings.Categories.get_Item(idOrName);
                    if (category != null)
                    {
                        var cwCategory = RvtToCwElementConverter.SetCategoryData(new CW_Category(), category);
                        result.Add(cwCategory);
                        break;
                    }
                }
                else
                {
                    foreach (Category category in document.Settings.Categories)
                    {
                        if (categoryTypes == null || categoryTypes.Any(x => (int)x == (int)category.CategoryType) || result.Any(x => x.Name == category.Name))
                        {
                            if (mustContainElements)
                            {
                                var categoryEvaluator = new FilterCategoryRule(new List <ElementId> {
                                    category.Id
                                });
                                var categoryFilter = new ElementParameterFilter(categoryEvaluator);
                                var collector      = new FilteredElementCollector(document).WherePasses(categoryFilter).WhereElementIsNotElementType();

                                if (collector.Any())
                                {
                                    var cwCategory = RvtToCwElementConverter.SetCategoryData(new CW_Category(), category);
                                    result.Add(cwCategory);
                                }
                            }
                            else
                            {
                                var cwCategory = RvtToCwElementConverter.SetCategoryData(new CW_Category(), category);
                                result.Add(cwCategory);
                            }
                        }
                    }
                }
            }

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

                ElementId id = new ElementId(
                  BuiltInParameter.ELEM_ROOM_NUMBER );

                ParameterValueProvider provider
                  = new ParameterValueProvider( id );

                FilterStringRuleEvaluator evaluator
                  = new FilterStringEquals();

                string sRoomNumber = "1";

                FilterRule rule = new FilterStringRule(
                  provider, evaluator, sRoomNumber, false );

                ElementParameterFilter filter
                  = new ElementParameterFilter( rule );

                FilteredElementCollector collector
                  = new FilteredElementCollector( doc );

                string s = string.Empty;

                foreach( Element e in collector )
                {
                  s += e.Name + e.Category.Name.ToString() + "\n";

                }
                System.Windows.Forms.MessageBox.Show( s );

                return Result.Succeeded;
            }
Example #37
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;

            Document doc = uiapp.ActiveUIDocument.Document;

            //create filter and cxollect elements
            ElementFilter catFilter = new ElementCategoryFilter(BuiltInCategory.OST_GenericModel);

            var elems = new FilteredElementCollector(doc)
                        .WhereElementIsNotElementType()
                        .WhereElementIsViewIndependent()
                        .WherePasses(catFilter)
                        .ToElements();

            string    textToSearch = "AECTEST";
            Parameter parameter    = elems[0].get_Parameter(new Guid("8160aed7-fe71-4da4-aea4-ad283b76a76a"));

            ParameterValueProvider pvp
                = new ParameterValueProvider(parameter.Id);

            FilterStringRuleEvaluator fnrvStr
                = new FilterStringEquals();

            FilterRule fRule
                = new FilterStringRule(pvp, fnrvStr, textToSearch, false);

            ElementParameterFilter filter
                = new ElementParameterFilter(fRule);

            FilteredElementCollector collector
                = new FilteredElementCollector(doc);

            ElementParameterFilter equalFilter
                = new ElementParameterFilter(fRule);

            IList <Element> filterByParam
                = collector.WherePasses(equalFilter)
                  .WherePasses(catFilter)
                  .ToElements();

            IList <Element> instances
                = new FilteredElementCollector(doc)
                  .OfClass(typeof(FamilyInstance))
                  .WherePasses(equalFilter)
                  .WherePasses(catFilter)
                  .ToElements();



            //define lists to store parameters and feed them
            List <int> listaID = new List <int>();

            List <string> listaKomentarz = new List <string>();
            List <string> listaZnak      = new List <string>();
            List <string> listaGuid      = new List <string>();



            foreach (var i in instances)
            {
                FamilyInstance fi           = i as FamilyInstance;
                String         parKomentarz = fi.ToRoom.Name;

                if (parKomentarz == null)
                {
                    listaKomentarz.Add("Brak danych w Revit");
                }
                else
                {
                    listaKomentarz.Add(parKomentarz);
                }
            }



            foreach (var e in filterByParam)
            {
                int parID = e.get_Parameter(BuiltInParameter.ID_PARAM).AsInteger();
                listaID.Add(parID);

/*
 *              String parKomentarz = e.get_Parameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS).AsString();
 *              if (parKomentarz == null)
 *              {
 *                  listaKomentarz.Add("Brak danych w Revit");
 *              }
 *              else
 *              {
 *                  listaKomentarz.Add(parKomentarz);
 *              }
 *              //BuiltInParameter.ALL_MODEL_MARK
 */
                String parZnak = e.get_Parameter(BuiltInParameter.ALL_MODEL_MARK).AsString();
                if (parZnak == null)
                {
                    listaZnak.Add("Brak danych w Revit");
                }
                else
                {
                    listaZnak.Add(parZnak);
                }

                String parGuid = e.get_Parameter(new Guid("61063061-01d9-4ecd-9876-f7ad906ef142")).AsString();
                if (parGuid == null)
                {
                    listaGuid.Add("Brak danych w Revit");
                }
                else
                {
                    listaGuid.Add(parGuid);
                }
            }


            //define the connection string of azure database.

            var cnString =
                "Server=tcp:revit-to-sql-svr-name.database.windows.net,1433;" +
                "Initial Catalog=RevitToSQL_DBName_01;" +
                "Persist Security Info=False;" +
                "User ID=kopeclogin;" +
                "Password=1qazXSW@;" +
                "MultipleActiveResultSets=False;" +
                "Encrypt=True;" +
                "TrustServerCertificate=False;" +
                "Connection Timeout=30;";

            //define the insert sql command, here I insert data into the GenericModel table in azure db.
            //@@@@@@@@@@@@@@@@@@
            // define datatable (dt) it could be helpfull in revittoexcel project
            var dt = new DataTable();

            dt.Columns.Add("ElementsId");
            dt.Columns.Add("Komentarz");
            dt.Columns.Add("Znak");
            dt.Columns.Add("ElementGUID");

            int n = 0;

            for (int i = 0; i < filterByParam.Count; i++)
            {
                dt.Rows.Add(n, listaKomentarz[i], listaZnak[i], listaGuid[i]);
                n++;
            }

/*
 *          using (var sqlBulk = new SqlBulkCopy(cnString))
 *          {
 *              sqlBulk.DestinationTableName = "GenericModels";
 *              sqlBulk.WriteToServer(dt);
 *          }
 */

            using (var connection = new SqlConnection(cnString))
            {
                connection.Open();

                var transaction = connection.BeginTransaction();

                using (var sqlBulk = new SqlBulkCopy(connection, SqlBulkCopyOptions.KeepIdentity, transaction))
                {
                    //sqlBulk.BatchSize = 5000;
                    sqlBulk.DestinationTableName = "GenericModels";
                    sqlBulk.WriteToServer(dt);
                }
                transaction.Commit();
            }


            TaskDialog.Show("Element Info", elems.Count.ToString());
            return(Result.Succeeded);
        }
        /// <summary>
        /// Return the all elements that
        /// use the given ElementType.
        /// </summary>
        static FilteredElementCollector GetAllElementsUsingType(
            Document doc,
            ElementType et)
        {
            // built-in parameter storing the type element id:

              BuiltInParameter bip
            = BuiltInParameter.ELEM_TYPE_PARAM;

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

              FilterNumericRuleEvaluator evaluator
            = new FilterNumericEquals();

              FilterRule rule = new FilterElementIdRule(
            provider, evaluator, et.Id );

              ElementParameterFilter filter
            = new ElementParameterFilter( rule );

              FilteredElementCollector collector
            = new FilteredElementCollector( doc )
              .WhereElementIsNotElementType()
              .WherePasses( filter );

              return collector;
        }
        private void BtnPreview_Click(object sender, RoutedEventArgs e)
        {
            //Use a Try block to keep any errors from crashing Revit
            try
            {
                //Clear the data in the Data Table for each search
                SheetTable.Clear();

                //Get the parameter value of any element passed to be used in the Filtered Element Collector
                ParameterValueProvider pvp;

                //Based on the Radio buttons for Name or Number to determine which parameter to use
                if (TogSheetNumber.IsToggled)
                {
                    //Set the parameter to the ElementId of BuiltInParameter for the Sheet Number
                    pvp = new ParameterValueProvider(new ElementId(BuiltInParameter.SHEET_NUMBER));
                }
                else
                {
                    //Set the parameter to the ElementId of BuiltInParameter for the Sheet Name
                    pvp = new ParameterValueProvider(new ElementId(BuiltInParameter.SHEET_NAME));
                }

                //Set how to compare the Sheet Name or Number. This will check to see if it Contains the value passed
                FilterStringRuleEvaluator fsr = new FilterStringContains();

                //Set the value from the "Find" text box. The "true" at the end is for case sensativity
                FilterRule fRule = new FilterStringRule(pvp, fsr, txtFind.Text, true);

                //Create a filter based on the Filter String Rule and the Filter rule to use int he Filtered Element Collector
                ElementParameterFilter filter = new ElementParameterFilter(fRule);

                //Check to see if the Data Table already has columns so we don't need to add them again.
                if (SheetTable.Columns.Count == 0)
                {
                    //Add a new columns to the Data Table with Name and the type of Column
                    SheetTable.Columns.Add(new DataColumn("SheetId", typeof(ElementId)));
                    SheetTable.Columns.Add(new DataColumn("SheetNumber", typeof(string)));
                    SheetTable.Columns.Add(new DataColumn("SheetName", typeof(string)));
                    SheetTable.Columns.Add(new DataColumn("Preview", typeof(string)));
                }

                //The Filtered Element Collector will get all Sheets in the model that contains the "Find" value based on the Prameter Value Provider above
                using (FilteredElementCollector fec = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Sheets).WherePasses(filter))
                {
                    //Loop through each sheet that is returned from the Collector
                    foreach (ViewSheet sheet in fec.ToElements())
                    {
                        //Based on the Radio buttons for Name or Number to determine which parameter to replace the values for the Preview
                        if (TogSheetNumber.IsToggled)
                        {
                            //Create a new row in the Data Table and add the sheet information to it when replacing the Sheet Number
                            SheetTable.Rows.Add(sheet.Id, sheet.SheetNumber, sheet.Name, sheet.SheetNumber.Replace(txtFind.Text, txtReplace.Text));
                        }
                        else
                        {
                            //Create a new row in the Data Table and add the sheet information to it when replacing the Sheet Name
                            SheetTable.Rows.Add(sheet.Id, sheet.SheetNumber, sheet.Name, sheet.Name.Replace(txtFind.Text, txtReplace.Text));
                        }
                    }
                }
                //Check to make sure there is at least one Sheet (row) in the DataTable
                if (SheetTable.Rows.Count > 0)
                {
                    //Enable the Replace button
                    btnReplace.IsEnabled = true;
                    //Use the Data Table to set the Data Source of the Data Grid View to display the sheet information
                    DataGridSheets.ItemsSource = SheetTable.DefaultView;
                }
                //Display a message that no Sheets were found based on the critera and set the Data Source to null for the Data Grid View
                else
                {
                    //Clear the data from the Data Grid
                    DataGridSheets.ItemsSource = null;
                    //Disable the Replace button
                    btnReplace.IsEnabled = false;
                }
            }
            //Catch any errors and display a Dialog with the informaiton
            catch (Exception ex)
            {
                TaskDialog.Show("Error", ex.ToString() + " : " + ex.InnerException);
            }
        }
        void f2( Document doc, Level level )
        {
            FilteredElementCollector collector
            = new FilteredElementCollector( doc );

              collector.OfCategory(
            BuiltInCategory.OST_StructuralFraming );

              collector.OfClass( typeof( FamilyInstance ) );

              BuiltInParameter bip = BuiltInParameter
            .INSTANCE_REFERENCE_LEVEL_PARAM;

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

              FilterNumericRuleEvaluator evaluator
            = new FilterNumericGreater();

              ElementId idRuleValue = level.Id;

              FilterElementIdRule rule
            = new FilterElementIdRule(
              provider, evaluator, idRuleValue );

              ElementParameterFilter filter
            = new ElementParameterFilter( rule );

              collector.WherePasses( filter );
        }
Example #41
0
        public static ParameterFilterElement CreateRebarHostFilter(
            Document doc, List <ElementId> rebarCatsIds, Parameter rebarIsFamilyParam, Parameter rebarHostParam, Parameter rebarMrkParam,
            string hostMark, string filterNamePrefix, RebarFilterMode filterMode)
        {
            string filterName = filterNamePrefix + "_Арм Конструкции " + hostMark;

            if (filterMode == RebarFilterMode.IfcMode)
            {
                filterName += " IFC";
            }
            ParameterFilterElement filter = DocumentGetter.GetFilterByName(doc, filterName);

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

            FilterRule ruleHostEquals = ParameterFilterRuleFactory.CreateEqualsRule(rebarHostParam.Id, hostMark, true);

            if (filterMode == RebarFilterMode.SingleMode)
            {
#if R2017 || R2018
                filter = ParameterFilterElement.Create(doc, filterName, rebarCatsIds);
                filter.SetRules(new List <FilterRule> {
                    ruleHostEquals
                });
#else
                ElementParameterFilter epf = new ElementParameterFilter(ruleHostEquals);
                filter = ParameterFilterElement.Create(doc, filterName, rebarCatsIds, epf);
#endif
                return(filter);
            }

            FilterRule ruleIsNotFamily = ParameterFilterRuleFactory.CreateEqualsRule(rebarIsFamilyParam.Id, 0);
            FilterRule ruleIsFamily    = ParameterFilterRuleFactory.CreateEqualsRule(rebarIsFamilyParam.Id, 1);
            FilterRule ruleMrkEquals   = ParameterFilterRuleFactory.CreateEqualsRule(rebarMrkParam.Id, hostMark, true);


#if R2017 || R2018
            if (filterMode == RebarFilterMode.StandardRebarMode)
            {
                filter = ParameterFilterElement.Create(doc, filterName, rebarCatsIds);
                filter.SetRules(new List <FilterRule> {
                    ruleIsNotFamily, ruleHostEquals
                });
                return(filter);
            }
            else if (filterMode == RebarFilterMode.IfcMode)
            {
                filter = ParameterFilterElement.Create(doc, filterName, rebarCatsIds);
                filter.SetRules(new List <FilterRule> {
                    ruleIsFamily, ruleMrkEquals
                });
                return(filter);
            }
#else
            if (filterMode == RebarFilterMode.DoubleMode)
            {
                ElementParameterFilter filterByStandardArm = new ElementParameterFilter(new List <FilterRule> {
                    ruleIsNotFamily, ruleHostEquals
                });
                ElementParameterFilter filterForIfcArm = new ElementParameterFilter(new List <FilterRule> {
                    ruleIsFamily, ruleMrkEquals
                });
                LogicalOrFilter orfilter = new LogicalOrFilter(filterByStandardArm, filterForIfcArm);
                filter = ParameterFilterElement.Create(doc, filterName, rebarCatsIds, orfilter);
                return(filter);
            }
#endif
            return(null);
        }
    /// <summary>
    /// Find a specific family type for a wall, which is a system family. 
    /// Most efficient way to find a named family symbol: use a parameter filter.
    /// </summary>
    public Element FindFamilyType_Wall_v3(
      string wallFamilyName,
      string wallTypeName)
    {
      ParameterValueProvider provider
        = new ParameterValueProvider(
          new ElementId(BuiltInParameter.DATUM_TEXT));

      FilterStringRuleEvaluator evaluator
        = new FilterStringEquals();

      FilterRule rule = new FilterStringRule(
        provider, evaluator, wallTypeName, true);

      ElementParameterFilter filter
        = new ElementParameterFilter(rule);

      return new FilteredElementCollector(_doc)
        .OfClass(typeof(WallType))
        .WherePasses(filter)
        .FirstElement();
    }
Example #43
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Document doc = commandData.Application.ActiveUIDocument.Document;

            AppBatchFilterCreation.assemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
            string dllPath = Path.GetDirectoryName(AppBatchFilterCreation.assemblyPath);

            OpenFileDialog openCsvDialog = new OpenFileDialog();

            openCsvDialog.Filter           = "CSV file|*.csv";
            openCsvDialog.Title            = "Выберите файл CSV (v2018.10.17)";
            openCsvDialog.Multiselect      = false;
            openCsvDialog.InitialDirectory = dllPath;

            if (openCsvDialog.ShowDialog() != DialogResult.OK)
            {
                return(Result.Cancelled);
            }
            ;

            //считываю файл
            string          path = openCsvDialog.FileName;
            List <string[]> data = ReadDataFromCSV.Read(path);

            string msg         = "";
            int    filterCount = 0;

            //одна строка в файле - один фильтр
            foreach (string[] line in data)
            {
                FilterSourceInfo filterSource = new FilterSourceInfo(line);
                string           filterName   = filterSource.FilterName;

                //Добавляю категории
                List <ElementId> catIds = new List <ElementId>();
                foreach (string stringCat in filterSource.Categories)
                {
                    BuiltInCategory cat = GetBuiltinCategory.GetCategoryByRussianName(stringCat);
                    catIds.Add(new ElementId(cat));
                }


                //добавляю критерии фильтрации
                List <FilterRule> filterRules = new List <FilterRule>();

                foreach (string[] sourceRule in filterSource.SourceRules)
                {
                    string paramName = sourceRule[0];
                    string function  = sourceRule[1];
                    string value     = sourceRule[2];


                    BuiltInCategory cat = GetBuiltinCategory.GetCategoryByRussianName(filterSource.Categories[0]);
                    if (cat == BuiltInCategory.OST_Sections || cat == BuiltInCategory.OST_Elev || cat == BuiltInCategory.OST_Callouts)
                    {
                        cat = BuiltInCategory.OST_Views;
                    }

                    FilteredElementCollector collector = new FilteredElementCollector(doc).OfCategory(cat);

                    Parameter param = null;
                    try
                    {
                        foreach (Element elem in collector)
                        {
                            param = elem.LookupParameter(paramName);
                            if (param == null)
                            {
                                continue;
                            }
                            break;
                        }
                    }
                    catch { }

                    if (collector.Count() == 0 || param == null)
                    {
                        message  = "Ошибка при создании фильтра: " + filterName;
                        message += "\nУстановите как минимум один элемент в категории: " + filterSource.Categories[0];
                        message += "\nТребуемый параметр: " + paramName;
                        return(Result.Failed);
                    }

                    FilterRule rule = FilterCreator.CreateRule2(param, function, value);
                    filterRules.Add(rule);
                }

                try
                {
                    using (Transaction t = new Transaction(doc))
                    {
                        t.Start("Создание фильтра" + filterName);
                        ParameterFilterElement filter = ParameterFilterElement.Create(doc, filterName, catIds);
#if R2017 || R2018
                        filter.SetRules(filterRules);
#else
                        ElementParameterFilter epf = new ElementParameterFilter(filterRules);
                        filter.SetElementFilter(epf);
#endif
                        filterCount++;
                        t.Commit();
                    }
                }
                catch
                {
                    msg += filterName + "\n";
                }
            }
            string finalMessage = "Создано фильтров: " + filterCount.ToString() + "\n";
            if (msg.Length != 0)
            {
                finalMessage += "Не удалось создать: \n" + msg;
            }

            TaskDialog.Show("Batch filter create", finalMessage);
            return(Result.Succeeded);
        }
Example #44
0
        Result IExternalCommand.Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            //GlobalParameter.
            //GlobalParameter one = ;
            FinishForm questions = new FinishForm(doc);

            questions.Show();
            questions.Activate();


            double     FT        = 0.3048;
            PhaseArray xcom      = doc.Phases;
            Phase      lastPhase = xcom.get_Item(xcom.Size - 1);
            ElementId  idPhase   = lastPhase.Id;
            FilterNumericRuleEvaluator evaluator = new FilterNumericEquals();

            List <SharedParameterElement> shParamElements = new FilteredElementCollector(doc)
                                                            .OfClass(typeof(SharedParameterElement))
                                                            .Cast <SharedParameterElement>()
                                                            .ToList();
            //SharedParameterElement shParam = shParamElements.Where(x => x.Name == "ADSK_Номер здания").First();

            //Фильтр: Помещения на последней стадии
            FilterableValueProvider providerRoom = new ParameterValueProvider(new ElementId((int)BuiltInParameter.ROOM_PHASE_ID));
            FilterElementIdRule     rRule        = new FilterElementIdRule(providerRoom, evaluator, idPhase);
            ElementParameterFilter  room_filter  = new ElementParameterFilter(rRule);
            //FilterableValueProvider provRoomSchool = new ParameterValueProvider(shParam.Id);
            FilterStringRuleEvaluator StrEvaluator = new FilterStringEquals();
            //FilterRule rScRule = new FilterStringRule(provRoomSchool, StrEvaluator, "",false);
            //ElementParameterFilter roomSc_filter = new ElementParameterFilter(rScRule);

            IList <Element> rooms = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Rooms)
                                    .WhereElementIsNotElementType()
                                    .WherePasses(room_filter)
                                    //.WherePasses(roomSc_filter)
                                    .ToElements();

            //Фильтр: Стены созданные на последней стадии
            FilterableValueProvider provider    = new ParameterValueProvider(new ElementId((int)BuiltInParameter.PHASE_CREATED));
            FilterElementIdRule     fRule       = new FilterElementIdRule(provider, evaluator, idPhase);
            ElementParameterFilter  door_filter = new ElementParameterFilter(fRule);

            IList <Element> allWalls = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Walls)
                                       .WhereElementIsNotElementType()
                                       .WherePasses(door_filter)
                                       .ToElements();

            //Фильтр: экземпляры дверей
            List <FamilyInstance> doors = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Doors)
                                          .WhereElementIsNotElementType()
                                          .Cast <FamilyInstance>()
                                          .ToList();

            List <FamilySymbol> ento = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Entourage)
                                       .WhereElementIsElementType()
                                       .Cast <FamilySymbol>()
                                       .ToList();

            List <String> entoName = new List <string>();

            foreach (FamilySymbol i in ento)
            {
                entoName.Add(i.Name);
            }

            List <String> entoFamily = new List <string>();

            //List<otdelka> otd = new List<otdelka>();
            foreach (FamilySymbol f in ento)
            {
                //otd.Add(new otdelka(f.FamilyName+':'+f.Name,f.getP("АР_Состав отделки")));
                entoFamily.Add(f.FamilyName);
            }
            //List<String> one = new List<string>();

            //foreach (FamilySymbol f in ento)
            //{

            //    one.Add(f.getP("АР_Состав отделки"));
            //}
            //string two = doc.GetElement(rooms[0].LookupParameter("ОТД_Пол").AsElementId()).Name;

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

            foreach (Element item in allWalls)
            {
                if (item.LookupParameter("Помещение").AsString() != null & item.LookupParameter("Помещение").AsString() != "")
                {
                    bool isLocal = (item as Wall).WallType.LookupParameter("rykomoika").AsInteger() == 1 ? true : false;
                    walls.Add(item);

                    cWalls.Add(new GhostWall(
                                   item.getP("Помещение"),
                                   item.LevelId,
                                   item.get_Parameter(BuiltInParameter.HOST_AREA_COMPUTED).AsDouble(),
                                   isLocal
                                   ));
                }
            }
            List <ElementId> Levels = new List <ElementId>();

            rooms = rooms.OrderBy(x => x.get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString()).ToList();
            List <RoomFinishing> novaRooms = new List <RoomFinishing>();

            foreach (Element e in rooms)
            {
                novaRooms.Add(new RoomFinishing(e));
            }

            novaRooms = novaRooms.OrderBy(x => x.Num).ToList();

            List <ElementId> wallLevels = new List <ElementId>();

            foreach (Element i in rooms)
            {
                Levels.Add(i.LevelId);
            }
            foreach (Element i in walls)
            {
                wallLevels.Add(i.LevelId);
            }
            IEnumerable <String> LevelsName = new List <String>();

            //Levels=Levels.Distinct().ToList();
            //Levels = Levels.OrderBy(x=>doc.GetElement(x).Name).ToList();

            foreach (ElementId i in Levels.Distinct().OrderBy(x => doc.GetElement(x).Name))
            {
                LevelsName = LevelsName.Append(doc.GetElement(i).Name);
            }
            String str = String.Join(",", LevelsName);


            IEnumerable <bool>             isNewC           = new List <bool>();
            IEnumerable <bool>             isNewW           = new List <bool>();
            IEnumerable <bool>             SecFin           = new List <bool>();
            List <String>                  CeilText         = new List <String>();
            List <String>                  MainText         = new List <String>();
            List <String>                  FloorText        = new List <String>();
            List <string>                  WallsLocal       = new List <string>();
            List <List <Element> >         roomByLevel      = new List <List <Element> >();
            List <List <String> >          roomNumByLevel   = new List <List <String> >();
            List <List <String> >          CeilTextByLevel  = new List <List <string> >();
            List <List <String> >          MainTextByLevel  = new List <List <string> >();
            List <List <String> >          FloorTextByLevel = new List <List <string> >();
            List <List <List <Element> > > FinishTable      = new List <List <List <Element> > >();
            List <List <List <String> > >  FinishTableNum   = new List <List <List <String> > >();
            List <List <List <double> > >  FinishTableW3S   = new List <List <List <double> > >();
            List <List <Element> >         wallByLevel      = new List <List <Element> >();
            List <List <String> >          wallNumByLevel   = new List <List <String> >();
            List <List <double> >          wallAreaByLevel  = new List <List <double> >();
            List <List <double> >          WallS1           = new List <List <double> >();
            List <List <double> >          WallS2           = new List <List <double> >();
            List <List <string> >          WallsLocalText   = new List <List <string> >();
            List <List <List <Element> > > floorTable       = new List <List <List <Element> > >();
            List <List <List <string> > >  floorTableNum    = new List <List <List <string> > >();
            List <List <List <double> > >  plintTable       = new List <List <List <double> > >();
            List <List <double> >          plintByLevel     = new List <List <double> >();
            List <List <double> >          perimByLevel     = new List <List <double> >();


            foreach (ElementId lev in Levels.Distinct().OrderBy(x => doc.GetElement(x).Name))
            {
                List <Element> s   = new List <Element>();
                List <String>  n   = new List <String>();
                List <String>  ct  = new List <String>();
                List <String>  mt  = new List <String>();
                List <String>  ft  = new List <String>();
                List <double>  ws  = new List <double>();
                List <double>  ws2 = new List <double>();
                List <string>  wt  = new List <string>();
                List <double>  pl  = new List <double>();
                List <double>  pr  = new List <double>();

                for (int i = 0; i < Levels.Count(); i++)
                {
                    if (Levels[i] == lev)
                    {
                        s.Add(rooms.ElementAt(i));
                        n.Add(rooms.ElementAt(i).get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString());
                        ct.Add(rooms.ElementAt(i).LookupParameter("ОТД_Потолок").AsValueString());
                        mt.Add(rooms.ElementAt(i).LookupParameter("ОТД_Стены").AsValueString());
                        ft.Add(rooms.ElementAt(i).LookupParameter("ОТД_Пол").AsValueString());
                        pr.Add(rooms.ElementAt(i).get_Parameter(BuiltInParameter.ROOM_PERIMETER).AsDouble());
                        ws.Add(0);
                        ws2.Add(0);
                        pl.Add(0);
                        wt.Add("");

                        CeilText.Add(rooms.ElementAt(i).LookupParameter("ОТД_Потолок").AsValueString());
                        MainText.Add(rooms.ElementAt(i).LookupParameter("ОТД_Стены").AsValueString());
                        FloorText.Add(rooms.ElementAt(i).LookupParameter("ОТД_Пол").AsValueString());
                    }
                }
                roomByLevel.Add(s);
                roomNumByLevel.Add(n);
                CeilTextByLevel.Add(ct);
                MainTextByLevel.Add(mt);
                FloorTextByLevel.Add(ft);
                WallS1.Add(ws);
                WallS2.Add(ws2);
                WallsLocalText.Add(wt);
                plintByLevel.Add(pl);
                perimByLevel.Add(pr);


                List <Element> w  = new List <Element>();
                List <String>  wn = new List <String>();
                List <double>  wa = new List <double>();
                //List<Wall> est = walls as List<Wall>;
                for (int i = 0; i < wallLevels.Count(); i++)
                {
                    if (wallLevels[i] == lev)
                    {
                        w.Add(walls[i]);
                        wn.Add(walls[i].LookupParameter("Помещение").AsString());
                        wa.Add(walls[i].get_Parameter(BuiltInParameter.HOST_AREA_COMPUTED).AsDouble());
                    }
                }
                wallAreaByLevel.Add(wa);
                wallByLevel.Add(w);
                wallNumByLevel.Add(wn);
            }

            //Плинтус
            foreach (FamilyInstance d in doors)
            {
                foreach (RoomFinishing r in novaRooms)
                {
                    try
                    {
                        if (d.get_FromRoom(lastPhase).Id == r.Id | d.get_ToRoom(lastPhase).Id == r.Id)
                        {
                            r.Perimeter -= d.LookupParameter("сп_Ширина проёма").AsDouble();
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
            }

            //Задаём площади отделки помещений и указываем неизменные помещения
            foreach (ElementId lev in novaRooms.Select(x => x.Level).Distinct())
            {
                foreach (RoomFinishing r in novaRooms.Where(x => x.Level == lev))
                {
                    //Стены
                    for (int i = 0; i < novaRooms.Select(x => x.Level).Distinct().Count(); i++)
                    {
                        for (int w = 0; w < wallNumByLevel[i].Count(); w++)
                        {
                            if (wallByLevel[i][w].LevelId != lev)
                            {
                                continue;
                            }
                            Wall checkWall = (Wall)wallByLevel[i][w];
                            if (r.Num == wallNumByLevel[i][w])
                            {
                                if (checkWall.WallType.LookupParameter("rykomoika").AsInteger() == 1)
                                {
                                    r.LocalWallVal += wallAreaByLevel[i][w];
                                    r.LocalWallText = checkWall.WallType.LookupParameter("СоставОтделкиСтен").AsString();
                                    WallsLocal.Add(checkWall.WallType.LookupParameter("СоставОтделкиСтен").AsString());
                                    continue;
                                }
                                r.MainWallVal += wallAreaByLevel[i][w];
                                WallsLocal.Add("");
                            }
                        }
                    }
                }
            }


            for (int lev = 0; lev < Levels.Distinct().Count(); lev++)
            {
                for (int r = 0; r < roomNumByLevel[lev].Count(); r++)
                {
                    //Плинтус
                    for (int i = 0; i < doors.Count(); i++)
                    {
                        try
                        {
                            if (doors[i].get_FromRoom(lastPhase).Id == roomByLevel[lev][r].Id | doors[i].get_ToRoom(lastPhase).Id == roomByLevel[lev][r].Id)
                            {
                                plintByLevel[lev][r] += doors[i].LookupParameter("Ширина").AsDouble();
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }

                    //Стены
                    for (int w = 0; w < wallNumByLevel[lev].Count(); w++)
                    {
                        Wall checkWall = (Wall)wallByLevel[lev][w];
                        if (roomNumByLevel[lev][r] == wallNumByLevel[lev][w])
                        {
                            if (checkWall.WallType.LookupParameter("rykomoika").AsInteger() == 1)
                            {
                                WallS2[lev][r]        += wallAreaByLevel[lev][w];
                                WallsLocalText[lev][r] = checkWall.WallType.LookupParameter("СоставОтделкиСтен").AsString();
                                WallsLocal.Add(checkWall.WallType.LookupParameter("СоставОтделкиСтен").AsString());
                                continue;
                            }
                            WallS1[lev][r] += wallAreaByLevel[lev][w];
                            WallsLocal.Add("");
                        }
                    }
                }
            }
            WallsLocal = WallsLocal.OrderBy(x => x).ToList();


            //Сортируем помещения по типу отделки потолка и стен
            int finishTypes = 0;
            List <List <RoomFinishing> > novaFinishTable = new List <List <RoomFinishing> >();


            if (WallsLocal.Count == 0)
            {
                foreach (string c in novaRooms.Select(x => x.CeilType).Distinct())
                {
                    foreach (string w in novaRooms.Select(x => x.WallType).Distinct())
                    {
                        List <RoomFinishing> cw = novaRooms
                                                  .Where(x => x.CeilType == c)
                                                  .Where(y => y.WallType == w)
                                                  .ToList();
                        novaFinishTable.Add(cw);
                        foreach (RoomFinishing r in cw)
                        {
                            r.SimilarWallVal = cw.Sum(x => x.MainWallVal);
                        }
                    }
                }
            }
            else
            {
                foreach (string wt3 in WallsLocal.Distinct())
                {
                    foreach (string c in novaRooms.Select(x => x.CeilType).Distinct())
                    {
                        foreach (string w in novaRooms.Select(x => x.WallType).Distinct())
                        {
                            List <RoomFinishing> cw = novaRooms
                                                      .Where(x => x.CeilType == c)
                                                      .Where(y => y.WallType == w)
                                                      .ToList();
                            novaFinishTable.Add(cw);
                            foreach (RoomFinishing r in cw)
                            {
                                r.SimilarWallVal = cw.Sum(x => x.MainWallVal);
                            }
                        }
                    }
                }
            }


            if (WallsLocal.Count == 0)
            {
                foreach (String i in CeilText.Distinct())
                {
                    foreach (String j in MainText.Distinct())
                    {
                        FinishTable.Add(new List <List <Element> >());
                        FinishTableNum.Add(new List <List <string> >());
                        FinishTableW3S.Add(new List <List <double> >());

                        for (int lev = 0; lev < Levels.Distinct().Count(); lev++)
                        {
                            List <Element> SimilarFinish    = new List <Element>();
                            List <String>  SimilarFinishNum = new List <String>();
                            List <double>  SimW3S           = new List <double>();
                            for (int r = 0; r < roomByLevel[lev].Count(); r++)
                            {
                                if (CeilTextByLevel[lev][r] == i & MainTextByLevel[lev][r] == j)
                                {
                                    SimilarFinish.Add(roomByLevel[lev][r]);
                                    SimilarFinishNum.Add(roomNumByLevel[lev][r]);
                                    SimW3S.Add(WallS2[lev][r]);
                                }
                            }
                            FinishTable[finishTypes].Add(SimilarFinish);
                            FinishTableNum[finishTypes].Add(SimilarFinishNum);
                            FinishTableW3S[finishTypes].Add(SimW3S);
                        }
                        finishTypes++;
                    }
                }
            }
            else
            {
                foreach (string wt3 in WallsLocal.Distinct())
                {
                    foreach (String i in CeilText.Distinct())
                    {
                        foreach (String j in MainText.Distinct())
                        {
                            FinishTable.Add(new List <List <Element> >());
                            FinishTableNum.Add(new List <List <string> >());
                            FinishTableW3S.Add(new List <List <double> >());

                            for (int lev = 0; lev < Levels.Distinct().Count(); lev++)
                            {
                                List <Element> SimilarFinish    = new List <Element>();
                                List <String>  SimilarFinishNum = new List <String>();
                                List <double>  SimW3S           = new List <double>();
                                for (int r = 0; r < roomByLevel[lev].Count(); r++)
                                {
                                    if (CeilTextByLevel[lev][r] == i & MainTextByLevel[lev][r] == j & WallsLocalText[lev][r] == wt3)
                                    {
                                        SimilarFinish.Add(roomByLevel[lev][r]);
                                        SimilarFinishNum.Add(roomNumByLevel[lev][r]);
                                        SimW3S.Add(WallS2[lev][r]);
                                    }
                                }
                                FinishTable[finishTypes].Add(SimilarFinish);
                                FinishTableNum[finishTypes].Add(SimilarFinishNum);
                                FinishTableW3S[finishTypes].Add(SimW3S);
                            }
                            finishTypes++;
                        }
                    }
                }
            }

            List <List <RoomFinishing> > novaFloorTable = new List <List <RoomFinishing> >();

            foreach (string i in novaRooms.Select(x => x.FloorType).Distinct())
            {
                foreach (string pl in novaRooms.Select(x => x.PlintusType).Distinct())
                {
                    List <RoomFinishing> flpl = novaRooms
                                                .Where(x => x.FloorType == i)
                                                .Where(y => y.PlintusType == pl)
                                                .ToList();
                    novaFloorTable.Add(flpl);
                    foreach (RoomFinishing r in flpl)
                    {
                        r.SimilarPlintusVal = flpl.Sum(x => x.Perimeter);
                    }
                }
            }

            //Сортируем помещения по типу пола
            int floorTypes = 0;

            foreach (string i in FloorText.Distinct())
            {
                floorTable.Add(new List <List <Element> >());
                floorTableNum.Add(new List <List <string> >());
                plintTable.Add(new List <List <double> >());
                for (int lev = 0; lev < Levels.Distinct().Count(); lev++)
                {
                    List <Element> simFloor    = new List <Element>();
                    List <string>  simFloorNum = new List <string>();
                    List <double>  simPlint    = new List <double>();
                    for (int r = 0; r < roomByLevel[lev].Count(); r++)
                    {
                        if (FloorTextByLevel[lev][r] == i)
                        {
                            simFloor.Add(roomByLevel[lev][r]);
                            simFloorNum.Add(roomNumByLevel[lev][r]);
                            simPlint.Add(perimByLevel[lev][r] - plintByLevel[lev][r]);
                        }
                    }
                    floorTable[floorTypes].Add(simFloor);
                    floorTableNum[floorTypes].Add(simFloorNum);
                    plintTable[floorTypes].Add(simPlint);
                }

                floorTypes++;
            }



            using (Transaction tr = new Transaction(doc, "otdelka"))
            {
                tr.Start();
                GlobalParameter ohohoh = GlobalParametersManager.FindByName(doc, "НесколькоЭтажей") != ElementId.InvalidElementId ?
                                         doc.GetElement(GlobalParametersManager.FindByName(doc, "НесколькоЭтажей")) as GlobalParameter :
                                         GlobalParameter.Create(doc, "НесколькоЭтажей", ParameterType.YesNo);



                int MoreThenOneLevel = ((IntegerParameterValue)ohohoh.GetValue()).Value;

                //Передаем номера помещений с одинаковым типом отделки стен и потолка
                for (int lev = 0; lev < roomByLevel.Count(); lev++)
                {
                    for (int r = 0; r < roomByLevel[lev].Count(); r++)
                    {
                        roomByLevel[lev][r].LookupParameter("SanT").Set(WallsLocalText[lev][r]);
                        roomByLevel[lev][r].LookupParameter("ДлинаПроемов").Set(plintByLevel[lev][r]);
                    }
                }

                for (int i = 0; i < FinishTable.Count(); i++)
                {
                    String fillText = "";
                    //String fillText2 = "";
                    double sumW3S = 0;
                    for (int lev = 0; lev < FinishTable[i].Count(); lev++)
                    {
                        sumW3S += FinishTableW3S[i][lev].Sum() * (FT * FT);
                        if (FinishTable[i][lev].Count() == 0)
                        {
                            continue;
                        }
                        else
                        {
                            if (MoreThenOneLevel == 1)
                            {
                                fillText += (lev + 1).ToString() + " этаж:\n";
                            }
                            fillText += Meta.shortLists(FinishTableNum[i][lev]);
                            fillText += "\n";
                        }
                    }
                    for (int lev = 0; lev < FinishTable[i].Count(); lev++)
                    {
                        for (int r = 0; r < FinishTable[i][lev].Count(); r++)
                        {
                            try
                            {
                                FinishTable[i][lev][r].LookupParameter("ОТД_Состав.Стены").Set(doc.GetElement(FinishTable[i][lev][r].LookupParameter("ОТД_Стены").AsElementId()).LookupParameter("АР_Состав отделки").AsString());
                                //FinishTable[i][lev][r].LookupParameter("ОТД_Состав.Потолок").Set(doc.GetElement(FinishTable[i][lev][r].LookupParameter("ОТД_Потолок").AsElementId()).LookupParameter("АР_Состав отделки").AsString());
                            }
                            catch (Exception)
                            {
                                FinishTable[i][lev][r].LookupParameter("ОТД_Состав.Стены").Set("НЕТ ОТДЕЛКИ");
                                //FinishTable[i][lev][r].LookupParameter("ОТД_Состав.Потолок").Set("НЕТ ОТДЕЛКИ");
                            }
                            try
                            {
                                //FinishTable[i][lev][r].LookupParameter("ОТД_Состав.Стены").Set(doc.GetElement(FinishTable[i][lev][r].LookupParameter("ОТД_Стены").AsElementId()).LookupParameter("АР_Состав отделки").AsString());
                                FinishTable[i][lev][r].LookupParameter("ОТД_Состав.Потолок").Set(doc.GetElement(FinishTable[i][lev][r].LookupParameter("ОТД_Потолок").AsElementId()).LookupParameter("АР_Состав отделки").AsString());
                            }
                            catch (Exception)
                            {
                                //FinishTable[i][lev][r].LookupParameter("ОТД_Состав.Стены").Set("НЕТ ОТДЕЛКИ");
                                FinishTable[i][lev][r].LookupParameter("ОТД_Состав.Потолок").Set("НЕТ ОТДЕЛКИ");
                            }
                            FinishTable[i][lev][r].LookupParameter("testW").Set(fillText);
                            //FinishTable[i][lev][r].LookupParameter("unitTest").Set(fillText2);
                            FinishTable[i][lev][r].LookupParameter("SanS").Set(sumW3S > 0 ? sumW3S.ToString("F1") : "");
                            FinishTable[i][lev][r].LookupParameter("snS").Set(FinishTableW3S[i][lev][r]);
                        }
                    }
                }

                for (int lev = 0; lev < Levels.Distinct().Count(); lev++)
                {
                    for (int r = 0; r < roomByLevel[lev].Count(); r++)
                    {
                        roomByLevel[lev][r].LookupParameter("WallS1n").Set(WallS1[lev][r]);
                    }
                }



                int withNames = questions.withnames;                //Если нужны имена помещений
                                                                    //Передаем номера помещений с одинаковым типом стен потолка
                foreach (List <RoomFinishing> item in novaFinishTable)
                {
                    if (item == null)
                    {
                        continue;
                    }
                    String fillText = "";
                    foreach (ElementId lev in item.Select(x => x.Level).Distinct())
                    {
                        if (MoreThenOneLevel == 1)
                        {
                            fillText += doc.GetElement(lev).LookupParameter("Название уровня").AsString() + ":\n";
                        }
                        if (withNames == 1)
                        {
                            foreach (RoomFinishing gg in item.Where(x => x.Level == lev))
                            {
                                fillText += gg.Name + "-" + gg.Num + ", ";
                            }
                            fillText = fillText.Remove(fillText.Length - 2, 2) + "\n";
                            continue;
                        }
                        fillText += Meta.shortLists(item.Where(x => x.Level == lev).Select(y => y.Num).ToList()) + "\n";
                    }
                    foreach (ElementId lev in item.Select(x => x.Level).Distinct())
                    {
                        foreach (RoomFinishing r in item.Where(x => x.Level == lev))
                        {
                            try
                            {
                                r.refElement.LookupParameter("ОТД_Состав.Потолок").Set(doc.GetElement(r.refElement.LookupParameter("ОТД_Потолок").AsElementId()).LookupParameter("АР_Состав отделки").AsString());
                            }
                            catch (Exception)
                            {
                                r.refElement.LookupParameter("ОТД_Состав.Потолок").Set("НЕТ ОТДЕЛКИ");
                            }
                            try
                            {
                                r.refElement.LookupParameter("ОТД_Состав.Стены").Set(doc.GetElement(r.refElement.LookupParameter("ОТД_Стены").AsElementId()).LookupParameter("АР_Состав отделки").AsString());
                            }
                            catch (Exception)
                            {
                                r.refElement.LookupParameter("ОТД_Состав.Стены").Set("НЕТ ОТДЕЛКИ");
                            }
                            r.refElement.LookupParameter("testW").Set(fillText);
                            //r.refElement.LookupParameter("ОТД_Кол.Стены").Set(0);
                            r.refElement.LookupParameter("ОТД_Кол.Стены").Set(r.SimilarWallVal);


                            //r.refElement.LookupParameter("PlintusTotal").Set(r.Perimeter);
                            //item.Select(x => x.refElement.LookupParameter("testF").Set(fillText));
                            //item.Select(x => x.refElement.LookupParameter("PlintusTotal").Set(x.SimilarPlintusVal));
                        }
                    }
                }

                //Передаем номера помещений с одинаковым типом отделки пола
                foreach (List <RoomFinishing> item in novaFloorTable)
                {
                    if (item == null)
                    {
                        continue;
                    }
                    String fillText = "";
                    foreach (ElementId lev in item.Select(x => x.Level).Distinct())
                    {
                        if (MoreThenOneLevel == 1)
                        {
                            fillText += doc.GetElement(lev).LookupParameter("Название уровня").AsString() + ":\n";
                        }
                        if (withNames == 1)
                        {
                            foreach (RoomFinishing gg in item.Where(x => x.Level == lev))
                            {
                                fillText += gg.Name + "-" + gg.Num + ", ";
                            }
                            fillText = fillText.Remove(fillText.Length - 2, 2) + "\n";
                            continue;
                        }
                        fillText += Meta.shortLists(item.Where(x => x.Level == lev).Select(y => y.Num).ToList()) + "\n";
                    }
                    foreach (ElementId lev in item.Select(x => x.Level).Distinct())
                    {
                        foreach (RoomFinishing r in item.Where(x => x.Level == lev))
                        {
                            r.refElement.LookupParameter("ОТД_Состав.Пол").Set("");
                            try
                            {
                                r.refElement.LookupParameter("ОТД_Состав.Пол").Set(doc.GetElement(r.refElement.LookupParameter("ОТД_Пол").AsElementId()).LookupParameter("АР_Состав отделки").AsString());
                            }
                            catch (Exception)
                            {
                                r.refElement.LookupParameter("ОТД_Состав.Пол").Set("НЕТ ОТДЕЛКИ");
                            }
                            try
                            {
                                r.refElement.LookupParameter("ОТД_Состав.Плинтус").Set(doc.GetElement(r.refElement.LookupParameter("ОТД_Плинтус").AsElementId()).LookupParameter("АР_Состав отделки").AsString());
                            }
                            catch (Exception)
                            {
                                r.refElement.LookupParameter("ОТД_Состав.Плинтус").Set("НЕТ ОТДЕЛКИ");
                            }
                            r.refElement.LookupParameter("testF").Set(fillText);
                            r.refElement.LookupParameter("ОТД_Кол.Плинтус").Set("");

                            if (r.PlintusType != "__Отделка : ---")
                            {
                                r.refElement.LookupParameter("ОТД_Кол.Плинтус").Set((r.SimilarPlintusVal * FT).ToString("F1"));
                            }

                            r.refElement.LookupParameter("PlintusTotal").Set(r.Perimeter);
                            //item.Select(x => x.refElement.LookupParameter("testF").Set(fillText));
                            //item.Select(x => x.refElement.LookupParameter("PlintusTotal").Set(x.SimilarPlintusVal));
                        }
                    }
                }
                //          for (int i = 0; i < floorTable.Count(); i++)
                //          {
                //              double sumPlint = 0;
                //              String fillText = "";
                //              for (int lev = 0; lev < floorTable[i].Count(); lev++)
                //              {
                //                  sumPlint += plintTable[i][lev].Sum() * FT;
                //                  if (floorTable[i][lev].Count() == 0)
                //                  {
                //                      continue;
                //                  }
                //                  else
                //                  {
                //	if (MoreThenOneLevel==1)
                //	{
                //		fillText += (lev + 1).ToString() + " этаж:\n";
                //	}
                //                      fillText += Meta.shortLists(floorTableNum[i][lev]);
                //                      fillText += "\n";
                //                  }
                //              }



                //              for (int lev = 0; lev < floorTable[i].Count(); lev++)
                //              {
                //for (int r = 0; r < floorTable[i][lev].Count(); r++)
                //{
                //                      try
                //                      {
                //		floorTable[i][lev][r].LookupParameter("ОТД_Состав.Пол").Set(doc.GetElement(floorTable[i][lev][r].LookupParameter("ОТД_Пол").AsElementId()).LookupParameter("АР_Состав отделки").AsString());

                //	}
                //                      catch (Exception)
                //                      {
                //		floorTable[i][lev][r].LookupParameter("ОТД_Состав.Пол").Set("НЕТ ОТДЕЛКИ");

                //	}
                //                      floorTable[i][lev][r].LookupParameter("testF").Set(fillText);
                //                      floorTable[i][lev][r].LookupParameter("PlintusTotal").Set(sumPlint);
                //                      if (floorTable[i][lev][r].LookupParameter("плинтус").AsInteger() == 1)
                //                      {
                //                          floorTable[i][lev][r].setP("PlintusTotalT", (sumPlint * FT).ToString("F1"));
                //                      }


                //                  }
                //              }
                //          }
                tr.Commit();
            }
            //String output = String.Join(", ", roomNumByLevel[0]);
            TaskDialog msg = new TaskDialog("Info");

            msg.MainInstruction = "Ok";             //output;// FinishTable.Count().ToString();
            msg.Show();

            return(Result.Succeeded);
        }
Example #45
0
        Result IExternalCommand.Execute(ExternalCommandData commandData, ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            UIApplication uiapp   = commandData.Application;
            UIDocument    uidoc   = uiapp.ActiveUIDocument;
            Application   app     = uiapp.Application;
            Document      doc     = uidoc.Document;
            ElementId     idPhase = doc.Phases.get_Item(doc.Phases.Size - 1).Id;

            //Фильтр  по общему параметру "ADSK_Номер здания"
            List <SharedParameterElement> shParamElements = new FilteredElementCollector(doc)
                                                            .OfClass(typeof(SharedParameterElement))
                                                            .Cast <SharedParameterElement>()
                                                            .ToList();
            SharedParameterElement shParam = shParamElements.Where(x => x.Name == "ADSK_Номер здания").First();

            //Фильтр помещений
            FilterableValueProvider    providerRoom   = new ParameterValueProvider(new ElementId((int)BuiltInParameter.ROOM_PHASE_ID));
            FilterNumericRuleEvaluator evaluator      = new FilterNumericEquals();
            FilterElementIdRule        rRule          = new FilterElementIdRule(providerRoom, evaluator, idPhase);
            ElementParameterFilter     room_filter    = new ElementParameterFilter(rRule);
            FilterableValueProvider    provRoomSchool = new ParameterValueProvider(shParam.Id);
            FilterStringRuleEvaluator  StrEvaluator   = new FilterStringEquals();
            FilterRule             rScRule            = new FilterStringRule(provRoomSchool, StrEvaluator, "", false);
            ElementParameterFilter roomSc_filter      = new ElementParameterFilter(rScRule);

            IList <Element> revit_rooms = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Rooms)
                                          .WhereElementIsNotElementType()
                                          .WherePasses(room_filter)
                                          .WherePasses(roomSc_filter)
                                          .ToElements();

            //Фильтр стен
            FilterableValueProvider provider    = new ParameterValueProvider(new ElementId((int)BuiltInParameter.PHASE_CREATED));
            FilterElementIdRule     fRule       = new FilterElementIdRule(provider, evaluator, idPhase);
            ElementParameterFilter  wall_filter = new ElementParameterFilter(fRule);

            IList <Element> revit_walls = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Walls)
                                          .WhereElementIsNotElementType()
                                          .WherePasses(wall_filter)
                                          .ToElements();

            //Перенос помещений и стен в объекты наших классов
            List <GhostRoom> rooms = revit_rooms.Select(x => new GhostRoom(x)).ToList();
            List <GhostWall> walls = new List <GhostWall>();

            foreach (Element w in revit_walls)
            {
                if (w.getP("Помещение") != null & w.getP("Помещение") != "")
                {
                    walls.Add(new GhostWall(w, null));
                }
            }


            foreach (string i in rooms.Select(x => x.Floor).Distinct())
            {
            }



            using (Transaction tr = new Transaction(doc, "Otdelka"))
            {
                tr.Start();
                foreach (GhostRoom r in rooms)
                {
                    r.Commit();
                }
                tr.Commit();
            }
            return(Result.Succeeded);
        }