Exemple #1
0
        public void Execute(UIApplication uiapp)
        {
            Application app = uiapp.Application;

            Document doc = uiapp.ActiveUIDocument.Document;

            try
            {
                // Get all the wall types in the current project and convert them in a Dictionary.
                FilteredElementCollector felc      = new FilteredElementCollector(doc).OfClass(typeof(WallType));
                Dictionary <string, int> dicwtypes = felc.ToDictionary(x => x.Name, y => y.Id.IntegerValue);
                felc.Dispose();

                // Create a view model that will be associated to the DataContext of the view.

                //ViewModels.viewmodelRevitBridge
                vmod                  = new ViewModels.viewmodelRevitBridge();
                vmod.DicWallType      = dicwtypes;
                vmod.SelectedWallType = dicwtypes.First().Value;

                // Create a new Revit model and assign it to the Revit model variable in the view model.
                vmod.RevitModel = new Models.modelRevitBridge(uiapp);

                System.Diagnostics.Process proc = System.Diagnostics.Process.GetCurrentProcess();


                /*
                 *
                 * // Load the WPF window viewRevitbridge.
                 * using (Views.viewRevitBridge view = new Views.viewRevitBridge())
                 * {
                 *  System.Windows.Interop.WindowInteropHelper helper = new System.Windows.Interop.WindowInteropHelper(view);
                 *  helper.Owner = proc.MainWindowHandle;
                 *
                 *  // Assign the view model to the DataContext of the view.
                 *  view.DataContext = vmod;
                 *
                 *
                 *
                 *
                 *  if (view.ShowDialog() != true)
                 *  {
                 *      return;
                 *  }
                 * }
                 */
            }
            catch
            {
                return;
            }
        }
Exemple #2
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            try
            {
                // Get all the wall types in the current project and convert them in a Dictionary.
                FilteredElementCollector felc      = new FilteredElementCollector(doc).OfClass(typeof(WallType));
                Dictionary <string, int> dicwtypes = felc.ToDictionary(x => x.Name, y => y.Id.IntegerValue);
                felc.Dispose();

                // Create a view model that will be associated to the DataContext of the view.
                ViewModels.ViewModelRevitBridge vmod = new ViewModels.ViewModelRevitBridge();
                vmod.DicWallType      = dicwtypes;
                vmod.SelectedWallType = dicwtypes.First().Value;

                // Create a new Revit model and assign it to the Revit model variable in the view model.
                vmod.RevitModel = new Models.ModelRevitBridge(uiapp);

                System.Diagnostics.Process proc = System.Diagnostics.Process.GetCurrentProcess();

                // Load the WPF window viewRevitbridge.
                using (Views.RevitBridge view = new Views.RevitBridge())
                {
                    System.Windows.Interop.WindowInteropHelper helper = new System.Windows.Interop.WindowInteropHelper(view);
                    helper.Owner = proc.MainWindowHandle;

                    // Assign the view model to the DataContext of the view.
                    view.DataContext = vmod;

                    if (view.ShowDialog() != true)
                    {
                        return(Result.Cancelled);
                    }
                }

                return(Result.Succeeded);
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return(Result.Failed);
            }
        }
Exemple #3
0
        internal Result ExecuteMyCommand(UIApplication uiApp)
        {
            Document doc = uiApp.ActiveUIDocument.Document;

            FilteredElementCollector collector = new FilteredElementCollector(doc);

            #region Pipeline schedule export

            //Collect piping systems
            collector.OfClass(typeof(PipingSystem));

            //Group all elements by their Family and Type
            IOrderedEnumerable <Element> orderedCollector            = collector.OrderBy(e => e.get_Parameter(BuiltInParameter.ELEM_FAMILY_AND_TYPE_PARAM).AsValueString());
            IEnumerable <IGrouping <string, Element> > elementGroups = from e in orderedCollector group e by e.get_Parameter(BuiltInParameter.ELEM_FAMILY_AND_TYPE_PARAM).AsValueString();

            xel.Application excel = new xel.Application();
            if (null == excel)
            {
                BuildingCoderUtilities.ErrorMsg("Failed to get or start Excel.");
                return(Result.Failed);
            }
            excel.Visible = true;

            xel.Workbook  workbook = excel.Workbooks.Add(Missing.Value);
            xel.Worksheet worksheet;
            worksheet      = excel.ActiveSheet as xel.Worksheet;
            worksheet.Name = "PCF Export - pipelines";

            worksheet.Columns.ColumnWidth = 20;

            worksheet.Cells[1, 1] = "Family and Type";

            //Change domain for query
            string curDomain = "PIPL", curUsage = "U";

            var query = from p in new plst().LPAll
                        where p.Domain == curDomain && p.Usage == curUsage
                        select p;

            worksheet.Range["A1", BuildingCoderUtilities.GetColumnName(query.Count()) + "1"].Font.Bold = true;

            //Export family and type names to first column and parameter values
            int row = 2, col = 2;
            foreach (IGrouping <string, Element> gp in elementGroups)
            {
                worksheet.Cells[row, 1] = gp.Key;
                foreach (var p in query.ToList())
                {
                    if (row == 2)
                    {
                        worksheet.Cells[1, col] = p.Name;           //Fill out top row only in the first iteration
                    }
                    ElementId        id = gp.First().GetTypeId();
                    PipingSystemType ps = (PipingSystemType)doc.GetElement(id); //SystemType parameters can only be read from type elements
                    worksheet.Cells[row, col] = ps.get_Parameter(p.Guid).AsString();
                    col++;                                                      //Increment column
                }
                row++; col = 2;                                                 //Increment row and reset column
            }

            #endregion

            #region Element schedule export

            //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 = Shared.Filter.GetElementsWithConnectors(doc);

            //Group all elements by their Family and Type
            orderedCollector =
                collector.OrderBy(e => e.get_Parameter(BuiltInParameter.ELEM_FAMILY_AND_TYPE_PARAM).AsValueString());
            elementGroups = from e in orderedCollector
                            group e by e.get_Parameter(BuiltInParameter.ELEM_FAMILY_AND_TYPE_PARAM).AsValueString();


            excel.Sheets.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value);
            worksheet      = excel.ActiveSheet as xel.Worksheet;
            worksheet.Name = "PCF Export - elements";

            worksheet.Columns.ColumnWidth = 20;

            worksheet.Cells[1, 1] = "Family and Type";

            //Query parameters
            curDomain = "ELEM";

            //Formatting must occur here, because it depends on query
            worksheet.Range["A1", BuildingCoderUtilities.GetColumnName(query.Count()) + "1"].Font.Bold = true;

            //Export family and type names to first column and parameter values
            row = 2; col = 2;
            foreach (IGrouping <string, Element> gp in elementGroups)
            {
                worksheet.Cells[row, 1] = gp.Key;
                foreach (var p in query)
                {
                    if (row == 2)
                    {
                        worksheet.Cells[1, col] = p.Name;           //Fill out top row only in the first iteration
                    }
                    worksheet.Cells[row, col] = gp.First().get_Parameter(p.Guid).AsString();
                    col++;      //Increment column
                }
                row++; col = 2; //Increment row and reset column
            }

            #endregion

            collector.Dispose();
            return(Result.Succeeded);
        }
        //private UIDocument _uiDoc;
        public Result CreateAllItemsSchedule(UIDocument uiDoc)
        {
            try
            {
                Document doc = uiDoc.Document;
                FilteredElementCollector sharedParameters = new FilteredElementCollector(doc);
                sharedParameters.OfClass(typeof(SharedParameterElement));

                #region Debug

                ////Debug
                //StringBuilder sbDev = new StringBuilder();
                //var list = new ParameterDefinition().ElementParametersAll;
                //int i = 0;

                //foreach (SharedParameterElement sp in sharedParameters)
                //{
                //    sbDev.Append(sp.GuidValue + "\n");
                //    sbDev.Append(list[i].Guid.ToString() + "\n");
                //    i++;
                //    if (i == list.Count) break;
                //}
                ////sbDev.Append( + "\n");
                //// Clear the output file
                //File.WriteAllBytes(InputVars.OutputDirectoryFilePath + "\\Dev.pcf", new byte[0]);

                //// Write to output file
                //using (StreamWriter w = File.AppendText(InputVars.OutputDirectoryFilePath + "\\Dev.pcf"))
                //{
                //    w.Write(sbDev);
                //    w.Close();
                //}

                #endregion

                Transaction t = new Transaction(doc, "Create items schedules");
                t.Start();

                #region Schedule ALL elements
                ViewSchedule schedAll = ViewSchedule.CreateSchedule(doc, ElementId.InvalidElementId,
                                                                    ElementId.InvalidElementId);
                schedAll.Name = "PCF - ALL Elements";
                schedAll.Definition.IsItemized = false;

                IList <SchedulableField> schFields = schedAll.Definition.GetSchedulableFields();

                foreach (SchedulableField schField in schFields)
                {
                    if (schField.GetName(doc) != "Family and Type")
                    {
                        continue;
                    }
                    ScheduleField          field          = schedAll.Definition.AddField(schField);
                    ScheduleSortGroupField sortGroupField = new ScheduleSortGroupField(field.FieldId);
                    schedAll.Definition.AddSortGroupField(sortGroupField);
                }

                string curUsage  = "U";
                string curDomain = "ELEM";
                var    query     = from p in new plst().LPAll where p.Usage == curUsage && p.Domain == curDomain select p;

                foreach (pdef pDef in query.ToList())
                {
                    SharedParameterElement parameter = (from SharedParameterElement param in sharedParameters
                                                        where param.GuidValue.CompareTo(pDef.Guid) == 0
                                                        select param).First();
                    SchedulableField queryField = (from fld in schFields where fld.ParameterId.IntegerValue == parameter.Id.IntegerValue select fld).First();

                    ScheduleField field = schedAll.Definition.AddField(queryField);
                    if (pDef.Name != "PCF_ELEM_TYPE")
                    {
                        continue;
                    }
                    ScheduleFilter filter = new ScheduleFilter(field.FieldId, ScheduleFilterType.HasParameter);
                    schedAll.Definition.AddFilter(filter);
                }
                #endregion

                #region Schedule FILTERED elements
                ViewSchedule schedFilter = ViewSchedule.CreateSchedule(doc, ElementId.InvalidElementId,
                                                                       ElementId.InvalidElementId);
                schedFilter.Name = "PCF - Filtered Elements";
                schedFilter.Definition.IsItemized = false;

                schFields = schedFilter.Definition.GetSchedulableFields();

                foreach (SchedulableField schField in schFields)
                {
                    if (schField.GetName(doc) != "Family and Type")
                    {
                        continue;
                    }
                    ScheduleField          field          = schedFilter.Definition.AddField(schField);
                    ScheduleSortGroupField sortGroupField = new ScheduleSortGroupField(field.FieldId);
                    schedFilter.Definition.AddSortGroupField(sortGroupField);
                }

                foreach (pdef pDef in query.ToList())
                {
                    SharedParameterElement parameter = (from SharedParameterElement param in sharedParameters
                                                        where param.GuidValue.CompareTo(pDef.Guid) == 0
                                                        select param).First();
                    SchedulableField queryField = (from fld in schFields where fld.ParameterId.IntegerValue == parameter.Id.IntegerValue select fld).First();

                    ScheduleField field = schedFilter.Definition.AddField(queryField);
                    if (pDef.Name != "PCF_ELEM_TYPE")
                    {
                        continue;
                    }
                    ScheduleFilter filter = new ScheduleFilter(field.FieldId, ScheduleFilterType.HasParameter);
                    schedFilter.Definition.AddFilter(filter);
                    filter = new ScheduleFilter(field.FieldId, ScheduleFilterType.NotEqual, "");
                    schedFilter.Definition.AddFilter(filter);
                }
                #endregion

                #region Schedule Pipelines
                ViewSchedule schedPipeline = ViewSchedule.CreateSchedule(doc, new ElementId(BuiltInCategory.OST_PipingSystem), ElementId.InvalidElementId);
                schedPipeline.Name = "PCF - Pipelines";
                schedPipeline.Definition.IsItemized = false;

                schFields = schedPipeline.Definition.GetSchedulableFields();

                foreach (SchedulableField schField in schFields)
                {
                    if (schField.GetName(doc) != "Family and Type")
                    {
                        continue;
                    }
                    ScheduleField          field          = schedPipeline.Definition.AddField(schField);
                    ScheduleSortGroupField sortGroupField = new ScheduleSortGroupField(field.FieldId);
                    schedPipeline.Definition.AddSortGroupField(sortGroupField);
                }

                curDomain = "PIPL";
                foreach (pdef pDef in query.ToList())
                {
                    SharedParameterElement parameter = (from SharedParameterElement param in sharedParameters
                                                        where param.GuidValue.CompareTo(pDef.Guid) == 0
                                                        select param).First();
                    SchedulableField queryField = (from fld in schFields where fld.ParameterId.IntegerValue == parameter.Id.IntegerValue select fld).First();
                    schedPipeline.Definition.AddField(queryField);
                }
                #endregion

                t.Commit();

                sharedParameters.Dispose();

                return(Result.Succeeded);
            }
            catch (Exception e)
            {
                BuildingCoderUtilities.InfoMsg(e.Message);
                return(Result.Failed);
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="OSM_ENV_Setting"/> class.
        /// </summary>
        /// <param name="document">The Revit document.</param>
        /// <exception cref="ArgumentException">There are no 'Floor Plans' in this document!</exception>
        public OSM_ENV_Setting(Document document)
        {
            InitializeComponent();

            this.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
            #region Getting the names of the levels that have floors assosiated to them
            FilteredElementCollector floorViewCollector = new FilteredElementCollector(document).OfClass(typeof(ViewPlan));
            floorPlanNames = new List <ViewPlan>();
            foreach (ViewPlan item in floorViewCollector)
            {
                if (item.ViewType == ViewType.FloorPlan && item.IsTemplate == false && item.Name != "Site")
                {
                    FilteredElementCollector floorCollector = new FilteredElementCollector(document, item.Id).OfClass(typeof(Floor));
                    bool hasFloor = false;
                    foreach (Floor floor in floorCollector)
                    {
                        hasFloor = true;
                        break;
                    }
                    floorCollector.Dispose();//releasing memory
                    if (hasFloor)
                    {
                        floorPlanNames.Add(item);
                        this.LevelMenu.Items.Add(item.Name);
                    }
                }
            }

            floorViewCollector.Dispose();//releasing memory
            if (this.floorPlanNames.Count == 0)
            {
                throw new ArgumentException("There are no 'Floor Plans' in this document!");
            }
            #endregion
            this.DoorIds  = new HashSet <ElementId>();
            this.uidoc    = new UIDocument(document);
            this.KeyDown += new System.Windows.Input.KeyEventHandler(FloorSetting_KeyDown);

            //set units
            UnitOfLength.Items.Add(Length_Unit_Types.FEET);
            UnitOfLength.Items.Add(Length_Unit_Types.INCHES);
            UnitOfLength.Items.Add(Length_Unit_Types.METERS);
            UnitOfLength.Items.Add(Length_Unit_Types.DECIMETERS);
            UnitOfLength.Items.Add(Length_Unit_Types.CENTIMETERS);
            UnitOfLength.Items.Add(Length_Unit_Types.MILLIMETERS);
            //get unit from Revit document
            FormatOptions   format         = document.GetUnits().GetFormatOptions(UnitType.UT_Length);
            DisplayUnitType lengthUnitType = format.DisplayUnits;
            bool            formatParsed   = false;
            switch (lengthUnitType)
            {
            case DisplayUnitType.DUT_METERS:
                unitType     = Length_Unit_Types.METERS;
                formatParsed = true;
                break;

            case DisplayUnitType.DUT_CENTIMETERS:
                unitType     = Length_Unit_Types.CENTIMETERS;
                formatParsed = true;
                break;

            case DisplayUnitType.DUT_DECIMETERS:
                unitType     = Length_Unit_Types.DECIMETERS;
                formatParsed = true;
                break;

            case DisplayUnitType.DUT_MILLIMETERS:
                unitType     = Length_Unit_Types.MILLIMETERS;
                formatParsed = true;
                break;

            case DisplayUnitType.DUT_DECIMAL_FEET:
                unitType     = Length_Unit_Types.FEET;
                formatParsed = true;
                break;

            case DisplayUnitType.DUT_FEET_FRACTIONAL_INCHES:
                unitType     = Length_Unit_Types.FEET;
                formatParsed = true;
                break;

            case DisplayUnitType.DUT_FRACTIONAL_INCHES:
                unitType     = Length_Unit_Types.INCHES;
                formatParsed = true;
                break;

            case DisplayUnitType.DUT_DECIMAL_INCHES:
                unitType     = Length_Unit_Types.INCHES;
                formatParsed = true;
                break;

            case DisplayUnitType.DUT_METERS_CENTIMETERS:
                unitType     = Length_Unit_Types.METERS;
                formatParsed = true;
                break;

            default:
                break;
            }
            if (!formatParsed)
            {
                MessageBox.Show("Failed to parse length unit system: " + lengthUnitType.ToString() + "\n" +
                                "The default choice is 'Feet'.\n" +
                                "Select a unit type from the available options."
                                , "Length Unit", MessageBoxButton.OK, MessageBoxImage.Warning);
                unitType = Length_Unit_Types.FEET;
                UnitOfLength.SelectedItem = unitType;
            }
            else
            {
                UnitOfLength.IsEditable       = false;
                UnitOfLength.IsHitTestVisible = false;
                UnitOfLength.Focusable        = false;
                UnitOfLength.SelectedItem     = unitType;
                updateTextBoxUnits(Length_Unit_Types.FEET, unitType);
            }
            UnitOfLength.SelectionChanged += UnitOfLength_SelectionChanged;
        }
Exemple #6
0
        public static List <List <DynamoRevitElements.Floor> > CreateRevitFloors(
            DynamoElements.Surface[][] srfList,
            DynamoRevitElements.FloorType floorType,
            string levelPrefixStr = "Dynamo Level")
        {
            if (srfList == null)
            {
                throw new ArgumentNullException(nameof(srfList));
            }

            if (!(floorType.InternalElement is RevitElements.FloorType revitFloorType))
            {
                throw new ArgumentOutOfRangeException(nameof(floorType));
            }

            DisplayUnitType unitType = Document.GetUnits().GetFormatOptions(UnitType.UT_Length).DisplayUnits;

            var FloorElements = new List <List <DynamoRevitElements.Floor> >();
            var collector     = new FilteredElementCollector(Document);

            var levels = collector.OfClass(typeof(RevitElements.Level)).ToElements()
                         .Where(e => e is RevitElements.Level)
                         .Cast <RevitElements.Level>();

            TransactionManager.Instance.EnsureInTransaction(Document);

            for (var i = 0; i < srfList.Length; i++)
            {
                if (srfList[i] == null)
                {
                    throw new ArgumentNullException(nameof(srfList));
                }

                FloorElements.Add(new List <DynamoRevitElements.Floor>());

                string levelName  = $"{levelPrefixStr} {i + 1}";
                var    revitLevel = levels.FirstOrDefault(level => level.Name == levelName);

                double elevation;

                using (var floorBounds = BoundingBox.ByGeometry(srfList[i]))
                {
                    elevation = UnitUtils.ConvertToInternalUnits(floorBounds.MaxPoint.Z, unitType);
                }

                if (revitLevel != null)
                {
                    // Adjust existing level to correct height.
                    revitLevel.Elevation = elevation;
                }
                else
                {
                    // Create new level.
                    revitLevel      = RevitElements.Level.Create(Document, elevation);
                    revitLevel.Name = levelName;
                }

                var revitCurves = new CurveArray();

                foreach (var surface in srfList[i])
                {
                    var loops = Building.GetSurfaceLoops(surface);

                    revitCurves.Clear();

                    loops[0].Curves().ForEach(curve => revitCurves.Append(curve.ToRevitType()));

                    var revitFloor = Document.Create.NewFloor(revitCurves, revitFloorType, revitLevel, true);

                    FloorElements.Last().Add(revitFloor.ToDSType(false) as DynamoRevitElements.Floor);

                    // Need to finish creating the floor before we add openings in it.
                    TransactionManager.Instance.ForceCloseTransaction();
                    TransactionManager.Instance.EnsureInTransaction(Document);

                    loops.Skip(1).ToArray().ForEach(loop =>
                    {
                        revitCurves.Clear();

                        loop.Curves().ForEach(curve => revitCurves.Append(curve.ToRevitType()));

                        Document.Create.NewOpening(revitFloor, revitCurves, true);
                    });

                    loops.ForEach(x => x.Dispose());
                    revitFloor.Dispose();
                }

                revitCurves.Dispose();
            }

            TransactionManager.Instance.TransactionTaskDone();

            collector.Dispose();

            return(FloorElements);
        }