public object Clone()
        {
            var handler = Handler is ICloneable cloneable?cloneable.Clone() as IExternalEventHandler : Handler;

            RevitTask.Log($"{handler?.GetName()} cloned from {Handler.GetName()}");
            return(new FutureExternalEvent(handler));
        }
        public async void Execute(object parameter)
        {
            //Run Revit API directly here
            var savePath = await RevitTask.RunAsync(async app =>
            {
                try
                {
                    //Support async task
                    //Raise global external event handler
                    Family randomFamily = await RevitTask
                                          .RaiseGlobal <GetRandomFamilyExternalEventHandler, bool, Family>(parameter as bool? ?? false);

                    //Raise scoped external event handler
                    return(await ScopedRevitTask.Raise <SaveFamilyToDesktopExternalEventHandler, Family, string>(randomFamily));
                }
                catch (Exception)
                {
                    return(null);
                }
            });

            var saveResult = !string.IsNullOrWhiteSpace(savePath);

            MessageBox.Show($"Family {(saveResult ? "" : "not ")}saved:\n{savePath}");
            if (saveResult && Path.GetDirectoryName(savePath) is string dir)
            {
                Process.Start(dir);
            }
        }
Exemple #3
0
        /// <summary>
        /// This is the method which launches the WPF window in a separate thread, and injects any methods that are
        /// wrapped by ExternalEventHandlers. This can be done in a number of different ways, and
        /// implementation will differ based on how the WPF is set up.
        /// </summary>
        /// <param name="uiapp">The Revit UIApplication within the add-in will operate.</param>
        public void ShowFormSeparateThread(UIApplication uiapp)
        {
            // If we do not have a thread started or has been terminated start a new one
            if (!(_uiThread is null) && _uiThread.IsAlive)
            {
                return;
            }

            //https://thebuildingcoder.typepad.com/blog/2020/02/external-communication-and-async-await-event-wrapper.html#2
            //https://github.com/WhiteSharq/RevitTask

            RevitTask aRevitTask = new RevitTask();

            _uiThread = new Thread(() =>
            {
                SynchronizationContext.SetSynchronizationContext(
                    new DispatcherSynchronizationContext(
                        Dispatcher.CurrentDispatcher));
                // The dialog becomes the owner responsible for disposing the objects given to it.
                _mMyForm         = new Ui(uiapp, aRevitTask, msalAuthHelper);
                _mMyForm.Closed += (s, e) => Dispatcher.CurrentDispatcher.InvokeShutdown();
                _mMyForm.Show();
                Dispatcher.Run();
            });

            _uiThread.SetApartmentState(ApartmentState.STA);
            _uiThread.IsBackground = true;
            _uiThread.Start();
        }
Exemple #4
0
        public void Execute(object parameter)
        {
            for (var i = 0; i < 5; i++)
            {
                RevitTask.RunAsync(async app =>
                {
                    //Revit API can be executed directly here

                    try
                    {
                        //Support async task
                        //Raise global external event handler
                        var randomFamily = await RevitTask.RaiseGlobalNew <GetRandomFamilyExternalEventHandler, bool, Family>(parameter as bool? ?? false);

                        //Raise scoped external event handler
                        return(await ScopedRevitTask.RaiseNew <SaveFamilyToDesktopExternalEventHandler, Family, string>(randomFamily));
                    }
                    catch (Exception)
                    {
                        return(null);
                    }
                }).ContinueWith(savePathTask =>
                {
                    var savePath   = savePathTask.Result;
                    var saveResult = !string.IsNullOrWhiteSpace(savePath);
                    if (saveResult && Path.GetDirectoryName(savePath) is string dir)
                    {
                        Process.Start(dir);
                    }
                });
            }
        }
        public SaveFamilyCommand()
        {
            //Create a RevitTask
            ScopedRevitTask = new RevitTask();

            //Register an external event handler to the scope
            ScopedRevitTask.Register(new SaveFamilyToDesktopExternalEventHandler());
        }
Exemple #6
0
        public WebServer(string _host, string _port, Document _doc, RevitTask _aRevitTask)
        {
            Host    = _host;
            Port    = _port;
            BaseUrl = string.Format("http://{0}:{1}/", Host, Port);

            Doc        = _doc;
            aRevitTask = _aRevitTask;
        }
Exemple #7
0
        public Ui(UIApplication uiApp, RevitTask _aRevitTask)
        {
            _uiDoc = uiApp.ActiveUIDocument;
            _doc   = _uiDoc.Document;

            Closed += MainWindow_Closed;

            InitializeComponent();
            aRevitTask = _aRevitTask;
        }
Exemple #8
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            //always initialize RevitTask in Revit API context before calling any RunAsync method
            RevitTask.Initialize();
            //Register your own global generic external event handler
            RevitTask.RegisterGlobal(new GetRandomFamilyExternalEventHandler());
            var window = new TestWindow();

            window.Show();
            return(Result.Succeeded);
        }
Exemple #9
0
 public override async void WriteStreamsToFile(List <StreamState> streams)
 {
     await RevitTask.RunAsync(
         app =>
     {
         using (Transaction t = new Transaction(CurrentDoc.Document, "Speckle Write State"))
         {
             t.Start();
             StreamStateManager2.WriteStreamStateList(CurrentDoc.Document, streams);
             t.Commit();
         }
     });
 }
Exemple #10
0
        public Ui(UIApplication uiApp, RevitTask revitTask, MsalAuthHelper _msalAuthHelper)
        {
            _uiDoc     = uiApp.ActiveUIDocument;
            _doc       = _uiDoc.Document;
            aRevitTask = revitTask;

            //_app = _doc.Application;
            //_uiApp = _doc.Application;
            Closed += MainWindow_Closed;

            InitializeComponent();
            msalAuthHelper = _msalAuthHelper;
            RefreshSignInStatus();
        }
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            var process = Process.GetCurrentProcess();
            var winname = typeof(MainWindow).Namespace + "." + nameof(MainWindow);

            if (WindowAlreadyExist(process, winname))
            {
                Message.Display("Main window already exist", WindowType.Information);
                return(Result.Failed);
            }

            RevitTask.Initialize();

            var mainWindow = new MainWindow(commandData.Application.ActiveUIDocument.Document);

            mainWindow.Closed += (s, e) => Utility.Properties.Settings.Default.Save();

            new WindowInteropHelper(mainWindow)
            {
                Owner = process.MainWindowHandle
            };

            if (!mainWindow.IsVisible)
            {
                mainWindow.Show();
            }
            if (mainWindow.WindowState == WindowState.Minimized)
            {
                mainWindow.WindowState = WindowState.Normal;
            }

            mainWindow.Activate();
            mainWindow.Topmost = true;
            mainWindow.Topmost = false;
            mainWindow.Focus();

            return(Result.Succeeded);
        }
Exemple #12
0
        /// <summary>
        /// Receives a stream and bakes into the existing revit file.
        /// </summary>
        /// <param name="state"></param>
        /// <returns></returns>
        public override async Task <StreamState> ReceiveStream(StreamState state, ProgressViewModel progress)
        {
            var kit       = KitManager.GetDefaultKit();
            var converter = kit.LoadConverter(ConnectorRevitUtils.RevitAppName);

            converter.SetContextDocument(CurrentDoc.Document);
            var previouslyReceiveObjects = state.ReceivedObjects;

            var transport = new ServerTransport(state.Client.Account, state.StreamId);

            var stream = await state.Client.StreamGet(state.StreamId);

            if (progress.CancellationTokenSource.Token.IsCancellationRequested)
            {
                return(null);
            }

            Commit myCommit = null;

            //if "latest", always make sure we get the latest commit when the user clicks "receive"
            if (state.CommitId == "latest")
            {
                var res = await state.Client.BranchGet(progress.CancellationTokenSource.Token, state.StreamId, state.BranchName, 1);

                myCommit = res.commits.items.FirstOrDefault();
            }
            else
            {
                myCommit = await state.Client.CommitGet(progress.CancellationTokenSource.Token, state.StreamId, state.CommitId);
            }
            string referencedObject = myCommit.referencedObject;

            var commitObject = await Operations.Receive(
                referencedObject,
                progress.CancellationTokenSource.Token,
                transport,
                onProgressAction : dict => progress.Update(dict),
                onErrorAction : (s, e) =>
            {
                progress.Report.LogOperationError(e);
                progress.CancellationTokenSource.Cancel();
            },
                onTotalChildrenCountKnown : count => { progress.Max = count; },
                disposeTransports : true
                );

            try
            {
                await state.Client.CommitReceived(new CommitReceivedInput
                {
                    streamId          = stream?.id,
                    commitId          = myCommit?.id,
                    message           = myCommit?.message,
                    sourceApplication = ConnectorRevitUtils.RevitAppName
                });
            }
            catch
            {
                // Do nothing!
            }

            if (progress.Report.OperationErrorsCount != 0)
            {
                return(state);
            }

            if (progress.CancellationTokenSource.Token.IsCancellationRequested)
            {
                return(null);
            }



            await RevitTask.RunAsync(app =>
            {
                using (var t = new Transaction(CurrentDoc.Document, $"Baking stream {state.StreamId}"))
                {
                    var failOpts = t.GetFailureHandlingOptions();
                    failOpts.SetFailuresPreprocessor(new ErrorEater(converter));
                    failOpts.SetClearAfterRollback(true);
                    t.SetFailureHandlingOptions(failOpts);

                    t.Start();
                    var flattenedObjects = FlattenCommitObject(commitObject, converter);
                    // needs to be set for editing to work
                    converter.SetPreviousContextObjects(previouslyReceiveObjects);
                    // needs to be set for openings in floors and roofs to work
                    converter.SetContextObjects(flattenedObjects.Select(x => new ApplicationPlaceholderObject {
                        applicationId = x.applicationId, NativeObject = x
                    }).ToList());
                    var newPlaceholderObjects = ConvertReceivedObjects(flattenedObjects, converter, state, progress);
                    // receive was cancelled by user
                    if (newPlaceholderObjects == null)
                    {
                        progress.Report.LogConversionError(new Exception("fatal error: receive cancelled by user"));
                        t.RollBack();
                        return;
                    }

                    DeleteObjects(previouslyReceiveObjects, newPlaceholderObjects);

                    state.ReceivedObjects = newPlaceholderObjects;

                    t.Commit();
                    progress.Report.Merge(converter.Report);
                }
            });



            if (converter.Report.ConversionErrors.Any(x => x.Message.Contains("fatal error")))
            {
                // the commit is being rolled back
                return(null);
            }


            return(state);
        }
 public ResolverEntry(Document _doc, RevitTask _aRevitTask)
 {
     Doc        = _doc;
     aRevitTask = _aRevitTask;
 }
Exemple #14
0
        /// <summary>
        /// Run desired tests.
        /// </summary>
        private void Run(RunRequest request, Response response, UIApplication application)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            if (response == null)
            {
                throw new ArgumentNullException(nameof(response));
            }

            string summaryPath = Path.Combine(response.Directory, FileNames.RunSummary);

            LogInfo(summaryPath, $"Test Request '{request.Id}' - {request.ClientName} ({request.ClientVersion})");

            RunResult runResult = new RunResult {
                Id          = request.Id,
                StartTime   = DateTime.Now,
                State       = TestState.Running,
                Cases       = request.Cases.ToArray(),
                SummaryFile = summaryPath
            };

            RevitTask        runnerTask = new RevitTask();
            ReflectionRunner runner     = new ReflectionRunner();

            runnerTask.Run(async uiApplication => {
                try {
                    runResult.Cases = request.Cases;

                    foreach (TestCase test in request.Cases)
                    {
                        var runTestResult = runResult.Cases.Single(t => t.Id == test.Id);

                        WriteTestResultFile(response.Directory, runResult, false);

                        var testResult = await runner.RunTest(test, application.Application);

                        runTestResult.State      = testResult.State;
                        runTestResult.Message    = testResult.Message;
                        runTestResult.StackTrace = testResult.StackTrace;

                        LogInfo(summaryPath, $"{test.Id,-8} Test {test.State,-7} - {test.TestClass}.{test.MethodName}");

                        if (!string.IsNullOrEmpty(test.Message))
                        {
                            LogInfo(summaryPath, $"\t{test.Message}");
                        }
                        if (!string.IsNullOrEmpty(test.StackTrace))
                        {
                            LogInfo(summaryPath, $"\t{test.StackTrace}");
                        }
                    }
                }
                catch (Exception e) {
                    runResult.Output = e.ToString();
                    LogInfo(summaryPath, e);
                }

                WriteTestResultFile(response.Directory, runResult, true);

                LogInfo(summaryPath, $"Test run end - duration {runResult.Timestamp - runResult.StartTime}");
            });
        }
Exemple #15
0
        public Result OnStartup(UIControlledApplication application)
        {
            //Always initialize RevitTask ahead of time within Revit API context
            RevitTask.Initialize();

            UICtrlApp = application;
            // Fires an init event, where we can get the UIApp
            UICtrlApp.Idling += Initialise;

            var    specklePanel  = application.CreateRibbonPanel("Speckle 2");
            var    speckleButton = specklePanel.AddItem(new PushButtonData("Speckle 2", "Revit Connector", typeof(App).Assembly.Location, typeof(SpeckleRevitCommand).FullName)) as PushButton;
            string path          = typeof(App).Assembly.Location;

            if (speckleButton != null)
            {
                speckleButton.Image                 = LoadPngImgSource("Speckle.ConnectorRevit.Assets.logo16.png", path);
                speckleButton.LargeImage            = LoadPngImgSource("Speckle.ConnectorRevit.Assets.logo32.png", path);
                speckleButton.ToolTip               = "Speckle Connector for Revit";
                speckleButton.AvailabilityClassName = typeof(CmdAvailabilityViews).FullName;
                speckleButton.SetContextualHelp(new ContextualHelp(ContextualHelpType.Url, "https://speckle.systems"));
            }

            //desktopui 2
            var speckleButton2 = specklePanel.AddItem(new PushButtonData("Speckle 2 New Ui", "Revit Connector\nNew UI (alpha)!", typeof(App).Assembly.Location, typeof(SpeckleRevitCommand2).FullName)) as PushButton;

            if (speckleButton2 != null)
            {
                speckleButton2.Image                 = LoadPngImgSource("Speckle.ConnectorRevit.Assets.logo16.png", path);
                speckleButton2.LargeImage            = LoadPngImgSource("Speckle.ConnectorRevit.Assets.logo32.png", path);
                speckleButton2.ToolTip               = "Speckle Connector for Revit - With a new UI";
                speckleButton2.AvailabilityClassName = typeof(CmdAvailabilityViews).FullName;
                speckleButton2.SetContextualHelp(new ContextualHelp(ContextualHelpType.Url, "https://speckle.systems"));
            }


            PulldownButton helpPulldown = specklePanel.AddItem(new PulldownButtonData("Help&Resources", "Help & Resources")) as PulldownButton;

            helpPulldown.Image      = LoadPngImgSource("Speckle.ConnectorRevit.Assets.help16.png", path);
            helpPulldown.LargeImage = LoadPngImgSource("Speckle.ConnectorRevit.Assets.help32.png", path);


            PushButton forum = helpPulldown.AddPushButton(new PushButtonData("forum", "Community Forum", typeof(App).Assembly.Location, typeof(ForumCommand).FullName)) as PushButton;

            forum.ToolTip    = "Check out our Community Forum! Opens a page in your web browser.";
            forum.Image      = LoadPngImgSource("Speckle.ConnectorRevit.Assets.forum16.png", path);
            forum.LargeImage = LoadPngImgSource("Speckle.ConnectorRevit.Assets.forum32.png", path);

            PushButton tutorials = helpPulldown.AddPushButton(new PushButtonData("tutorials", "Tutorials", typeof(App).Assembly.Location, typeof(TutorialsCommand).FullName)) as PushButton;

            tutorials.ToolTip    = "Check out our tutorials! Opens a page in your web browser.";
            tutorials.Image      = LoadPngImgSource("Speckle.ConnectorRevit.Assets.tutorials16.png", path);
            tutorials.LargeImage = LoadPngImgSource("Speckle.ConnectorRevit.Assets.tutorials32.png", path);

            PushButton docs = helpPulldown.AddPushButton(new PushButtonData("docs", "Docs", typeof(App).Assembly.Location, typeof(DocsCommand).FullName)) as PushButton;

            docs.ToolTip    = "Check out our documentation! Opens a page in your web browser.";
            docs.Image      = LoadPngImgSource("Speckle.ConnectorRevit.Assets.docs16.png", path);
            docs.LargeImage = LoadPngImgSource("Speckle.ConnectorRevit.Assets.docs32.png", path);

            PushButton manager = helpPulldown.AddPushButton(new PushButtonData("manager", "Manager", typeof(App).Assembly.Location, typeof(ManagerCommand).FullName)) as PushButton;

            manager.ToolTip    = "Manage accounts and connectors. Opens SpeckleManager.";
            manager.Image      = LoadPngImgSource("Speckle.ConnectorRevit.Assets.logo16.png", path);
            manager.LargeImage = LoadPngImgSource("Speckle.ConnectorRevit.Assets.logo32.png", path);



            return(Result.Succeeded);
        }
 private void LogRequest(ExternalEventRequest request)
 {
     RevitTask.Log($"{Handler.GetName()} {Enum.GetName(typeof(ExternalEventRequest), request)}");
 }
Exemple #17
0
 protected override ExternalEvent Handle(UIApplication app, IExternalEventHandler parameter)
 {
     RevitTask.Log($"creating ExternalEvent for {parameter.GetName()}");
     return(ExternalEvent.Create(parameter));
 }