Beispiel #1
0
        /// <summary>
        /// If Family is marked as Completed it will post the data to MC.
        /// </summary>
        /// <param name="app"></param>
        public void SubmitFamily(UIApplication app)
        {
            var doc = app.ActiveUIDocument.Document;

            if (doc == null || doc.IsFamilyDocument)
            {
                return;
            }

            var centralPath   = FileInfoUtil.GetCentralFilePath(doc);
            var familyStatsId = MissionControlSetup.FamilyData[centralPath].Id;

            if (string.IsNullOrEmpty(familyStatsId))
            {
                return;
            }

            FamilyTask.CompletedOn = DateTime.UtcNow;
            FamilyTask.CompletedBy = Environment.UserName.ToLower();

            if (!ServerUtilities.Post(FamilyTask,
                                      "families/" + familyStatsId + "/family/" + FamilyItem.Name + "/updatetask/" + FamilyTask.Id, out FamilyData unused))
            {
                Log.AppendLog(LogMessageType.ERROR, "Failed to submit Family Task Completed update.");
            }
        }
Beispiel #2
0
        /// <summary>
        /// Unregisters all updaters that might have been registered when we checked into Mission Control.
        /// Also cleans up any static variables that might cause issues on re-open.
        /// </summary>
        /// <param name="doc">Revit Document.</param>
        public static void UnregisterUpdaters(Document doc)
        {
            var centralPath = FileInfoUtil.GetCentralFilePath(doc);

            if (MissionControlSetup.Configurations.ContainsKey(centralPath))
            {
                var currentConfig = MissionControlSetup.Configurations[centralPath];
                foreach (var updater in currentConfig.Updaters)
                {
                    if (!updater.IsUpdaterOn)
                    {
                        continue;
                    }

                    if (string.Equals(updater.UpdaterId,
                                      AppCommand.Instance.DoorUpdaterInstance.UpdaterGuid.ToString(), StringComparison.OrdinalIgnoreCase))
                    {
                        AppCommand.Instance.DoorUpdaterInstance.Unregister(doc);
                    }
                    else if (string.Equals(updater.UpdaterId,
                                           AppCommand.Instance.DtmUpdaterInstance.UpdaterGuid.ToString(), StringComparison.OrdinalIgnoreCase))
                    {
                        AppCommand.Instance.DtmUpdaterInstance.Unregister(doc);
                    }
                }
            }

            // (Konrad) Clean up all static classes that would be holding any relevant information.
            // This would cause issues in case that user closes a MissionControl registered project without
            // closing Revit app. These static classes retain their values, and then would trick rest of app
            // to think that it is registered in Mission Control.
            MissionControlSetup.ClearAll();
            AppCommand.ClearAll();
        }
Beispiel #3
0
        private void RegisterUpdatersOnOpen(object source, DocumentOpenedEventArgs args)
        {
            try
            {
                if (null != args.Document && !args.IsCancelled())
                {
                    Document doc = args.Document;
                    if (doc.IsWorkshared)
                    {
                        string centralPath = FileInfoUtil.GetCentralFilePath(doc);
                        if (!string.IsNullOrEmpty(centralPath))
                        {
                            //serch for config
                            SingleSessionMonitor.OpenedDocuments.Add(centralPath, doc);

                            LogUtil.AppendLog(centralPath + " Opned.");
                            if (configDictionary.ContainsKey(centralPath))
                            {
                                bool applied = ApplyConfiguration(doc, configDictionary[centralPath]);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogUtil.AppendLog("RegisterUpdatersOnOpen:" + ex.Message);
            }
        }
 public void Execute(UIApplication app)
 {
     try
     {
         if (null != currentConfig)
         {
             DocumentSet docSet = app.Application.Documents;
             foreach (Document doc in docSet)
             {
                 if (doc.IsWorkshared)
                 {
                     string centralPath = FileInfoUtil.GetCentralFilePath(doc);
                     var    fileFound   = from file in currentConfig.files where file.centralPath.ToLower() == centralPath.ToLower() select file;
                     if (fileFound.Count() > 0)
                     {
                         //apply config
                         MessageBoxResult msgResult = MessageBox.Show("Configuration has been changed.\n" + centralPath, socketMessage, MessageBoxButton.OKCancel, MessageBoxImage.Question);
                         if (msgResult == MessageBoxResult.OK)
                         {
                             ApplyConfiguration(doc, centralPath);
                         }
                     }
                 }
             }
         }
     }
     catch (Exception ex)
     {
         string message = ex.Message;
     }
 }
Beispiel #5
0
        /// <summary>
        /// Handler for Document Synchronizing event.
        /// </summary>
        private static void OnDocumentSynchronizing(object source, DocumentSynchronizingWithCentralEventArgs args)
        {
            try
            {
                IsSynching = true; // disables DTM Tool
                FailureProcessor.IsSynchronizing = true;
                if (args.Document == null)
                {
                    return;
                }

                var doc         = args.Document;
                var centralPath = FileInfoUtil.GetCentralFilePath(doc);
                if (string.IsNullOrEmpty(centralPath))
                {
                    return;
                }

                SynchTime["from"] = DateTime.UtcNow;
            }
            catch (Exception ex)
            {
                Log.AppendLog(LogMessageType.EXCEPTION, ex.Message);
            }
        }
 public WarningItem(FailureMessage msg, Document doc)
 {
     CentralPath     = FileInfoUtil.GetCentralFilePath(doc).ToLower();
     FailingElements = msg.GetFailingElements().Select(x => doc.GetElement(x).UniqueId).ToList();
     DescriptionText = msg.GetDescriptionText();
     // (Konrad) I am not setting created by here on purpose. This will be set when warnings are reconciled.
     UniqueId = msg.GetFailureDefinitionId().Guid + string.Join("", FailingElements);
 }
 public WarningItem(FailureMessageAccessor msg, Document doc)
 {
     CentralPath     = FileInfoUtil.GetCentralFilePath(doc).ToLower();
     FailingElements = msg.GetFailingElementIds().Select(x => doc.GetElement(x).UniqueId).ToList();
     DescriptionText = msg.GetDescriptionText();
     CreatedBy       = Environment.UserName.ToLower();
     UniqueId        = msg.GetFailureDefinitionId().Guid + string.Join("", FailingElements);
 }
Beispiel #8
0
        public void Execute(UpdaterData data)
        {
            try
            {
                Document doc         = data.GetDocument();
                string   centralPath = FileInfoUtil.GetCentralFilePath(doc);
                string   configId    = "";
                if (AppCommand.Instance.ConfigDictionary.ContainsKey(centralPath))
                {
                    configId = AppCommand.Instance.ConfigDictionary[centralPath]._id;
                }

                List <ElementId> addedElementIds = data.GetAddedElementIds().ToList();
                foreach (ElementId id in addedElementIds)
                {
                    Element element = doc.GetElement(id);
                    if (null != element)
                    {
                        BuiltInCategory bltCategory = (BuiltInCategory)element.Category.Id.IntegerValue;
                        if (bltCategory == BuiltInCategory.OST_RvtLinks)
                        {
                            RunCategoryActionItems(centralPath, data, element);
                        }
                        else
                        {
                            AddCategoryCache(configId, centralPath, element);
                        }
                    }
                }

                List <ElementId> modifiedElementIds = data.GetModifiedElementIds().ToList();
                foreach (ElementId id in modifiedElementIds)
                {
                    Element element = doc.GetElement(id);
                    if (null != element)
                    {
                        RunCategoryActionItems(centralPath, data, element);
                    }
                }

                List <ElementId> deletedElementIds = data.GetDeletedElementIds().ToList();
                foreach (ElementId id in deletedElementIds)
                {
                    //Process Failure
                    var infoFound = from info in reportingElements where info.CentralPath == centralPath && info.ReportingElementId == id select info;
                    if (infoFound.Count() > 0)
                    {
                        ReportFailure(doc, infoFound.First());
                    }
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message;
                LogUtil.AppendLog("DTMUpdater-Execute:" + ex.Message);
            }
        }
Beispiel #9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="app"></param>
        private static void GetCentralPath(UIApplication app)
        {
            var doc = app.ActiveUIDocument.Document;

            CentralPath = FileInfoUtil.GetCentralFilePath(doc);

            Messenger.Default.Send(new CentralPathObtained
            {
                CentralPath = CentralPath
            });
        }
Beispiel #10
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            var uiApp = commandData.Application;
            var doc   = uiApp.ActiveUIDocument.Document;

            Log.AppendLog(LogMessageType.INFO, "Started");

            try
            {
                // (Konrad) We are gathering information about the addin use. This allows us to
                // better maintain the most used plug-ins or discontinue the unused ones.
                AddinUtilities.PublishAddinLog(
                    new AddinLog("MissionControl-WebsiteLink", commandData.Application.Application.VersionNumber));

                var launchHome = false;
                if (!string.IsNullOrWhiteSpace(doc.PathName))
                {
                    var centralPath = FileInfoUtil.GetCentralFilePath(doc);
                    if (!string.IsNullOrWhiteSpace(centralPath))
                    {
                        if (MissionControlSetup.Projects.ContainsKey(centralPath))
                        {
                            var id = MissionControlSetup.Projects[centralPath].Id;
                            Process.Start(ServerUtilities.RestApiBaseUrl + "/#/projects/edit/" + id);
                        }
                        else
                        {
                            launchHome = true;
                        }
                    }
                    else
                    {
                        launchHome = true;
                    }
                }
                else
                {
                    launchHome = true;
                }

                if (launchHome)
                {
                    Process.Start(ServerUtilities.RestApiBaseUrl + "/#/home");
                }
            }
            catch (Exception e)
            {
                Log.AppendLog(LogMessageType.EXCEPTION, e.Message);
            }

            Log.AppendLog(LogMessageType.INFO, "Ended");
            return(Result.Succeeded);
        }
Beispiel #11
0
        /// <summary>
        /// Document Synchronized handler.
        /// </summary>
        private static void OnDocumentSynchronized(object source, DocumentSynchronizedWithCentralEventArgs args)
        {
            try
            {
                IsSynching = false; // enables DTM Tool again
                var doc = args.Document;
                if (doc == null)
                {
                    return;
                }

                var centralPath = FileInfoUtil.GetCentralFilePath(doc);
                if (string.IsNullOrEmpty(centralPath))
                {
                    return;
                }

                FailureProcessor.IsSynchronizing = false;

                // (Konrad) If project is not registered with MongoDB let's skip this
                if (MissionControlSetup.Projects.ContainsKey(centralPath) &&
                    MissionControlSetup.Configurations.ContainsKey(centralPath))
                {
                    var config = MissionControlSetup.Configurations[centralPath];
                    foreach (var updater in config.Updaters)
                    {
                        if (!updater.IsUpdaterOn)
                        {
                            continue;
                        }

                        if (string.Equals(updater.UpdaterId, Properties.Resources.HealthReportTrackerGuid, StringComparison.OrdinalIgnoreCase))
                        {
                            Tools.MissionControl.MissionControl.ProcessModels(ActionType.Synch, doc, centralPath);
                            Tools.MissionControl.MissionControl.ProcessWorksets(ActionType.Synch, doc, centralPath);
#if RELEASE2015 || RELEASE2016 || RELEASE2017
                            // (Konrad) We are not going to process warnings here.
#else
                            Tools.MissionControl.MissionControl.ProcessWarnings(ActionType.Synch, doc, centralPath);
#endif
                        }
                        else if (string.Equals(updater.UpdaterId, Properties.Resources.SheetsTrackerGuid, StringComparison.OrdinalIgnoreCase))
                        {
                            Tools.MissionControl.MissionControl.ProcessSheets(ActionType.Synch, doc, centralPath);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.AppendLog(LogMessageType.EXCEPTION, ex.Message);
            }
        }
Beispiel #12
0
        private void UnregisterUpdaterOnClosing(object source, DocumentClosingEventArgs args)
        {
            try
            {
                Document doc = args.Document;
                if (doc.IsWorkshared)
                {
                    string centralPath = FileInfoUtil.GetCentralFilePath(doc);
                    if (!string.IsNullOrEmpty(centralPath))
                    {
                        SingleSessionMonitor.CloseFile(centralPath);

                        if (configDictionary.ContainsKey(centralPath))
                        {
                            Configuration configFound = configDictionary[centralPath];
                            foreach (ProjectUpdater updater in configFound.updaters)
                            {
                                if (!updater.isUpdaterOn)
                                {
                                    continue;
                                }
                                if (updater.updaterId.ToLower() == doorUpdater.UpdaterGuid.ToString().ToLower())
                                {
                                    doorUpdater.Unregister(doc);
                                }
                                else if (updater.updaterId.ToLower() == dtmUpdater.UpdaterGuid.ToString().ToLower())
                                {
                                    dtmUpdater.Unregister(doc);
                                }
                                else if (updater.updaterId.ToLower() == revisionUpdater.UpdaterGuid.ToString().ToLower())
                                {
                                    revisionUpdater.Unregister(doc);
                                }
                            }
                            configDictionary.Remove(centralPath);
                        }

                        if (SingleSessionMonitor.OpenedDocuments.Count == 0)
                        {
                            DisconnectSocket();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogUtil.AppendLog("UnregisterUpdaterOnClosing:" + ex.Message);
            }
        }
        /// <summary>
        ///
        /// </summary>
        public void LaunchWebsite()
        {
            AppCommand.EnqueueTask(app =>
            {
                var doc         = app.ActiveUIDocument.Document;
                var centralPath = FileInfoUtil.GetCentralFilePath(doc);
                if (string.IsNullOrEmpty(centralPath))
                {
                    return;
                }

                if (MissionControlSetup.Projects.ContainsKey(centralPath))
                {
                    Process.Start("http://missioncontrol.hok.com/#/projects/healthreport/" + MissionControlSetup.Projects[centralPath].Id);
                }
            });
        }
Beispiel #14
0
        /// <summary>
        ///
        /// </summary>
        public void LaunchWebsite()
        {
            AppCommand.EnqueueTask(app =>
            {
                var doc         = app.ActiveUIDocument.Document;
                var centralPath = FileInfoUtil.GetCentralFilePath(doc);
                if (string.IsNullOrWhiteSpace(centralPath))
                {
                    return;
                }

                if (MissionControlSetup.Projects.ContainsKey(centralPath))
                {
                    Process.Start(ServerUtilities.RestApiBaseUrl + "/#/projects/healthreport/" + MissionControlSetup.Projects[centralPath].Id);
                }
            });
        }
Beispiel #15
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="data"></param>
        public void Execute(UpdaterData data)
        {
            try
            {
                if (AppCommand.IsSynching)
                {
                    return;
                }
                var doc         = data.GetDocument();
                var centralPath = FileInfoUtil.GetCentralFilePath(doc);

                foreach (var id in data.GetModifiedElementIds())
                {
                    var infoFound = _reportingElements.FirstOrDefault(x => x.CentralPath == centralPath && x.ReportingElementId == id);
                    if (infoFound == null)
                    {
                        continue;
                    }

                    var element = doc.GetElement(id);
                    if (element != null)
                    {
                        RunCategoryActionItems(centralPath, data, element, infoFound);
                    }
                }

                foreach (var id in data.GetDeletedElementIds())
                {
                    //Process Failure
                    var infoFound = _reportingElements.FirstOrDefault(x => x.CentralPath == centralPath && x.ReportingElementId == id);
                    if (infoFound != null)
                    {
                        ReportFailure(doc, infoFound);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.AppendLog(LogMessageType.EXCEPTION, ex.Message);
            }
        }
Beispiel #16
0
        /// <summary>
        /// Method to "check into" mission control. It posts all initial data, and stores all needed references.
        /// </summary>
        /// <param name="doc"></param>
        public void CheckIn(Document doc)
        {
            try
            {
                var centralPath = FileInfoUtil.GetCentralFilePath(doc);

                // (Konrad) We can publish a file path to the DB.
                // That will make it easier to create Configurations.
                // Valid file is:
                // - not detached
                // - not a family
                // - is workshared
                // - is saved on the network, revit server or bim 360 server
                if (!doc.IsDetached && !doc.IsFamilyDocument && doc.IsWorkshared && FilePathItem.IsValidFilePath(centralPath))
                {
                    if (!ServerUtilities.Post(new FilePathItem(centralPath, doc.Application.VersionNumber), "filepaths/add", out FilePathItem unused))
                    {
                        Log.AppendLog(LogMessageType.ERROR, "Failed to publish File Path: " + centralPath);
                    }
                }

                // (Konrad) Get Configuration/Project.
                if (!ServerUtilities.GetByCentralPath(centralPath, "configurations/centralpath", out Configuration configFound))
                {
                    DisableMissionControl();
                    return;
                }

                if (!ServerUtilities.Get("projects/configid/" + configFound.Id, out Project projectFound))
                {
                    DisableMissionControl();
                    return;
                }

                if (MissionControlSetup.Configurations.ContainsKey(centralPath))
                {
                    MissionControlSetup.Configurations.Remove(centralPath);
                }
                MissionControlSetup.Configurations.Add(centralPath, configFound);

                if (MissionControlSetup.Projects.ContainsKey(centralPath))
                {
                    MissionControlSetup.Projects.Remove(centralPath);
                }
                MissionControlSetup.Projects.Add(centralPath, projectFound);

                // (Konrad) This might be a good time to let users know that Mission Control is ready to go.
                AppCommand.CommunicatorHandler.Status  = Status.Success;
                AppCommand.CommunicatorHandler.Message = "Successfully connected to Mission Control!";
                AppCommand.CommunicatorHandler.Request.Make(RequestId.ReportStatus);
                AppCommand.CommunicatorEvent.Raise();

                // (Konrad) Register Updaters that are in the config file.
                CommunicatorUtilities.LaunchCommunicator();
                ApplyConfiguration(doc);
#if RELEASE2015 || RELEASE2016 || RELEASE2017
                // (Konrad) We are not going to process warnings here.
#else
                CollectWarnings(doc);
#endif
                EnableMissionControl();

                Log.AppendLog(LogMessageType.INFO, "Mission Control check in succeeded.");
            }
            catch (Exception ex)
            {
                Log.AppendLog(LogMessageType.EXCEPTION, ex.Message);
            }
        }
        public MissionControlSocket(Document doc)
        {
            _alive = false;
            _t     = new Thread(() =>
            {
                try
                {
                    var centralPath = FileInfoUtil.GetCentralFilePath(doc);

                    var options = new IO.Options
                    {
                        IgnoreServerCertificateValidation = true,
                        AutoConnect = true,
                        ForceNew    = true,
                        Upgrade     = false
                    };

                    options.Transports = ImmutableList.Create <string>(WebSocket.NAME);

                    _socket = IO.Socket(BaseUrlLocal, options);

                    _socket.On(Quobject.SocketIoClientDotNet.Client.Socket.EVENT_CONNECT,
                               () =>
                    {
                        _socket.Emit("room", centralPath.ToLower());
                        Log.AppendLog(LogMessageType.INFO, "Connected to Mission Control socket.");
                        Log.AppendLog(LogMessageType.INFO, "Joined Room: " + centralPath.ToLower());
                    });

                    _socket.On(Quobject.SocketIoClientDotNet.Client.Socket.EVENT_DISCONNECT,
                               () => { Log.AppendLog(LogMessageType.INFO, "Disconnected from Mission Control socket."); });

                    _socket.On(Quobject.SocketIoClientDotNet.Client.Socket.EVENT_CONNECT_TIMEOUT,
                               () => { Log.AppendLog(LogMessageType.INFO, "Mission Control socket connection timed out."); });

                    #region Family Tasks

                    _socket.On("task_deleted", body =>
                    {
                        if (body != null)
                        {
                            var data       = JObject.FromObject(body);
                            var deletedIds = data.Property("deletedIds") != null
                                ? data["deletedIds"].ToObject <List <string> >()
                                : new List <string>();
                            var familyName = data.Property("familyName") != null
                                ? data["familyName"].ToObject <string>()
                                : string.Empty;
                            if (!deletedIds.Any() || string.IsNullOrEmpty(familyName))
                            {
                                return;
                            }

                            Messenger.Default.Send(new FamilyTaskDeletedMessage
                            {
                                FamilyName = familyName,
                                DeletedIds = deletedIds
                            });
                        }
                        else
                        {
                            Log.AppendLog(LogMessageType.ERROR, "task_deleted: Data was null!");
                        }
                    });

                    _socket.On("familyTask_added", body =>
                    {
                        if (body != null)
                        {
                            var data       = JObject.FromObject(body);
                            var familyName = data.Property("familyName") != null
                                ? data["familyName"].ToObject <string>()
                                : string.Empty;
                            var task = data.Property("task") != null ? data["task"].ToObject <FamilyTask>() : null;
                            if (string.IsNullOrEmpty(familyName) || task == null)
                            {
                                return;
                            }

                            // (Konrad) We want to filter out tasks that don't belong to us or to this model.
                            // We can use "collectionId" to identify the model since that is tied to centralPath.
                            if (!string.Equals(task.AssignedTo, Environment.UserName, StringComparison.CurrentCultureIgnoreCase))
                            {
                                return;
                            }

                            Messenger.Default.Send(new FamilyTaskAddedMessage {
                                FamilyName = familyName, Task = task
                            });
                        }
                        else
                        {
                            Log.AppendLog(LogMessageType.ERROR, "familyTask_added: Data was null!");
                        }
                    });

                    _socket.On("familyTask_updated", body =>
                    {
                        if (body != null)
                        {
                            var data       = JObject.FromObject(body);
                            var familyName = data.Property("familyName") != null
                                ? data["familyName"].ToObject <string>()
                                : string.Empty;
                            var task = data.Property("task") != null ? data["task"].ToObject <FamilyTask>() : null;
                            if (task == null || string.IsNullOrEmpty(familyName))
                            {
                                return;
                            }

                            Messenger.Default.Send(new FamilyTaskUpdatedMessage {
                                FamilyName = familyName, Task = task
                            });
                        }
                        else
                        {
                            Log.AppendLog(LogMessageType.ERROR, "familyTask_updated: Data was null!");
                        }
                    });

                    #endregion

                    #region Sheet Tasks

                    _socket.On("sheetTask_added", body =>
                    {
                        if (body != null)
                        {
                            var data       = JObject.FromObject(body);
                            var sheetsData = data.Property("body") != null ? data["body"].ToObject <SheetData>() : null;
                            var sheetId    = data.Property("sheetId") != null
                                ? data["sheetId"].ToObject <string>()
                                : string.Empty;
                            var taskId = data.Property("taskId") != null
                                ? data["taskId"].ToObject <string>()
                                : string.Empty;
                            if (sheetsData == null || string.IsNullOrEmpty(sheetId) || string.IsNullOrEmpty(taskId))
                            {
                                return;
                            }

                            var sheet = sheetsData.Sheets.FirstOrDefault(x =>
                                                                         string.Equals(x.Id, sheetId, StringComparison.Ordinal));
                            var task = sheet?.Tasks.FirstOrDefault(x =>
                                                                   string.Equals(x.Id, taskId, StringComparison.Ordinal));

                            // (Konrad) We want to filter out tasks that don't belong to us or to this model.
                            // We can use "collectionId" to identify the model since that is tied to centralPath.
                            if (task == null || !string.Equals(task.AssignedTo, Environment.UserName, StringComparison.OrdinalIgnoreCase))
                            {
                                return;
                            }

                            Messenger.Default.Send(new SheetsTaskAddedMessage
                            {
                                Sheet       = sheet,
                                Task        = task,
                                CentralPath = centralPath
                            });
                        }
                        else
                        {
                            Log.AppendLog(LogMessageType.ERROR, "sheetTask_added: Data was null!");
                        }
                    });

                    _socket.On("sheetTask_updated", body =>
                    {
                        if (body != null)
                        {
                            var data       = JObject.FromObject(body);
                            var sheetsData = data.Property("body") != null ? data["body"].ToObject <SheetData>() : null;
                            var sheetId    = data.Property("sheetId") != null
                                ? data["sheetId"].ToObject <string>()
                                : string.Empty;
                            var taskId = data.Property("taskId") != null
                                ? data["taskId"].ToObject <string>()
                                : string.Empty;
                            if (sheetsData == null || string.IsNullOrEmpty(sheetId) || string.IsNullOrEmpty(taskId))
                            {
                                return;
                            }

                            var sheet = sheetsData.Sheets.FirstOrDefault(x =>
                                                                         string.Equals(sheetId, x.Id, StringComparison.Ordinal));
                            var task = sheet?.Tasks.FirstOrDefault(x =>
                                                                   string.Equals(x.Id, taskId, StringComparison.Ordinal));

                            if (task == null)
                            {
                                return;
                            }

                            Messenger.Default.Send(new SheetsTaskUpdatedMessage
                            {
                                Sheet       = sheet,
                                Task        = task,
                                CentralPath = centralPath
                            });
                        }
                        else
                        {
                            Log.AppendLog(LogMessageType.ERROR, "sheetTask_updated: Data was null!");
                        }
                    });

                    _socket.On("sheetTask_deleted", body =>
                    {
                        if (body != null)
                        {
                            var data    = JObject.FromObject(body);
                            var sheetId = data.Property("sheetId") != null
                                ? data["sheetId"].ToObject <string>()
                                : string.Empty;
                            var deletedIds = data.Property("deletedIds") != null
                                ? data["deletedIds"].ToObject <List <string> >()
                                : new List <string>();
                            if (string.IsNullOrEmpty(sheetId) || !deletedIds.Any())
                            {
                                return;
                            }

                            Messenger.Default.Send(new SheetsTaskDeletedMessage
                            {
                                SheetId     = sheetId,
                                DeletedIds  = deletedIds,
                                CentralPath = centralPath
                            });
                        }
                        else
                        {
                            Log.AppendLog(LogMessageType.ERROR, "sheetTask_deleted: Data was null!");
                        }
                    });

                    _socket.On("sheetTask_sheetsAdded", body =>
                    {
                        if (body != null)
                        {
                            var data       = JObject.FromObject(body);
                            var sheetsData = data.Property("body") != null ? data["body"].ToObject <SheetData>() : null;
                            var sheetsIds  = data.Property("sheetIds") != null
                                ? data["sheetIds"].ToObject <List <string> >()
                                : new List <string>();
                            if (sheetsData == null || !sheetsIds.Any())
                            {
                                return;
                            }

                            Messenger.Default.Send(new SheetTaskSheetsCreatedMessage
                            {
                                Sheets      = sheetsData.Sheets.Where(x => sheetsIds.Contains(x.Id)).ToList(),
                                CentralPath = centralPath
                            });
                        }
                        else
                        {
                            Log.AppendLog(LogMessageType.ERROR, "sheetTask_sheetsAdded: Data was null!");
                        }
                    });

                    _socket.On("sheetTask_sheetDeleted", body =>
                    {
                        if (body != null)
                        {
                            var data    = JObject.FromObject(body);
                            var sheetId = data.Property("sheetId") != null
                                ? data["sheetId"].ToObject <string>()
                                : string.Empty;
                            var deletedIds = data.Property("deletedIds") != null
                                ? data["deletedIds"].ToObject <List <string> >()
                                : new List <string>();
                            if (string.IsNullOrEmpty(sheetId) || !deletedIds.Any())
                            {
                                return;
                            }

                            Messenger.Default.Send(new SheetTaskSheetDeletedMessage
                            {
                                SheetId     = sheetId,
                                DeletedIds  = deletedIds,
                                CentralPath = centralPath
                            });
                        }
                        else
                        {
                            Log.AppendLog(LogMessageType.ERROR, "sheetTask_sheetDeleted: Data was null!");
                        }
                    });

                    #endregion

                    while (_alive)
                    {
                        Thread.Sleep(100);
                    }
                }
                catch (ThreadInterruptedException)
                {
                    _socket.Disconnect();
                    Log.AppendLog(LogMessageType.ERROR, "Socket was canceled. Most likely because Document was closed.");
                }
                catch (Exception e)
                {
                    Log.AppendLog(LogMessageType.ERROR, e.Message);
                }
            })
            {
                IsBackground = true,
                Priority     = ThreadPriority.BelowNormal
            };
        }
Beispiel #18
0
        private DTMConfigurations GetConfiguration(Document doc)
        {
            DTMConfigurations config = new DTMConfigurations();

            try
            {
                string projectFileId = DataStorageUtil.GetProjectFileId(doc).ToString();
                string centralPath   = FileInfoUtil.GetCentralFilePath(doc);
                if (projectFileId == Guid.Empty.ToString())
                {
                    //first time use
                    List <ProjectFile> items = ServerUtil.GetProjectFiles("centralpath/" + centralPath);
                    if (items.Count > 0)
                    {
                        //import file info by central path
                        ProjectFile projectFile = items.First();
                        bool        found       = ServerUtil.GetConfiguration(projectFile._id, out config);
                        projectFileId = projectFile._id;
                    }
                    else
                    {
                        //create file info
                        projectFileId = Guid.NewGuid().ToString();

                        Project        projectInfo  = FileInfoUtil.GetProjectInfo(centralPath);
                        List <Project> projects     = ServerUtil.GetProjects("");
                        var            projectFound = from p in projects where p.ProjectNumber == projectInfo.ProjectNumber && p.ProjectName == projectInfo.ProjectName select p;
                        if (projectFound.Count() > 0)
                        {
                            projectInfo = projectFound.First();
                        }
                        else
                        {
                            projectInfo._id = Guid.NewGuid().ToString();
                        }

                        ProjectFile pFile = new ProjectFile(projectFileId, centralPath, projectInfo._id, projectInfo);
                        config.ProjectFileInfo = pFile;

                        ProjectUpdater pUpdater = new ProjectUpdater(Guid.NewGuid().ToString(), DTMUpdater.updaterGuid.ToString(), dtmUpdater.GetUpdaterName(), addInGuid.ToString(), addInName, false, pFile._id);
                        foreach (string categoryName in updaterCategories)
                        {
                            CategoryTrigger catTrigger = new CategoryTrigger(Guid.NewGuid().ToString(), categoryName, pUpdater._id, false, Environment.UserName, DateTime.Now);
                            pUpdater.CategoryTriggers.Add(catTrigger);
                        }
                        config.ProjectUpdaters.Add(pUpdater);

                        string         content = "";
                        string         errMsg  = "";
                        HttpStatusCode status  = ServerUtil.PostConfiguration(out content, out errMsg, config);
                    }

                    bool stored = DataStorageUtil.StoreProjectFileId(doc, new Guid(projectFileId));
                }
                else
                {
                    bool found = ServerUtil.GetConfiguration(projectFileId, out config);
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message;
                MessageBox.Show("Failed to get configuration.\n" + ex.Message, "Get Configuration from Database", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            return(config);
        }
Beispiel #19
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="data"></param>
        public void Execute(UpdaterData data)
        {
            try
            {
                var doc = data.GetDocument();
                if (data.GetModifiedElementIds().Count > 0)
                {
                    var doorId       = data.GetModifiedElementIds().First();
                    var doorInstance = doc.GetElement(doorId) as FamilyInstance;
                    if (null != doorInstance)
                    {
                        var pushParameter = doorInstance.LookupParameter(pushParamName);

                        if (null != pushParameter)
                        {
                            if (data.IsChangeTriggered(doorId, Element.GetChangeTypeParameter(pushParameter)))
                            {
                                var pushValue = pushParameter.AsValueString();
                                if (!pushValue.Contains("Approach"))
                                {
                                    DoorFailure.IsDoorFailed        = true;
                                    DoorFailure.FailingDoorId       = doorId;
                                    DoorFailure.CurrentDoc          = doc;
                                    FailureProcessor.IsFailureFound = true;

                                    var dr = MessageBox.Show(pushValue + " is not a correct value for the parameter " + pushParamName, "Invalid Door Parameter.", MessageBoxButton.OK, MessageBoxImage.Information);
                                }
                            }
                        }
                        var pullParameter = doorInstance.LookupParameter(pullParamName);
                        if (null != pullParameter)
                        {
                            if (data.IsChangeTriggered(doorId, Element.GetChangeTypeParameter(pullParameter)))
                            {
                                var pullValue = pullParameter.AsValueString();
                                if (!pullValue.Contains("Approach"))
                                {
                                    DoorFailure.IsDoorFailed        = true;
                                    DoorFailure.FailingDoorId       = doorId;
                                    FailureProcessor.IsFailureFound = true;

                                    var dr = MessageBox.Show(pullValue + " is not a correct value for the parameter " + pullParamName, "Invalid Door Parameter.", MessageBoxButton.OK, MessageBoxImage.Information);
                                }
                            }
                        }
                        var caParameter = doorInstance.LookupParameter(stateCAParamName);
                        if (null != caParameter)
                        {
                            if (data.IsChangeTriggered(doorId, Element.GetChangeTypeParameter(caParameter)))
                            {
                                var centralPath = FileInfoUtil.GetCentralFilePath(doc);
                                if (MissionControlSetup.Projects.ContainsKey(centralPath))
                                {
                                    var project = MissionControlSetup.Projects[centralPath];
                                    if (project.Address.State == "CA")
                                    {
                                        caParameter.Set(1);
                                    }
                                    else
                                    {
                                        caParameter.Set(0);
                                    }
                                }
                            }
                        }
                    }
                }
                else if (data.GetAddedElementIds().Count > 0)
                {
                    var doorId       = data.GetAddedElementIds().First();
                    var doorInstance = doc.GetElement(doorId) as FamilyInstance;
                    if (null != doorInstance)
                    {
                        var caParameter = doorInstance.LookupParameter(stateCAParamName);
                        if (null != caParameter)
                        {
                            var centralPath = FileInfoUtil.GetCentralFilePath(doc);
                            if (MissionControlSetup.Projects.ContainsKey(centralPath))
                            {
                                var project = MissionControlSetup.Projects[centralPath];
                                if (project.Address.State == "CA")
                                {
                                    caParameter.Set(1);
                                }
                                else
                                {
                                    caParameter.Set(0);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.AppendLog(LogMessageType.EXCEPTION, ex.Message);
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public ObservableCollection <DimensionWrapper> CollectDimensionOverrides()
        {
            var dInstances = new FilteredElementCollector(_doc)
                             .OfClass(typeof(Dimension))
                             .WhereElementIsNotElementType()
                             .Cast <Dimension>();

            // (Konrad) There is a user override in Configuration that controls what dimension overrides are ignored
            var centralPath = FileInfoUtil.GetCentralFilePath(_doc);
            var config      = MissionControlSetup.Configurations.ContainsKey(centralPath)
                ? MissionControlSetup.Configurations[centralPath]
                : null;

            var dimensionValueCheck = new List <string> {
                "EQ"
            };                                                   //defaults

            if (config != null)
            {
                dimensionValueCheck = config.Updaters.First(x => string.Equals(x.UpdaterId,
                                                                               Properties.Resources.HealthReportTrackerGuid, StringComparison.OrdinalIgnoreCase)).UserOverrides.DimensionValueCheck.Values;
            }

            var units = _doc.GetUnits();
            var dims  = new List <DimensionWrapper>();

            foreach (var d in dInstances)
            {
                if (d.NumberOfSegments == 0)
                {
                    if (string.IsNullOrEmpty(d.ValueOverride))
                    {
                        continue;
                    }

                    // dim w/ zero segments
                    dims.Add(new DimensionWrapper(d)
                    {
                        DimensionId   = d.Id,
                        OwnerViewType = d.ViewSpecific
                            ? ((View)_doc.GetElement(d.OwnerViewId)).ViewType.ToString()
                            : string.Empty,
                        OwnerViewId         = d.OwnerViewId,
                        ValueString         = UnitFormatUtils.Format(units, d.DimensionType.UnitType, (double)d.Value, false, false),
                        IsValueOverrideHuge = EvaluateValueOverride(d.ValueOverride, d.Value),
                        IsVisible           = !dimensionValueCheck.Any(d.ValueOverride.Contains),
                        IsFiltered          = dimensionValueCheck.Any(d.ValueOverride.Contains)
                    });
                }
                else
                {
                    // dim w/ multiple segments
                    foreach (DimensionSegment s in d.Segments)
                    {
                        // not every segment has to be overriden
                        if (string.IsNullOrEmpty(s.ValueOverride))
                        {
                            continue;
                        }

                        dims.Add(new DimensionWrapper(s)
                        {
                            DimensionId   = d.Id,
                            OwnerViewType = d.ViewSpecific
                                ? ((View)_doc.GetElement(d.OwnerViewId)).ViewType.ToString()
                                : string.Empty,
                            OwnerViewId         = d.OwnerViewId,
                            ValueString         = UnitFormatUtils.Format(units, d.DimensionType.UnitType, (double)s.Value, false, false),
                            IsValueOverrideHuge = EvaluateValueOverride(s.ValueOverride, s.Value),
                            IsVisible           = !dimensionValueCheck.Any(s.ValueOverride.Contains),
                            IsFiltered          = dimensionValueCheck.Any(s.ValueOverride.Contains)
                        });
                    }
                }
            }

            return(new ObservableCollection <DimensionWrapper>(dims));
        }
Beispiel #21
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            var uiApp = commandData.Application;
            var doc   = uiApp.ActiveUIDocument.Document;

            Log.AppendLog(LogMessageType.INFO, "Started");

            try
            {
                // (Konrad) We are gathering information about the addin use. This allows us to
                // better maintain the most used plug-ins or discontiue the unused ones.
                AddinUtilities.PublishAddinLog(
                    new AddinLog("MissionControl-PublishFamilyData", commandData.Application.Application.VersionNumber));

                var pathName = doc.PathName;
                if (string.IsNullOrEmpty(pathName))
                {
                    Log.AppendLog(LogMessageType.ERROR, "Path is Empty. File was not saved yet.");
                    var dialog = new FamilyMonitorView
                    {
                        DataContext =
                            new FamilyMonitorViewModel(null,
                                                       "...establish a connection to Mission Control for unsaved files."),
                        CancelButton = { Visibility = Visibility.Collapsed }
                    };
                    dialog.ShowDialog();

                    return(Result.Failed);
                }

                var centralPath = FileInfoUtil.GetCentralFilePath(doc);
                if (string.IsNullOrEmpty(centralPath))
                {
                    Log.AppendLog(LogMessageType.ERROR, "Could not get Central Path.");
                    var dialog = new FamilyMonitorView
                    {
                        DataContext =
                            new FamilyMonitorViewModel(null,
                                                       "...get a Central File Path. Only Workshared projects can be added to Mission Control."),
                        CancelButton = { Visibility = Visibility.Collapsed }
                    };
                    dialog.ShowDialog();

                    return(Result.Failed);
                }

                if (!MissionControlSetup.Projects.ContainsKey(centralPath) ||
                    !MissionControlSetup.Configurations.ContainsKey(centralPath) ||
                    !MissionControlSetup.FamilyData.ContainsKey(centralPath))
                {
                    Log.AppendLog(LogMessageType.ERROR, "No Config Found.");
                    var dialog = new FamilyMonitorView
                    {
                        DataContext =
                            new FamilyMonitorViewModel(null,
                                                       "...find your project in Mission Control database. Please make sure that it was added."),
                        CancelButton = { Visibility = Visibility.Collapsed }
                    };
                    dialog.ShowDialog();

                    return(Result.Failed);
                }

                uiApp.Application.FailuresProcessing += FailureProcessing;
                var familiesId = MissionControlSetup.FamilyData[centralPath].Id;
                var model      = new FamilyMonitorModel(doc, MissionControlSetup.Configurations[centralPath], MissionControlSetup.Projects[centralPath], familiesId, centralPath);
                var viewModel  = new FamilyMonitorViewModel(model, "...make this any faster. Hang in there!")
                {
                    ExecuteFamilyPublish = true
                };
                var view = new FamilyMonitorView
                {
                    DataContext = viewModel,
                    CloseButton = { Visibility = Visibility.Collapsed }
                };
                var unused = new WindowInteropHelper(view)
                {
                    Owner = Process.GetCurrentProcess().MainWindowHandle
                };
                view.ShowDialog();
            }
            catch (Exception ex)
            {
                Log.AppendLog(LogMessageType.EXCEPTION, ex.Message);
            }

            uiApp.Application.FailuresProcessing -= FailureProcessing;
            Log.AppendLog(LogMessageType.INFO, "Ended");
            return(Result.Succeeded);
        }
Beispiel #22
0
        public void RefreshTriggers(Document doc, ProjectUpdater pUpdater)
        {
            try
            {
                string centralPath = FileInfoUtil.GetCentralFilePath(doc);
                string configId    = "";
                if (AppCommand.Instance.ConfigDictionary.ContainsKey(centralPath))
                {
                    configId = AppCommand.Instance.ConfigDictionary[centralPath]._id;
                }

                UpdaterRegistry.RemoveDocumentTriggers(updaterId, doc);

                var elementsToDelete = from eInfo in reportingElements where eInfo.CentralPath == centralPath select eInfo;
                if (elementsToDelete.Count() > 0)
                {
                    List <ReportingElementInfo> elementsInfo = elementsToDelete.ToList();
                    foreach (ReportingElementInfo eInfo in elementsInfo)
                    {
                        reportingElements.Remove(eInfo);
                    }
                }

                foreach (CategoryTrigger trigger in pUpdater.CategoryTriggers)
                {
                    if (trigger.isEnabled)
                    {
                        ElementCategoryFilter catFilter = new ElementCategoryFilter(catDictionary[trigger.categoryName]);
                        UpdaterRegistry.AddTrigger(updaterId, catFilter, Element.GetChangeTypeAny());
                        UpdaterRegistry.AddTrigger(updaterId, catFilter, Element.GetChangeTypeElementAddition());
                        UpdaterRegistry.AddTrigger(updaterId, catFilter, Element.GetChangeTypeElementDeletion());

                        if (trigger.categoryName == "Grids")
                        {
                            GridUtils.CollectGridExtents(doc, centralPath);
                            if (GridUtils.gridParameters.ContainsKey(centralPath))
                            {
                                foreach (ElementId paramId in GridUtils.gridParameters[centralPath])
                                {
                                    UpdaterRegistry.AddTrigger(updaterId, catFilter, Element.GetChangeTypeParameter(paramId));
                                }
                            }

                            FilteredElementCollector collector = new FilteredElementCollector(doc);
                            List <Element>           elements  = collector.WherePasses(catFilter).WhereElementIsNotElementType().ToElements().ToList();
                            foreach (Element element in elements)
                            {
                                ReportingElementInfo reportingInfo = new ReportingElementInfo(configId, updaterGuid.ToString(), centralPath, trigger.categoryName, trigger.description, element.Id, element.UniqueId);
                                reportingElements.Add(reportingInfo);
                            }
                        }
                        else if (trigger.categoryName == "Views")
                        {
                            FilteredElementCollector collector = new FilteredElementCollector(doc);
                            List <View> views         = collector.WherePasses(catFilter).WhereElementIsNotElementType().ToElements().Cast <View>().ToList();
                            var         viewTemplates = from view in views where view.IsTemplate select view;
                            if (viewTemplates.Count() > 0)
                            {
                                foreach (Element view in viewTemplates)
                                {
                                    ReportingElementInfo reportingInfo = new ReportingElementInfo(configId, updaterGuid.ToString(), centralPath, trigger.categoryName, trigger.description, view.Id, view.UniqueId);
                                    reportingElements.Add(reportingInfo);
                                }
                            }
                        }
                        else
                        {
                            FilteredElementCollector collector = new FilteredElementCollector(doc);
                            List <Element>           elements  = collector.WherePasses(catFilter).WhereElementIsNotElementType().ToElements().ToList();
                            foreach (Element element in elements)
                            {
                                ReportingElementInfo reportingInfo = new ReportingElementInfo(configId, updaterGuid.ToString(), centralPath, trigger.categoryName, trigger.description, element.Id, element.UniqueId);
                                reportingElements.Add(reportingInfo);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message;
                LogUtil.AppendLog("DTMUpdater-RefreshTriggers:" + ex.Message);
            }
        }
Beispiel #23
0
        /// <summary>
        /// Submits edits to a sheet.
        /// </summary>
        /// <param name="app"></param>
        private void UpdateSheet(UIApplication app)
        {
            var doc = app.ActiveUIDocument.Document;

            CentralPath = FileInfoUtil.GetCentralFilePath(doc);

            IsUpdatingSheet = true;
            app.Application.FailuresProcessing += FailureProcessing;

            var view = doc.GetElement(SheetItem.UniqueId) as ViewSheet;

            if (view != null)
            {
                if (WorksharingUtils.GetCheckoutStatus(doc, view.Id) == CheckoutStatus.OwnedByOtherUser)
                {
                    IsUpdatingSheet = false;
                    Messenger.Default.Send(new SheetTaskCompletedMessage
                    {
                        Completed   = false,
                        Message     = "Element owned by another user. Try reloading latest.",
                        CentralPath = CentralPath
                    });
                    return;
                }
                using (var trans = new Transaction(doc, "UpdateSheet"))
                {
                    trans.Start();
                    var action = "update";
                    try
                    {
                        if (SheetTask.IsDeleted)
                        {
                            action = "delete";
                            doc.Delete(view.Id);
                        }
                        else
                        {
                            view.get_Parameter(BuiltInParameter.SHEET_NUMBER)?.Set(SheetTask.Number);
                            view.get_Parameter(BuiltInParameter.SHEET_NAME)?.Set(SheetTask.Name);
                        }

                        trans.Commit();
                        IsUpdatingSheet = false;
                    }
                    catch (Exception e)
                    {
                        trans.RollBack();
                        IsUpdatingSheet = false;

                        Log.AppendLog(LogMessageType.EXCEPTION, "Failed to " + action + " sheet.");
                        Messenger.Default.Send(new SheetTaskCompletedMessage
                        {
                            Completed   = false,
                            Message     = e.Message,
                            CentralPath = CentralPath
                        });
                    }
                }
            }

            // (Konrad) We don't want Revit to keep triggering this even when we are not processing updates.
            app.Application.FailuresProcessing -= FailureProcessing;
        }
Beispiel #24
0
        /// <summary>
        /// Registers availble configuration based on Central Model path match.
        /// </summary>
        private static void ApplyConfiguration(Document doc)
        {
            try
            {
                var centralPath   = FileInfoUtil.GetCentralFilePath(doc);
                var config        = MissionControlSetup.Configurations[centralPath];
                var launchSockets = false;
                foreach (var updater in config.Updaters)
                {
                    if (!updater.IsUpdaterOn)
                    {
                        continue;
                    }

                    if (string.Equals(updater.UpdaterId, AppCommand.Instance.DoorUpdaterInstance.UpdaterGuid.ToString(),
                                      StringComparison.OrdinalIgnoreCase))
                    {
                        // (Konrad) We need to register updaters from within Revit context.
                        // That's why we are running this in the Idling Event.
                        AppCommand.EnqueueTask(app =>
                        {
                            AppCommand.Instance.DoorUpdaterInstance.Register(doc, updater);
                        });
                    }
                    else if (string.Equals(updater.UpdaterId, AppCommand.Instance.DtmUpdaterInstance.UpdaterGuid.ToString(),
                                           StringComparison.OrdinalIgnoreCase))
                    {
                        ProcessTriggerRecords(centralPath);

                        AppCommand.EnqueueTask(app =>
                        {
                            AppCommand.Instance.DtmUpdaterInstance.Register(doc, updater);
                        });

                        DTMTool.DtmSynchOverrides.CreateReloadLatestOverride();
                        DTMTool.DtmSynchOverrides.CreateSynchToCentralOverride();
                    }
                    else if (string.Equals(updater.UpdaterId, Properties.Resources.LinkUnloadTrackerGuid,
                                           StringComparison.OrdinalIgnoreCase))
                    {
                        AppCommand.EnqueueTask(app =>
                        {
                            LinkUnloadMonitor.LinkUnloadMonitor.CreateLinkUnloadOverride(app);
                        });
                    }
                    else if (string.Equals(updater.UpdaterId, Properties.Resources.SheetsTrackerGuid,
                                           StringComparison.OrdinalIgnoreCase))
                    {
                        ProcessSheets(ActionType.CheckIn, doc, centralPath);

                        launchSockets = true;
                    }
                    else if (string.Equals(updater.UpdaterId, Properties.Resources.HealthReportTrackerGuid,
                                           StringComparison.OrdinalIgnoreCase))
                    {
                        // (Konrad) These are read-only methods so they don't need to run in Revit context.
                        ProcessModels(ActionType.CheckIn, doc, centralPath);
                        ProcessWorksets(ActionType.CheckIn, doc, centralPath);
#if RELEASE2015 || RELEASE2016 || RELEASE2017
                        // (Konrad) We are not going to process warnings here.
#else
                        ProcessWarnings(ActionType.CheckIn, doc, centralPath);
#endif
                        ProcessFamilies(centralPath);
                        ProcessStyle(doc, centralPath);
                        ProcessLinks(doc, centralPath);
                        ProcessViews(doc, centralPath);
                        ProcessGroups(doc, centralPath);

                        launchSockets = true;
                    }
                }

                // (Konrad) This tool will reset Shared Parameters Location to one specified in Mission Control
                if (config.GetType().GetProperty("sharedParamMonitor") != null &&
                    config.SharedParamMonitor.IsMonitorOn)
                {
                    if (File.Exists(config.SharedParamMonitor.FilePath))
                    {
                        doc.Application.SharedParametersFilename = config.SharedParamMonitor.FilePath;
                    }
                    else
                    {
                        Log.AppendLog(LogMessageType.ERROR, "Failed to reset Shared Parameter location. Could not find file specified.");
                    }
                }

                if (launchSockets)
                {
                    // (Konrad) in order not to become out of synch with the database we need a way
                    // to communicate live updates from the database to task assistant/communicator
                    var socket = new MissionControlSocket(doc);
                    socket.Start();
                    AppCommand.Socket = socket;
                }

                // Publish user/machine info to be used by Zombie
                var userInfo = new UserItem
                {
                    User    = Environment.UserName.ToLower(),
                    Machine = Environment.MachineName
                };

                if (!ServerUtilities.Post(userInfo, "users/add", out ResponseCreated unused1))
                {
                    Log.AppendLog(LogMessageType.ERROR, "Failed to publish User/Machine Data.");
                }
            }
            catch (Exception ex)
            {
                Log.AppendLog(LogMessageType.EXCEPTION, ex.Message);
            }
        }
Beispiel #25
0
        /// <summary>
        /// Ovveride method for when user synchs to central.
        /// The goal here is to disable the DTM Tool and prevent pop-ups while synching.
        /// </summary>
        public static void OnSynchToCentral(object sender, ExecutedEventArgs args, SynchType synchType)
        {
            // (Konrad) This will disable the DTM Tool when we are synching to central.
            AppCommand.IsSynching = true;

            RevitCommandId commandId;

            switch (synchType)
            {
            case SynchType.Synch:
                commandId = RevitCommandId.LookupCommandId("ID_FILE_SAVE_TO_MASTER");
                break;

            case SynchType.SynchNow:
                commandId = RevitCommandId.LookupCommandId("ID_FILE_SAVE_TO_MASTER_SHORTCUT");
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(synchType), synchType, null);
            }
            if (commandId == null || !commandId.CanHaveBinding)
            {
                return;
            }

            AppCommand.EnqueueTask(app =>
            {
                try
                {
                    app.RemoveAddInCommandBinding(commandId);

                    switch (synchType)
                    {
                    case SynchType.Synch:
                        AppCommand.IsSynchOverriden = false;
                        break;

                    case SynchType.SynchNow:
                        AppCommand.IsSynchNowOverriden = false;
                        break;

                    default:
                        throw new ArgumentOutOfRangeException(nameof(synchType), synchType, null);
                    }
                }
                catch (Exception e)
                {
                    Log.AppendLog(LogMessageType.EXCEPTION, e.Message);
                }
            });

            AppCommand.EnqueueTask(app =>
            {
                // (Konrad) We can now post the same Command we were overriding since the override is OFF.
                app.PostCommand(commandId);

                // (Konrad) Once the command executes this will turn the override back ON.
                AppCommand.IsSynching = false;

                var doc         = app.ActiveUIDocument.Document;
                var centralPath = FileInfoUtil.GetCentralFilePath(doc);
                if (string.IsNullOrEmpty(centralPath))
                {
                    return;
                }

                // (Konrad) Let's turn the synch command override back on.
                var config = MissionControlSetup.Configurations[centralPath];
                foreach (var updater in config.Updaters)
                {
                    if (!updater.IsUpdaterOn)
                    {
                        continue;
                    }

                    if (string.Equals(updater.UpdaterId.ToLower(),
                                      AppCommand.Instance.DtmUpdaterInstance.UpdaterGuid.ToString().ToLower(), StringComparison.Ordinal))
                    {
                        CreateSynchToCentralOverride();
                    }
                }
            });
        }
Beispiel #26
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="doc"></param>
        public void SynchSheets(Document doc)
        {
            try
            {
                var centralPath = FileInfoUtil.GetCentralFilePath(doc);
                var sheetsData  = MissionControlSetup.SheetsData.ContainsKey(centralPath)
                    ? MissionControlSetup.SheetsData[centralPath]
                    : null;
                if (sheetsData == null)
                {
                    return;
                }

                var sheets = new FilteredElementCollector(doc)
                             .OfCategory(BuiltInCategory.OST_Sheets)
                             .WhereElementIsNotElementType()
                             .Cast <ViewSheet>()
                             .Select(x => new SheetItem(x, centralPath))
                             .ToDictionary(key => key.UniqueId, value => value);

                var revisions = new FilteredElementCollector(doc)
                                .OfCategory(BuiltInCategory.OST_Revisions)
                                .WhereElementIsNotElementType()
                                .Select(x => new RevisionItem(x))
                                .ToDictionary(key => key.UniqueId, value => value);

                var finalList = new List <SheetItem>();
                foreach (var ms in sheetsData.Sheets)
                {
                    if (sheets.ContainsKey(ms.UniqueId))
                    {
                        // sheet still exists in our model
                        // we can update it
                        var localSheet = sheets[ms.UniqueId];
                        localSheet.Tasks        = ms.Tasks;        // preserve mongo tasks
                        localSheet.Id           = ms.Id;           // preserve mongoIds
                        localSheet.CollectionId = ms.CollectionId; // preserve mongoIds

                        finalList.Add(localSheet);
                        sheets.Remove(ms.UniqueId);
                    }
                    else
                    {
                        // TODO: Something about this is not right. When a new sheet is added from the web interface, then approved in Revit and synched
                        var task = ms.Tasks.LastOrDefault();
                        if (task != null && task.IsNewSheet)
                        {
                            finalList.Add(ms); // this already has the ids
                        }
                        else
                        {
                            // sheet was deleted locally but still exists in mongo
                            ms.IsDeleted = true;
                            finalList.Add(ms);
                        }
                    }
                }
                finalList.AddRange(sheets.Values); // add whatever was not stored in mongo before

                var data = new SheetData
                {
                    CentralPath = centralPath.ToLower(),
                    Sheets      = finalList,
                    Revisions   = revisions.Values.ToList(),
                    Id          = sheetsData.Id
                };

                if (!ServerUtilities.Post(data, "sheets/" + sheetsData.Id,
                                          out SheetData unused))
                {
                    Log.AppendLog(LogMessageType.ERROR, "Failed to publish Sheets.");
                }

                if (MissionControlSetup.SheetsData.ContainsKey(centralPath))
                {
                    MissionControlSetup.SheetsData.Remove(centralPath);
                }
                MissionControlSetup.SheetsData.Add(centralPath, data); // store sheets record
            }
            catch (Exception e)
            {
                Log.AppendLog(LogMessageType.EXCEPTION, e.Message);
            }
        }
Beispiel #27
0
        public void Execute(UpdaterData data)
        {
            try
            {
                Document doc = data.GetDocument();
                if (data.GetModifiedElementIds().Count > 0)
                {
                    ElementId      doorId       = data.GetModifiedElementIds().First();
                    FamilyInstance doorInstance = doc.GetElement(doorId) as FamilyInstance;
                    if (null != doorInstance)
                    {
#if RELEASE2013 || RELEASE2014
                        Parameter pushParameter = doorInstance.get_Parameter(pushParamName);
#elif RELEASE2015 || RELEASE2016
                        Parameter pushParameter = doorInstance.LookupParameter(pushParamName);
#endif

                        if (null != pushParameter)
                        {
                            if (data.IsChangeTriggered(doorId, Element.GetChangeTypeParameter(pushParameter)))
                            {
                                string pushValue = pushParameter.AsValueString();
                                if (!pushValue.Contains("Approach"))
                                {
                                    DoorFailure.IsDoorFailed        = true;
                                    DoorFailure.FailingDoorId       = doorId;
                                    FailureProcessor.IsFailureFound = true;

                                    MessageBoxResult dr = MessageBox.Show(pushValue + " is not a correct value for the parameter " + pushParamName, "Invalid Door Parameter.", MessageBoxButton.OK, MessageBoxImage.Information);
                                }
                            }
                        }
#if RELEASE2013 || RELEASE2014
                        Parameter pullParameter = doorInstance.get_Parameter(pullParamName);
#elif RELEASE2015 || RELEASE2016
                        Parameter pullParameter = doorInstance.LookupParameter(pullParamName);
#endif


                        if (null != pullParameter)
                        {
                            if (data.IsChangeTriggered(doorId, Element.GetChangeTypeParameter(pullParameter)))
                            {
                                string pullValue = pullParameter.AsValueString();
                                if (!pullValue.Contains("Approach"))
                                {
                                    DoorFailure.IsDoorFailed        = true;
                                    DoorFailure.FailingDoorId       = doorId;
                                    FailureProcessor.IsFailureFound = true;

                                    MessageBoxResult dr = MessageBox.Show(pullValue + " is not a correct value for the parameter " + pullParamName, "Invalid Door Parameter.", MessageBoxButton.OK, MessageBoxImage.Information);
                                }
                            }
                        }

#if RELEASE2013 || RELEASE2014
                        Parameter caParameter = doorInstance.get_Parameter(stateCAParamName);
#elif RELEASE2015 || RELEASE2016
                        Parameter caParameter = doorInstance.LookupParameter(stateCAParamName);
#endif
                        if (null != caParameter)
                        {
                            if (data.IsChangeTriggered(doorId, Element.GetChangeTypeParameter(caParameter)))
                            {
                                string centralPath = FileInfoUtil.GetCentralFilePath(doc);
                                if (AppCommand.Instance.ProjectDictionary.ContainsKey(centralPath))
                                {
                                    Project project = AppCommand.Instance.ProjectDictionary[centralPath];
                                    if (project.address.state == "CA")
                                    {
                                        caParameter.Set(1);
                                    }
                                    else
                                    {
                                        caParameter.Set(0);
                                    }
                                }
                            }
                        }
                    }
                }
                else if (data.GetAddedElementIds().Count > 0)
                {
                    ElementId      doorId       = data.GetAddedElementIds().First();
                    FamilyInstance doorInstance = doc.GetElement(doorId) as FamilyInstance;
                    if (null != doorInstance)
                    {
#if RELEASE2013 || RELEASE2014
                        Parameter caParameter = doorInstance.get_Parameter(stateCAParamName);
#elif RELEASE2015 || RELEASE2016
                        Parameter caParameter = doorInstance.LookupParameter(stateCAParamName);
#endif
                        if (null != caParameter)
                        {
                            string centralPath = FileInfoUtil.GetCentralFilePath(doc);
                            if (AppCommand.Instance.ProjectDictionary.ContainsKey(centralPath))
                            {
                                Project project = AppCommand.Instance.ProjectDictionary[centralPath];
                                if (project.address.state == "CA")
                                {
                                    caParameter.Set(1);
                                }
                                else
                                {
                                    caParameter.Set(0);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogUtil.AppendLog("DoorUpdater-Execute:" + ex.Message);
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="stylesId"></param>
        public void PublishData(Document doc, string stylesId)
        {
            try
            {
                _doc = doc;

                #region Text Note Type stats

                var textTypes = new FilteredElementCollector(doc)
                                .OfClass(typeof(TextNoteType))
                                .ToDictionary(x => x.Id.IntegerValue, x => new Tuple <Element, int>(x, 0));

                var textInstances = new FilteredElementCollector(doc)
                                    .OfClass(typeof(TextNote))
                                    .WhereElementIsNotElementType();

                foreach (var t in textInstances)
                {
                    var key = t.GetTypeId().IntegerValue;
                    if (textTypes.ContainsKey(key))
                    {
                        // increment instance count
                        textTypes[key] = new Tuple <Element, int>(textTypes[key].Item1, textTypes[key].Item2 + 1);
                    }
                }

                var textStats = textTypes.Select(x => new TextNoteTypeInfo(x.Value.Item1)
                {
                    Instances = x.Value.Item2
                })
                                .ToList();

                #endregion

                #region Dimension Type stats

                var dimTypes = new FilteredElementCollector(doc)
                               .OfClass(typeof(DimensionType))
                               .Cast <DimensionType>()
                               .Where(x => !string.IsNullOrEmpty(x.get_Parameter(BuiltInParameter.SYMBOL_NAME_PARAM).AsString()))
                               .ToDictionary(x => x.Id.IntegerValue, x => new Tuple <DimensionType, int>(x, 0));

                var dimInstances = new FilteredElementCollector(doc)
                                   .OfClass(typeof(Dimension))
                                   .WhereElementIsNotElementType()
                                   .Cast <Dimension>();

                // (Konrad) There is a user override in Configuration that controls what dimension overrides are ignored
                var centralPath = FileInfoUtil.GetCentralFilePath(doc);
                var config      = MissionControlSetup.Configurations.ContainsKey(centralPath)
                    ? MissionControlSetup.Configurations[centralPath]
                    : null;

                var dimensionValueCheck = new List <string> {
                    "EQ"
                };                                                   //defaults
                if (config != null)
                {
                    dimensionValueCheck = config.Updaters.First(x => string.Equals(x.UpdaterId,
                                                                                   Properties.Resources.HealthReportTrackerGuid, StringComparison.OrdinalIgnoreCase)).UserOverrides.DimensionValueCheck.Values;
                }

                var units           = _doc.GetUnits();
                var dimSegmentStats = new List <DimensionSegmentInfo>();
                foreach (var d in dimInstances)
                {
                    var key = d.GetTypeId().IntegerValue;
                    if (dimTypes.ContainsKey(key))
                    {
                        // increment instance count
                        dimTypes[key] = new Tuple <DimensionType, int>(dimTypes[key].Item1, dimTypes[key].Item2 + 1);
                    }

                    if (d.NumberOfSegments == 0)
                    {
                        if (string.IsNullOrEmpty(d.ValueOverride))
                        {
                            continue;
                        }
                        if (dimensionValueCheck.Any(d.ValueOverride.Contains))
                        {
                            continue;
                        }

                        // dim w/ zero segments
                        dimSegmentStats.Add(new DimensionSegmentInfo(d)
                        {
#if RELEASE2021
                            ValueString = UnitFormatUtils.Format(units, d.DimensionType.GetSpecTypeId(), (double)d.Value, false),
#else
                            ValueString = UnitFormatUtils.Format(units, d.DimensionType.UnitType, (double)d.Value, false, false),
#endif
                            OwnerViewType = d.ViewSpecific
                                ? ((View)doc.GetElement(d.OwnerViewId)).ViewType.ToString()
                                : string.Empty,
                            OwnerViewId = d.OwnerViewId.IntegerValue
                        });
                    }
                    else
                    {
                        // dim w/ multiple segments
                        foreach (DimensionSegment s in d.Segments)
                        {
                            if (string.IsNullOrEmpty(s.ValueOverride))
                            {
                                continue;
                            }
                            if (dimensionValueCheck.Any(s.ValueOverride.Contains))
                            {
                                continue;
                            }

                            dimSegmentStats.Add(new DimensionSegmentInfo(s)
                            {
#if RELEASE2021
                                ValueString = UnitFormatUtils.Format(units, d.DimensionType.GetSpecTypeId(), (double)d.Value, false),
#else
                                ValueString = UnitFormatUtils.Format(units, d.DimensionType.UnitType, (double)d.Value, false, false),
#endif
                                OwnerViewType = d.ViewSpecific
                                    ? ((View)doc.GetElement(d.OwnerViewId)).ViewType.ToString()
                                    : string.Empty,
                                OwnerViewId = d.OwnerViewId.IntegerValue
                            });
                        }
                    }
                }

                var dimStats = dimTypes.Select(x => new DimensionTypeInfo(x.Value.Item1)
                {
                    Instances = x.Value.Item2
                })
                               .ToList();

                #endregion

                #region Line Style stats

                //TODO: Finish this out.

                #endregion

                var stylesStats = new StylesDataItem
                {
                    User            = Environment.UserName.ToLower(),
                    TextStats       = textStats,
                    DimStats        = dimStats,
                    DimSegmentStats = dimSegmentStats
                };

                if (!ServerUtilities.Post(stylesStats, "styles/" + stylesId + "/stylestats",
                                          out StylesDataItem unused))
                {
                    Log.AppendLog(LogMessageType.ERROR, "Failed to publish Styles Data.");
                }
            }
            catch (Exception e)
            {
                Log.AppendLog(LogMessageType.EXCEPTION, e.Message);
            }
        }
Beispiel #29
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="pUpdater"></param>
        public void RefreshTriggers(Document doc, ProjectUpdater pUpdater)
        {
            try
            {
                var centralPath = FileInfoUtil.GetCentralFilePath(doc);
                var configId    = "";
                if (MissionControlSetup.Configurations.ContainsKey(centralPath))
                {
                    configId = MissionControlSetup.Configurations[centralPath].Id;
                }

                UpdaterRegistry.RemoveDocumentTriggers(_updaterId, doc);

                var elementsToDelete = _reportingElements.Where(x => x.CentralPath == centralPath).ToList();
                if (elementsToDelete.Any())
                {
                    foreach (var eInfo in elementsToDelete)
                    {
                        _reportingElements.Remove(eInfo);
                    }
                }

                foreach (var trigger in pUpdater.CategoryTriggers)
                {
                    if (!trigger.IsEnabled)
                    {
                        continue;
                    }

                    var catFilter = new ElementCategoryFilter(_catDictionary[trigger.CategoryName]);
                    UpdaterRegistry.AddTrigger(_updaterId, catFilter, Element.GetChangeTypeAny());
                    UpdaterRegistry.AddTrigger(_updaterId, catFilter, Element.GetChangeTypeElementAddition());
                    UpdaterRegistry.AddTrigger(_updaterId, catFilter, Element.GetChangeTypeElementDeletion());

                    switch (trigger.CategoryName)
                    {
                    case "Grids":
                    {
                        GridUtils.CollectGridExtents(doc, centralPath);
                        if (GridUtils.gridParameters.ContainsKey(centralPath))
                        {
                            foreach (var paramId in GridUtils.gridParameters[centralPath])
                            {
                                UpdaterRegistry.AddTrigger(_updaterId, catFilter, Element.GetChangeTypeParameter(paramId));
                            }
                        }

                        var elements = new FilteredElementCollector(doc)
                                       .WherePasses(catFilter)
                                       .WhereElementIsNotElementType()
                                       .ToElements();
                        foreach (var element in elements)
                        {
                            var reportingInfo = new ReportingElementInfo(
                                configId,
                                UpdaterGuid.ToString(),
                                centralPath,
                                trigger.CategoryName,
                                trigger.Description,
                                element.Id,
                                element.UniqueId);
                            _reportingElements.Add(reportingInfo);
                        }
                    }
                    break;

                    case "Views":
                    {
                        var viewTemplates = new FilteredElementCollector(doc)
                                            .WherePasses(catFilter)
                                            .WhereElementIsNotElementType()
                                            .Cast <View>()
                                            .Where(x => x.IsTemplate)
                                            .ToList();

                        if (viewTemplates.Any())
                        {
                            foreach (var view in viewTemplates)
                            {
                                var reportingInfo = new ReportingElementInfo(
                                    configId,
                                    UpdaterGuid.ToString(),
                                    centralPath,
                                    trigger.CategoryName,
                                    trigger.Description,
                                    view.Id,
                                    view.UniqueId);
                                _reportingElements.Add(reportingInfo);
                            }
                        }
                    }
                    break;

                    default:
                    {
                        var elements = new FilteredElementCollector(doc)
                                       .WherePasses(catFilter)
                                       .WhereElementIsNotElementType()
                                       .ToElements();
                        foreach (var element in elements)
                        {
                            var reportingInfo = new ReportingElementInfo(
                                configId,
                                UpdaterGuid.ToString(),
                                centralPath,
                                trigger.CategoryName,
                                trigger.Description,
                                element.Id,
                                element.UniqueId);
                            _reportingElements.Add(reportingInfo);
                        }
                    }
                    break;
                    }
                }
            }
            catch (Exception ex)
            {
                Log.AppendLog(LogMessageType.EXCEPTION, ex.Message);
            }
        }
Beispiel #30
0
        /// <summary>
        /// Submits request to create new sheet.
        /// </summary>
        /// <param name="app"></param>
        private void CreateSheet(UIApplication app)
        {
            var doc = app.ActiveUIDocument.Document;

            CentralPath = FileInfoUtil.GetCentralFilePath(doc);

            IsUpdatingSheet = true;
            app.Application.FailuresProcessing += FailureProcessing;

            using (var trans = new Transaction(doc, "CreateSheet"))
            {
                trans.Start();

                try
                {
                    ViewSheet sheet;
                    if (SheetTask.IsPlaceholder)
                    {
                        sheet = ViewSheet.CreatePlaceholder(doc);
                    }
                    else
                    {
                        // TODO: This should be exposed to user in Mission Control.
                        var titleblock = new FilteredElementCollector(doc).OfClass(typeof(FamilySymbol)).FirstOrDefault(x => x.Category.Name == "Title Blocks");
                        if (titleblock == null)
                        {
                            IsUpdatingSheet = false;
                            Messenger.Default.Send(new SheetTaskCompletedMessage
                            {
                                Completed   = false,
                                Message     = "Could not find a valid TitleBlock.",
                                CentralPath = CentralPath
                            });
                            return;
                        }
                        sheet = ViewSheet.Create(doc, titleblock.Id);
                    }

                    sheet.get_Parameter(BuiltInParameter.SHEET_NUMBER)?.Set(SheetTask.Number);
                    sheet.get_Parameter(BuiltInParameter.SHEET_NAME)?.Set(SheetTask.Name);

                    // (Konrad) We can set this here and pick up in the UI before sending off to MongoDB.
                    var newSheetItem = new SheetItem(sheet, CentralPath)
                    {
                        Tasks        = SheetItem.Tasks,
                        CollectionId = SheetItem.CollectionId,
                        Id           = SheetItem.Id,
                        IsNewSheet   = true // this was overriden to false by default constructor
                    };
                    SheetItem = newSheetItem;

                    trans.Commit();
                    IsUpdatingSheet = false;
                }
                catch (Exception e)
                {
                    trans.RollBack();
                    IsUpdatingSheet = false;

                    Log.AppendLog(LogMessageType.EXCEPTION, "Failed to create sheet.");
                    Messenger.Default.Send(new SheetTaskCompletedMessage
                    {
                        Completed   = false,
                        Message     = e.Message,
                        CentralPath = CentralPath
                    });
                }
            }

            // (Konrad) We don't want Revit to keep triggering this even when we are not processing updates.
            app.Application.FailuresProcessing -= FailureProcessing;
        }