/// <summary>
        /// Login to a SpeckleServer
        /// </summary>
        private void Login(object sender, RoutedEventArgs e)
        {
            var signInWindow = new SpecklePopup.SignInWindow(true);

            var helper = new System.Windows.Interop.WindowInteropHelper(signInWindow)
            {
                Owner = new System.Windows.Interop.WindowInteropHelper(this).Handle
            };

            this.IsEnabled = false;

            signInWindow.ShowDialog();

            this.IsEnabled = true;

            if (signInWindow.AccountListBox.SelectedIndex != -1)
            {
                var account = signInWindow.accounts[signInWindow.AccountListBox.SelectedIndex];

                EmailAddress = account.Email;
                RestApi      = account.RestApi;
                ApiToken     = account.Token;
                (SenderTab.Content as Grid).IsEnabled   = FileOpened && LoggedIn;
                (ReceiverTab.Content as Grid).IsEnabled = FileOpened && LoggedIn;
                UpdateClientLists();

                Status.AddMessage("Logged in to account at: " + RestApi);
            }
            else
            {
                Status.AddError("Failed to log in");
            }
        }
        private void SenderStreams_CloneStreams(object sender, RoutedEventArgs e)
        {
            if (RestApi == null && ApiToken == null)
            {
                Status.AddError("Not logged in");
                return;
            }

            var cell = SenderStreams.CurrentCell.Item;

            if (cell.GetType() == typeof(Tuple <string, string>))
            {
                string streamID = (cell as Tuple <string, string>).Item2;

                Task.Run(() => SpeckleStreamManager.CloneStream(RestApi, ApiToken, streamID)).ContinueWith(res =>
                {
                    Application.Current.Dispatcher.BeginInvoke(
                        DispatcherPriority.Background,
                        new Action(() =>
                    {
                        try
                        {
                            Status.AddMessage("Cloned to: " + res.Result);
                        }
                        catch { Status.AddError("Could not clone " + streamID); }
                    }
                                   ));
                });
            }
        }
Beispiel #3
0
        public void CLIReceiver()
        {
            if (!arguments.ContainsKey("streamIDs"))
            {
                Console.WriteLine("Missing -streamIDs argument");
                return;
            }

            var streamIds = arguments["streamIDs"].Split(new char[] { ',' });

            foreach (string id in streamIds)
            {
                GSA.ReceiverInfo.Add(new Tuple <string, string>(id, null));
            }
            GSA.SetSpeckleClients(EmailAddress, RestApi);

            if (arguments.ContainsKey("layer"))
            {
                if (arguments["layer"].ToLower() == "analysis")
                {
                    GSA.Settings.TargetLayer = GSATargetLayer.Analysis;
                }
            }

            if (arguments.ContainsKey("nodeAllowance"))
            {
                try
                {
                    GSA.Settings.CoincidentNodeAllowance = Convert.ToDouble(arguments["nodeAllowance"]);
                }
                catch { }
            }

            GSA.GetSpeckleClients(EmailAddress, RestApi);
            var gsaReceiver = new Receiver();

            Task.Run(() =>
            {
                var nonBlankReceivers = GSA.ReceiverInfo.Where(r => !string.IsNullOrEmpty(r.Item1)).ToList();

                foreach (var streamInfo in nonBlankReceivers)
                {
                    Status.AddMessage("Creating receiver " + streamInfo.Item1);
                    gsaReceiver.Receivers[streamInfo.Item1] = new SpeckleGSAReceiver(RestApi, ApiToken);
                }
            });
            Task.Run(() => gsaReceiver.Initialize(RestApi, ApiToken)).Wait();
            GSA.SetSpeckleClients(EmailAddress, RestApi);
            gsaReceiver.Trigger(null, null);
            gsaReceiver.Dispose();

            GSA.gsaProxy.SaveAs(arguments["file"]);
            GSA.Close();

            Console.WriteLine("Receiving complete");
        }
        /// <summary>
        /// Start and stop receiving.
        /// </summary>
        private async void ReceiveStream(object sender, RoutedEventArgs e)
        {
            if (RestApi == null && ApiToken == null)
            {
                Status.AddError("Not logged in");
                return;
            }

            if (status == UIStatus.IDLE)
            {
                Status.AddMessage("Preparing to receive ...");
                Application.Current.DoEvents();

                status = UIStatus.BUSY;
                ReceiveButtonPath.Data = Geometry.Parse(PAUSE_BUTTON);
                ReceiveButtonPath.Fill = Brushes.DimGray;

                GSA.Settings.TargetLayer = (ReceiverLayerToggle.IsChecked.Value) ? GSATargetLayer.Analysis : GSA.Settings.TargetLayer = GSATargetLayer.Design;

                ReceiverLayerToggle.IsEnabled      = false;
                ReceiverContinuousToggle.IsEnabled = false;
                ReceiverControlPanel.IsEnabled     = false;
                ReceiveButton.IsEnabled            = false;

                Application.Current.DoEvents();

                GSA.GetSpeckleClients(EmailAddress, RestApi);
                if (!GSA.SetSpeckleClients(EmailAddress, RestApi))
                {
                    Status.AddError("Error in communicating GSA - please check if the GSA file has been closed down");
                    status = UIStatus.RECEIVING;
                    ReceiveStream(sender, e);
                    return;
                }

                gsaReceiver = new Receiver();
                try
                {
                    await Task.Run(() =>
                    {
                        var nonBlankReceivers = GSA.ReceiverInfo.Where(r => !string.IsNullOrEmpty(r.Item1)).ToList();

                        foreach (var streamInfo in nonBlankReceivers)
                        {
                            Status.AddMessage("Creating receiver " + streamInfo.Item1);
                            gsaReceiver.Receivers[streamInfo.Item1] = new SpeckleGSAReceiver(RestApi, ApiToken);
                        }
                    });

                    await gsaReceiver.Initialize(RestApi, ApiToken);
                }
                catch (Exception ex)
                {
                    Status.AddError(ex.Message);
                    return;
                }

                status = UIStatus.RECEIVING;
                if (ReceiverContinuousToggle.IsChecked.Value)
                {
                    try
                    {
                        await Task.Run(() =>
                        {
                            gsaReceiver.Trigger(null, null);
                            foreach (var m in ((SpeckleAppUI)GSA.appUi).GroupMessages())
                            {
                                Status.AddMessage(m);
                            }
                        })
                        .ContinueWith(res =>
                        {
                            Application.Current.Dispatcher.BeginInvoke(
                                DispatcherPriority.Background,
                                new Action(() =>
                            {
                                ReceiveStream(sender, e);
                            })
                                );
                        });
                    }
                    catch (Exception ex)
                    {
                        Status.AddError(ex.Message);

                        ReceiveStream(sender, e);
                    }
                }
                else
                {
                    try
                    {
                        await Task.Run(() => gsaReceiver.Trigger(null, null));
                    }
                    catch (Exception ex)
                    {
                        Status.AddError(ex.Message);

                        ReceiveStream(sender, e);
                    }
                    ReceiveButtonPath.Fill = (SolidColorBrush)FindResource("SecondaryAccentBrush");// (SolidColorBrush)(new BrushConverter().ConvertFrom("#0080ff"));
                }
            }
            else if (status == UIStatus.RECEIVING)
            {
                status = UIStatus.IDLE;
                ReceiveButtonPath.Data = Geometry.Parse(PLAY_BUTTON);
                ReceiveButtonPath.Fill = (SolidColorBrush)FindResource("PrimaryHueMidBrush");

                ReceiverLayerToggle.IsEnabled      = true;
                ReceiverContinuousToggle.IsEnabled = true;
                ReceiverControlPanel.IsEnabled     = true;

                if (!ReceiverContinuousToggle.IsChecked.Value)
                {
                    MessageBoxResult result = MessageBox.Show("Bake received objects permanently? ", "SpeckleGSA", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (result != MessageBoxResult.Yes)
                    {
                        gsaReceiver.DeleteSpeckleObjects();
                    }
                }

                gsaReceiver.Dispose();
            }
            ReceiveButton.IsEnabled = true;
        }
        public MainWindow()
        {
            InitializeComponent();

            mainWindow.Title = mainWindow.Title + " - " + getRunningVersion();

            DataContext = this;

            Messages = new ObservableCollection <string>();

            gsaSender   = new Sender();
            gsaReceiver = new Receiver();

            triggerTimer     = new Timer();
            status           = UIStatus.IDLE;
            previousTabIndex = 0;

            //Default settings
            SendOnlyMeaningfulNodes.IsChecked = GSA.Settings.SendOnlyMeaningfulNodes;
            SeparateStreams.IsChecked         = GSA.Settings.SeparateStreams;
            PollingRate.Text             = GSA.Settings.PollingRate.ToString();
            CoincidentNodeAllowance.Text = GSA.Settings.CoincidentNodeAllowance.ToString();
            SendOnlyResults.IsChecked    = GSA.Settings.SendOnlyResults;
            EmbedResults.IsChecked       = GSA.Settings.EmbedResults;
            ResultCases.Text             = string.Join("\r\n", GSA.Settings.ResultCases);
            ResultInLocalAxis.IsChecked  = GSA.Settings.ResultInLocalAxis;
            Result1DNumPosition.Text     = GSA.Settings.Result1DNumPosition.ToString();

            //Result List
            foreach (string s in Result.NodalResultMap.Keys)
            {
                CheckBox chk = new CheckBox
                {
                    Content = s,
                    Tag     = Result.NodalResultMap[s]
                };
                chk.Checked   += UpdateNodalResult;
                chk.Unchecked += UpdateNodalResult;
                ResultSelection.Children.Add(chk);
            }

            foreach (string s in Result.Element1DResultMap.Keys)
            {
                CheckBox chk = new CheckBox
                {
                    Content = s,
                    Tag     = Result.Element1DResultMap[s]
                };
                chk.Checked   += UpdateElement1DResult;
                chk.Unchecked += UpdateElement1DResult;
                ResultSelection.Children.Add(chk);
            }

            foreach (string s in Result.Element2DResultMap.Keys)
            {
                CheckBox chk = new CheckBox
                {
                    Content = s,
                    Tag     = Result.Element2DResultMap[s]
                };
                chk.Checked   += UpdateElement2DResult;
                chk.Unchecked += UpdateElement2DResult;
                ResultSelection.Children.Add(chk);
            }

            foreach (string s in Result.MiscResultMap.Keys)
            {
                CheckBox chk = new CheckBox
                {
                    Content = s,
                    Tag     = Result.MiscResultMap[s]
                };
                chk.Checked   += UpdateMiscResult;
                chk.Unchecked += UpdateMiscResult;
                ResultSelection.Children.Add(chk);
            }

            //Draw buttons
            SendButtonPath.Data    = Geometry.Parse(PLAY_BUTTON);
            SendButtonPath.Fill    = (SolidColorBrush)FindResource("PrimaryHueMidBrush");
            ReceiveButtonPath.Data = Geometry.Parse(PLAY_BUTTON);
            ReceiveButtonPath.Fill = (SolidColorBrush)FindResource("PrimaryHueMidBrush");

            //Adds event handling delegates to the status events
            Status.Init(this.AddMessage, this.AddError, this.ChangeStatus);
            GSA.Init();

            //Add further event handling delegates - this time for logging - to the status events
            Status.MessageAdded += (sender, eventArgs) => { Log.Information(eventArgs.Message); };
            Status.ErrorAdded   += (sender, eventArgs) =>
            {
                if (eventArgs.Exception == null)
                {
                    Log.Error(eventArgs.Message);
                }
                else
                {
                    Log.Error(eventArgs.Exception, eventArgs.Message);
                    if (eventArgs.Exception.InnerException != null)
                    {
                        Log.Error(eventArgs.Exception.InnerException, eventArgs.Message);
                    }
                }
            };

            MessagePane.ItemsSource = Messages;

            SpeckleCore.SpeckleInitializer.Initialize();
            SpeckleCore.LocalContext.Init();

            try
            {
                //This will throw an exception if there is no default account
                var account = SpeckleCore.LocalContext.GetDefaultAccount();
                if (account != null)
                {
                    EmailAddress = account.Email;
                    RestApi      = account.RestApi;
                    ApiToken     = account.Token;

                    Status.AddMessage("Logged in to default account at: " + RestApi);
                }
            }
            catch
            {
                Status.AddMessage("No default account found - press the Login button to login/select an account");
            }
        }
        /// <summary>
        /// Start and stop sending.
        /// </summary>
        private async void SendStream(object sender, RoutedEventArgs e)
        {
            if (RestApi == null && ApiToken == null)
            {
                Status.AddError("Not logged in");
                return;
            }

            if (status == UIStatus.IDLE)
            {
                if (GSA.Settings.NodalResults.Count > 0 || GSA.Settings.Element1DResults.Count > 0 ||
                    GSA.Settings.Element2DResults.Count > 0 || GSA.Settings.MiscResults.Count > 0)
                {
                    //SenderLayerToggle is a boolean toggle, where zero is design layer
                    if (!SenderLayerToggle.IsChecked.Value)
                    {
                        var dialogResult = MessageBox.Show("Results only supported for analysis layer.\r\nNo results will be sent.  Do you still wish to proceed?",
                                                           "SpeckleGSA", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                        if (dialogResult == MessageBoxResult.No)
                        {
                            return;
                        }
                        GSA.Settings.SendResults = false;
                    }
                    else if (!SenderContinuousToggle.IsChecked.Value)
                    {
                        var dialogResult = MessageBox.Show("Results only supported for single send mode.\r\nNo results will be sent.  Do you still wish to proceed?",
                                                           "SpeckleGSA", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                        if (dialogResult == MessageBoxResult.No)
                        {
                            return;
                        }
                        GSA.Settings.SendResults = false;
                    }
                    else
                    {
                        GSA.Settings.SendResults = true;
                    }
                }
                else
                {
                    GSA.Settings.SendResults = false;
                }

                Status.AddMessage("Preparing to send ...");
                Application.Current.DoEvents();

                status = UIStatus.BUSY;
                SendButtonPath.Data = Geometry.Parse(PAUSE_BUTTON);
                SendButtonPath.Fill = Brushes.DimGray;

                if (SenderLayerToggle.IsChecked.Value)
                {
                    GSA.Settings.TargetLayer = GSATargetLayer.Analysis;
                }
                else
                {
                    GSA.Settings.TargetLayer = GSATargetLayer.Design;
                }
                SenderLayerToggle.IsEnabled      = false;
                SenderContinuousToggle.IsEnabled = false;

                SenderButton.IsEnabled = false;
                Application.Current.DoEvents();

                try
                {
                    if (!GSA.GetSpeckleClients(EmailAddress, RestApi))
                    {
                        Status.AddError("Error in communicating GSA - please check if the GSA file has been closed down");
                        status = UIStatus.SENDING;
                        SendStream(sender, e);
                        return;
                    }
                    gsaSender = new Sender();
                    var statusMessages = await gsaSender.Initialize(RestApi, ApiToken, (restApi, apiToken) => new SpeckleGSASender(restApi, apiToken));

                    GSA.SetSpeckleClients(EmailAddress, RestApi);
                }
                catch (Exception ex)
                {
                    Status.AddError(ex.Message);
                    return;
                }

                var resultCases = GSA.Settings.ResultCases;

                if (GSA.Settings.SendResults && resultCases.Count() > 0)
                {
                    var startTime = DateTime.Now;

                    var expandedCases = GSA.gsaCache.ExpandLoadCasesAndCombinations(string.Join(" ", resultCases));

                    if (!expandedCases.SequenceEqual(resultCases))
                    {
                        Status.AddMessage("Expanded list of load cases/combinations to be sent: " + string.Join(" ", expandedCases));

                        GSA.Settings.ResultCases = expandedCases;

                        TimeSpan duration = DateTime.Now - startTime;
                        if (duration.Milliseconds > 100)
                        {
                            Status.AddMessage("Duration of expanding and validating load cases/combinations: " + duration.ToString(@"hh\:mm\:ss"));
                        }
                    }
                }

                status = UIStatus.SENDING;
                if (SenderContinuousToggle.IsChecked.Value)
                {
                    try
                    {
                        await Task.Run(() => gsaSender.Trigger())
                        .ContinueWith(res =>
                        {
                            Application.Current.Dispatcher.BeginInvoke(
                                DispatcherPriority.Background,
                                new Action(() =>
                            {
                                UpdateClientLists();
                                SendStream(sender, e);
                            })
                                );
                        });
                    }
                    catch (Exception ex)
                    {
                        Status.AddError(ex.Message);
                        //SendStream(sender, e);
                    }
                }
                else
                {
                    triggerTimer           = new Timer(GSA.Settings.PollingRate);
                    triggerTimer.Elapsed  += SenderTimerTrigger;
                    triggerTimer.AutoReset = false;
                    triggerTimer.Start();

                    SendButtonPath.Fill = (SolidColorBrush)FindResource("SecondaryAccentBrush");// (new BrushConverter().ConvertFrom("#0080ff"));
                }
            }
            else if (status == UIStatus.SENDING)
            {
                gsaSender.Dispose();
                status = UIStatus.IDLE;
                SendButtonPath.Data = Geometry.Parse(PLAY_BUTTON);
                SendButtonPath.Fill = (SolidColorBrush)FindResource("PrimaryHueMidBrush");

                SenderLayerToggle.IsEnabled      = true;
                SenderContinuousToggle.IsEnabled = true;
                SenderButton.IsEnabled           = true;
            }
        }