Beispiel #1
0
        /// <summary>
        /// NEED TO REFINE.
        /// Function to send code to Rhino.
        /// </summary>
        /// <param name="resetEngine"></param>
        private void SendCodeToRhino(bool resetEngine)
        {
            // bypass the function if the code is running
            if (IsSending)
            {
                Alert("Cannot send code.\nAn existing code is still running.");
                return;
            }
            // run in another thread to send the code
            System.Threading.Tasks.Task.Run(() =>
            {
                // set running flag
                IsSending = true;

                // compose the message
                msgObject objMsg = new msgObject();
                objMsg.filename  = GetTempFilePath();
                objMsg.temp      = false;
                objMsg.reset     = resetEngine;
                objMsg.run       = true;

                string sendingMessage = JsonConvert.SerializeObject(objMsg);
                Byte[] sendingBytes   = System.Text.Encoding.ASCII.GetBytes(sendingMessage);

                // get output panel
                var outputPane = GetOutputPane();
                outputPane.Clear();
                outputPane.OutputString($"====== {DateTime.Now.ToString(CultureInfo.CurrentCulture)} ======\n");

                // init tcp connection
                const int portNo      = 614;
                const string serverIp = "127.0.0.1";
                try
                {
                    TcpClient client = new TcpClient(serverIp, portNo);

                    // Get a client stream for reading and writing.
                    NetworkStream stream = client.GetStream();

                    // Send the message to the connected TcpServer.
                    stream.Write(sendingBytes, 0, sendingBytes.Length);

                    // Receive the TcpServer.response.
                    bool isConnected = true;
                    while (isConnected)
                    {
                        // Buffer to store the response bytes.
                        var data = new Byte[256];

                        // Read the the TcpServer response bytes.
                        Int32 bytes = stream.Read(data, 0, data.Length);

                        // String to store the response ASCII representation.
                        string responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);

                        // display message

                        outputPane.OutputString(responseData);

                        // Detect if client disconnected
                        if (client.Client.Poll(0, SelectMode.SelectRead))
                        {
                            byte[] buff = new byte[1];
                            // Client disconnected
                            isConnected = client.Client.Receive(buff, SocketFlags.Peek) != 0;
                        }
                    }

                    // Close everything.
                    stream.Close();
                    client.Close();

                    // delete the file after it's done.
                    deleteTempFile();
                }

                catch (SocketException ex)
                {
                    Alert("Cannot connect Rhino.\nPlease make sure Rhino is running CodeListener.");
                    outputPane.OutputString("Failed:\n" + ex.Message);
                }
                catch (Exception ex)
                {
                    Alert("Unexpected Error.\\Please see the error message in the output panel.");
                    outputPane.OutputString("Failed:\n" + ex.Message);
                }
                finally
                {
                    // set running flag
                    IsSending = false;
                }
            });
        }
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void SendCodeToRhino(object sender, bool resetEngine)
        {
            // bypass the function if the code is running
            if (IsSending)
            {
                Alert("Cannot send code.\nAn existing code is still running.");
                return;
            }
            // run in another thread to send the code
            System.Threading.Tasks.Task.Run(() =>
            {
                // set running flag
                IsSending = true;
                // get the top level vs instance object
                var dte = this.ServiceProvider.GetService(typeof(_DTE)) as _DTE;

                if (dte == null)
                {
                    string message = "Cannot init RhinoPython extension.\nTry to restart visual studio.";
                    Alert(message);
                    IsSending = false;
                    return;
                }
                // save all the documents
                dte.Documents.SaveAll();

                // get the filename with absolute path
                var activeDocument = dte.ActiveDocument;
                if (activeDocument == null)
                {
                    string message = "Cannot read current document.\nMake sure you have the code opening.";
                    Alert(message);
                    IsSending = false;
                    return;
                }
                var activeDocumentName = dte.ActiveDocument.FullName;
                // check if the file is temp file by checking the if the path of file is inside temp folder
                var tempPath           = System.IO.Path.GetTempPath();
                var activeDocumentPath = dte.ActiveDocument.Path;
                var isTempFile         = tempPath == activeDocumentPath;
                // compose the message
                msgObject objMsg = new msgObject();
                objMsg.filename  = activeDocumentName;
                objMsg.temp      = isTempFile;
                objMsg.reset     = resetEngine;
                objMsg.run       = true;

                string sendingMessage = JsonConvert.SerializeObject(objMsg);
                Byte[] sendingBytes   = System.Text.Encoding.ASCII.GetBytes(sendingMessage);

                // get output panel
                var outputPane = GetOutputPane();
                outputPane.Clear();
                outputPane.OutputString($"====== {DateTime.Now.ToString(CultureInfo.CurrentCulture)} ======\n");

                // init tcp connection
                const int portNo      = 614;
                const string serverIp = "127.0.0.1";
                try
                {
                    TcpClient client = new TcpClient(serverIp, portNo);

                    // Get a client stream for reading and writing.
                    NetworkStream stream = client.GetStream();

                    // Send the message to the connected TcpServer.
                    stream.Write(sendingBytes, 0, sendingBytes.Length);

                    // Receive the TcpServer.response.
                    bool isConnected = true;
                    while (isConnected)
                    {
                        // Buffer to store the response bytes.
                        var data = new Byte[256];

                        // Read the the TcpServer response bytes.
                        Int32 bytes = stream.Read(data, 0, data.Length);

                        // String to store the response ASCII representation.
                        string responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);

                        // display message

                        outputPane.OutputString(responseData);

                        // Detect if client disconnected
                        if (client.Client.Poll(0, SelectMode.SelectRead))
                        {
                            byte[] buff = new byte[1];
                            // Client disconnected
                            isConnected = client.Client.Receive(buff, SocketFlags.Peek) != 0;
                        }
                    }

                    // Close everything.
                    stream.Close();
                    client.Close();
                }

                catch (SocketException ex)
                {
                    Alert("Cannot connect Rhino.\nPlease make sure Rhino is running CodeListener.");
                    outputPane.OutputString("Failed:\n" + ex.Message);
                }
                catch (Exception ex)
                {
                    Alert("Unexpected Error.\\Please see the error message in the output panel.");
                    outputPane.OutputString("Failed:\n" + ex.Message);
                }
                finally
                {
                    // set running flag
                    IsSending = false;
                }
            });
        }