示例#1
0
        private void UpdateFilter(string filterName,
                                  dynamic newValue, ScheduleDefinition scheduleDefinition)
        {
            ScheduleFilter filter = null;
            int            index  = 0;

            for (int i = 0; i < scheduleDefinition.GetFilterCount(); ++i)
            {
                ScheduleFilter curFilter = scheduleDefinition.GetFilter(i);
                ScheduleField  field     = scheduleDefinition.GetField(curFilter.FieldId);

                if (field.GetName().Equals(filterName))
                {
                    index  = i;
                    filter = curFilter;
                    break;
                }
            }

            if (newValue != null && filter != null && scheduleDefinition != null)
            {
                filter.SetValue(newValue);
                scheduleDefinition.SetFilter(index, filter);
            }
        }
        internal ScheduleFilter AppendFilter(ViewSchedule _viewSchedule, ScheduleField field, ScheduleFilterType filterType, object value)
        {
            ScheduleFilter _filter;

            if (value is int _valueInt)
            {
                _filter = new ScheduleFilter(field.FieldId, filterType, _valueInt);
            }
            else if (value is double _valueDouble)
            {
                _filter = new ScheduleFilter(field.FieldId, filterType, _valueDouble);
            }
            else if (value is string _valueString)
            {
                _filter = new ScheduleFilter(field.FieldId, filterType, _valueString);
            }
            else if (value is ElementId _valueId)
            {
                _filter = new ScheduleFilter(field.FieldId, filterType, _valueId);
            }
            else if (value == null)
            {
                _filter = new ScheduleFilter(field.FieldId, filterType);
            }
            else
            {
                return(null);
            }

            _viewSchedule.Definition.AddFilter(_filter);
            return(_filter);
        }
        internal ScheduleSortGroupField AppendSortField(ViewSchedule _viewSchedule, ScheduleField field)
        {
            ScheduleSortGroupField _sortGroupField = new ScheduleSortGroupField(field.FieldId);

            _viewSchedule.Definition.AddSortGroupField(_sortGroupField);
            return(_sortGroupField);
        }
示例#4
0
        private void HideEmptyColumns(ElementId id)
        {
            if (id == ElementId.InvalidElementId)
            {
                return;
            }

            ViewSchedule viewSchd = m_doc.GetElement(id)
                                    as ViewSchedule;
            ScheduleDefinition schdDef   = viewSchd.Definition;
            TableSectionData   tableData =
                viewSchd.GetTableData().GetSectionData(SectionType.Body);

            Func <ScheduleFieldId, bool> filterHiddenFields = delegate(ScheduleFieldId fId)
            {
                if (schdDef.GetField(fId).IsHidden)
                {
                    return(false);
                }
                else
                {
                    return(true);
                }
            };

            IList <ScheduleFieldId> visibleFields = schdDef
                                                    .GetFieldOrder()
                                                    .Where(filterHiddenFields)
                                                    .ToList();

            StringBuilder strBld = new StringBuilder();

            for (int i = tableData.FirstColumnNumber + 2; i <= tableData.LastColumnNumber; ++i)
            {
                double sum = 0;

                for (int j = tableData.FirstRowNumber + 1; j <= tableData.LastRowNumber; ++j)
                {
                    string cellContent = tableData.GetCellText(j, i);
                    strBld.AppendFormat("({0}, {1}) = {2}\n", i, j, cellContent);
                    double cellValue;
                    if (Double.TryParse(cellContent, out cellValue))
                    {
                        sum += cellValue;
                    }
                }

                // if the current column holds no value, then have it hidden
                if (sum == 0)
                {
                    ScheduleField field = schdDef.GetField(visibleFields[i]);
                    field.IsHidden = true;
                }
            }
            System.Diagnostics.Trace.Write(strBld.ToString());
        }
        internal ScheduleSortGroupField AppendGroupField(ViewSchedule _viewSchedule, ScheduleField field)
        {
            ScheduleSortGroupField _sortGroupField = new ScheduleSortGroupField(field.FieldId);

            _sortGroupField.ShowHeader    = false;
            _sortGroupField.SortOrder     = ScheduleSortOrder.Descending;
            _sortGroupField.ShowBlankLine = false;

            _viewSchedule.Definition.AddSortGroupField(_sortGroupField);
            return(_sortGroupField);
        }
示例#6
0
        internal ScheduleField AppendField(ViewSchedule _viewSchedule, string fieldName)
        {
            SchedulableField _schedulableField = _viewSchedule.Definition.GetSchedulableFields()
                                                 .FirstOrDefault(p => p.GetName(_doc).Equals(fieldName));

            if (_schedulableField == null)
            {
                return(null);
            }

            ScheduleField _scheduleField = _viewSchedule.Definition.AddField(_schedulableField);

            return(_scheduleField);
        }
示例#7
0
        Parameter GetScheduleFieldParameter(ScheduleField scheduleField, Element elem)
        {
            Parameter parameter = null;

            switch (scheduleField.FieldType)
            {
            case ScheduleFieldType.Instance:
                // If the parameter is not a shared parameter,
                // then it is an instance parameter
                if (scheduleField.ParameterId == null)
                {
                    parameter =
                        elem.LookupParameter(scheduleField.GetName());
                }
                // Conversely, it is a shared parameter
                else
                {
                    Document doc = elem.Document;
                    SharedParameterElement sharedParam =
                        doc.GetElement(scheduleField.ParameterId)
                        as SharedParameterElement;

                    // All shared parameteres use this type,
                    // be they instance or type parameters

                    // Try retrieving the parameter from an instance
                    parameter = elem.LookupParameter(sharedParam.Name);

                    // If the parameter is not present,
                    // then resort to a family type
                    if (parameter == null)
                    {
                        parameter = ((FamilyInstance)elem)
                                    .Symbol.LookupParameter(sharedParam.Name);
                    }
                }
                return(parameter);

            case ScheduleFieldType.ElementType:
                // A type parameter of the schedules elements
                parameter = ((FamilyInstance)elem)
                            .Symbol.LookupParameter(scheduleField.GetName());
                return(parameter);

            default:
                throw new NotImplementedException(
                          "Other filed types have not been implemented yet.");
            }
        }
示例#8
0
        protected Parameter GetParameter(ScheduleField field)
        {
            var sheets =
                new FilteredElementCollector(Document)
                .OfClass(typeof(ViewSheet))
                .Cast <ViewSheet>();

            Parameter parameter = null;

            foreach (var sheet in sheets)
            {
                parameter = GetParameter(sheet, field.ParameterId);
                break;
            }
            return(parameter);
        }
        /// <summary>
        /// Lấy về List ScheduleField có thể export ra file txt
        /// </summary>
        /// <param name="schedule"></param>
        /// <returns></returns>
        internal static IList <ScheduleField> GetCanExportScheduleFields(this ViewSchedule schedule)
        {
            if (schedule == null)
            {
                return(null);
            }

            List <ScheduleField> scheduleFields = new List <ScheduleField>();

            foreach (ScheduleFieldId fieldOrder in schedule.Definition.GetFieldOrder())
            {
                ScheduleField field = schedule.Definition.GetField(fieldOrder);
                if (field.IsHidden)
                {
                    continue;
                }
                scheduleFields.Add(field);
            }
            return(scheduleFields);
        }
        public static ViewSchedule CreateLayoutLoadSchedule(Document doc, string levelName, string suffix)
        {
            ScheduleCreator _scheduleCreator = new ScheduleCreator(doc);

            ViewSchedule  _viewSchedule      = _scheduleCreator.CreateSchedule(false, levelName + suffix, BuiltInCategory.OST_Levels);
            ScheduleField _nameField         = _scheduleCreator.AppendField(_viewSchedule, "Name");
            ScheduleField _elevationField    = _scheduleCreator.AppendField(_viewSchedule, "Elevation");
            ScheduleField _levelLoadCapacity = _scheduleCreator.AppendField(_viewSchedule, "Level Load Capacity");
            ScheduleField _loadDemand        = _scheduleCreator.AppendField(_viewSchedule, "Load Demand");
            ScheduleField _liveLoadDemand    = _scheduleCreator.AppendField(_viewSchedule, "Live Load Demand");
            ScheduleField _formworkDemand    = _scheduleCreator.AppendField(_viewSchedule, "Formwork Demand");

            if (_elevationField != null)
            {
                _scheduleCreator.AppendSortField(_viewSchedule, _elevationField);
            }

            _scheduleCreator.AppendFilter(_viewSchedule, _nameField, ScheduleFilterType.Equal, levelName);

            return(_viewSchedule);
        }
        /// <summary>
        /// Formats the schedule with alternating background colors
        /// </summary>
        /// <param name="viewSchedule"></param>
        public void FormatScheduleColumns(ViewSchedule viewSchedule)
        {
            ScheduleDefinition definition = viewSchedule.Definition;
            int index = 0;

            Color white          = new Color(0xFF, 0xFF, 0xFF);
            Color highlight      = new Color(0xd8, 0xd8, 0xd8);
            bool  applyHighlight = false;

            // Loop over fields in order
            foreach (ScheduleFieldId id in definition.GetFieldOrder())
            {
                // Index 0, 2, etc use highlight color
                if (index % 2 == 0)
                {
                    applyHighlight = true;
                }
                // Index 1, 3, etc use no background color
                else
                {
                    applyHighlight = false;
                }

                // Get the field style
                ScheduleField  field = definition.GetField(id);
                TableCellStyle style = field.GetStyle();
                TableCellStyleOverrideOptions options = style.GetCellStyleOverrideOptions();

                // Set override options for background color per requirement
                options.BackgroundColor = applyHighlight;
                style.SetCellStyleOverrideOptions(options);

                // Set background color per requirement
                style.BackgroundColor = applyHighlight ? highlight : white;
                field.SetStyle(style);

                index++;
            }
        }
        internal ScheduleField AppendField(ViewSchedule _viewSchedule, string fieldName)
        {
            SchedulableField _schedulableField = null;

            if (fieldName.Equals("Elevation", StringComparison.InvariantCultureIgnoreCase))
            {
                // BuiltInParameter.LEVEL_ELEV
            }
            else
            {
                _schedulableField = _viewSchedule.Definition.GetSchedulableFields()
                                    .FirstOrDefault(p => p.GetName(_doc).Equals(fieldName));
            }

            if (_schedulableField == null)
            {
                return(null);
            }

            ScheduleField _scheduleField = _viewSchedule.Definition.AddField(_schedulableField);

            return(_scheduleField);
        }
        public override void DrillDown()
        {
            if (!HasDrillDown)
            {
                return;
            }

            List <SnoopableObjectWrapper> scheduleFieldObjects = new List <SnoopableObjectWrapper>();

            for (int i = 0; i < _scheduleDefinition.GetFieldCount(); i++)
            {
                ScheduleField field = _scheduleDefinition.GetField(i);
                scheduleFieldObjects.Add(new SnoopableObjectWrapper("[" + i + "] " + field.GetName(), field));
            }

            if (!scheduleFieldObjects.Any())
            {
                return;
            }

            var form = new Forms.Objects(scheduleFieldObjects);

            form.ShowDialog();
        }
        public static ViewSchedule CreatePourColumnSchedule(Document doc, string name, string suffix)
        {
            ScheduleCreator _scheduleCreator = new ScheduleCreator(doc);

            ViewSchedule  _viewSchedule     = _scheduleCreator.CreateSchedule(false, name + suffix, BuiltInCategory.OST_Columns);
            ScheduleField _pourNameField    = _scheduleCreator.AppendField(_viewSchedule, "Pour Name");
            ScheduleField _count            = _scheduleCreator.AppendField(_viewSchedule, "Count");
            ScheduleField _familyAndType    = _scheduleCreator.AppendField(_viewSchedule, "Family and Type");
            ScheduleField _clearShoreHeight = _scheduleCreator.AppendField(_viewSchedule, "Clear Shore Height"); //Total Shore Length
            ScheduleField _maxHeight        = _scheduleCreator.AppendField(_viewSchedule, "Max. Height");
            ScheduleField _minHeight        = _scheduleCreator.AppendField(_viewSchedule, "Min. Height");
            ScheduleField _loadCapacity     = _scheduleCreator.AppendField(_viewSchedule, "Load Capacity"); //Safe Working Load

            _scheduleCreator.AppendSortField(_viewSchedule, _pourNameField);
            _scheduleCreator.AppendSortField(_viewSchedule, _familyAndType);
            _scheduleCreator.AppendSortField(_viewSchedule, _clearShoreHeight);

            if (_pourNameField != null)
            {
                _scheduleCreator.AppendFilter(_viewSchedule, _pourNameField, ScheduleFilterType.Equal, name);
            }

            return(_viewSchedule);
        }
        //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);
            }
        }
示例#16
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;
        }
示例#17
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);
        }
示例#18
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Document           doc  = commandData.Application.ActiveUIDocument.Document;
            ViewSchedule       vs   = commandData.Application.ActiveUIDocument.ActiveView as ViewSchedule;
            ScheduleDefinition sdef = null;

            if (vs == null)
            {
                Selection sel = commandData.Application.ActiveUIDocument.Selection;
                if (sel.GetElementIds().Count == 0)
                {
                    return(Result.Failed);
                }
                ScheduleSheetInstance ssi = doc.GetElement(sel.GetElementIds().First()) as ScheduleSheetInstance;
                if (ssi == null)
                {
                    return(Result.Failed);
                }
                if (!ssi.Name.Contains("ВРС"))
                {
                    return(Result.Failed);
                }
                vs = doc.GetElement(ssi.ScheduleId) as ViewSchedule;
            }
            sdef = vs.Definition;


            int firstWeightCell   = 0;
            int startHiddenFields = 0;
            int borderCell        = 9999;

            //определяю первую и последнюю ячейку с массой
            for (int i = 0; i < sdef.GetFieldCount(); i++)
            {
                ScheduleField sfield   = sdef.GetField(i);
                string        cellName = sfield.GetName();
                if (firstWeightCell == 0)
                {
                    if (char.IsNumber(cellName[0]))
                    {
                        firstWeightCell = i;
                    }
                    else
                    {
                        if (sfield.IsHidden)
                        {
                            startHiddenFields++;
                        }
                    }
                }
                if (cellName.StartsWith("="))
                {
                    borderCell = i;
                    break;
                }
            }

            using (Transaction t = new Transaction(doc))
            {
                t.Start("Отобразить все ячейки");
                for (int i = firstWeightCell; i < borderCell; i++)
                {
                    ScheduleField sfield   = sdef.GetField(i);
                    string        cellName = sfield.GetName();
                    sfield.IsHidden = false;
                }


                doc.Regenerate();

                TableData        tdata = vs.GetTableData();
                TableSectionData tsd   = tdata.GetSectionData(SectionType.Body);
                int firstRownumber     = tsd.FirstRowNumber;
                int lastRowNumber      = tsd.LastRowNumber;
                int rowsCount          = lastRowNumber - firstRownumber;

                for (int i = firstWeightCell; i < borderCell; i++)
                {
                    ScheduleField sfield   = sdef.GetField(i);
                    string        cellName = sfield.GetName();

                    List <string> values = new List <string>();
                    for (int j = firstRownumber; j <= lastRowNumber; j++)
                    {
                        string cellText = tsd.GetCellText(j, i - startHiddenFields);
                        values.Add(cellText);
                    }

                    bool checkOnlyTextAndZeros = OnlyTextAndZeros(values);
                    if (checkOnlyTextAndZeros)
                    {
                        sfield.IsHidden = true;
                    }
                }
                t.Commit();
            }
            return(Result.Succeeded);
        }
示例#19
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            // Add an EventLogTraceListener object
            System.Diagnostics.Trace.Listeners.Add(
                new System.Diagnostics.EventLogTraceListener("Application"));

            // Lay the hands on the active document
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document   doc   = uidoc.Document;

            // Set up a timer
            Timing myTimer = new Timing();

            myTimer.StartTime();
            StringBuilder strBld = new StringBuilder();

            // Make some preparations
            List <ElementId> selectedElemIds = new List <ElementId>();
            EnumValuesWnd    wnd             = null;

            try
            {
                if (doc.ActiveView.ViewType != ViewType.Schedule)
                {
                    TaskDialog.Show("Exception", "Open a schedule view before running this command.");
                    return(Result.Failed);
                }
                else if (uidoc.Selection.GetElementIds().Count == 0)
                {
                    TaskDialog.Show("Exception", "No element has been picked out.");
                    return(Result.Failed);
                }

                selectedElemIds = uidoc.Selection.GetElementIds().ToList();
                ViewSchedule       scheduleView       = doc.ActiveView as ViewSchedule;
                ScheduleDefinition scheduleDefinition = scheduleView.Definition;
                bool             sorted  = scheduleDefinition.GetSortGroupFieldCount() > 0 ? true : false;
                List <TmpObject> tmpObjs = new List <TmpObject>();

                for (int i = 0; i < selectedElemIds.Count; ++i)
                {
                    Element   elem = doc.GetElement(selectedElemIds[i]);
                    TmpObject tmp  = new TmpObject(elem.Id);

                    for (int j = 0; j < scheduleDefinition.GetSortGroupFieldCount(); ++j)
                    {
                        ScheduleSortGroupField srtGrpField = scheduleDefinition.GetSortGroupField(j);
                        ScheduleField          schField    = scheduleDefinition.GetField(srtGrpField.FieldId);

                        Parameter p = GetScheduleFieldParameter(schField, elem);
                        if (p != null)
                        {
                            tmp.AddParameter(p);
                        }
                    }
                    tmpObjs.Add(tmp);
                }

                // Sort the elements by a series of parameters
                tmpObjs.Sort();

                // Create the window and subscribe to its event
                IList <string> parameterNames = doc.GetElement(selectedElemIds[0])
                                                .GetOrderedParameters()
                                                .Where(p => p.StorageType == StorageType.String && !p.IsReadOnly)
                                                .Select(p => p.Definition.Name)
                                                .ToList();

                wnd            = new EnumValuesWnd(parameterNames);
                wnd.OkClicked += (sender, args) =>
                {
                    using (Transaction t = new Transaction(doc))
                    {
                        t.Start("Enumerate parameters");

                        // Deal with the first element
                        TmpObject prevObj = tmpObjs[0];
                        doc.GetElement(prevObj.Id).LookupParameter(args.ParameterName).Set(
                            string.Format("{0}{1}{2}", args.Prefix, args.Position, args.Suffix));
                        int position = args.Position;

                        // See about the other elements in the list
                        for (int i = 1; i < tmpObjs.Count; ++i)
                        {
                            TmpObject curObj = tmpObjs[i];
                            Element   e      = doc.GetElement(curObj.Id);

                            if (curObj.CompareTo(prevObj) == 0 && sorted)
                            {
                                e.LookupParameter(args.ParameterName).Set(
                                    string.Format("{0}{1}{2}", args.Prefix, position, args.Suffix));
                            }
                            else
                            {
                                ++position;
                                e.LookupParameter(args.ParameterName).Set(
                                    string.Format("{0}{1}{2}", args.Prefix, position, args.Suffix));
                            }
                            prevObj = curObj;
                        }
                        t.Commit();
                    }
                };

                // Show the window
                wnd.ShowDialog();

                return(Result.Succeeded);
            }
            catch (Autodesk.Revit.Exceptions.OperationCanceledException)
            {
                return(Result.Cancelled);
            }
            catch (Exception ex)
            {
                TaskDialog.Show("Exception",
                                string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
                System.Diagnostics.Trace.Write(string.Format("{0}\n{1}",
                                                             ex.Message, ex.StackTrace));
                return(Result.Failed);
            }
            finally
            {
                wnd.Close();
                myTimer.StopTime();
                System.Diagnostics.Trace
                .Write(string.Format("Time elapsed: {0}s",
                                     myTimer.Duration.TotalSeconds));
            }
        }
示例#20
0
        public void createMaterialTakeOffSchedule(String name, ElementId elementId)
        {
            //Get UIDocument
            UIDocument uidoc = _cachedCmdData.Application.ActiveUIDocument;
            //Get Document
            Document doc = uidoc.Document;

            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.CreateMaterialTakeoff(CachedDoc, elementId);
                schedule.Name = name + " Schedule";

                ElementId volumeId = new ElementId(BuiltInParameter.MATERIAL_VOLUME);
                ElementId areaId   = new ElementId(BuiltInParameter.MATERIAL_AREA);
                //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.ParameterId == volumeId || schedulableField.ParameterId == areaId || schedulableField.GetName(doc).Equals("Material: Keynote"))
                    {
                        //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 (schedulableField.GetName(doc).Equals("Material: Keynote"))
                        {
                            ScheduleSortGroupField sortGroupField = new ScheduleSortGroupField(field.FieldId);
                            schedule.Definition.AddSortGroupField(sortGroupField);
                            schedule.Definition.IsItemized = false;
                        }

                        if (field.ParameterId == volumeId)
                        {
                            FormatOptions formatOpt = new FormatOptions(DisplayUnitType.DUT_CUBIC_FEET, UnitSymbolType.UST_CF, 0.01);
                            formatOpt.UseDefault = false;
                            field.SetFormatOptions(formatOpt);
                            field.DisplayType = ScheduleFieldDisplayType.Totals;
                        }

                        if (field.ParameterId == areaId)
                        {
                            FormatOptions formatOpt = new FormatOptions(DisplayUnitType.DUT_SQUARE_FEET, UnitSymbolType.UST_SF, 0.01);
                            formatOpt.UseDefault = false;
                            field.SetFormatOptions(formatOpt);
                            field.DisplayType = ScheduleFieldDisplayType.Totals;
                        }
                    }
                }


                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);
        }
示例#21
0
        public QaqcCSVRequest(UIApplication uiApp, String text)
        {
            //Prepare a DataTable just for this operation
            DataTable  dt              = new DataTable();
            DataColumn paramIdColumn   = dt.Columns.Add("ID", typeof(Int32));
            DataColumn paramNameColumn = dt.Columns.Add("Name", typeof(String));
            DataColumn paramElemColumn = dt.Columns.Add("Element", typeof(Object));

            //Create some lists for collecting data
            List <string>    fieldNamesCollection = new List <string>();
            List <Parameter> elementParameters    = new List <Parameter>();
            List <DataRow>   duplicateRows        = new List <DataRow>();
            List <ElementId> idsToUpdate          = new List <ElementId>();
            List <string>    failList             = new List <string>();


            RVTDocument doc = uiApp.ActiveUIDocument.Document;
            //Give a dialog box to verify the user has synchronized model changes, and only proceed if they click Yes
            DialogResult result = MessageBox.Show("Have you synchronized your model changes?", "Synchronization Prompt", MessageBoxButtons.YesNo);

            if (result == DialogResult.Yes)
            {
                //Double check the active view is a schedule
                if (doc.ActiveView.ViewType == ViewType.Schedule)
                {
                    ViewSchedule viewSchedule = doc.ActiveView as ViewSchedule;
                    //Collect all of the elements displayed in the schedule
                    var scheduleCollector = new FilteredElementCollector(doc, doc.ActiveView.Id).ToElements();
                    //Get the number of fields in the schedule
                    ScheduleDefinition scheduleDefinition = viewSchedule.Definition;
                    int scheduleFieldCount = scheduleDefinition.GetFieldCount();
                    for (int i = 0; i < scheduleFieldCount; i++)
                    {
                        //Get the fields and replace "Material: " in any name because those come from Material elemements that just have parameters with normal names
                        ScheduleField scheduleField = scheduleDefinition.GetField(i);
                        fieldNamesCollection.Add(scheduleField.GetName().Replace("Material: ", ""));
                    }

                    //For each element in the schedule...
                    foreach (Element elem in scheduleCollector)
                    {
                        //Get every instance parameter for the element and add it to the list of parameters to evaluate
                        foreach (Parameter instanceParam in elem.Parameters)
                        {
                            elementParameters.Add(instanceParam);

                            //Also, add a new row to the DataTable with the parameter ID, parameter Name, and the parameter Element
                            DataRow row = dt.NewRow();
                            row["ID"]      = instanceParam.Id.IntegerValue;
                            row["Name"]    = instanceParam.Definition.Name;
                            row["Element"] = instanceParam;
                            dt.Rows.Add(row);
                        }

                        //Then, get the type parameters of each element
                        ElementId typeId      = elem.GetTypeId();
                        Element   typeElement = doc.GetElement(typeId);
                        try
                        {
                            //For each type parameter, add it to the list of parameters to evaluate
                            foreach (Parameter typeParameter in typeElement.Parameters)
                            {
                                elementParameters.Add(typeParameter);

                                //Also, add a new row to the DataTable with the parameter ID, parameter Name, and parameter Element
                                DataRow row = dt.NewRow();
                                row["ID"]      = typeParameter.Id.IntegerValue;
                                row["Name"]    = typeParameter.Definition.Name;
                                row["Element"] = typeParameter;
                                dt.Rows.Add(row);
                            }
                        }
                        catch { continue; }
                    }

                    //Get the list of distinct parameters
                    List <Parameter> elementParameterList = elementParameters.Distinct().ToList();

                    //Make a new HashTable
                    Hashtable hashTable = new Hashtable();
                    //Cycle through the rows in the DataTable
                    foreach (DataRow row in dt.Rows)
                    {
                        if (hashTable.Contains(row["ID"]))
                        {
                            //If the hash table already contains the parameter ID of the row being evaluated, add the row to the list of duplicate rows
                            duplicateRows.Add(row);
                        }
                        else
                        {
                            //Otherwise, add the parameter ID to the hash table for further evaluations
                            hashTable.Add(row["ID"], null);
                        }
                    }

                    //For each row in the list of duplicate rows, delete them from the DataTable
                    foreach (DataRow item in duplicateRows)
                    {
                        dt.Rows.Remove(item);
                    }


                    //With a DataTable of unique parameters, start a transaction
                    Transaction t1 = new Transaction(doc, "CapitalizeScheduleValues");
                    t1.Start();
                    //For each row in the DataTable...
                    foreach (DataRow row in dt.Rows)
                    {
                        try
                        {
                            //If the list of field names contains the parameter name in the row...
                            if (fieldNamesCollection.Contains(row["Name"].ToString()))
                            {
                                Parameter rowParam = row["Element"] as Parameter;
                                //Get the parameter of the row and verify its data type is a string, and it is not read only
                                if (rowParam.StorageType == StorageType.String && !rowParam.IsReadOnly)
                                {
                                    //Add to the list of parameter IDs to update the ID of the parameter in the row
                                    idsToUpdate.Add(new ElementId(Convert.ToInt32(row["ID"])));
                                }
                            }
                        }
                        catch { continue; }
                    }

                    //For each Element in the schedule...
                    foreach (Element elem in scheduleCollector)
                    {
                        try
                        {
                            //For each parameter in the list of parameters
                            foreach (Parameter param in elementParameterList)
                            {
                                //If the list of parameter IDs to update contains the parameter in the list, and the parameter value is not null...
                                if (idsToUpdate.Contains(param.Id) && param.AsString() != null)
                                {
                                    //If the element happens to be a view with brackets it will be skipped because a name value cannot be set with brackets
                                    if (!param.AsString().Contains("{") && !param.AsString().Contains("}"))
                                    {
                                        try
                                        {
                                            //Try setting the parameter's value to an all caps value
                                            param.Set(param.AsString().ToUpper());
                                        }
                                        catch
                                        {
                                            //Otherwise add the parameter's name to a list for failed capitalizations
                                            failList.Add(param.Definition.Name);
                                            continue;
                                        }
                                    }
                                }
                            }
                        }
                        catch { continue; }
                    }
                    t1.Commit();
                }

                else
                {
                    //If the active view is not a schedule view, let the user know
                    MessageBox.Show(String.Format("The currently active view is of type: {0}. " +
                                                  "Please make the desired schedule the active view by clicking into the schedule view and rerun the script",
                                                  doc.ActiveView.ViewType.ToString()));
                }
            }
            else if (result == DialogResult.No)
            {
                //If the user selected No when asked if they synchronized, remind them to synchronize and try again
                MessageBox.Show("Please synchronize and/or save the model, then run again");
            }
            else
            {
                ;
            }

            //If there were any failures, output the list of parameter names that failed to a string in a MessageBox
            if (failList.Count > 1)
            {
                string failMessage = StringOperations.BuildStringFromList(failList).ToString();
                MessageBox.Show(String.Format("Could not convert the following parameters: {0}", failMessage));
            }
        }
示例#22
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);
        }
示例#23
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;
        }
示例#24
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);
        }