private static void DeleteKeeperElementOnce(object sender, IdlingEventArgs idlingEventArgs) { var uiApplication = DocumentManager.Instance.CurrentUIApplication; uiApplication.Idling -= DeleteKeeperElementOnce; DeleteKeeperElement(); }
private void OnIdling(object sender, IdlingEventArgs e) { var uiApp = sender as UIApplication; Debug.Print("OnIdling: {0}", DateTime.Now.ToString("HH:mm:ss.fff")); // be carefull. It loads CPU e.SetRaiseWithoutDelay(); if (!TaskContainer.Instance.HasTaskToPerform) { return; } try { Debug.Print("{0}: {1}", Resources.StartExecuteTask, DateTime.Now.ToString("HH:mm:ss.fff")); var task = TaskContainer.Instance.DequeueTask(); task(uiApp); Debug.Print("{0}: {1}", Resources.EndExecuteTask, DateTime.Now.ToString("HH:mm:ss.fff")); } catch (Exception ex) { uiApp.Application.WriteJournalComment( string.Format("RevitExternalService. {0}:\r\n{2}", Resources.AnErrorOccuredWhileExecutingTheOnIdlingEvent, ex.ToString()), true); Debug.WriteLine(ex); } //e.SetRaiseWithoutDelay(); }
private void OnIdling(object sender, IdlingEventArgs e) { if (IdlingHandlers != null) { IdlingHandlers(sender, e); } }
//run by task scheduler or instant export to IFC public void IdlingUpdate(object sender, IdlingEventArgs arg) { UIApplication uiApp = sender as UIApplication; try { if (projectSettings.Count > 0) { ProjectSettings ps = FindProjectOfTask(); if (null != ps) { UtilityMethods utilityMethods = new UtilityMethods(uiApp, ps); utilityMethods.Upgrade(); } } } catch (Exception ex) { string message = ex.Message; LogFileManager.AppendLog("[Error] Idling Updates", message); } finally { SetRegistryKey("ActivateAddIn", false); uiControlApp.DialogBoxShowing -= new EventHandler <DialogBoxShowingEventArgs>(HandleDialogBoxShowing); uiControlApp.Idling -= new EventHandler <IdlingEventArgs>(IdlingUpdate); uiControlApp.ControlledApplication.FailuresProcessing -= new EventHandler <FailuresProcessingEventArgs>(OnFailuresProcessing); RevitKill(); } }
/// <summary> /// Idling Handler /// </summary> /// <remarks> /// It reaches out to the analyzer and ask it to update /// the results in Revit if more data has been calculated /// since the last time we asked. /// <para> /// If there is no more data available, we unsubscribe /// from the Idling event, for we do not need it anymore. /// </para> /// </remarks> /// public void IdlingHandler(object sender, IdlingEventArgs args) { bool processing = false; if (m_analyzer != null) { UIApplication uiapp = sender as UIApplication; if (uiapp.ActiveUIDocument != null) { // In order for the analysis to appear correctly in the view // we seem to need the mechanism of a transaction to be run // even though the results are not really parts of the document. using (Transaction trans = new Transaction(uiapp.ActiveUIDocument.Document)) { trans.Start("bogus transaction"); processing = m_analyzer.UpdateResults(); trans.Commit(); } // In our case, we want Revit to get back to as as soon as possible args.SetRaiseWithoutDelay(); } } // We do not need the event once the analysis is over if (!processing) { UnsubscribeFromIdling(sender as UIApplication); m_analyzer = null; } }
private void NewElementPropertyValueUpdater(object sender, IdlingEventArgs e) { // cancel if txn is completed if (_txnCompleted) { App.Idling -= new EventHandler <IdlingEventArgs>(NewElementPropertyValueUpdater); EndCancellingAllDialogs(); EndTrackingElements(); } // now update element parameters try { var TXN = new Transaction(_doc, _txnName); TXN.Start(); foreach (var newElId in NewElements) { var element = _doc.GetElement(newElId); if (element != null) { var parameter = element.get_Parameter(_paramToUpdate); if (parameter != null && !parameter.IsReadOnly) { parameter.Set(_paramToUpdateStringValue); } } } TXN.Commit(); } catch (Exception ex) { } _txnCompleted = true; }
/// <summary> /// A handler for the Idling event. /// </summary> /// <remarks> /// We keep the handler very simple. First we check /// if we still have the dialog. If not, we unsubscribe from Idling, /// for we no longer need it and it makes Revit speedier. /// If we do have the dialog around, we check if it has a request ready /// and process it accordingly. /// </remarks> /// public void IdlingHandler(object sender, IdlingEventArgs e) { if (uiApp == null) { uiApp = sender as UIApplication; } else { // fetch the request from the dialog RequestId request = shellViewModel.Request.Take(); if (request != RequestId.None) { try { // we take the request, if any was made, // and pass it on to the request executor FamilyRequestHandler.Execute(uiApp, request); } finally { // The dialog may be in its waiting state; // make sure we wake it up even if we get an exception. shellViewModel.WakeUp(); } } } e.SetRaiseWithoutDelay(); return; }
private void OnIdling(object sender, IdlingEventArgs e) { var uiApp = sender as UIApplication; Debug.Print("OnIdling: {0}", DateTime.Now.ToString("HH:mm:ss.fff")); e.SetRaiseWithoutDelay(); if (!TaskContainer.Instance.HasTaskToPerform) { return; } try { Debug.Print("{0}:{1}", "Revit binding ... ", DateTime.Now.ToString("HH:mm:ss.fff")); var task = TaskContainer.Instance.DequeueTask(); task(uiApp); // TaskDialog.Show("Reivt", string.Format("{0}:{1}", "Revit binding ... ", DateTime.Now.ToString("HH:mm:ss.fff"))); Debug.Print("{0}:{1}", "Revit binding", DateTime.Now.ToString("HH:mm:ss.fff")); } catch (Exception ex) { uiApp.Application.WriteJournalComment( string.Format("RevitExternalService. {0}\r\n{1}", "Error on Idling", ex.ToString()), true); TaskDialog.Show("Revit", string.Format("RevitExternalService. {0}\r\n{1}", "Error on Idling", ex.ToString())); Debug.WriteLine(ex); } }
/// <summary> /// A handler for the Idling event. /// </summary> /// <remarks> /// We keep the handler very simple. First we check /// if we still have the dialog. If not, we unsubscribe from Idling, /// for we no longer need it and it makes Revit speedier. /// If we do have the dialog around, we check if it has a request ready /// and process it accordingly. /// </remarks> /// public void IdlingHandler(object sender, IdlingEventArgs args) { UIApplication uiapp = sender as UIApplication; UIDocument uidoc = uiapp.ActiveUIDocument; if (m_MyForm.IsDisposed) { uiapp.Idling -= IdlingHandler; return; } else // dialog still exists { // fetch the request from the dialog RequestId requestId = m_MyForm.Request.Take(); if (requestId != RequestId.None) { try { // we take the request, if any was made, // and pass it on to the request executor RequestHandler.Execute(this, requestId); } finally { // The dialog may be in its waiting state; // make sure we wake it up even if we get an exception. m_MyForm.EnableButtons(IsLighterEnabled(), IsDarkerEnabled()); } } } return; }
public void OnIdlingEvent(object sender, IdlingEventArgs e) { ICollection <ElementId> latestSelection = App.UIApp.ActiveUIDocument.Selection.GetElementIds(); if (latestSelection.Count == 0) { if (SelectedElementIds != null && SelectedElementIds.Count > 0) { HandleSelectionChange(latestSelection); } } else { if (SelectedElementIds == null) { HandleSelectionChange(latestSelection); } else { if (SelectedElementIds.Count != latestSelection.Count) { HandleSelectionChange(latestSelection); } else { if (SelectionHasChanged(latestSelection)) { HandleSelectionChange(latestSelection); } } } } }
private void OnIdling(object sender, IdlingEventArgs e) { if (serverActive) { if (uiApp == null) { uiApp = sender as UIApplication; } e.SetRaiseWithoutDelay(); if (!TaskContainer.Instance.HasTaskToPerform) { return; } try { var task = TaskContainer.Instance.DequeueTask(); task(uiApp); } catch (Exception ex) { //TaskDialog.Show("Error at Idle", ex.Message); if (uiApp != null) { uiApp.Application.WriteJournalComment("Lyrebird Error: " + ex.ToString(), true); } } } }
private static void ShutdownRevitHostOnce(object sender, IdlingEventArgs idlingEventArgs) { var uiApplication = DocumentManager.Instance.CurrentUIApplication; uiApplication.Idling -= ShutdownRevitHostOnce; ShutdownRevitHost(); }
private void OnIdling(object sender, IdlingEventArgs e) { uiControlledApplication.Idling -= OnIdling; uiApplication = sender as UIApplication; revitWakaTimePlugin = new RevitWakaTimePlugin(uiApplication); revitWakaTimePlugin.BindEditorEvents(); }
public void app_Idling(Object sender, IdlingEventArgs arg) { callCounter++; //do the short time taking task here. Trace.WriteLine("Idling session called " + callCounter.ToString()); //When Revit users don't move the mouse if (Math.Abs(lastCursor.X - System.Windows.Forms.Cursor.Position.X) <= 1) { //move the cursor left and right with small distance: //1 pixel. so it looks like it is stable //this way can trigger the Idling event repeatedly if (callCounter % 2 == 0) { System.Windows.Forms.Cursor.Position = new System.Drawing.Point( System.Windows.Forms.Cursor.Position.X + 10, System.Windows.Forms.Cursor.Position.Y); } else if (callCounter % 2 == 1) { System.Windows.Forms.Cursor.Position = new System.Drawing.Point( System.Windows.Forms.Cursor.Position.X - 10, System.Windows.Forms.Cursor.Position.Y); } } lastCursor = System.Windows.Forms.Cursor.Position; }
private void Application_Idling(object sender, IdlingEventArgs e) { //var app = sender as Application; //var uiApp = new UIApplication(app); var uiApp = sender as UIApplication; var uiDoc = uiApp.ActiveUIDocument; var view = uiDoc.ActiveView; var doc = uiDoc.Document; e.SetRaiseWithoutDelay(); if (Math.Abs(lastCursor.X - System.Windows.Forms.Cursor.Position.X) >= 1) { var curPt = GetCurrentCursorPosition(uiDoc); using (var t = new Transaction(doc, "TestIdling")) { t.Start(); var l = Line.CreateBound(pt1, curPt); if (line == null) { line = doc.Create.NewDetailCurve(view, l); } else { line.GeometryCurve = l; } t.Commit(); } } lastCursor = System.Windows.Forms.Cursor.Position; }
public void onIdling(object sender, IdlingEventArgs iea) { //MessageBox.Show("idling"); //一直觸發 UIApplication uiapp = sender as UIApplication; if (uiapp != null) { UIDocument uidoc = uiapp.ActiveUIDocument; // Document doc = uidoc.Document; CusParameters cp = new CusParameters(uidoc); ItemsModel im = new ItemsModel(); ItemController ic = new ItemController(im, cp); this._ic = ic; if (_outputForm != null) { _outputForm.setItemController(ic); } else { Thread ofthread = new Thread(openForm); ofthread.Start(); } } }
/// <summary> /// When Revit goes idle it gets here and process all tasks in the scheduler /// queue. The control returns to Revit only when all tasks are processed. /// This method will be called again the next time Revit goes into idle state. /// </summary> /// <param name="sender">Reference to the current Revit application.</param> /// <param name="e">Idling event argument.</param> /// private void OnRevitIdle(object sender, IdlingEventArgs e) { const bool waitIfTaskQueueIsEmpty = false; while (scheduler.ProcessNextTask(waitIfTaskQueueIsEmpty)) { // Does nothing here, loop ends when all tasks processed. } }
private static void Application_Idling(object sender, IdlingEventArgs e) { e.SetRaiseWithoutDelay(); while (UnlockKeys.TryDequeue(out var unlockKey)) { unlockKey.Dispose(); } }
// Iding事件 private void OnIdlingEvent(object sender, IdlingEventArgs idlingArgs) { if (this.m_uiDoc == null) { return; } ShowGridApplication.m_gridNumberShowForm.DrawGridNumText(true); }
private void Application_Idling(object sender, IdlingEventArgs e) { // see if there's something for us to do. try { // we want frequent callbacks e.SetRaiseWithoutDelay(); ActionEnum tmpAction = _action; _action = ActionEnum.None; switch (tmpAction) { case ActionEnum.ShowElement: performShow(); break; case ActionEnum.Shutdown: performShutdown(); break; case ActionEnum.ColorElements: performColor(); break; case ActionEnum.RemoveColor: removeColor(_uiDoc.ActiveGraphicalView); break; case ActionEnum.ResetColors: resetColors(); break; case ActionEnum.ShowSolid: performShowSolid(); break; case ActionEnum.ShowMove: performShowMove(); break; case ActionEnum.ShowRotation: performShowRotate(); break; case ActionEnum.Select: performSelect(); break; } } catch (Exception ex) { TaskDialog td = new TaskDialog("Error in Revit Fingerprint"); td.MainContent = "An unexpected error occurred."; td.ExpandedContent = ex.GetType().Name + ": " + ex.Message + " " + ex.StackTrace; } }
static void OnIdle(object sender, IdlingEventArgs args) { ActiveUIApplication = (sender as UIApplication); if (ProcessIdleActions()) { args.SetRaiseWithoutDelay(); } }
private void ApplicationOnIdling(object sender, IdlingEventArgs e) { if (!_started) { Run(); } _started = true; }
private void OnIdling(object sender, IdlingEventArgs e) { _uiCtrlApp.Idling -= OnIdling; UiApp = sender as UIApplication; Uidoc = UiApp.ActiveUIDocument; App = UiApp.Application; Doc = Uidoc.Document; }
internal static void Idling(object sender, IdlingEventArgs e, MainPage mainWindow) { UIApplication uiapp = sender as UIApplication; if (uiapp != null) { mainWindow.ActiveDocument = uiapp.ActiveUIDocument.Document; mainWindow.txtProjectName.Title = string.Format("[{0}]", uiapp.ActiveUIDocument.Document.Title); } }
private static void Application_Idling(object sender, IdlingEventArgs e) { idle = true; Thread.Sleep(1); while (HasPendingPromises()) { Promises.Dequeue()(); } idle = false; }
/// <summary> /// The idling callback for the animation. /// </summary> /// <param name="senter"></param> /// <param name="e"></param> private void IdlingResponse(object senter, IdlingEventArgs e) { // Set to reraise idling immediately (unaffected by user activity) e.SetRaiseWithoutDelay(); if (timerTripped) { timerTripped = false; AnimateNextStep(); } }
private void OnIdling(object sender, IdlingEventArgs e) { // Idling events happen when the application has // nothing else to do, // They can happen very frequently and the user // will experience a lag if this code takes a // significant amount of time to execute. UIApplication uiApplication = (UIApplication)sender; ICollection <ElementId> selected = uiApplication .ActiveUIDocument.Selection.GetElementIds(); if (0 == selected.Count) { if (null != Selection && 0 < Selection.Count) { // if something was selected previously, and // now the selection is empty, report change HandleSelectionChange(selected); } } else // elements are selected { if (null == Selection) { // previous selection was null, report change HandleSelectionChange(selected); } else { if (Selection.Count != selected.Count) { // size has changed, no need to check // selection IDs, report the change HandleSelectionChange(selected); } else { // count is the same... // compare IDs to see if selection has changed if (SelectionHasChanged(selected)) { HandleSelectionChange(selected); } } } } }
void OnIdle(object sender, IdlingEventArgs args) { // 1. Do Rhino pending OnIdle tasks if (rhinoCore.OnIdle()) { args.SetRaiseWithoutDelay(); return; } // Load this assembly as a Grasshopper assembly if (!LoadedAsGHA && PlugIn.GetPlugInInfo(new Guid(0xB45A29B1, 0x4343, 0x4035, 0x98, 0x9E, 0x04, 0x4E, 0x85, 0x80, 0xD9, 0xCF)).IsLoaded) { LoadedAsGHA = LoadGrasshopperComponents(); } // Document dependant tasks need a document ActiveUIApplication = (sender as UIApplication); if (ActiveDBDocument != null) { // 1. Do all document read actions if (ProcessReadActions()) { args.SetRaiseWithoutDelay(); return; } // 2. Do all document write actions if (!ActiveDBDocument.IsReadOnly) { ProcessWriteActions(); } // 3. Refresh Active View if necesary bool regenComplete = DirectContext3DServer.RegenComplete(); if (pendingRefreshActiveView || !regenComplete || GH.PreviewServer.PreviewChanged()) { pendingRefreshActiveView = false; var RefreshTime = new Stopwatch(); RefreshTime.Start(); ActiveUIApplication.ActiveUIDocument.RefreshActiveView(); RefreshTime.Stop(); DirectContext3DServer.RegenThreshold = Math.Min(RefreshTime.ElapsedMilliseconds, 200); } if (!regenComplete) { args.SetRaiseWithoutDelay(); } } }
/// <summary> /// Idling event handler for all buttons. /// This is where we have access to the Revit /// API again. /// </summary> void OnButtonIdling( object sender, IdlingEventArgs e) { UIApplication uiapp = sender as UIApplication; if (uiapp != null) { UIDocument uidoc = uiapp.ActiveUIDocument; Command.OnButton(_button_nr, uidoc.ActiveView); } _controlledApp.Idling -= OnButtonIdling; }
/// <summary> /// Revit Idling event handler. /// Whenever the user has selected an element to /// zoom to in the modeless dialogue, the pending /// element id is set. The event handler picks it /// up and zooms to it. We are not modifying the /// Revit document, so it seems we can get away /// with not starting a transaction. /// </summary> static void OnIdling( object sender, IdlingEventArgs ea) { if (!SearchHitNavigator.IsShowing) { Unsubscribe(); } int id = _pending_element_id; if (0 != id) { // Support both 2011, where sender is an // Application instance, and 2012, where // it is a UIApplication instance: UIApplication uiapp = sender is UIApplication ? sender as UIApplication // 2012 : new UIApplication( sender as Application); // 2011 UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; ElementId eid = new ElementId(id); Element e = doc.GetElement(eid); Debug.Print( "Element id {0} requested --> {1}", id, new ElementData(e)); // No transaction required: //uidoc.Selection.Elements.Clear(); //uidoc.Selection.Elements.Add( e ); //uidoc.ShowElements( e ); List <ElementId> ids = new List <ElementId>(1); ids.Add(eid); uidoc.Selection.SetElementIds(ids); uidoc.ShowElements(ids); _pending_element_id = 0; } }
void OnIdling( object sender, IdlingEventArgs e ) { // access active document from sender: //Application app = sender as Application; // 2011 //Debug.Assert( null != app, // 2011 // "expected a valid Revit application instance" ); // 2011 //UIApplication uiapp = new UIApplication( app ); // 2011 UIApplication uiapp = sender as UIApplication; // 2012 Document doc = uiapp.ActiveUIDocument.Document; Log( "OnIdling with active document " + doc.Title ); }
void OnIdling( object sender, IdlingEventArgs ea) { ++_counter; if( 0 == ( _counter % _message_interval ) ) { Debug.Print( "{0} OnIdling called {1} times", DateTime.Now.ToString( "HH:mm:ss.fff" ), _counter ); } ea.SetRaiseWithoutDelay(); }
/// <summary> /// Idling event handler for all buttons. /// This is where we have access to the Revit /// API again. /// </summary> void OnButtonIdling( object sender, IdlingEventArgs e) { UIApplication uiapp = sender as UIApplication; if( uiapp != null ) { UIDocument uidoc = uiapp.ActiveUIDocument; Command.OnButton( _button_nr, uidoc.ActiveView ); } _controlledApp.Idling -= OnButtonIdling; }
private void OnIdling(object sender, IdlingEventArgs e) { var uiApp = sender as UIApplication; Debug.Print("OnIdling: {0}", DateTime.Now.ToString("HH:mm:ss.fff")); // be carefull. It loads CPU e.SetRaiseWithoutDelay(); if (!TaskContainer.Instance.HasTaskToPerform) return; try { Debug.Print("{0}: {1}", Resources.StartExecuteTask, DateTime.Now.ToString("HH:mm:ss.fff")); var task = TaskContainer.Instance.DequeueTask(); task(uiApp); Debug.Print("{0}: {1}", Resources.EndExecuteTask, DateTime.Now.ToString("HH:mm:ss.fff")); } catch (Exception ex) { uiApp.Application.WriteJournalComment( string.Format("RevitExternalService. {0}:\r\n{2}", Resources.AnErrorOccuredWhileExecutingTheOnIdlingEvent, ex.ToString()), true); Debug.WriteLine(ex); } //e.SetRaiseWithoutDelay(); }
/// <summary> /// The idling callback which adds data to the AVF results. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void UpdateWhileIdling(object sender, IdlingEventArgs e) { UIApplication uiApp = sender as UIApplication; // Get SpatialFieldManager SpatialFieldManager sfm = SpatialFieldManager.GetSpatialFieldManager(uiApp.ActiveUIDocument.Document.ActiveView); if (sfm == null) sfm = SpatialFieldManager.CreateSpatialFieldManager(uiApp.ActiveUIDocument.Document.ActiveView, 1); // If stopping, clear results and unset event. if (m_stop) { lock (results) { results.Clear(); } uiApp.Idling -= UpdateWhileIdling; return; } // If document was closed and new document opened, do not run the update. if (uiApp.ActiveUIDocument.Document.PathName == m_docName) { // Lock access to current calculated results lock (results) { if (results.Count == 0) return; // Turn each result to an AVF ValueAtPoint foreach (ResultsData rData in results) { uvPts.Add(new UV(rData.UV.U, rData.UV.V)); IList<double> doubleList = new List<double>(); doubleList.Add(rData.Value); valList.Add(new ValueAtPoint(doubleList)); } FieldDomainPointsByUV pntsByUV = new FieldDomainPointsByUV(uvPts); FieldValues fieldValues = new FieldValues(valList); // Update with calculated values Transaction t = new Transaction(uiApp.ActiveUIDocument.Document); t.SetName("AVF"); t.Start(); if (!m_stop) sfm.UpdateSpatialFieldPrimitive(s_spatialFieldId, pntsByUV, fieldValues); t.Commit(); // Clear results already processed. results.Clear(); // If no more results to process, remove the idling event if (m_uvToCalculateCount == 0) { uiApp.Idling -= UpdateWhileIdling; s_oldViewId = s_activeViewId; s_oldSpatialFieldId = s_spatialFieldId; } } } }
private static void ShutdownRevitHostOnce(object sender, IdlingEventArgs idlingEventArgs) { var uiApplication = DocumentManager.Instance.CurrentUIApplication; uiApplication.Idling -= ShutdownRevitHostOnce; RevitDynamoModel.ShutdownRevitHost(); }
private void OnIdling(object sender, IdlingEventArgs e) { if(thisUiapp == null) { thisUiapp = sender as UIApplication; } if (racket == null) return; callCounter++; try { if (racket.IsConnected()) { while (racket.ReadCommandBuff()) { //ExecuteCommand(); namestrc n = namestrc.ParseDelimitedFrom(racket.getChannel()); Func<bool> f = funcDictionary[n.Name]; if (f == null) { TaskDialog.Show("Revit", "Unknown Form"); } else { f.Invoke(); } } //When Revit users don't move the mouse if (Math.Abs(lastCursor.X - Cursor.Position.X) <= 1) { //move the cursor left and right with small distance: //1 pixel. so it looks like it is stable //this way can trigger the Idling event repeatedly if (callCounter % 2 == 0) { Cursor.Position = new System.Drawing.Point( Cursor.Position.X + 1, Cursor.Position.Y); } else if (callCounter % 2 == 1) { Cursor.Position = new System.Drawing.Point( Cursor.Position.X - 1, Cursor.Position.Y); } } lastCursor = Cursor.Position; } else { DisconnectCMD(); } } catch (Exception exc) { TaskDialog.Show("Revit", exc.ToString()); } }
void OnIdling(object sender, IdlingEventArgs e) { }
/// <summary> /// Wait far a moment before requerying database. /// </summary> //static Stopwatch _stopwatch = null; void OnIdling( object sender, IdlingEventArgs ea ) { using( JtTimer pt = new JtTimer( "OnIdling" ) ) { // Use with care! This loads the CPU: ea.SetRaiseWithoutDelay(); ++_counter; if( 0 == ( _counter % _update_interval ) ) { if( 0 == ( _counter % _message_interval ) ) { Util.Log( string.Format( "OnIdling called {0} times", _counter ) ); } // Have we waited long enough since the last attempt? //if( null == _stopwatch // || _stopwatch.ElapsedMilliseconds > 500 ) RoomEditorDb rdb = new RoomEditorDb(); //int n = rdb.LastSequenceNumber; if( rdb.LastSequenceNumberChanged( DbUpdater.LastSequence ) ) { UIApplication uiapp = sender as UIApplication; Document doc = uiapp.ActiveUIDocument.Document; Util.Log( "furniture update begin" ); //FilteredElementCollector rooms // = new FilteredElementCollector( doc ) // .OfClass( typeof( SpatialElement ) ) // .OfCategory( BuiltInCategory.OST_Rooms ); //IEnumerable<string> roomUniqueIds // = rooms.Select<Element, string>( // e => e.UniqueId ); //CouchDatabase db = rdb.Db; //ChangeOptions opt = new ChangeOptions(); //opt.IncludeDocs = true; //opt.Since = CmdUpdate.LastSequence; //opt.View = "roomedit/map_room_to_furniture"; //CouchChanges<DbFurniture> changes // = db.GetChanges<DbFurniture>( opt ); //CouchChangeResult<DbFurniture>[] results // = changes.Results; //DbUpdater updater = new DbUpdater( // doc, roomUniqueIds ); //foreach( CouchChangeResult<DbFurniture> result // in results ) //{ // updater.UpdateBimFurniture( result.Doc ); // CmdUpdate.LastSequence = result.Sequence; //} DbUpdater updater = new DbUpdater( uiapp ); updater.UpdateBim(); Util.Log( "furniture update end" ); // _stopwatch = new Stopwatch(); // _stopwatch.Start(); //} //catch( Exception ex ) //{ // //uiapp.Application.WriteJournalComment // Debug.Print( // "Room Editor: an error occurred " // + "executing the OnIdling event:\r\n" // + ex.ToString() ); // Debug.WriteLine( ex ); //} } } } }
private void OnIdling(object sender, IdlingEventArgs e) { if (serverActive) { if (uiApp == null) { uiApp = sender as UIApplication; } e.SetRaiseWithoutDelay(); if (!TaskContainer.Instance.HasTaskToPerform) { return; } try { var task = TaskContainer.Instance.DequeueTask(); task(uiApp); } catch (Exception ex) { //TaskDialog.Show("Error at Idle", ex.Message); if (uiApp != null) uiApp.Application.WriteJournalComment("Lyrebird Error: " + ex.ToString(), true); } } }
private static void DeleteKeeperElementOnce(object sender, IdlingEventArgs idlingEventArgs) { var uiApplication = DocumentManager.Instance.CurrentUIApplication; uiApplication.Idling -= DeleteKeeperElementOnce; DynamoRevit.DeleteKeeperElement(); }
public static void OnIdle(object sender, IdlingEventArgs e) { if (Queue.IsEmpty) return; //do work var application = (UIApplication)sender; if (application == null) return; if (application.ActiveUIDocument.Document == null) return; Task task = null; try { application.Application.WriteJournalComment( "Main thread id :" + Thread.CurrentThread.ManagedThreadId, false); task = new Task(() => { RevitContext.BindToken(_cts.Token); RevitContext.UIApplication = application; application.Application.WriteJournalComment( "worker thread id :" + Thread.CurrentThread.ManagedThreadId, false); Interlocked.Exchange(ref _working, 1); //working string worker; if (!Queue.TryDequeue(out worker)) return; if (String.IsNullOrEmpty(worker)) return; var workerType = Type.GetType(worker); if (workerType == null) return; var workerObject = (IWorker)Activator.CreateInstance(workerType); workerObject.DoWork(); },_cts.Token); task.RunSynchronously(TaskScheduler.Current); task.Wait(_cts.Token); } catch (OperationCanceledException ex) { // YES we cancelled } catch (AggregateException age) { } catch (Exception ex) { // something else happened } finally { var isCancelled = _cts.IsCancellationRequested; _cts = new CancellationTokenSource(); if (task != null) switch (task.Status) { case TaskStatus.RanToCompletion: RevitContext.OutputNoCancel(isCancelled ? "RanToCompletion and tried to Cancel" : "RanToCompletion"); break; case TaskStatus.Faulted: RevitContext.OutputNoCancel(isCancelled ? "Faulted and tried to Cancel" : "Faulted"); break; case TaskStatus.Canceled: RevitContext.OutputNoCancel(isCancelled ? "Cancelled and tried to Cancel" : "Cancelled"); break; } Interlocked.Exchange(ref _working, 0); task = null; // more work try idle again if (!Queue.IsEmpty) e.SetRaiseWithoutDelay(); } }
/// <summary> /// This method (Application.Idling event handler) is called exactly once /// during the creation of Dynamo Revit plug-in. It is in this call both /// DynamoScheduler and its RevitSchedulerThread objects are created. All /// other AsyncTask beyond this point are scheduled through the scheduler. /// </summary> /// private static void OnRevitIdleOnce(object sender, IdlingEventArgs e) { // We only need to initialize this once, unregister. extCommandData.Application.Idling -= OnRevitIdleOnce; // create core data models revitDynamoModel = InitializeCoreModel(extCommandData); dynamoViewModel = InitializeCoreViewModel(revitDynamoModel); // show the window InitializeCoreView().Show(); TryOpenWorkspaceInCommandData(extCommandData); SubscribeViewActivating(extCommandData); }