Ejemplo n.º 1
0
        public static ViewSchedule Create(Document doc, BuiltInCategory elementType, string schName)
        {
            ViewSchedule schedule      = null;
            var          canBeModified = doc.IsModifiable;
            var          isReadonly    = doc.IsReadOnly;

            if (!canBeModified && isReadonly)
            {
                throw new CancellableException("The document has an open transaction somewhere");
            }

            using (var trans = new Transaction(doc, $"Creating new {elementType.GetType().Name} schedule"))
            {
                var opts = trans.GetFailureHandlingOptions();
                opts.SetDelayedMiniWarnings(true);

                if (!trans.HasStarted())
                {
                    trans.Start();
                }

                schedule      = ViewSchedule.CreateSchedule(doc, new ElementId(elementType), ElementId.InvalidElementId);
                schedule.Name = schName;

                trans.Commit(opts);
            }

            return(schedule);
        }
        public List <string> categoryparameters(Document doc, BuiltInCategory cat)
        {
            if (cat == null)
            {
                return(null);
            }
            List <string> parameters = new List <string>();

            using (Transaction tr = new Transaction(doc, "make_schedule"))
            {
                tr.Start();
                // Create schedule
                ViewSchedule vs = ViewSchedule.CreateSchedule(doc, Category.GetCategory(doc, cat).Id);
                doc.Regenerate();

                // Find schedulable fields
                foreach (SchedulableField sField in vs.Definition.GetSchedulableFields())
                {
                    if (sField.FieldType != ScheduleFieldType.ElementType)
                    {
                        continue;
                    }
                    parameters.Add(sField.GetName(doc));
                }
                tr.RollBack();
            }
            return(parameters);
        }
        public static void CreateWallsSchedule(UIDocument uidoc)
        {
            Document doc = uidoc.Document;

            using (Transaction t = new Transaction(doc, "Create Schedule"))
            {
                t.Start();

                // Создание спецификации для стен
                ViewSchedule wallsSchedule =
                    ViewSchedule.CreateSchedule(doc,
                                                new ElementId(BuiltInCategory.OST_Walls));

                // Добавление полей в спецификацию
                foreach (SchedulableField schedulableFields
                         in GetSchedulableFields(doc))
                {
                    wallsSchedule.Definition.AddField(schedulableFields);
                }

                // Назначение стадии
                SetPhaseByName(wallsSchedule, "KR-3");

                // Для каждого экземпляра = false
                wallsSchedule.Definition.IsItemized = false;

                // Вычесление итогов
                wallsSchedule.Definition.GetField(0).DisplayType =
                    ScheduleFieldDisplayType.Totals;
                wallsSchedule.Definition.GetField(1).DisplayType =
                    ScheduleFieldDisplayType.Totals;

                // Назначение ширины столбцам
                wallsSchedule.Definition.GetField(0).GridColumnWidth = 30 * mmToft;
                wallsSchedule.Definition.GetField(1).GridColumnWidth = 30 * mmToft;
                wallsSchedule.Definition.GetField(2).GridColumnWidth = 55 * mmToft;

                // Назначение выравнивания
                wallsSchedule.Definition.GetField(1).HorizontalAlignment =
                    ScheduleHorizontalAlignment.Right;
                wallsSchedule.Definition.GetField(2).HorizontalAlignment =
                    ScheduleHorizontalAlignment.Center;

                // Установка сортировки/групировки
                ScheduleSortGroupField sortGroupField =
                    new ScheduleSortGroupField(
                        wallsSchedule.Definition.GetField(2).FieldId,
                        ScheduleSortOrder.Ascending);
                wallsSchedule.Definition.AddSortGroupField(sortGroupField);

                t.Commit();
                uidoc.ActiveView = wallsSchedule;
            }
        }
        public ViewSchedule CreateSchedule(bool isItemized, string scheduleName, BuiltInCategory category)
        {
            ViewSchedule _viewSchedule = ViewSchedule.CreateSchedule(_doc, new ElementId(category));

            if (string.IsNullOrWhiteSpace(scheduleName) == false)
            {
                _viewSchedule.Name = scheduleName;
            }

            _viewSchedule.Definition.IsItemized = isItemized;

            return(_viewSchedule);
        }
Ejemplo n.º 5
0
        public static void CreateSched(Document doc)
        {
            var schedCollector = new FilteredElementCollector(doc).OfClass(typeof(ViewSchedule)).ToList();

            if (!schedCollector.Any(x => x.Name == "DOOR SCHEDULE"))
            {
                using (Transaction t = new Transaction(doc, "Add Door Schedule"))
                {
                    t.Start();
                    var sched = ViewSchedule.CreateSchedule(doc, Category.GetCategory(doc, BuiltInCategory.OST_Doors).Id);
                    sched.Name = "DOOR SCHEDULE";

                    var Number = sched.Definition.GetSchedulableFields().FirstOrDefault(x => (BuiltInParameter)x.ParameterId.IntegerValue == BuiltInParameter.ALL_MODEL_MARK);
                    if (Number != null)
                    {
                        sched.Definition.AddField(Number);
                    }

                    var Level = sched.Definition.GetSchedulableFields().FirstOrDefault(x => (BuiltInParameter)x.ParameterId.IntegerValue == BuiltInParameter.SCHEDULE_LEVEL_PARAM);
                    if (Level != null)
                    {
                        sched.Definition.AddField(Level);
                    }

                    foreach (var sd in DoorParameters)
                    {
                        var Field = sched.Definition.GetSchedulableFields().
                                    FirstOrDefault(x => IsSharedParameterSchedulableField(doc, x.ParameterId, sd));

                        if (Field != null)
                        {
                            sched.Definition.AddField(Field);
                        }
                    }

                    var Comments = sched.Definition.GetSchedulableFields().FirstOrDefault(x => (BuiltInParameter)x.ParameterId.IntegerValue == BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS);
                    if (Comments != null)
                    {
                        sched.Definition.AddField(Comments);
                    }

                    t.Commit();
                }
            }
            else
            {
                TaskDialog.Show("Error", "The Schedule Already Exists");
            }
        }
Ejemplo n.º 6
0
        private void CreateSchedule()
        {
            DirectoryInfo d = new DirectoryInfo(@"C:\Programming\Test");

            FileInfo[] files = d.GetFiles("*.txt");
            int        cnt   = 1;

            foreach (FileInfo file in files)
            {
                Transaction t = new Transaction(myRevitDoc, "Create Schedule");
                t.Start();

                string          scheduleName = "Equipment Schedule " + cnt;
                BuiltInCategory category     = BuiltInCategory.OST_MechanicalEquipment;

                List <ViewSchedule> schedules = new List <ViewSchedule>();
                List <string>       guids     = new List <string>();

                ViewSchedule schedule = ViewSchedule.CreateSchedule(myRevitDoc, new ElementId(category), ElementId.InvalidElementId);
                schedule.Name = scheduleName;
                schedules.Add(schedule);

                string   filePath = file.FullName;
                string[] readText = File.ReadAllLines(filePath);

                foreach (string s in readText)
                {
                    guids.Add(s);
                }

                foreach (string guid in guids)
                {
                    SchedulableField schedulableField = schedule.Definition.GetSchedulableFields().FirstOrDefault(x => IsSharedParameterSchedulableField(schedule.Document, x.ParameterId, new Guid(guid)));
                    if (schedulableField != null)
                    {
                        schedule.Definition.AddField(schedulableField);
                    }
                }

                t.Commit();
                cnt++;
            }
        }
Ejemplo n.º 7
0
        public static ViewSchedule Create(Document doc, BuiltInCategory elementType, string schName)
        {
            ViewSchedule schedule = null;

            using (var trans = new Transaction(doc, $"Creating new {elementType.GetType().Name} schedule"))
            {
                var opts = trans.GetFailureHandlingOptions();
                opts.SetDelayedMiniWarnings(true);

                if (!trans.HasStarted())
                {
                    trans.Start();
                }

                schedule      = ViewSchedule.CreateSchedule(doc, new ElementId(elementType), ElementId.InvalidElementId);
                schedule.Name = schName;

                trans.Commit(opts);
            }

            return(schedule);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Create a schedule for a given property set.
        /// </summary>
        /// <param name="doc">The document.</param>
        /// <param name="element">The element being created.</param>
        /// <param name="parameterGroupMap">The parameters of the element.  Cached for performance.</param>
        /// <param name="parametersCreated">The created parameters.</param>
        protected void CreateScheduleForPropertySet(Document doc, Element element, IFCParameterSetByGroup parameterGroupMap, ISet <string> parametersCreated)
        {
            // Don't bother creating schedules if we are maximizing performance.
            if (IFCImportFile.TheFile.Options.UseStreamlinedOptions)
            {
                return;
            }

            if (parametersCreated.Count == 0)
            {
                return;
            }

            Category category = element.Category;

            if (category == null)
            {
                return;
            }

            ElementId categoryId    = category.Id;
            bool      elementIsType = (element is ElementType);

            Tuple <ElementId, bool, string> scheduleKey = new Tuple <ElementId, bool, string>(categoryId, elementIsType, Name);

            ISet <string> viewScheduleNames = Importer.TheCache.ViewScheduleNames;
            IDictionary <Tuple <ElementId, bool, string>, ElementId> viewSchedules = Importer.TheCache.ViewSchedules;

            ElementId viewScheduleId;

            if (!viewSchedules.TryGetValue(scheduleKey, out viewScheduleId))
            {
                string scheduleName     = scheduleKey.Item3;
                string scheduleTypeName = elementIsType ? " " + Resources.IFCTypeSchedule : string.Empty;

                int index = 1;
                while (viewScheduleNames.Contains(scheduleName))
                {
                    string indexString = (index > 1) ? " " + index.ToString() : string.Empty;
                    scheduleName += " (" + category.Name + scheduleTypeName + indexString + ")";
                    index++;
                    if (index > 1000)
                    {
                        Importer.TheLog.LogWarning(Id, "Too many property sets with the name " + scheduleKey.Item3 +
                                                   ", no longer creating schedules with that name.", true);
                        return;
                    }
                }

                // Not all categories allow creating schedules.  Skip these.
                ViewSchedule viewSchedule = null;
                try
                {
                    viewSchedule = ViewSchedule.CreateSchedule(doc, scheduleKey.Item1);
                }
                catch
                {
                    // Only try to create the schedule once per key.
                    viewSchedules[scheduleKey] = ElementId.InvalidElementId;
                    return;
                }

                if (viewSchedule != null)
                {
                    viewSchedule.Name          = scheduleName;
                    viewSchedules[scheduleKey] = viewSchedule.Id;
                    viewScheduleNames.Add(scheduleName);

                    ElementId ifcGUIDId           = new ElementId(elementIsType ? BuiltInParameter.IFC_TYPE_GUID : BuiltInParameter.IFC_GUID);
                    string    propertySetListName = elementIsType ? Resources.IFCTypeSchedule + " IfcPropertySetList" : "IfcPropertySetList";

                    IList <SchedulableField> schedulableFields = viewSchedule.Definition.GetSchedulableFields();

                    bool filtered = false;
                    foreach (SchedulableField sf in schedulableFields)
                    {
                        string fieldName = sf.GetName(doc);
                        if (parametersCreated.Contains(fieldName) || sf.ParameterId == ifcGUIDId)
                        {
                            viewSchedule.Definition.AddField(sf);
                        }
                        else if (!filtered && fieldName == propertySetListName)
                        {
                            // We want to filter the schedule for specifically those elements that have this property set assigned.
                            ScheduleField scheduleField = viewSchedule.Definition.AddField(sf);
                            scheduleField.IsHidden = true;
                            ScheduleFilter filter = new ScheduleFilter(scheduleField.FieldId, ScheduleFilterType.Contains, "\"" + Name + "\"");
                            viewSchedule.Definition.AddFilter(filter);
                            filtered = true;
                        }
                    }
                }
            }

            return;
        }
Ejemplo n.º 9
0
        public void createCountSchedule(String name, ElementId elementId)
        {
            ViewSchedule schedule = new FilteredElementCollector(CachedDoc).OfClass(typeof(ViewSchedule)).Where(x => x.Name == name + " Schedule").FirstOrDefault() as ViewSchedule;

            if (schedule == null)
            {
                Transaction tSchedule = new Transaction(CachedDoc, "Create Schedule");
                tSchedule.Start();

                //Create an empty view schedule for doors.
                //schedule = ViewSchedule.CreateSchedule(CachedDoc, new ElementId(BuiltInCategory.INVALID), ElementId.InvalidElementId);
                schedule      = ViewSchedule.CreateSchedule(CachedDoc, elementId, ElementId.InvalidElementId);
                schedule.Name = name + " Schedule";

                ElementId keynoteId = new ElementId(BuiltInParameter.KEYNOTE_PARAM);
                //Iterate all the schedulable fields gotten from the doors view schedule.
                foreach (SchedulableField schedulableField in schedule.Definition.GetSchedulableFields())
                {
                    //See if the FieldType is ScheduleFieldType.Instance.
                    if (schedulableField.FieldType == ScheduleFieldType.Count || schedulableField.ParameterId == keynoteId)
                    {
                        //Get ParameterId of SchedulableField.
                        ElementId parameterId = schedulableField.ParameterId;

                        //Add a new schedule field to the view schedule by using the SchedulableField as argument of AddField method of Autodesk.Revit.DB.ScheduleDefinition class.
                        ScheduleField field = schedule.Definition.AddField(schedulableField);

                        //See if the parameterId is a BuiltInParameter.
                        if (Enum.IsDefined(typeof(BuiltInParameter), parameterId.IntegerValue))
                        {
                            BuiltInParameter bip = (BuiltInParameter)parameterId.IntegerValue;
                            //Get the StorageType of BuiltInParameter.
                            Autodesk.Revit.DB.StorageType st = CachedDoc.get_TypeOfStorage(bip);
                            //if StorageType is String or ElementId, set GridColumnWidth of schedule field to three times of current GridColumnWidth.
                            //And set HorizontalAlignment property to left.
                            if (st == Autodesk.Revit.DB.StorageType.String || st == Autodesk.Revit.DB.StorageType.ElementId)
                            {
                                field.GridColumnWidth     = 3 * field.GridColumnWidth;
                                field.HorizontalAlignment = ScheduleHorizontalAlignment.Left;
                            }
                            //For other StorageTypes, set HorizontalAlignment property to center.
                            else
                            {
                                field.HorizontalAlignment = ScheduleHorizontalAlignment.Center;
                            }
                        }

                        if (field.ParameterId == keynoteId)
                        {
                            ScheduleSortGroupField sortGroupField = new ScheduleSortGroupField(field.FieldId);
                            schedule.Definition.AddSortGroupField(sortGroupField);
                            schedule.Definition.IsItemized = false;
                        }
                        if (schedulableField.FieldType == ScheduleFieldType.Count)
                        {
                        }
                    }
                }


                tSchedule.Commit();
                tSchedule.Dispose();
            }
            else
            {
                schedule.RefreshData();
            }

            ViewScheduleExportOptions opt = new ViewScheduleExportOptions();

            opt.FieldDelimiter = ",";
            opt.Title          = false;

            string path = _export_folder_name;


            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }


            string file = System.IO.Path.GetFileNameWithoutExtension(name) + ".csv";

            schedule.Export(path, file, opt);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Create a view schedule of wall category and add schedule field, filter and sorting/grouping field to it.
        /// </summary>
        /// <param name="uiDocument">UIdocument of revit file.</param>
        /// <returns>ICollection of created view schedule(s).</returns>
        private ICollection <ViewSchedule> CreateSchedules(UIDocument uiDocument)
        {
            Document document = uiDocument.Document;

            Transaction t = new Transaction(document, "Create Schedules");

            t.Start();

            List <ViewSchedule> schedules = new List <ViewSchedule>();

            //Create an empty view schedule of wall category.
            ViewSchedule schedule = ViewSchedule.CreateSchedule(document, new ElementId(BuiltInCategory.OST_Walls), ElementId.InvalidElementId);

            schedule.Name = "Wall Schedule 1";
            schedules.Add(schedule);

            //Iterate all the schedulable field gotten from the walls view schedule.
            foreach (SchedulableField schedulableField in schedule.Definition.GetSchedulableFields())
            {
                //Judge if the FieldType is ScheduleFieldType.Instance.
                if (schedulableField.FieldType == ScheduleFieldType.Instance)
                {
                    //Get ParameterId of SchedulableField.
                    ElementId parameterId = schedulableField.ParameterId;

                    //If the ParameterId is id of BuiltInParameter.ALL_MODEL_MARK then ignore next operation.
                    if (ShouldSkip(parameterId))
                    {
                        continue;
                    }

                    //Add a new schedule field to the view schedule by using the SchedulableField as argument of AddField method of Autodesk.Revit.DB.ScheduleDefinition class.
                    ScheduleField field = schedule.Definition.AddField(schedulableField);

                    //Judge if the parameterId is a BuiltInParameter.
                    if (Enum.IsDefined(typeof(BuiltInParameter), parameterId.IntegerValue))
                    {
                        BuiltInParameter bip = (BuiltInParameter)parameterId.IntegerValue;
                        //Get the StorageType of BuiltInParameter.
                        StorageType st = document.get_TypeOfStorage(bip);
                        //if StorageType is String or ElementId, set GridColumnWidth of schedule field to three times of current GridColumnWidth.
                        //And set HorizontalAlignment property to left.
                        if (st == StorageType.String || st == StorageType.ElementId)
                        {
                            field.GridColumnWidth     = 3 * field.GridColumnWidth;
                            field.HorizontalAlignment = ScheduleHorizontalAlignment.Left;
                        }
                        //For other StorageTypes, set HorizontalAlignment property to center.
                        else
                        {
                            field.HorizontalAlignment = ScheduleHorizontalAlignment.Center;
                        }
                    }


                    //Filter the view schedule by volume
                    if (field.ParameterId == new ElementId(BuiltInParameter.HOST_VOLUME_COMPUTED))
                    {
                        double         volumeFilterInCubicFt = 0.8 * Math.Pow(3.2808399, 3.0);
                        ScheduleFilter filter = new ScheduleFilter(field.FieldId, ScheduleFilterType.GreaterThan, volumeFilterInCubicFt);
                        schedule.Definition.AddFilter(filter);
                    }

                    //Group and sort the view schedule by type
                    if (field.ParameterId == new ElementId(BuiltInParameter.ELEM_TYPE_PARAM))
                    {
                        ScheduleSortGroupField sortGroupField = new ScheduleSortGroupField(field.FieldId);
                        sortGroupField.ShowHeader = true;
                        schedule.Definition.AddSortGroupField(sortGroupField);
                    }
                }
            }

            t.Commit();

            uiDocument.ActiveView = schedule;

            return(schedules);
        }
Ejemplo n.º 11
0
        //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);
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Create a schedule for a given property set.
        /// </summary>
        /// <param name="doc">The document.</param>
        /// <param name="element">The element being created.</param>
        /// <param name="parameterGroupMap">The parameters of the element.  Cached for performance.</param>
        /// <param name="parametersCreated">The created parameters.</param>
        protected void CreateScheduleForPropertySet(Document doc, Element element, IFCParameterSetByGroup parameterGroupMap, ISet <string> parametersCreated)
        {
            if (parametersCreated.Count == 0)
            {
                return;
            }

            Category category = element.Category;

            if (category == null)
            {
                return;
            }

            ElementId categoryId = category.Id;
            KeyValuePair <ElementId, string> scheduleKey = new KeyValuePair <ElementId, string>(categoryId, Name);

            ISet <string> viewScheduleNames = Importer.TheCache.ViewScheduleNames;
            IDictionary <KeyValuePair <ElementId, string>, ElementId> viewSchedules = Importer.TheCache.ViewSchedules;

            ElementId viewScheduleId;

            if (!viewSchedules.TryGetValue(scheduleKey, out viewScheduleId))
            {
                // Not all categories allow creating schedules.  Skip these.
                ViewSchedule viewSchedule = null;
                try
                {
                    viewSchedule = ViewSchedule.CreateSchedule(doc, scheduleKey.Key);
                }
                catch
                {
                }

                if (viewSchedule != null)
                {
                    string scheduleName = scheduleKey.Value;
                    if (viewScheduleNames.Contains(scheduleName))
                    {
                        scheduleName += " (" + category.Name + ")";
                    }
                    viewSchedule.Name          = scheduleName;
                    viewSchedules[scheduleKey] = viewSchedule.Id;
                    viewScheduleNames.Add(scheduleName);

                    bool      elementIsType       = (element is ElementType);
                    ElementId ifcGUIDId           = new ElementId(elementIsType ? BuiltInParameter.IFC_TYPE_GUID : BuiltInParameter.IFC_GUID);
                    string    propertySetListName = elementIsType ? "Type IfcPropertySetList" : "IfcPropertySetList";

                    IList <SchedulableField> schedulableFields = viewSchedule.Definition.GetSchedulableFields();

                    bool filtered = false;
                    foreach (SchedulableField sf in schedulableFields)
                    {
                        string fieldName = sf.GetName(doc);
                        if (parametersCreated.Contains(fieldName) || sf.ParameterId == ifcGUIDId)
                        {
                            viewSchedule.Definition.AddField(sf);
                        }
                        else if (!filtered && fieldName == propertySetListName)
                        {
                            // We want to filter the schedule for specifically those elements that have this property set assigned.
                            ScheduleField scheduleField = viewSchedule.Definition.AddField(sf);
                            scheduleField.IsHidden = true;
                            ScheduleFilter filter = new ScheduleFilter(scheduleField.FieldId, ScheduleFilterType.Contains, "\"" + Name + "\"");
                            viewSchedule.Definition.AddFilter(filter);
                            filtered = true;
                        }
                    }
                }
            }

            return;
        }
Ejemplo n.º 13
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;

            _itemizar    = false;
            _linked      = false;
            _numerar     = true;
            _prefijo     = "-";
            _sufijo      = "";
            _marca       = false;
            _comentarios = false;
            _descripcion = true;
            _modelo      = false;
            _marcaTipo   = false;

            System.Windows.Forms.DialogResult resultado = (new frmCrearTablas(uidoc.Document)).ShowDialog();

            if (resultado == System.Windows.Forms.DialogResult.OK)
            {
                List <ViewSchedule> tablas = new List <ViewSchedule>();

                // Creamos y abrimos una transacción
                using (Transaction t = new Transaction(doc, "Crear Tablas"))
                {
                    t.Start();
                    // Ordenar Categorias
                    Tools.categorias = Tools.categorias.OrderBy(x => x.Name).ToList();

                    int count     = 1;
                    int countMats = 1;
                    try
                    {
                        // Crear una Tabla para cada Categoría
                        foreach (Category cat in Tools._selectedCategories)
                        {
                            string nombre = "";
                            if (_numerar)
                            {
                                nombre += count.ToString();
                            }
                            if (_prefijo != "")
                            {
                                nombre += _prefijo;
                            }
                            nombre += " " + cat.Name;
                            if (_sufijo != "")
                            {
                                nombre += _sufijo;
                            }

                            ViewSchedule tabla = ViewSchedule.CreateSchedule(doc, cat.Id);
                            tabla.Name = nombre;
                            count++;
                            // ver 1.4 MEP
                            bool mep        = false;
                            bool pipeSystem = false;
                            bool ductSystem = false;
                            if (cat.Id.IntegerValue == -2008044) //Pipes
                            {
                                mep        = true;
                                pipeSystem = true;
                            }
                            if (cat.Id.IntegerValue == -2008049) //PipeFittings
                            {
                                mep        = true;
                                pipeSystem = true;
                            }
                            if (cat.Id.IntegerValue == -2008055) //Pipe Accesories
                            {
                                mep        = true;
                                pipeSystem = true;
                            }
                            if (cat.Id.IntegerValue == -2008050) //FlexPipe
                            {
                                //mep = true; // DEBE SER TAMAÑO TOTAL
                                pipeSystem = true;
                            }
                            if (cat.Id.IntegerValue == -2008000) // Duct
                            {
                                mep        = true;
                                ductSystem = true;
                            }
                            if (cat.Id.IntegerValue == -2008010) // DuctFitting
                            {
                                mep        = true;
                                ductSystem = true;
                            }
                            if (cat.Id.IntegerValue == -2008016) // Duct Accesories
                            {
                                mep        = true;
                                ductSystem = true;
                            }
                            if (cat.Id.IntegerValue == -2008020) // FlexDuct
                            {
                                //mep = true; // DEBE SER TAMAÑO TOTAL
                                ductSystem = true;
                            }
                            if (cat.Id.IntegerValue == -2008132) // Conduit
                            {
                                mep = true;
                            }
                            if (cat.Id.IntegerValue == -2008128) // ConduitFitting
                            {
                                mep = true;
                            }
                            if (cat.Id.IntegerValue == -2008130) // CableTray
                            {
                                mep = true;
                            }
                            if (cat.Id.IntegerValue == -2008126) // CableTrayFittings
                            {
                                mep = true;
                            }
                            Tools.FillSchedule(tabla, _itemizar, _linked, mep, pipeSystem, ductSystem);
                            // Phase Filter
                            Parameter tablaFilter = tabla.get_Parameter(BuiltInParameter.VIEW_PHASE_FILTER);
                            tablaFilter.Set(new ElementId(-1));
                            tablas.Add(tabla);
                        }
                        // Create Material Schedules
                        foreach (Category cat in Tools._selectedMatCategories)
                        {
                            int createMat = 0;

                            if (cat.HasMaterialQuantities)// && cat.Material != null)
                            {
                                if (cat.Id == new ElementId(BuiltInCategory.OST_Walls))
                                {
                                    createMat = 1;
                                }
                                if (cat.Id == new ElementId(BuiltInCategory.OST_Floors))
                                {
                                    createMat = 1;
                                }
                                if (cat.Id == new ElementId(BuiltInCategory.OST_Roofs))
                                {
                                    createMat = 1;
                                }
                                if (cat.Id == new ElementId(BuiltInCategory.OST_Ceilings))
                                {
                                    createMat = 1;
                                }
                                if (cat.Id == new ElementId(BuiltInCategory.OST_BuildingPad))
                                {
                                    createMat = 1;
                                }

                                if (createMat == 1)
                                {
                                    string nombre = "M";
                                    if (_numerar)
                                    {
                                        nombre += countMats.ToString();
                                    }
                                    if (_prefijo != "")
                                    {
                                        nombre += _prefijo;
                                    }
                                    nombre += " " + cat.Name;
                                    if (_sufijo != "")
                                    {
                                        nombre += _sufijo;
                                    }

                                    ViewSchedule tablaMat = ViewSchedule.CreateMaterialTakeoff(doc, cat.Id);
                                    tablaMat.Name = nombre + " (Materiales)";
                                    // Phase Filter
                                    Parameter tablaFilter = tablaMat.get_Parameter(BuiltInParameter.VIEW_PHASE_FILTER);
                                    tablaFilter.Set(new ElementId(-1));
                                    countMats++;
                                    Tools.FillScheduleMaterial(tablaMat, _itemizar, _linked);
                                    tablas.Add(tablaMat);
                                }
                            }
                        }
                        t.Commit();
                    }
                    catch (Exception ex)
                    {
                        TaskDialog.Show("Universo BIM", "Error: " + ex.Message);
                        t.RollBack();
                    }
                }
                TaskDialog.Show("Universo BIM", "Se han creado " + tablas.Count + " Tablas");
            }

            return(Result.Succeeded);
        }
Ejemplo n.º 14
0
        // Create a new schedule
        public ViewSchedule CreateSchedule(string filePath, UIDocument uidoc)
        {
            ViewSchedule sched = null;

            _doc = uidoc.Document;

            if (uidoc.Document.IsWorkshared)
            {
                docPath = ModelPathUtils.ConvertModelPathToUserVisiblePath(uidoc.Document.GetWorksharingCentralModelPath());
            }
            else
            {
                docPath = uidoc.Document.PathName;
            }


            excelFilePath = filePath;
            if (File.Exists(excelFilePath))
            {
                // read the Excel file and create the schedule
                Excel.Application excelApp   = new Excel.Application();
                Excel.Workbook    workbook   = excelApp.Workbooks.Open(excelFilePath, ReadOnly: true);
                Excel.Sheets      worksheets = workbook.Worksheets;

                List <WorksheetObject> worksheetObjs = new List <WorksheetObject>();
                foreach (Excel.Worksheet ws in worksheets)
                {
                    WorksheetObject wo   = new WorksheetObject();
                    string          name = ws.Name;
                    wo.Name = name;
                    Excel.Range range = ws.UsedRange;
                    try
                    {
                        range.CopyPicture(Excel.XlPictureAppearance.xlPrinter, Excel.XlCopyPictureFormat.xlBitmap);
                        if (Clipboard.GetDataObject() != null)
                        {
                            IDataObject data = Clipboard.GetDataObject();
                            if (data.GetDataPresent(DataFormats.Bitmap))
                            {
                                System.Drawing.Image img = (System.Drawing.Image)data.GetData(DataFormats.Bitmap, true);
                                wo.Image = img;
                            }
                        }
                    }
                    catch { }
                    worksheetObjs.Add(wo);
                }

                // Pop up the worksheet form
                WorksheetSelectForm wsForm = new WorksheetSelectForm(worksheetObjs, this, _doc);


                // Revit version
                int version = Convert.ToInt32(uidoc.Application.Application.VersionNumber);

                // Get the Revit window handle
                IntPtr handle = IntPtr.Zero;
                if (version < 2019)
                {
                    handle = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;
                }
                else
                {
                    handle = uidoc.Application.GetType().GetProperty("MainWindowHandle") != null
                        ? (IntPtr)uidoc.Application.GetType().GetProperty("MainWindowHandle").GetValue(uidoc.Application)
                        : IntPtr.Zero;
                }
                System.Windows.Interop.WindowInteropHelper wih = new System.Windows.Interop.WindowInteropHelper(wsForm)
                {
                    Owner = handle
                };

                //Show the Worksheet Select form
                wsForm.ShowDialog();
                if (wsForm.DialogResult.HasValue && wsForm.DialogResult.Value)
                {
                    foreach (Excel.Worksheet ws in worksheets)
                    {
                        if (ws.Name == selectedWorksheet.Name)
                        {
                            worksheet = ws;
                            break;
                        }
                    }
                }
                else
                {
                    worksheet = null;
                }

                if (worksheet != null)
                {
                    workSheetName = worksheet.Name;
                    Transaction trans = new Transaction(_doc, "Create Schedule");
                    trans.Start();

                    // Create the schedule
                    sched      = ViewSchedule.CreateSchedule(_doc, new ElementId(-1));
                    sched.Name = worksheet.Name;

                    // Add a single parameter for data, Assembly Code
                    ElementId       assemblyCodeId = new ElementId(BuiltInParameter.UNIFORMAT_DESCRIPTION);
                    ScheduleFieldId fieldId        = null;
                    foreach (SchedulableField sField in sched.Definition.GetSchedulableFields())
                    {
                        ElementId paramId = sField.ParameterId;

                        if (paramId == assemblyCodeId)
                        {
                            ScheduleField field = sched.Definition.AddField(sField);
                            fieldId = field.FieldId;
                            break;
                        }
                    }

                    if (fieldId != null && sched.Definition.GetFieldCount() > 0)
                    {
                        ScheduleDefinition schedDef = sched.Definition;

                        // Add filters to hide all elements in the schedule, ie make sure nothing shows up in the body.
                        ScheduleFilter filter0 = new ScheduleFilter(fieldId, ScheduleFilterType.Equal, "NO VALUES FOUND");
                        ScheduleFilter filter1 = new ScheduleFilter(fieldId, ScheduleFilterType.Equal, "ALL VALUES FOUND");
                        schedDef.AddFilter(filter0);
                        schedDef.AddFilter(filter1);

                        // Turn off the headers
                        schedDef.ShowHeaders = false;

                        // Fill out the schedule from Excel data
                        AddScheduleData(filePath, sched, _doc, PathType.Absolute, false);
                    }



                    if (linkFile)
                    {
                        AssignSchemaData(sched.Id, workSheetName, _doc);
                    }

                    trans.Commit();
                }

                //workbook.Close();
                workbook.Close(false);
                Marshal.ReleaseComObject(worksheets);
                if (worksheet != null)
                {
                    Marshal.ReleaseComObject(worksheet);
                }
                Marshal.ReleaseComObject(workbook);
                excelApp.Quit();
                Marshal.ReleaseComObject(excelApp);
            }
            return(sched);
        }
Ejemplo n.º 15
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            //throw new NotImplementedException();
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            //获取所有墙体的墙体类型
            //FilteredElementCollector wallCollector = new FilteredElementCollector(doc);
            //wallCollector.OfCategory(BuiltInCategory.OST_Walls).OfClass(typeof(Wall));
            FilteredElementCollector roomCollector = new FilteredElementCollector(doc);

            roomCollector.OfCategory(BuiltInCategory.OST_Rooms).OfClass(typeof(SpatialElement));

            List <Element> roomList = roomCollector.ToList();

            TaskDialog.Show("room COUNT", roomList.Count().ToString());
            try {
                List <Element> elemList  = ElementList(doc, "墙");
                List <Element> roomsList = WallList(doc);
                TaskDialog.Show("revit", roomsList.ToList().Count.ToString());
                //如果没有墙体直接退出
                if (!(roomsList.Count > 0))
                {
                    message = "模型没有房间";
                    return(Result.Failed);
                }
                ////获取元素
                //List<string> createSetting=ShowDialog(roomsList);
                //if (!(createSetting.Count > 0))
                //{
                //    message = "没得参数值";
                //    return Result.Cancelled;
                //}

                //创建明细表---创建面积明细表测试
                Transaction t = new Transaction(doc, "创建明细表");
                FilteredElementCollector collector1 = new FilteredElementCollector(doc);
                collector1.OfCategory(BuiltInCategory.OST_AreaSchemes);
                //创建明细表
                //collector1.OfCategory(BuiltInCategory.OST_Schedules);
                ElementId    areaSchemeId = collector1.FirstElementId();
                ViewSchedule Schedule     = ViewSchedule.CreateSchedule(doc, new ElementId(BuiltInCategory.OST_Areas)
                                                                        , areaSchemeId);



                //添加字段到明细表
                //AddFieldToSchedule(Lis);
            } catch
            {
                return(Result.Cancelled);
            }

            //RibbonWPF ribbonWPF = new RibbonWPF();
            //ribbonWPF.ShowDialog();

            //GetWallElement(doc);


            return(Result.Succeeded);
        }