예제 #1
0
        public EmailSupport(Document document, Application application)
        {
            doc = document;
            app = application;

            // Collect info about user
            UserName = Environment.UserName;

            // Following only works when computer is on a domain
            try
            {
                UserFullName = UserPrincipal.Current.DisplayName;
                Email        = UserPrincipal.Current.EmailAddress;
            }
            catch
            {
                UserFullName = UserName;
                Email        = "";
            }

            Computer = Environment.MachineName;

            // Collect info about Revit
            RevitVersion           = app.VersionName + " | " + app.VersionBuild;
            RevitServerAccelerator = app.CurrentRevitServerAccelerator;
            LocalModel             = doc.PathName;

            // Check to see if model is a worksharing model
            if (doc.GetWorksharingCentralModelPath() != null)
            {
                CentralModel = ModelPathUtils.ConvertModelPathToUserVisiblePath(doc.GetWorksharingCentralModelPath());
            }
            else
            {
                CentralModel = "Central model couldn't be found";
            }

            ModelSize();
            GetMemory();
        }
예제 #2
0
        /// <summary>
        /// Returns model's Central File path.
        /// </summary>
        /// <param name="doc">Revit Document.</param>
        /// <returns></returns>
        public static string GetCentralFilePath(Document doc)
        {
            var centralPath = "";

            try
            {
                var centralModelPath = doc.GetWorksharingCentralModelPath();
                if (null != centralModelPath)
                {
                    var userVisiblePath = ModelPathUtils.ConvertModelPathToUserVisiblePath(centralModelPath);
                    if (!string.IsNullOrEmpty(userVisiblePath))
                    {
                        centralPath = userVisiblePath;
                    }
                }
            }
            catch (Exception ex)
            {
                Log.AppendLog(LogMessageType.EXCEPTION, ex.Message);
            }
            return(centralPath.ToLower());
        }
예제 #3
0
        public static string GetCentralFilePath(Document doc)
        {
            string centralPath = "";

            try
            {
                ModelPath centralModelPath = doc.GetWorksharingCentralModelPath();
                if (null != centralModelPath)
                {
                    string userVisiblePath = ModelPathUtils.ConvertModelPathToUserVisiblePath(centralModelPath);
                    if (!string.IsNullOrEmpty(userVisiblePath))
                    {
                        centralPath = userVisiblePath;
                    }
                }
            }
            catch (Exception ex)
            {
                LogUtil.AppendLog("FileInfoUtil-GetCentralFilePath:" + ex.Message);
            }
            return(centralPath);
        }
예제 #4
0
        public static void updateLinks(UIApplication uiapp)
        {
            Document doc = uiapp.ActiveUIDocument.Document;
            FilteredElementCollector links
                = new FilteredElementCollector(doc)
                  .OfCategory(BuiltInCategory.OST_RvtLinks);

            foreach (Element e in links)
            {
                if (e is RevitLinkInstance)
                {
                    RevitLinkInstance     ee = e as RevitLinkInstance;
                    ExternalFileReference er = e.GetExternalFileReference();
                    if (er != null)
                    {
                        ModelPath mp = er.GetPath();
                        string    userVisiblePath = ModelPathUtils.ConvertModelPathToUserVisiblePath(mp);

                        //if(ee.Is)
                    }
                }
            }
        }
예제 #5
0
 public string FindDiffuseTextureDecal(Element element)
 {
     //查找漫反射纹理贴图
     try
     {
         // 获取元素ID
         ElementId typeId = element.GetTypeId();
         //获取外部文件参考
         ExternalFileReference externalFileReference = (document.GetElement(typeId) as ElementType).GetExternalFileReference();
         //判断外部文件参考类型是不是
         if (externalFileReference.ExternalFileReferenceType.Equals(AssetPropertyType.Float))
         {
             //是的话将模型路径转换为用户可见路径,(链接模型的完整路径作为参数)
             string inputPath = ModelPathUtils.ConvertModelPathToUserVisiblePath(externalFileReference.GetAbsolutePath());
             //最后返回文件绝对路径。
             return(FixTexturePath(inputPath));
         }
     }
     catch (Exception)
     {
     }
     return("");
 }
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            var uiApp = commandData.Application;
            var doc   = uiApp.ActiveUIDocument.Document;

            using (var namedPipeClient = new NamedPipeClientStream(".", "PilotRevitAddinUpdateSettingsPipe", PipeDirection.InOut))
            {
                try
                {
                    namedPipeClient.Connect(10000);
                }
                catch (TimeoutException)
                {
                    return(Result.Failed);
                }

                namedPipeClient.ReadMode = PipeTransmissionMode.Message;

                var centralModelPath = doc.GetWorksharingCentralModelPath();
                var centralFilePath  = ModelPathUtils.ConvertModelPathToUserVisiblePath(centralModelPath);
                if (string.IsNullOrEmpty(centralFilePath))
                {
                    return(Result.Failed);
                }

                var messageBytes = Encoding.UTF8.GetBytes(centralFilePath);
                namedPipeClient.Write(messageBytes, 0, messageBytes.Length);

                var revitProject = GetAnswerFromPilot(namedPipeClient);

                UpdateProjectInfo(doc, revitProject);

                doc.Save();
            }

            return(Result.Succeeded);
        }
예제 #7
0
        // If an application only needs read-only access to a server file, the example below
        // demonstrates how to copy the server model locally and open it detached. Note this
        // code sample re-uses methods demonstrated in previous examples.
        public Document CopyAndOpenDetached(UIApplication uiApp)
        {
            // Copy a server model locally and open detached
            Application application = uiApp.Application;
            String      hostId      = application.GetRevitServerNetworkHosts().First();

            // Try to get the server path for the particular model on the server
            String    rootFolder = "|";
            ModelPath serverPath = FindWSAPIModelPathOnServer(application, hostId, rootFolder, "ServerModel.rvt");

            // For debugging
            String sourcePath = ModelPathUtils.ConvertModelPathToUserVisiblePath(serverPath);

            // Setup the target location for the copy
            ModelPath localPath = GetWSAPIModelPath("CopiedModel.rvt");

            // Copy, allowing overwrite
            application.CopyModel(serverPath, ModelPathUtils.ConvertModelPathToUserVisiblePath(localPath), true);

            // Open the copy as detached
            Document openedDoc = OpenDetached(localPath);

            return(openedDoc);
        }
예제 #8
0
        private static string GetCentralPath(Document doc)
        {
            string docCentralPath;

            try
            {
                if (doc.IsWorkshared)
                {
                    var modelPath   = doc.GetWorksharingCentralModelPath();
                    var centralPath = ModelPathUtils.ConvertModelPathToUserVisiblePath(modelPath);
                    docCentralPath = !string.IsNullOrEmpty(centralPath) ? centralPath : doc.PathName;
                }
                else
                {
                    docCentralPath = doc.PathName;
                }
            }
            catch (Exception e)
            {
                Log.AppendLog(LogMessageType.EXCEPTION, e.Message);
                docCentralPath = doc.PathName;
            }
            return(docCentralPath);
        }
예제 #9
0
        /// <summary>
        /// Get paths of external references associated with the Revit document used to initialize the class.
        /// </summary>
        /// <returns>A dictionary of reference types, and reference paths.</returns>
        public Dictionary <ExternalFileReferenceType, string> GetExternalReferencePaths()
        {
            Dictionary <ExternalFileReferenceType, string> referenceDictionary = new Dictionary <ExternalFileReferenceType, string>();
            string location = Doc.PathName;

            try
            {
                ModelPath               modelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(location);
                TransmissionData        transData = TransmissionData.ReadTransmissionData(modelPath);
                ICollection <ElementId> externalFileReferenceIds = transData.GetAllExternalFileReferenceIds();

                foreach (ElementId referenceElementId in externalFileReferenceIds)
                {
                    ExternalFileReference externalFileReference = transData.GetLastSavedReferenceData(referenceElementId);
                    ModelPath             refPath = externalFileReference.GetPath();
                    string path = ModelPathUtils.ConvertModelPathToUserVisiblePath(refPath);
                    ExternalFileReferenceType referenceType = externalFileReference.ExternalFileReferenceType;
                    referenceDictionary.Add(referenceType, path);
                }
            }
            catch (Exception exceptionReference) { Console.WriteLine(exceptionReference.ToString()); }

            return(referenceDictionary);
        }
예제 #10
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            var uiApp = commandData.Application;
            var doc   = uiApp.ActiveUIDocument.Document;

            // Obtain user confirmation
            var confirmation = new TaskDialog(Properties.Resources.DeleteBackups_MessageTitle)
            {
                MainIcon        = TaskDialogIcon.TaskDialogIconWarning,
                MainInstruction = Properties.Resources.DeleteBackups_MainInstruction
            };

            confirmation.AddCommandLink(TaskDialogCommandLinkId.CommandLink1,
                                        Properties.Resources.DeleteBackups_YesDelete,
                                        Properties.Resources.DeleteBackups_InstructionDescription);
            confirmation.AddCommandLink(TaskDialogCommandLinkId.CommandLink2,
                                        Properties.Resources.DeleteBackups_NoDontDelete);

            // Cancel if user hasn't explicitly clicked YES.
            if (confirmation.Show() != TaskDialogResult.CommandLink1)
            {
                return(Result.Cancelled);
            }

            try
            {
                FileInfo file;

                if (doc.PathName == string.Empty)
                {
                    throw new Exception(Properties.Resources.DeleteBackups_FileNotSavedException);
                }
                // Determine which document location to use.
                if (doc.IsWorkshared)
                {
                    var modelPathName = ModelPathUtils.ConvertModelPathToUserVisiblePath(doc.GetWorksharingCentralModelPath());
                    file = new FileInfo(modelPathName);
                }
                else
                {
                    file = new FileInfo(doc.PathName);
                }

                // Get all files from parent directory that match a regex pattern.
                var          parentDir    = file.Directory?.Parent;
                const string regexPattern = @".*\.\d{4}\.(rfa|rvt)";
                if (parentDir == null)
                {
                    return(Result.Succeeded);
                }
                var files = Directory.GetFiles(parentDir.FullName, "*.rfa", SearchOption.AllDirectories)
                            .Where(x => Regex.IsMatch(x, regexPattern)).ToList();

                var    familyCount  = 0;
                var    projectCount = 0;
                var    n            = files.Count;
                var    s            = "{0} of " + n + " Files processed...";
                string pfCaption    = Properties.Resources.DeleteBackups_ProgressFormTitle;
                using (var pf = new ProgressForm(pfCaption, s, n))
                {
                    pf.Show();
                    foreach (var f in files)
                    {
                        try
                        {
                            File.Delete(f);
                        }
                        catch
                        {
                            // ignored
                        }
                        pf.Increment();
                        if (f.Contains(".rvt"))
                        {
                            projectCount++;
                        }
                        if (f.Contains(".rfa"))
                        {
                            familyCount++;
                        }
                    }
                }
                TaskDialog.Show(Properties.Resources.DeleteBackups_MessageTitle,
                                string.Format("You have sucessfully deleted :" +
                                              Environment.NewLine +
                                              familyCount + " family backup files." +
                                              Environment.NewLine +
                                              projectCount + " project backup files"));
                return(Result.Succeeded);
            }
            catch (Exception x)
            {
                message = x.Message;
                return(Result.Failed);
            }
        }
예제 #11
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app   = commandData.Application;
            UIDocument    uidoc = app.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            // Obtain all external resource references
            // (saying BIM360 Cloud references and local
            // file references this time)

            ISet <ElementId> xrefs = ExternalResourceUtils
                                     .GetAllExternalResourceReferences(doc);

            string caption = "BIM360 Links";

            try
            {
                int n   = 0;
                var msg = string.Empty;

                foreach (ElementId eid in xrefs)
                {
                    var elem = doc.GetElement(eid);
                    if (elem == null)
                    {
                        continue;
                    }

                    // Get RVT document links only this time

                    var link = elem as RevitLinkType;
                    if (link == null)
                    {
                        continue;
                    }

                    var map  = link.GetExternalResourceReferences();
                    var keys = map.Keys;

                    foreach (var key in keys)
                    {
                        var reference = map[key];

                        // Contains Forge BIM360 ProjectId
                        // (i.e., LinkedModelModelId) and
                        // ModelId (i.e., LinkedModelModelId)
                        // if it's from BIM360 Docs.
                        // They can be used in calls to
                        // ModelPathUtils.ConvertCloudGUIDsToCloudPath.

                        var dictinfo = reference.GetReferenceInformation();

                        // Link Name shown on the Manage Links dialog

                        var displayName = reference.GetResourceShortDisplayName();
                        var path        = reference.InSessionPath;
                    }

                    try
                    {
                        // Load model temporarily to get the model
                        // path of the cloud link

                        var result = link.Load();

                        // Link ModelPath for Revit internal use

                        var mdPath = result.GetModelName();

                        link.Unload(null);

                        // Convert model path to user visible path,
                        // i.e., saved Path shown on the Manage Links
                        // dialog

                        var path = ModelPathUtils
                                   .ConvertModelPathToUserVisiblePath(mdPath);

                        // Reference Type shown on the Manage Links dialog

                        var refType = link.AttachmentType;

                        msg += string.Format("{0} {1}\r\n",
                                             link.AttachmentType, path);

                        ++n;
                    }
                    catch (Exception ex) // never catch all exceptions!
                    {
                        TaskDialog.Show(caption, ex.Message);
                    }
                }

                caption = string.Format("{0} BIM360 Link{1}",
                                        n, Util.PluralSuffix(n));

                TaskDialog.Show(caption, msg);
            }
            catch (Exception ex)
            {
                TaskDialog.Show(caption, ex.Message);
            }
            return(Result.Succeeded);
        }
예제 #12
0
        public void DocumentOpened(object sender, DocumentOpenedEventArgs e)
        {
            Document doc = e.Document;

            if (doc.IsFamilyDocument)
            {
                return;
            }

            Schema schema = Schema.Lookup(schemaGUID);

            if (schema == null || !schema.IsValidObject)
            {
                return;
            }

            // Check to see if there is out-dated data stored in ProjectInformation
            Entity entity = null;

            entity = doc.ProjectInformation.GetEntity(schema);
            if (entity != null && entity.IsValid())
            {
                // Need to transition the data to a datastorage object.
                // First make sure this isn't a workshared document with the ProjectInfo already checked out by another user
                // If it's checked out by another person, we'll just skip this since we can't fix it now.
                if (doc.IsWorkshared && WorksharingUtils.GetCheckoutStatus(doc, doc.ProjectInformation.Id) == CheckoutStatus.OwnedByOtherUser)
                {
                    return;
                }

                // Otherwise, lets transition the data from the old to the new.
                if (entity.Get <IList <ElementId> >("ScheduleId") != null)
                {
                    // Get the information from the ProjectInformation entity
                    var schedIds = entity.Get <IList <ElementId> >("ScheduleId").ToList();
                    var paths    = entity.Get <IList <string> >("ExcelFilePath").ToList();
                    var wsNames  = entity.Get <IList <string> >("WorksheetName").ToList();
                    var dts      = entity.Get <IList <string> >("DateTime").ToList();
                    var pTypes   = entity.Get <IList <int> >("PathType")?.ToList() ?? new List <int>();

                    // Purge the old Schema and Entity, then assign the data to a new Schema and DataStorage element
                    RebuildSchema(doc, schema, schedIds, paths, wsNames, dts, pTypes);
                }
            }

            // Find if a datstorage element exists now and update as needed.
            DataStorage ds = new FilteredElementCollector(doc).OfClass(typeof(DataStorage)).Where(x => x.Name.Equals(dsName)).Cast <DataStorage>().FirstOrDefault();

            // Get the ExcelScheduleEntity from the data storage and verify its valid
            ExcelScheduleEntity ent = ds?.GetEntity <ExcelScheduleEntity>();

            if (ent == null)
            {
                return;
            }

            // Check if any schedules need to be updated
            List <int>      modifyIndices = new List <int>();
            List <DateTime> modDateTimes  = new List <DateTime>();

            for (int i = 0; i < ent.ScheduleId.Count; i++)
            {
                string currentFilePath;
                string docPath;
                if (doc.IsWorkshared)
                {
                    docPath = ModelPathUtils.ConvertModelPathToUserVisiblePath(doc.GetWorksharingCentralModelPath());
                }
                else
                {
                    docPath = doc.PathName;
                }

                if ((PathType)ent.PathType[i] == PathType.Absolute)
                {
                    currentFilePath = ent.ExcelFilePath[i];
                }
                else
                {
                    currentFilePath = PathExchange.GetFullPath(ent.ExcelFilePath[i], docPath);
                }

                // Get the file write time as UTC
                DateTime modTime    = new FileInfo(currentFilePath).LastWriteTimeUtc;
                DateTime storedTime = Convert.ToDateTime(ent.DateTime[i]);

                // Make sure the save time isn't more or less the same as stored.
                if ((modTime - storedTime).Seconds > 1)
                {
                    modifyIndices.Add(i);
                    modDateTimes.Add(modTime);
                }
            }

            if (modifyIndices.Count == modDateTimes.Count && modifyIndices.Count > 0)
            {
                IntPtr statusBar = FindWindowEx(RevitHandle, IntPtr.Zero, "msctls_statusbar32", "");
                foreach (int i in modifyIndices)
                {
                    if (statusBar != IntPtr.Zero)
                    {
                        SetWindowText(statusBar, string.Format("Updating Excel Schedule {0}.", ent.WorksheetName[modifyIndices[i]]));
                    }
                    Scheduler scheduler = new Scheduler();
                    scheduler.ModifySchedule(doc, ent.ScheduleId[modifyIndices[i]], ent.ExcelFilePath[modifyIndices[i]],
                                             ent.WorksheetName[modifyIndices[i]], "Update Excel Schedule", ent.PathType[modifyIndices[i]],
                                             Properties.Settings.Default.reloadValuesOnly);

                    ent.DateTime[modifyIndices[i]] = modDateTimes[i].ToString();
                }
                if (statusBar != IntPtr.Zero)
                {
                    SetWindowText(statusBar, "");
                }

                // change the dateTimes
                using (Transaction t = new Transaction(doc, "Update schedule date"))
                {
                    t.Start();
                    ds.SetEntity(ent);
                    t.Commit();
                }

                // Write to home
                RevitCommon.FileUtils.WriteToHome("Excel Import - Document Open Reload", doc.Application.VersionName, doc.Application.Username);
            }
        }
        void MiroReloadLinks(IList <RevitLinkType> fecLinkTypes)
        {
            // Loop all RVT Links

            foreach (RevitLinkType typeLink in fecLinkTypes)
            {
                // ...

                // Skip1 - not IsFromRevitServer

                if (!typeLink.IsFromRevitServer())
                {
                    //…
                    continue;
                }

                // Skip2 - not ExternalFileReference
                // 99% it would already skip above as
                // RevitServer MUST be ExternalFileReference,
                // but leave just in case...

                ExternalFileReference er = typeLink.GetExternalFileReference();

                if (er == null)
                {
                    // ...

                    continue;
                }

                // If here, we can cache ModelPath related
                // info and show to user regardless if we skip
                // on next checks or not....

                ModelPath mp = er.GetPath();

                string userVisiblePath = ModelPathUtils
                                         .ConvertModelPathToUserVisiblePath(mp);

                // Skip3 - if ModelPath is NOT Server Path
                // 99% redundant as we already checked raw
                // RevitLinkType for this, but keep
                // just in case...

                if (!mp.ServerPath)
                {
                    // ...

                    continue;
                }

                // Skip4 - if NOT "NOT Found" problematic one
                // there is nothing to fix

                if (er.GetLinkedFileStatus()
                    != LinkedFileStatus.NotFound)
                {
                    // ...

                    continue;
                }

                // Skip5 - if Nested Link (can’t (re)load these!)

                if (typeLink.IsNestedLink)
                {
                    // ...

                    continue;
                }

                // If here, we MUST offer user to "Reload from..."

                // ...

                RevitLinkLoadResult res = null;

                try
                {
                    // This fails for problematic Server files
                    // since it also fails on "Reload" button in
                    // UI (due to the GUID issue in the answer)

                    //res = typeLink.Reload();

                    // This fails same as above :-(!

                    //res = typeLink.Load();

                    // This WORKS!
                    // Basically, this is the equivalent of UI
                    // "Reload from..." + browsing to the *same*
                    // Saved path showing in the manage Links
                    // dialogue.
                    // ToDo: Check if we need to do anything
                    // special with WorksetConfiguration?
                    // In tests, it works fine with the
                    // default c-tor.

                    ModelPath mpForReload = ModelPathUtils
                                            .ConvertUserVisiblePathToModelPath(
                        userVisiblePath);

                    res = typeLink.LoadFrom(mpForReload,
                                            new WorksetConfiguration());

                    Util.InfoMsg(string.Format(
                                     "Result = {0}", res.LoadResult));
                }
                catch (Exception ex)
                {
                    Debug.Print(ex.Message);
                }
            } // foreach typeLink
        }
예제 #14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="sched"></param>
        /// <param name="doc"></param>
        /// <param name="pt"></param>
        /// <param name="contentOnly"></param>
        public void AddScheduleData(string filePath, ViewSchedule sched, Document doc, PathType pt, bool contentOnly)
        {
            string docPath;

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

            string fullPath;

            if (pt == PathType.Absolute)
            {
                fullPath = filePath;
            }
            else
            {
                fullPath = PathExchange.GetFullPath(filePath, docPath);
            }

            // Get the file path
            excelFilePath = fullPath;
            if (!File.Exists(excelFilePath))
            {
                return;
            }


            // read the Excel file and create the schedule
            Excel.Application excelApp   = new Excel.Application();
            Excel.Workbook    workbook   = excelApp.Workbooks.Open(excelFilePath);
            Excel.Sheets      worksheets = workbook.Worksheets;
            worksheet = null;
            foreach (Excel.Worksheet ws in worksheets)
            {
                if (ws.Name.Trim() == sched.Name.Trim())
                {
                    worksheet = ws;
                }
            }

            if (worksheet == null)
            {
                return;
            }

            //TaskDialog.Show("Test", "Worksheet found");
            // Find the ThinLine linestyle
            CategoryNameMap lineSubCats   = doc.Settings.Categories.get_Item(BuiltInCategory.OST_Lines).SubCategories;
            ElementId       thinLineStyle = new ElementId(-1);
            ElementId       hairlineStyle = new ElementId(-1);
            ElementId       thinStyle     = new ElementId(-1);
            ElementId       mediumStyle   = new ElementId(-1);
            ElementId       thickStyle    = new ElementId(-1);

            foreach (Category style in lineSubCats)
            {
                if (style.Name == "Thin Lines")
                {
                    thinLineStyle = style.Id;
                }

                if (style.GetGraphicsStyle(GraphicsStyleType.Projection).Id.IntegerValue == Properties.Settings.Default.hairlineInt)
                {
                    hairlineStyle = style.Id;
                }
                else if (style.GetGraphicsStyle(GraphicsStyleType.Projection).Id.IntegerValue == Properties.Settings.Default.thinInt)
                {
                    thinStyle = style.Id;
                }
                else if (style.GetGraphicsStyle(GraphicsStyleType.Projection).Id.IntegerValue == Properties.Settings.Default.mediumInt)
                {
                    mediumStyle = style.Id;
                }
                else if (style.GetGraphicsStyle(GraphicsStyleType.Projection).Id.IntegerValue == Properties.Settings.Default.thickInt)
                {
                    thickStyle = style.Id;
                }
            }

            if (hairlineStyle.IntegerValue == -1)
            {
                hairlineStyle = thinLineStyle;
            }
            if (thinStyle.IntegerValue == -1)
            {
                thinStyle = thinLineStyle;
            }
            if (mediumStyle.IntegerValue == -1)
            {
                mediumStyle = thinLineStyle;
            }
            if (thickStyle.IntegerValue == -1)
            {
                thickStyle = thinLineStyle;
            }



            // Find out how many rows and columns we need in the schedule
            Excel.Range rng = ActualUsedRange(worksheet);

            Excel.Range range       = rng;
            int         rowCount    = range.Rows.Count;
            int         columnCount = range.Columns.Count;

            // Get the schedule body to set the overall width
            TableSectionData bodyData = sched.GetTableData().GetSectionData(SectionType.Body);

            if (!contentOnly)
            {
                double schedWidth = range.Columns.Width;
                try
                {
                    bodyData.SetColumnWidth(0, (schedWidth * pointWidthInches) / 12);
                }
                catch { }
            }

            // Get the header body to create the necessary rows and columns
            TableSectionData headerData = sched.GetTableData().GetSectionData(SectionType.Header);

            if (!contentOnly)
            {
                //TaskDialog.Show("Test: ", "Row Count: " + rowCount.ToString() + "\nColumn Count:  " + columnCount.ToString());
                for (int i = 0; i < columnCount - 1; i++)
                {
                    headerData.InsertColumn(1);
                }
                for (int i = 0; i < rowCount - 1; i++)
                {
                    headerData.InsertRow(1);
                }

                for (int i = 1; i <= headerData.NumberOfColumns; i++)
                {
                    try
                    {
                        Excel.Range cell = worksheet.Cells[1, i];
                        headerData.SetColumnWidth(i - 1, (cell.Width * pointWidthInches) / 12);
                    }
                    catch { }
                }

                for (int i = 1; i <= headerData.NumberOfRows; i++)
                {
                    try
                    {
                        Excel.Range cell = worksheet.Cells[i, 1];

                        headerData.SetRowHeight(i - 1, (cell.Height * pointWidthInches) / 12);
                    }
                    catch { }
                }
            }



            List <TableMergedCell> mergedCells = new List <TableMergedCell>();
            int errorCount = 0;

            for (int i = 1; i <= headerData.NumberOfRows; i++)        // Iterate through rows of worksheet data
            {
                for (int j = 1; j <= headerData.NumberOfColumns; j++) // Iterate through columns of worksheet data
                {
                    // Get the current cell in the worksheet grid
                    Excel.Range cell = worksheet.Cells[i, j];

                    // If adjusting the formatting or adding content is not necessary,
                    // just update the text content. This is via a UI switch.
                    if (contentOnly)
                    {
                        try
                        {
                            headerData.SetCellText(i - 1, j - 1, cell.Text);
                            continue;
                        }
                        catch {
                            errorCount++;
                            continue;
                        }
                    }

                    Excel.Font          font       = cell.Font;
                    Excel.DisplayFormat dispFormat = cell.DisplayFormat;

                    TableCellStyle cellStyle = new TableCellStyle();
                    TableCellStyleOverrideOptions styleOverride = cellStyle.GetCellStyleOverrideOptions();

                    Excel.Border topEdge    = cell.Borders.Item[Excel.XlBordersIndex.xlEdgeTop];
                    Excel.Border bottomEdge = cell.Borders.Item[Excel.XlBordersIndex.xlEdgeBottom];
                    Excel.Border leftEdge   = cell.Borders.Item[Excel.XlBordersIndex.xlEdgeLeft];
                    Excel.Border rightEdge  = cell.Borders.Item[Excel.XlBordersIndex.xlEdgeRight];

                    // Determine Bottom Edge Line Style
                    if (bottomEdge.LineStyle == (int)Excel.XlLineStyle.xlLineStyleNone)
                    {
                        cellStyle.BorderBottomLineStyle = new ElementId(-1);
                    }
                    else
                    {
                        switch (bottomEdge.Weight)
                        {
                        case (int)Excel.XlBorderWeight.xlHairline:
                            cellStyle.BorderBottomLineStyle = hairlineStyle;
                            break;

                        case (int)Excel.XlBorderWeight.xlThin:
                            cellStyle.BorderBottomLineStyle = thinStyle;
                            break;

                        case (int)Excel.XlBorderWeight.xlMedium:
                            cellStyle.BorderBottomLineStyle = mediumStyle;
                            break;

                        case (int)Excel.XlBorderWeight.xlThick:
                            cellStyle.BorderBottomLineStyle = thickStyle;
                            break;
                        }
                    }


                    // Determine Top Edge Line Style
                    if (topEdge.LineStyle == (int)Excel.XlLineStyle.xlLineStyleNone)
                    {
                        cellStyle.BorderTopLineStyle = new ElementId(-1);
                    }
                    else
                    {
                        switch (topEdge.Weight)
                        {
                        case (int)Excel.XlBorderWeight.xlHairline:
                            cellStyle.BorderTopLineStyle = hairlineStyle;
                            break;

                        case (int)Excel.XlBorderWeight.xlThin:
                            cellStyle.BorderTopLineStyle = thinStyle;
                            break;

                        case (int)Excel.XlBorderWeight.xlMedium:
                            cellStyle.BorderTopLineStyle = mediumStyle;
                            break;

                        case (int)Excel.XlBorderWeight.xlThick:
                            cellStyle.BorderTopLineStyle = thickStyle;
                            break;
                        }
                    }

                    // Determine Left Edge Line Style
                    if (leftEdge.LineStyle == (int)Excel.XlLineStyle.xlLineStyleNone)
                    {
                        cellStyle.BorderLeftLineStyle = new ElementId(-1);
                    }
                    else
                    {
                        switch (leftEdge.Weight)
                        {
                        case (int)Excel.XlBorderWeight.xlHairline:
                            cellStyle.BorderLeftLineStyle = hairlineStyle;
                            break;

                        case (int)Excel.XlBorderWeight.xlThin:
                            cellStyle.BorderLeftLineStyle = thinStyle;
                            break;

                        case (int)Excel.XlBorderWeight.xlMedium:
                            cellStyle.BorderLeftLineStyle = mediumStyle;
                            break;

                        case (int)Excel.XlBorderWeight.xlThick:
                            cellStyle.BorderLeftLineStyle = thickStyle;
                            break;
                        }
                    }

                    // Determine Right Edge Line Style
                    if (rightEdge.LineStyle == (int)Excel.XlLineStyle.xlLineStyleNone)
                    {
                        cellStyle.BorderRightLineStyle = new ElementId(-1);
                    }
                    else
                    {
                        switch (rightEdge.Weight)
                        {
                        case (int)Excel.XlBorderWeight.xlHairline:
                            cellStyle.BorderRightLineStyle = hairlineStyle;
                            break;

                        case (int)Excel.XlBorderWeight.xlThin:
                            cellStyle.BorderRightLineStyle = thinStyle;
                            break;

                        case (int)Excel.XlBorderWeight.xlMedium:
                            cellStyle.BorderRightLineStyle = mediumStyle;
                            break;

                        case (int)Excel.XlBorderWeight.xlThick:
                            cellStyle.BorderRightLineStyle = thickStyle;
                            break;
                        }
                    }
                    // Border Styles are always overridden
                    styleOverride.BorderBottomLineStyle = true;
                    styleOverride.BorderTopLineStyle    = true;
                    styleOverride.BorderLeftLineStyle   = true;
                    styleOverride.BorderRightLineStyle  = true;

                    if (styleOverride.BorderBottomLineStyle || styleOverride.BorderTopLineStyle ||
                        styleOverride.BorderLeftLineStyle || styleOverride.BorderRightLineStyle)
                    {
                        styleOverride.BorderLineStyle = true;
                    }

                    // Get Background color and font name
                    System.Drawing.Color backGroundColor = System.Drawing.ColorTranslator.FromOle((int)cell.Interior.Color);
                    cellStyle.BackgroundColor     = new Color(backGroundColor.R, backGroundColor.G, backGroundColor.B);
                    styleOverride.BackgroundColor = true;
                    cellStyle.FontName            = cell.Font.Name;
                    styleOverride.Font            = true;

                    // Determine Horizontal Alignment
                    // If its not set to left, right or center, do not modify
                    switch (dispFormat.HorizontalAlignment)
                    {
                    case (int)Excel.XlHAlign.xlHAlignLeft:
                        cellStyle.FontHorizontalAlignment = HorizontalAlignmentStyle.Left;
                        styleOverride.HorizontalAlignment = true;
                        break;

                    case (int)Excel.XlHAlign.xlHAlignRight:
                        cellStyle.FontHorizontalAlignment = HorizontalAlignmentStyle.Right;
                        styleOverride.HorizontalAlignment = true;
                        break;

                    case (int)Excel.XlHAlign.xlHAlignGeneral:     // No specific style assigned
                        // Check if it's a number which is typically right aligned
                        if (double.TryParse(cell.Text, out double alignTest))
                        {
                            cellStyle.FontHorizontalAlignment = HorizontalAlignmentStyle.Right;
                            styleOverride.HorizontalAlignment = true;
                        }
                        else     // Assume text and left align it
                        {
                            cellStyle.FontHorizontalAlignment = HorizontalAlignmentStyle.Left;
                            styleOverride.HorizontalAlignment = true;
                        }
                        break;

                    case (int)Excel.XlHAlign.xlHAlignCenter:
                        cellStyle.FontHorizontalAlignment = HorizontalAlignmentStyle.Center;
                        styleOverride.HorizontalAlignment = true;
                        break;
                    }

                    // Get the vertical alignment of the cell
                    switch (dispFormat.VerticalAlignment)
                    {
                    case (int)Excel.XlVAlign.xlVAlignBottom:
                        cellStyle.FontVerticalAlignment = VerticalAlignmentStyle.Bottom;
                        styleOverride.VerticalAlignment = true;
                        break;

                    case (int)Excel.XlVAlign.xlVAlignTop:
                        cellStyle.FontVerticalAlignment = VerticalAlignmentStyle.Top;
                        styleOverride.VerticalAlignment = true;
                        break;

                    default:
                        cellStyle.FontVerticalAlignment = VerticalAlignmentStyle.Middle;
                        styleOverride.VerticalAlignment = true;
                        break;
                    }

                    switch (dispFormat.Orientation)
                    {
                    case (int)Excel.XlOrientation.xlUpward:
                        cellStyle.TextOrientation     = 9;
                        styleOverride.TextOrientation = true;
                        break;

                    case (int)Excel.XlOrientation.xlDownward:
                        cellStyle.TextOrientation     = -9;
                        styleOverride.TextOrientation = true;
                        break;

                    case (int)Excel.XlOrientation.xlVertical:
                        cellStyle.TextOrientation     = 9;
                        styleOverride.TextOrientation = true;
                        break;

                    default:
                        int rotation = (int)cell.Orientation;
                        if (rotation != (int)Excel.XlOrientation.xlHorizontal)
                        {
                            cellStyle.TextOrientation     = rotation;
                            styleOverride.TextOrientation = true;
                        }
                        break;
                    }


                    // Determine Text Size
                    double textSize = Convert.ToDouble(font.Size);
                    //double newTextSize = (textSize / 72) / 12;
                    cellStyle.TextSize     = textSize;
                    styleOverride.FontSize = true;

                    // Determine Font Color
                    System.Drawing.Color fontColor = System.Drawing.ColorTranslator.FromOle((int)font.Color);
                    cellStyle.TextColor     = new Color(fontColor.R, fontColor.G, fontColor.B);
                    styleOverride.FontColor = true;

                    // NOTES: Bold  is a bool
                    //        Italic is a bool
                    //        Underline is an int
                    cellStyle.IsFontBold      = (bool)font.Bold;
                    cellStyle.IsFontItalic    = (bool)font.Italic;
                    cellStyle.IsFontUnderline = (int)font.Underline == 2;
                    styleOverride.Bold        = true;
                    styleOverride.Italics     = true;
                    styleOverride.Underline   = true;

                    cellStyle.SetCellStyleOverrideOptions(styleOverride);

                    if (cell.MergeCells == true)
                    {
                        TableMergedCell tmc = new TableMergedCell()
                        {
                            Left   = j - 1,
                            Right  = cell.MergeArea.Columns.Count - 1,
                            Top    = i - 1,
                            Bottom = (i - 1) + cell.MergeArea.Rows.Count - 1
                        };

                        // Check to see if the cell is already merged...
                        bool alreadyMerged = false;
                        foreach (TableMergedCell mergedCell in mergedCells)
                        {
                            bool left   = false;
                            bool right  = false;
                            bool top    = false;
                            bool bottom = false;

                            if (i - 1 >= mergedCell.Top)
                            {
                                top = true;
                            }
                            if (i - 1 <= mergedCell.Bottom)
                            {
                                bottom = true;
                            }
                            if (j - 1 >= mergedCell.Left)
                            {
                                left = true;
                            }
                            if (j - 1 <= mergedCell.Right)
                            {
                                right = true;
                            }

                            //TaskDialog.Show("MergedCell", string.Format("Top: {0}\nBottom: {1}\nLeft: {2}\nRight: {3}\ni-1: {4}\nj-1: {5}", mergedCell.Top, mergedCell.Bottom, mergedCell.Left, mergedCell.Right, i - 1, j - 1));
                            if (top && bottom && left && right)
                            {
                                alreadyMerged = true;
                                break;
                            }
                        }


                        if (!alreadyMerged)
                        {
                            try
                            {
                                headerData.MergeCells(tmc);
                                headerData.SetCellText(i - 1, j - 1, cell.Text);
                                headerData.SetCellStyle(i - 1, j - 1, cellStyle);
                                j += cell.MergeArea.Columns.Count - 1;
                                mergedCells.Add(tmc);
                                //    TaskDialog.Show("Test", string.Format("This cell [{0},{1}] is merged.\nMerged Area: [{2},{3}]", cell.Row - 1, cell.Column - 1, cell.MergeArea.Rows.Count.ToString(), cell.MergeArea.Columns.Count.ToString()));
                            }
                            catch
                            {
                            }
                        }
                    }
                    else
                    {
                        //TaskDialog.Show("Non Merged", string.Format("This cell is not merged with any others [{0}, {1}]", i - 1, j - 1));
                        try
                        {
                            headerData.SetCellText(i - 1, j - 1, cell.Text);
                            headerData.SetCellStyle(i - 1, j - 1, cellStyle);
                        }
                        catch { }
                    }
                }
            }

            if (errorCount > 0)
            {
                TaskDialog.Show("Warning", "Error reloading content for " + errorCount.ToString() + " cells.\n\nConsider unchecking the \"Content Only\" checkbox and reloading the schedule to force it to rebuild.");
            }

            // Write the Schema to the project
            Schema schema = null;

            try
            {
                schema = Schema.Lookup(schemaGUID);
            }
            catch { }

            ModifySchemaData(schema, sched.Id);



            workbook.Close(false);
            Marshal.ReleaseComObject(worksheets);
            Marshal.ReleaseComObject(worksheet);
            Marshal.ReleaseComObject(workbook);
            excelApp.Quit();
            Marshal.ReleaseComObject(excelApp);
        }
예제 #15
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;

            Translate translation = new Translate();
            string    path        = @"W:\S\BIM\Z-LINKED EXCEL\SOM-Chinese Translation.xlsx";
            //used to debug.
            //string path = @"C:\SOM-Chinese Translation.xlsx";

            //Project file path and name to track sheets annotations and titles.
            string centralFilePath = ModelPathUtils.ConvertModelPathToUserVisiblePath(doc.GetWorksharingCentralModelPath());

            //Translation for Annotations, Title on Sheets and Sheet Names
            translation.StartTranslation(doc, app, path, centralFilePath);
            // Annotations which are not translated.
            List <string[]> UpdateExcelTranslationGenericAnno         = translation._UpdateExcelTranslationGenericAnno;
            Dictionary <string, string[]> Anno_IDandEnglishDictionary = new Dictionary <string, string[]>();

            // Title on sheets not translated
            List <string[]> NotTranslatedTitleOnSheet = translation._NotTranslatedTitleOnSheet;
            // Title on sheet which was on hold is found in Revit.
            List <string[]> HoldIsFoundInRevitTitleOnSheet = translation._HoldIsFoundInRevitTitleOnSheet;
            // Dictionary of Key and Values from Excel
            Dictionary <string, string[]> TitleOnSheet_IDEnglishChineseDict = translation._TitleOnSheet_IDEnglishChineseDict;
            // Sheet names not translated
            List <string[]> NotTranslatedSheets = translation._NotTranslatedSheets;
            // Sheet which is on hold is found in Revit.
            List <string[]> HoldIsFoundInRevitTSheets = translation._HoldIsFoundInRevitSheets;
            // Dictionary of Key and Values from Excel
            Dictionary <string, string[]> Sheet_IDEnglishChineseDict = translation._Sheet_IDEnglishChineseDict;
            string BuildingName = doc.ProjectInformation.BuildingName;

            // Get project paramter Author number to assign color.
            var BuildingColor = doc.ProjectInformation.Author;

            //Annotation Excel Sheet
            if (UpdateExcelTranslationGenericAnno.Count > 0)
            {
                ExcelSheet Excel = new ExcelSheet();
                Excel.Update(Anno_IDandEnglishDictionary, UpdateExcelTranslationGenericAnno, path, 1, "");
            }
            //Title on Sheet Excel Sheet
            if (NotTranslatedTitleOnSheet.Count > 0)
            {
                // combine dictionarys to update Excel file.
                HoldIsFoundInRevitTitleOnSheet.AddRange(NotTranslatedTitleOnSheet);
            }
            //Title on Sheet Hold was found
            if (HoldIsFoundInRevitTitleOnSheet.Count > 0)
            {
                ExcelSheet Excel = new ExcelSheet();
                Excel.Update(TitleOnSheet_IDEnglishChineseDict, HoldIsFoundInRevitTitleOnSheet, path, 2, BuildingColor);
            }
            //Sheet Name Excel Sheet
            if (NotTranslatedSheets.Count > 0)
            {
                // combine dictionarys to update Excel file.
                HoldIsFoundInRevitTSheets.AddRange(NotTranslatedSheets);
            }

            //Sheet Hold was found
            if (HoldIsFoundInRevitTSheets.Count > 0)
            {
                ExcelSheet Excel = new ExcelSheet();
                Excel.Update(Sheet_IDEnglishChineseDict, HoldIsFoundInRevitTSheets, path, 3, BuildingColor);
            }
            return(Result.Succeeded);
        }
예제 #16
0
        /// <summary>
        /// Create the email file
        /// </summary>
        /// <returns></returns>
        public string CreateEmail()
        {
            string EmailFrom = Email;

            if (string.IsNullOrEmpty(EmailFrom))
            {
                EmailFrom = Properties.Settings.Default.EmailSupport;
            }

            var mailMessage = new MailMessage(EmailFrom, Properties.Settings.Default.EmailSupport);

            mailMessage.Subject    = "Revit Support";
            mailMessage.IsBodyHtml = true;

            // Create the email body of text
            string message = "<p>&lt;<i>PLEASE DESCRIBE ISSUE HERE</i>&gt;</p><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><p>";

            message = message + "<b><i>DIAGNOSTIC INFO</i></b><br /><b>===============</b>";
            message = message + "<br /><b>USER:</b> " + UserFullName;
            message = message + "<br /><b>EMAIL:</b> " + Email;
            message = message + "<br /><b>COMPUTER:</b> " + Computer;
            message = message + "<br /><b>REVIT VERSION:</b> " + RevitVersion;
            message = message + "<br /><b>TOTAL MEMORY:</b> " + totalMemory;
            message = message + "<br /><b>FREE MEMORY:</b> " + freeMemory;
            message = message + "<br /><br /><b>LOCAL MODEL:</b> " + LocalModel;
            message = message + "<br /><b>CENTRAL MODEL:</b> " + CentralModel;
            message = message + "<br /><b>MODEL FILE SIZE:</b> " + modelSize;
            message = message + "<br /><b>REVIT SERVER ACCELERATOR:</b> " + RevitServerAccelerator;
            message = message + "<br /><br /><br />";

            mailMessage.Body = message;

            // Attach the journal file
            string journalFile = app.RecordingJournalFilename;

            File.Copy(journalFile, Path.GetTempPath() + Path.GetFileName(journalFile), true);
            mailMessage.Attachments.Add(new Attachment(Path.GetTempPath() + Path.GetFileName(journalFile)));

            // Attach the central log file
            if (doc.GetWorksharingCentralModelPath() != null)
            {
                try
                {
                    string centralPath = ModelPathUtils.ConvertModelPathToUserVisiblePath(doc.GetWorksharingCentralModelPath());
                    string centralName = Path.GetFileName(centralPath);
                    string centralLog  = centralName.Replace(".rvt", @"_backup\" +
                                                             Path.GetFileNameWithoutExtension(centralPath) + ".slog");
                    File.Copy(centralLog, Path.GetTempPath() + Path.GetFileName(centralLog), true);
                    mailMessage.Attachments.Add(new Attachment(Path.GetTempPath() + Path.GetFileName(centralLog)));
                }
                catch
                {
                }
            }

            //Save the email file
            string emailFile = Path.GetTempPath() + Path.GetRandomFileName() + ".eml";

            mailMessage.Save(emailFile);

            return(emailFile);
        }
예제 #17
0
        public Document OpenNewLocalFromModelPath(ModelPath centralPath, ModelPath localPath, List <string> InverseWorksetList, out bool isWrkShared)
        {
            List <WorksetId> worksetsToOpen = new List <WorksetId>();
            // First set to close all worksets
            WorksetConfiguration worksetConfig  = new WorksetConfiguration(WorksetConfigurationOption.CloseAllWorksets);
            OpenOptions          theOpenOptions = new OpenOptions();

            try {
                // Create the new local at the given path
                WorksharingUtils.CreateNewLocal(centralPath, localPath);
                // Select specific worksets to open
                // Get a list of worksets from the unopened document
                IList <WorksetPreview> worksets = WorksharingUtils.GetUserWorksetInfo(localPath);
                foreach (WorksetPreview preview in worksets)
                {
                    bool Include = true;
                    // The inverse list is the inverse of the worksets checked. In other
                    // words an exclusion list.
                    foreach (string ws in InverseWorksetList)
                    {
                        if (ws == "")
                        {
                            continue;
                        }
                        if (preview.Name.StartsWith(ws))
                        {
                            Include = false;
                            continue;
                        }
                        else
                        {
                        }
                    }
                    if (Include)
                    {
                        worksetsToOpen.Add(preview.Id);
                    }
                    else
                    {
                        //System.Windows.MessageBox.Show("Excluding " + preview.Name);
                    }
                }
                // Setup option to open the target worksets
                // then set specific ones to open
                worksetConfig.Open(worksetsToOpen);
                theOpenOptions.SetOpenWorksetsConfiguration(worksetConfig);
                // Now open the new local
                Document openedDoc = _app.OpenDocumentFile(localPath, theOpenOptions);

                isWrkShared = true;
                return(openedDoc);
            } catch (Exception ex) {
                System.Windows.MessageBox.Show("Opening the file from its location.\n\n" + ex.Message, "This Is Not A Workshared File");
            }
            // If here then not a workshared file.
            string   fname      = ModelPathUtils.ConvertModelPathToUserVisiblePath(centralPath);
            Document openedDocN = _app.OpenDocumentFile(fname);

            isWrkShared = false;
            return(openedDocN);
        }
예제 #18
0
        Result IExternalCommand.Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication  uiapp       = commandData.Application;
            UIDocument     uidoc       = uiapp.ActiveUIDocument;
            Application    app         = uiapp.Application;
            Document       doc         = uidoc.Document;
            List <Element> titleBlocks = new FilteredElementCollector(doc)
                                         .OfCategory(BuiltInCategory.OST_TitleBlocks)
                                         .WhereElementIsNotElementType()
                                         .ToElements()
                                         .ToList();

            List <ElementId> elt  = uidoc.Selection.GetElementIds().ToList();
            List <Element>   beta = new List <Element>();

            foreach (ElementId i in elt)
            {
                beta.Add(doc.GetElement(i));
            }
            ViewSheet a;

            a = doc.GetElement(elt.First()) as ViewSheet;
            ViewSet b = new ViewSet();
            List <List <Element> > elementOnSheet = new List <List <Element> >();


            for (int i = 0; i < elt.Count(); i++)
            {
                List <Element> sheetEl = new List <Element>();
                foreach (Element e in new FilteredElementCollector(doc).OwnedByView(elt[i]))
                {
                    sheetEl.Add(e);
                }
                elementOnSheet.Add(sheetEl);
            }
            List <Element> titleOnSheet = new List <Element>();


            for (int i = 0; i < elt.Count(); i++)
            {
                titleOnSheet.Add(null);
                foreach (Element e in elementOnSheet[i])
                {
                    foreach (Element tb in titleBlocks)
                    {
                        if (e.Id == tb.Id)
                        {
                            titleOnSheet[i] = tb;
                        }
                    }
                }
            }

            List <int> formatA = new List <int>();
            List <int> kratn   = new List <int>();
            List <int> knign   = new List <int>();

            for (int i = 0; i < titleOnSheet.Count(); i++)
            {
                try
                {
                    formatA.Add(titleOnSheet[i].LookupParameter("Формат А").AsInteger());
                    kratn.Add(titleOnSheet[i].LookupParameter("Кратность").AsInteger());
                    knign.Add(titleOnSheet[i].LookupParameter("Книжная ориентация").AsInteger());
                }
                catch (Exception)
                {
                }
            }
            string namePrefix = "Export";
            //string nameOfExportDWFX = "AutoExport " + DateTime.Now.Hour.ToString() + "_" + DateTime.Now.Minute.ToString() + "_" + DateTime.Now.Second.ToString();
            List <string>    viewName = new List <string>();
            List <ViewSheet> listNum  = new List <ViewSheet>();

            foreach (ElementId i in elt)
            {
                b.Insert(doc.GetElement(i) as ViewSheet);
                listNum.Add(doc.GetElement(i) as ViewSheet);
            }


            DWGExportOptions options = new DWGExportOptions();

            options.MergedViews = true;
            options.Colors      = ExportColorMode.TrueColorPerView;
            options.FileVersion = ACADVersion.R2013;
            //options.


            string dir = doc.PathName.Substring(0, doc.PathName.Length - doc.Title.Length - 4);


            ModelPath mp  = doc.GetWorksharingCentralModelPath();
            string    vmp = ModelPathUtils.ConvertModelPathToUserVisiblePath(mp);
            int       arr = 0;

            for (int i = vmp.Length - 1; i != 0; i--)
            {
                if (vmp.ElementAt(i) == '\\')
                {
                    arr = i;
                    break;
                }
            }


            //string newPath = Path.GetTempPath();
            string newPath = vmp.Substring(0, arr + 1) + "DWG";

            for (int i = 0; i < listNum.Count(); i++)
            {
                viewName.Add(newPath + listNum[i].SheetNumber + listNum[i].Name + ".dwfx");
            }
            string fileName = newPath + namePrefix + ".dwg";

            System.IO.DirectoryInfo printDir = System.IO.Directory.CreateDirectory(newPath);


            using (Transaction tr = new Transaction(doc, "MyExort"))

            {
                tr.Start();

                /*
                 * foreach (ViewSheet i in listNum)
                 * {
                 *      ViewSet vSet = new ViewSet();
                 *      vSet.Insert(i);
                 *
                 *      doc.Export(newPath, i.SheetNumber + i.Name,vSet, options);
                 * }
                 */
                doc.Export(newPath, "", elt, options);
                //doc.Export(newPath.Substring(0, newPath.Length - 1), namePrefix, b, options);
                tr.Commit();
            }

            //Form1 SheetControl = new Form1();
            //SheetControl.ShowDialog();
            //string[] amm=Directory.GetFiles(newPath+"\\");

            return(Result.Succeeded);
        }
예제 #19
0
        public async Task <string[]> HandleAsync(string request)
        {
            string[] result;

            Task <string[]> task;

            if (request == "FILEDIALOG")
            {
                task = _revitTask
                       .Run((app) =>
                {
                    //// var document = app.Document;

                    var dialog = new FileOpenDialog("Revit Files (*.rvt)|*.rvt");

                    var dialogResult = dialog.Show();

                    var modelPath = dialog.GetSelectedModelPath();

                    var path = ModelPathUtils
                               .ConvertModelPathToUserVisiblePath(modelPath);

                    return(new[] { path });
                });
            }
            else if (request == "VIEWLIST")
            {
                task = _revitTask
                       .Run((uiapp) =>
                {
                    if (uiapp.ActiveUIDocument?.Document == null)
                    {
                        return(new[] { "No opened documents" });
                    }

                    var document = uiapp.ActiveUIDocument.Document;

                    var plans = new FilteredElementCollector(document)
                                .WhereElementIsNotElementType()
                                .OfClass(typeof(View))
                                .Select(x => x.Name)
                                .ToArray();

                    return(plans);
                });
            }
            else
            {
                task = _revitTask
                       .Run(uiapp =>
                {
                    //// TaskDialog.Show("Deb", $"Requested: {request}");

                    var command = (PostableCommand)Enum.Parse(
                        typeof(PostableCommand),
                        request,
                        true);

                    var id = RevitCommandId
                             .LookupPostableCommandId(command);

                    uiapp.PostCommand(id);

                    return(new[] { $"Successfully posted command {command}" });
                });
            }


            try
            {
                result = await task;
            }
            catch (Exception e)
            {
                result = new[] { $"{e.Message} in {e.StackTrace}" };
            }

            return(result);
        }
예제 #20
0
 public SynchronizeViewModel(Document document)
 {
     _document   = document;
     Synchronize = InitializationModel();
     Synchronize.CentralModelPath = ModelPathUtils.ConvertModelPathToUserVisiblePath(_document.GetWorksharingCentralModelPath());
 }
        /// <summary>
        /// Reports the results of loads from the DB server (SampleExternalResourceServer).
        /// This method should be implemented to provide UI to communicate success or failure
        /// of a particular external resource load operation to the user.
        /// </summary>
        /// <param name="doc">The Revit model into which the External Resource was loaded.
        /// </param>
        /// <param name="loadDataList">Contains a list of ExternalResourceLoadData with results
        /// for all external resources loaded by the DB server.  It is possible for the DB server
        /// to have loaded more than one resource (for example, loading several linked files
        /// when a host file is opened by the user).
        /// </param>
        public void HandleLoadResourceResults(Document doc, IList <ExternalResourceLoadData> loadDataList)
        {
            foreach (ExternalResourceLoadData data in loadDataList)
            {
                ExternalResourceType resourceType = data.ExternalResourceType;

                // This message will be posted in a dialog box at the end of this method.
                String myMessage = String.Empty;

                ExternalResourceLoadContext loadContext        = data.GetLoadContext();
                ExternalResourceReference   desiredRef         = data.GetExternalResourceReference();
                ExternalResourceReference   currentlyLoadedRef = loadContext.GetCurrentlyLoadedReference();

                LoadOperationType loadType = loadContext.LoadOperationType;

                switch (loadType)
                {
                case LoadOperationType.Automatic:
                    myMessage = "This is an Automatic load operation. ";
                    break;

                case LoadOperationType.Explicit:
                    myMessage = "This is an Explicit load operation. ";
                    break;

                default:
                    myMessage = "There is no load type information!! ";
                    break;
                }


                bool bUnrecognizedStatus = false;
                if (data.LoadStatus == ExternalResourceLoadStatus.ResourceAlreadyCurrent)
                {
                    if (data.GetLoadContext().LoadOperationType == LoadOperationType.Explicit)
                    {
                        string resourcePath = currentlyLoadedRef.InSessionPath;
                        myMessage += "\n No new changes to load for link: " + resourcePath;
                    }
                    else
                    {
                        continue;
                    }
                }
                else if (data.LoadStatus == ExternalResourceLoadStatus.Uninitialized)
                {
                    myMessage += "\n The load status is uninitialized - this generally shouldn't happen";
                }
                else if (data.LoadStatus == ExternalResourceLoadStatus.Failure)
                {
                    myMessage += "\n The load failed and the reason is unknown.";
                }
                else if (data.LoadStatus == ExternalResourceLoadStatus.Success)
                {
                    if (resourceType == ExternalResourceTypes.BuiltInExternalResourceTypes.KeynoteTable)
                    {
                        string resourcePath = data.GetExternalResourceReference().InSessionPath;
                        myMessage += "\n Version " + data.GetLoadContent().Version + " of keynote data \'" + resourcePath + "\' has been loaded successfully";
                    }
                    else if (resourceType == ExternalResourceTypes.BuiltInExternalResourceTypes.RevitLink)
                    {
                        string          resourcePath    = data.GetExternalResourceReference().InSessionPath;
                        LinkLoadContent ldrlc           = (LinkLoadContent)(data.GetLoadContent());
                        string          destinationPath = ModelPathUtils.ConvertModelPathToUserVisiblePath(ldrlc.GetLinkDataPath());
                        myMessage += "\n Version " + data.GetLoadContent().Version +
                                     " of the file: " + resourcePath +
                                     " has been downloaded into the cached folder: " + destinationPath +
                                     " for this Revit Link.";
                    }
                }
                else
                {
                    myMessage          += "Unrecognized external resource load status.";
                    bUnrecognizedStatus = true;
                }


                if (!bUnrecognizedStatus && resourceType == ExternalResourceTypes.BuiltInExternalResourceTypes.RevitLink)
                {
                    // For Revit links, the UI server can also obtain a RevitLinkLoadResult which contains detailed
                    // information about the status of the attempt to load the local copy of the link into Revit.
                    LinkLoadContent ldrlc      = (LinkLoadContent)(data.GetLoadContent());
                    LinkLoadResult  loadResult = ldrlc.GetLinkLoadResult();
                    if (loadResult != null)
                    {
                        myMessage += "\n LinkLoadResultType: " + loadResult.LoadResult.ToString("g");
                    }
                }
                System.Windows.Forms.MessageBox.Show(myMessage, "UI Server for SDK Sample External Resource Server");
            }
        }
예제 #22
0
        public bool IsCentralFile(Document document)
        {
            var isCentralFile = false;

            try
            {
                var centralModelPath = document.GetWorksharingCentralModelPath();
                if (null != centralModelPath)
                {
                    var userVisiblePath = ModelPathUtils.ConvertModelPathToUserVisiblePath(centralModelPath);
                    if (centralModelPath.ServerPath)
                    {
                        const string revitServerPrefix = "RSN://";
                        const string a360Prefix        = "A360://";
                        var          relativePath      = "";

                        if (userVisiblePath.Contains(revitServerPrefix))
                        {
                            var serverLocation = revitServerPrefix + centralModelPath.CentralServerPath;
                            relativePath = userVisiblePath.Substring(serverLocation.Length);
                        }
                        else if (userVisiblePath.Contains(a360Prefix))
                        {
                            var serverLocation = a360Prefix + centralModelPath.CentralServerPath;
                            relativePath = userVisiblePath.Substring(serverLocation.Length);
                        }

                        var serverPath  = new ServerPath(centralModelPath.CentralServerPath, relativePath);
                        var centralGUID = document.Application.GetWorksharingCentralGUID(serverPath);
                        if (centralGUID != Guid.Empty)
                        {
                            var currentModelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(document.PathName);
                            if (null != currentModelPath)
                            {
                                var currentGuid = currentModelPath.GetModelGUID();
                                if (currentGuid != Guid.Empty)
                                {
                                    if (centralGUID.Equals(currentGuid))
                                    {
                                        isCentralFile = true;
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        if (document.PathName.ToUpper() == userVisiblePath.ToUpper())
                        {
                            isCentralFile = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.AppendLog(LogMessageType.EXCEPTION, ex.Message);
                MessageBox.Show("Failed to determine whether the file is central or local.\n" + ex.Message, "IsCentralFile", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            return(isCentralFile);
        }
예제 #23
0
        private bool FindINI()
        {
            bool result = false;

            try
            {
                string masterFilePath = "";
                if (doc.IsWorkshared)
                {
                    ModelPath modelPath = doc.GetWorksharingCentralModelPath();
                    masterFilePath = ModelPathUtils.ConvertModelPathToUserVisiblePath(modelPath);
                    if (string.IsNullOrEmpty(masterFilePath))
                    {
                        masterFilePath = doc.PathName;
                    }
                }
                else
                {
                    masterFilePath = doc.PathName;
                }

                if (!string.IsNullOrEmpty(masterFilePath))
                {
                    iniPath = masterFilePath.Replace(".rvt", "_mass.ini");
                    if (!File.Exists(iniPath))
                    {
                        FileStream fs = File.Create(iniPath);

                        TaskDialog taskdialog = new TaskDialog("Mass from Room");
                        taskdialog.MainInstruction   = "Select a directory for the Mass families.";
                        taskdialog.MainContent       = "If you choose the option for the default directory,\n the new folder will be created in the same directory as the Revit project.";
                        taskdialog.AllowCancellation = true;
                        taskdialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Select a directory.");
                        taskdialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Default Directory.");

                        TaskDialogResult tResult = taskdialog.Show();

                        if (TaskDialogResult.CommandLink1 == tResult)
                        {
                            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
                            folderBrowserDialog.Description         = "Select a directory that you want to use as the default.";
                            folderBrowserDialog.ShowNewFolderButton = true;

                            if (DialogResult.OK == folderBrowserDialog.ShowDialog())
                            {
                                massFolder = folderBrowserDialog.SelectedPath;
                            }
                        }
                        else if (TaskDialogResult.CommandLink2 == tResult)
                        {
                            massFolder = Path.GetDirectoryName(masterFilePath) + @"\RoomMass";
                            if (!Directory.Exists(massFolder))
                            {
                                Directory.CreateDirectory(massFolder);
                            }
                        }

                        using (StreamWriter sw = new StreamWriter(fs))
                        {
                            sw.WriteLine("MassFolder:" + massFolder);
                        }
                        fs.Close();
                    }

                    if (File.Exists(iniPath))
                    {
                        result = true;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to find INI file. \n" + ex.Message, "INIDataManager : FindINI", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                result = false;
            }
            return(result);
        }
예제 #24
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);
        }
예제 #25
0
        /// <summary>
        /// Remove DWF links from model and return
        /// the total number of deleted elements.
        /// </summary>
        int RemoveDwfLinkUsingExternalFileUtils(
            Document doc)
        {
            List <ElementId> idsToDelete
                = new List <ElementId>();

            ICollection <ElementId> ids = ExternalFileUtils
                                          .GetAllExternalFileReferences(doc);

            foreach (ElementId id in ids)
            {
                Element e = doc.GetElement(id);

                Debug.Print(Util.ElementDescription(e));

                ExternalFileReference xr = ExternalFileUtils
                                           .GetExternalFileReference(doc, id);

                ExternalFileReferenceType xrType
                    = xr.ExternalFileReferenceType;

                if (xrType == ExternalFileReferenceType.DWFMarkup)
                {
                    ModelPath xrPath = xr.GetPath();

                    string path = ModelPathUtils
                                  .ConvertModelPathToUserVisiblePath(xrPath);

                    if (path.EndsWith(".dwf") ||
                        path.EndsWith(".dwfx"))
                    {
                        idsToDelete.Add(id);
                    }
                }
            }

            int n = idsToDelete.Count;

            ICollection <ElementId> idsDeleted = null;

            if (0 < n)
            {
                using (Transaction t = new Transaction(doc))
                {
                    t.Start("Delete DWFx Links");

                    idsDeleted = doc.Delete(idsToDelete);

                    t.Commit();
                }
            }

            int m = (null == idsDeleted)
        ? 0
        : idsDeleted.Count;

            Debug.Print(string.Format(
                            "Selected {0} DWF external file reference{1}, "
                            + "{2} element{3} successfully deleted.",
                            n, Util.PluralSuffix(n), m, Util.PluralSuffix(m)));

            return(m);
        }
예제 #26
0
        /// <summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application
        /// which contains data related to the command,
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application
        /// which will be displayed if a failure or cancellation is returned by
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command.
        /// A result of Succeeded means that the API external method functioned as expected.
        /// Cancelled can be used to signify that the user cancelled the external operation
        /// at some point. Failure should be returned if the application is unable to proceed with
        /// the operation.</returns>
        public virtual Result Execute(ExternalCommandData commandData
                                      , ref string message, ElementSet elements)
        {
            try
            {
                // check user selection
                var uidoc = commandData.Application.ActiveUIDocument;
                var doc   = uidoc.Document;

                ISet <ElementId> parts = null;

                using (Transaction tr = new Transaction(doc, "Optimise Preselection"))
                {
                    tr.Start();
                    ICollection <ElementId> selElems = uidoc.Selection.GetElementIds();
                    if (selElems.Count > 0)
                    {
                        parts = new HashSet <ElementId>(selElems);
                    }

                    tr.Commit();
                }

                if (parts == null)
                {
                    MessageBox.Show("Select parts to export.");
                    return(Result.Failed);
                }

                var callingFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

                var saveAsDlg = new FileSaveDialog("CSV Files (*.csv)|*.csv");

                saveAsDlg.InitialFileName = callingFolder + "\\geomExport";
                saveAsDlg.Title           = "Save Part Geometry As";
                var result = saveAsDlg.Show();

                if (result == ItemSelectionDialogResult.Canceled)
                {
                    return(Result.Cancelled);
                }

                string filename = ModelPathUtils.ConvertModelPathToUserVisiblePath(saveAsDlg.GetSelectedModelPath());
                string ext      = Path.GetExtension(filename);
                filename = Path.GetFileNameWithoutExtension(filename);

                int partcount = 1, exported = 0;

                foreach (ElementId eid in parts)
                {
                                // get all rods and kist with rods
                                FabricationPart part = doc.GetElement(eid) as FabricationPart;
                    if (part != null)
                    {
                        Options options = new Options();
                        options.DetailLevel = ViewDetailLevel.Coarse;

                        IList <Mesh> main = getMeshes(part.get_Geometry(options));
                        IList <Mesh> ins  = getMeshes(part.GetInsulationLiningGeometry());

                        int mlp = 0;
                        foreach (Mesh mesh in main)
                        {
                            String file = String.Concat(filename, partcount.ToString(), "-main-", (++mlp).ToString(), ext);
                            if (exportMesh(file, mesh))
                            {
                                exported++;
                            }
                        }

                        int ilp = 0;
                        foreach (Mesh mesh in ins)
                        {
                            String file = String.Concat(filename, partcount.ToString(), "-ins-", (++ilp).ToString(), ext);
                            if (exportMesh(file, mesh))
                            {
                                exported++;
                            }
                        }
                    }
                    partcount++;
                }

                String res         = (exported > 0) ? "Export was successful" : "Nothing was exported";
                String manywritten = String.Format("{0} Parts were exported", exported);

                TaskDialog td = new TaskDialog("Export Part Mesh Geometry")
                {
                    MainIcon          = TaskDialogIcon.TaskDialogIconInformation,
                    TitleAutoPrefix   = false,
                    MainInstruction   = res,
                    MainContent       = manywritten,
                    AllowCancellation = false,
                    CommonButtons     = TaskDialogCommonButtons.Ok
                };

                td.Show();

                return(Result.Succeeded);
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return(Result.Failed);
            }
        }
예제 #27
0
        public void Execute(UIApplication app)
        {
            Transaction transaction = null;

            try
            {
                this.calculator = new SimpleCalculator();

                this.App = app;
                this.Doc = app.ActiveUIDocument.Document;
                using (transaction = new Transaction(Doc))
                {
                    transaction.Start("auto arrangement");
                    this.symbol = GetFamilySymbol();
                    var ids = app.ActiveUIDocument.Selection.GetElementIds().ToList();
                    if (ids == null || ids.Count == 0)
                    {
                        TaskDialog.Show("Ошибка", "Помещения не выбраны");
                        return;
                    }
                    if (symbol == null)
                    {
                        var dr = TaskDialog.Show("Ошибка загрузки", "Семейство не найдено. Выберите путь...", TaskDialogCommonButtons.Ok | TaskDialogCommonButtons.Cancel, TaskDialogResult.Ok);
                        if (dr == TaskDialogResult.Ok)
                        {
                            FileOpenDialog fileOpenDialog = new FileOpenDialog("revit files (*.rfa)|*.rfa|All files (*.*)|*.*");
                            var            fodr           = fileOpenDialog.Show();
                            if (fodr == ItemSelectionDialogResult.Confirmed)
                            {
                                var model  = fileOpenDialog.GetSelectedModelPath();
                                var path   = ModelPathUtils.ConvertModelPathToUserVisiblePath(model);
                                var loaded = Doc.LoadFamilySymbol(path, this.FamilySymbolName, out FamilySymbol loadedFS);
                                if (!loaded)
                                {
                                    TaskDialog.Show("Ошибка загрузки семейства", "Не найдено семейство с названием \"ИП 212-64 прот. R3 ПАСН.425232.038\"");
                                    return;
                                }
                                else
                                {
                                    this.symbol = loadedFS;
                                }
                            }
                        }
                    }
                    if (!this.symbol.IsActive)
                    {
                        this.symbol.Activate();
                    }
                    ids.ForEach(CreateDevices);
                    transaction.Commit();
                }
            }
            catch (Exception ex)
            {
                var s = ex.Message;
                if (transaction != null && transaction.GetStatus() != TransactionStatus.Uninitialized)
                {
                    transaction.RollBack();
                }
            }
        }
예제 #28
0
        Stream(ArrayList data, Document doc)
        {
            data.Add(new Snoop.Data.ClassSeparator(typeof(Document)));

            data.Add(new Snoop.Data.Object("Application", doc.Application));
            data.Add(new Snoop.Data.String("Title", doc.Title));
            data.Add(new Snoop.Data.String("Pathname", doc.PathName));
            data.Add(new Snoop.Data.Object("Settings", doc.Settings));
            data.Add(new Snoop.Data.BindingMap("Parameter bindings", doc.ParameterBindings));
            data.Add(new Snoop.Data.Enumerable("Phases", doc.Phases));
            data.Add(new Snoop.Data.Bool("Reactions are up to date", doc.ReactionsAreUpToDate));
            data.Add(new Snoop.Data.Object("Active View", doc.ActiveView));
            data.Add(new Snoop.Data.String("Display unit system", doc.DisplayUnitSystem.ToString()));
            data.Add(new Snoop.Data.Object("Active project location", doc.ActiveProjectLocation));
            data.Add(new Snoop.Data.Object("Project information", doc.ProjectInformation));
            data.Add(new Snoop.Data.Enumerable("Project locations", doc.ProjectLocations));
            data.Add(new Snoop.Data.Object("Site location", doc.SiteLocation));
            data.Add(new Snoop.Data.Object("Project unit", doc.GetUnits()));
            try
            {
                Transaction t = new Transaction(doc);
                t.SetName("PlanTopologies");
                t.Start();
                data.Add(new Snoop.Data.Enumerable("Plan topologies", doc.PlanTopologies));
                t.RollBack();
            }
            catch (Autodesk.Revit.Exceptions.ArgumentException)
            {
                //catch exception caused because of inability to create transaction for linked document
            }
            ElementSet elemSet1                    = new ElementSet();
            FilteredElementCollector fec           = new FilteredElementCollector(doc);
            ElementClassFilter       wallFilter    = new ElementClassFilter(typeof(Wall));
            ElementClassFilter       notWallFilter = new ElementClassFilter(typeof(Wall), true);
            LogicalOrFilter          orFilter      = new LogicalOrFilter(wallFilter, notWallFilter);

            fec.WherePasses(orFilter);
            List <Element> elements = fec.ToElements() as List <Element>;

            foreach (Element element in elements)
            {
                elemSet1.Insert(element);
            }

            data.Add(new Snoop.Data.ElementSet("Elements", elemSet1));

            data.Add(new Snoop.Data.Bool("Is modified", doc.IsModified));
            data.Add(new Snoop.Data.Bool("Is workshared", doc.IsWorkshared));

            data.Add(new Snoop.Data.Bool("Is A Family Document", doc.IsFamilyDocument));
            if (doc.IsFamilyDocument)
            {
                data.Add(new Snoop.Data.Object("Family Manager", doc.FamilyManager));
                data.Add(new Snoop.Data.Object("Owner Family", doc.OwnerFamily));
            }

            if (doc.GetWorksharingCentralModelPath() != null)
            {
                data.Add(new Snoop.Data.String("Worksharing central model path", ModelPathUtils.ConvertModelPathToUserVisiblePath(doc.GetWorksharingCentralModelPath())));
            }
            else
            {
                data.Add(new Snoop.Data.String("Worksharing central model path", ""));
            }
            data.Add(new Snoop.Data.Object("Print manager", doc.PrintManager));

            //data.Add(new Snoop.Data.Enumerable("Print settings", doc.PrintSettings));  //TBD: Behaves badly, need to investigate.

            data.Add(new Snoop.Data.Enumerable("Beam system types", collectorOfClass <BeamSystemType>(doc)));
            data.Add(new Snoop.Data.Enumerable("Continuous footing types", collectorOfClass <ContFootingType>(doc)));
            data.Add(new Snoop.Data.Enumerable("Curtain system types", collectorOfClass <CurtainSystemType>(doc)));
            data.Add(new Snoop.Data.Enumerable("Dimension types", collectorOfClass <DimensionType>(doc)));
            data.Add(new Snoop.Data.Enumerable("Electrical equipment types", collectorOfCategoryForFamilySymbol(doc, BuiltInCategory.OST_ElectricalEquipment)));
            data.Add(new Snoop.Data.Enumerable("Fascia types", collectorOfClass <FasciaType>(doc)));
            data.Add(new Snoop.Data.Enumerable("Floor types", collectorOfClass <FloorType>(doc)));
            data.Add(new Snoop.Data.Enumerable("Grid types", collectorOfClass <GridType>(doc)));
            data.Add(new Snoop.Data.Enumerable("Gutter types", collectorOfClass <GutterType>(doc)));
            data.Add(new Snoop.Data.Enumerable("Level types", collectorOfClass <LevelType>(doc)));
            data.Add(new Snoop.Data.Enumerable("Lighting device types", collectorOfCategoryForFamilySymbol(doc, BuiltInCategory.OST_LightingDevices)));
            data.Add(new Snoop.Data.Enumerable("Lighting fixture types", collectorOfCategoryForFamilySymbol(doc, BuiltInCategory.OST_LightingFixtures)));
            data.Add(new Snoop.Data.Enumerable("Mechanical equipment types", collectorOfCategoryForFamilySymbol(doc, BuiltInCategory.OST_MechanicalEquipment)));
            data.Add(new Snoop.Data.Enumerable("Mullion types", doc.MullionTypes));
            data.Add(new Snoop.Data.Enumerable("Panel types", collectorOfClass <PanelType>(doc)));
            data.Add(new Snoop.Data.Enumerable("Annotation symbol types", collectorForAnnotationSymbolTypes(doc)));
            data.Add(new Snoop.Data.Enumerable("Text note types", collectorOfClass <TextNoteType>(doc)));
            data.Add(new Snoop.Data.Enumerable("Rebar bar types", collectorOfClass <RebarBarType>(doc)));
            data.Add(new Snoop.Data.Enumerable("Rebar cover types", collectorOfClass <RebarCoverType>(doc)));
            data.Add(new Snoop.Data.Enumerable("Rebar hook types", collectorOfClass <RebarHookType>(doc)));
            data.Add(new Snoop.Data.Enumerable("Rebar shapes", collectorOfClass <RebarShape>(doc)));
            data.Add(new Snoop.Data.Enumerable("Roof types", collectorOfClass <RoofType>(doc)));
            data.Add(new Snoop.Data.Enumerable("Room tag types", collectorOfCategoryForFamilySymbol(doc, BuiltInCategory.OST_RoomTags)));
            data.Add(new Snoop.Data.Enumerable("Slab edge types", collectorOfClass <SlabEdgeType>(doc)));
            data.Add(new Snoop.Data.Enumerable("Space tag types", collectorOfCategoryForFamilySymbol(doc, BuiltInCategory.OST_MEPSpaceTags)));
            data.Add(new Snoop.Data.Enumerable("Spot dimension types", collectorOfClass <SpotDimensionType>(doc)));
            data.Add(new Snoop.Data.Enumerable("Text note types", collectorOfClass <TextNoteType>(doc)));
            data.Add(new Snoop.Data.Enumerable("Title blocks", collectorOfCategoryForFamilySymbol(doc, BuiltInCategory.OST_TitleBlocks)));
            data.Add(new Snoop.Data.Enumerable("Truss types", collectorOfCategoryForFamilySymbol(doc, BuiltInCategory.OST_Truss)));
            data.Add(new Snoop.Data.Enumerable("View sheet sets", collectorOfClass <ViewSheetSet>(doc)));
            data.Add(new Snoop.Data.Enumerable("Wall types", collectorOfClass <WallType>(doc)));
        }
예제 #29
0
        /// <summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application
        /// which contains data related to the command,
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application
        /// which will be displayed if a failure or cancellation is returned by
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command.
        /// A result of Succeeded means that the API external method functioned as expected.
        /// Cancelled can be used to signify that the user cancelled the external operation
        /// at some point. Failure should be returned if the application is unable to proceed with
        /// the operation.</returns>
        public virtual Result Execute(ExternalCommandData commandData
                                      , ref string message, ElementSet elements)
        {
            try
            {
                // check user selection
                var uidoc              = commandData.Application.ActiveUIDocument;
                var doc                = uidoc.Document;
                var collection         = uidoc.Selection.GetElementIds();
                var hasFabricationPart = false;

                using (var trans = new Transaction(doc, "Change Spool Name"))
                {
                    trans.Start();

                    foreach (var elementId in collection)
                    {
                        var part = doc.GetElement(elementId) as FabricationPart;
                        if (part != null)
                        {
                            hasFabricationPart = true;
                            part.SpoolName     = "My Spool";
                        }
                    }

                    trans.Commit();
                }

                if (hasFabricationPart == false)
                {
                    message = "Select at least one fabrication part";
                    return(Result.Failed);
                }

                var callingFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

                var saveAsDlg = new FileSaveDialog("PCF Files (*.pcf)|*.pcf");

                saveAsDlg.InitialFileName = callingFolder + "\\pcfExport";
                saveAsDlg.Title           = "Export To PCF";
                var result = saveAsDlg.Show();

                if (result == ItemSelectionDialogResult.Canceled)
                {
                    return(Result.Cancelled);
                }

                var fabParts = collection.ToList();

                string filename = ModelPathUtils.ConvertModelPathToUserVisiblePath(saveAsDlg.GetSelectedModelPath());

                FabricationUtils.ExportToPCF(doc, fabParts, filename);

                TaskDialog td = new TaskDialog("Export to PCF")
                {
                    MainIcon          = TaskDialogIcon.TaskDialogIconInformation,
                    TitleAutoPrefix   = false,
                    MainInstruction   = "Export to PCF was successful",
                    MainContent       = filename,
                    AllowCancellation = false,
                    CommonButtons     = TaskDialogCommonButtons.Ok
                };

                td.Show();

                return(Result.Succeeded);
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return(Result.Failed);
            }
        }
예제 #30
0
        /// <summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application
        /// which contains data related to the command,
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application
        /// which will be displayed if a failure or cancellation is returned by
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command.
        /// A result of Succeeded means that the API external method functioned as expected.
        /// Cancelled can be used to signify that the user cancelled the external operation
        /// at some point. Failure should be returned if the application is unable to proceed with
        /// the operation.</returns>
        public virtual Result Execute(ExternalCommandData commandData
                                      , ref string message, ElementSet elements)
        {
            try
            {
                // check user selection
                var uidoc      = commandData.Application.ActiveUIDocument;
                var doc        = uidoc.Document;
                var elementIds = new HashSet <ElementId>();
                uidoc.Selection.GetElementIds().ToList().ForEach(x => elementIds.Add(x));

                var hasFabricationParts = false;
                foreach (var elementId in elementIds)
                {
                    var part = doc.GetElement(elementId) as FabricationPart;
                    if (part != null)
                    {
                        hasFabricationParts = true;
                        break;
                    }
                }

                if (hasFabricationParts == false)
                {
                    message = "Select at least one fabrication part";
                    return(Result.Failed);
                }

                var callingFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                var saveAsDlg     = new FileSaveDialog("MAJ Files (*.maj)|*.maj");
                saveAsDlg.InitialFileName = callingFolder + "\\majExport";
                saveAsDlg.Title           = "Export To MAJ";
                var result = saveAsDlg.Show();

                if (result == ItemSelectionDialogResult.Canceled)
                {
                    return(Result.Cancelled);
                }

                string filename = ModelPathUtils.ConvertModelPathToUserVisiblePath(saveAsDlg.GetSelectedModelPath());

                ISet <ElementId> exported = FabricationPart.SaveAsFabricationJob(doc, elementIds, filename, new FabricationSaveJobOptions(true));
                if (exported.Count > 0)
                {
                    TaskDialog td = new TaskDialog("Export to MAJ")
                    {
                        MainIcon          = TaskDialogIcon.TaskDialogIconInformation,
                        TitleAutoPrefix   = false,
                        MainInstruction   = string.Concat("Export to MAJ was successful - ", exported.Count.ToString(), " Parts written"),
                        MainContent       = filename,
                        AllowCancellation = false,
                        CommonButtons     = TaskDialogCommonButtons.Ok
                    };

                    td.Show();
                }

                return(Result.Succeeded);
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return(Result.Failed);
            }
        }