Represents the SuperPuTTY application itself
Example #1
0
        private void buttonOk_Click(object sender, EventArgs e)
        {
            List <String> errors = new List <string>();

            if (String.IsNullOrEmpty(textBoxFilezillaLocation.Text) || File.Exists(textBoxFilezillaLocation.Text))
            {
                SuperPuTTY.Settings.FileZillaExe = textBoxFilezillaLocation.Text;
            }

            if (String.IsNullOrEmpty(textBoxWinSCPLocation.Text) || File.Exists(textBoxWinSCPLocation.Text))
            {
                SuperPuTTY.Settings.WinSCPExe = textBoxWinSCPLocation.Text;
            }

            if (String.IsNullOrEmpty(textBoxPscpLocation.Text) || File.Exists(textBoxPscpLocation.Text))
            {
                SuperPuTTY.Settings.PscpExe = textBoxPscpLocation.Text;
            }

            if (String.IsNullOrEmpty(textBoxVNCLocation.Text) || File.Exists(textBoxVNCLocation.Text))
            {
                SuperPuTTY.Settings.VNCExe = textBoxVNCLocation.Text;
            }

            string settingsDir = textBoxSettingsFolder.Text;

            if (String.IsNullOrEmpty(settingsDir) || !Directory.Exists(settingsDir))
            {
                errors.Add("Settings Folder must be set to valid directory");
            }
            else
            {
                SuperPuTTY.Settings.SettingsFolder = settingsDir;
            }

            if (this.comboBoxLayouts.SelectedValue != null)
            {
                SuperPuTTY.Settings.DefaultLayoutName = (string)comboBoxLayouts.SelectedValue;
            }

            if (!String.IsNullOrEmpty(textBoxPuttyLocation.Text) && File.Exists(textBoxPuttyLocation.Text))
            {
                SuperPuTTY.Settings.PuttyExe = textBoxPuttyLocation.Text;
            }
            else
            {
                errors.Insert(0, "PuTTY is required to properly use this application.");
            }

            string mintty = this.textBoxMinttyLocation.Text;

            if (!string.IsNullOrEmpty(mintty) && File.Exists(mintty))
            {
                SuperPuTTY.Settings.MinttyExe = mintty;
            }

            if (errors.Count == 0)
            {
                SuperPuTTY.Settings.SingleInstanceMode            = this.checkSingleInstanceMode.Checked;
                SuperPuTTY.Settings.RestrictContentToDocumentTabs = this.checkConstrainPuttyDocking.Checked;
                SuperPuTTY.Settings.MultipleTabCloseConfirmation  = this.checkConfirmTabClose.Checked;
                SuperPuTTY.Settings.RestoreWindowLocation         = this.checkRestoreWindow.Checked;
                SuperPuTTY.Settings.ExitConfirmation            = this.checkExitConfirmation.Checked;
                SuperPuTTY.Settings.ExpandSessionsTreeOnStartup = this.checkExpandTree.Checked;
                SuperPuTTY.Settings.EnableControlTabSwitching   = this.checkEnableControlTabSwitching.Checked;
                SuperPuTTY.Settings.EnableKeyboadShortcuts      = this.checkEnableKeyboardShortcuts.Checked;
                SuperPuTTY.Settings.MinimizeToTray        = this.checkMinimizeToTray.Checked;
                SuperPuTTY.Settings.TabTextBehavior       = (string)this.comboBoxTabText.SelectedItem;
                SuperPuTTY.Settings.TabSwitcher           = (string)this.comboBoxTabSwitching.SelectedItem.GetType().FullName;
                SuperPuTTY.Settings.SessionsTreeShowLines = this.checkSessionsTreeShowLines.Checked;
                SuperPuTTY.Settings.SessionsTreeFont      = this.btnFont.Font;
                SuperPuTTY.Settings.WindowActivator       = (string)this.comboBoxActivatorType.SelectedItem;
                SuperPuTTY.Settings.Opacity            = (double)this.numericUpDownOpacity.Value / 100.0;
                SuperPuTTY.Settings.SessionsSearchMode = (string)this.comboSearchMode.SelectedItem;
                SuperPuTTY.Settings.QuickSelectorCaseSensitiveSearch = this.checkQuickSelectorCaseSensitiveSearch.Checked;
                SuperPuTTY.Settings.ShowDocumentIcons = this.checkShowDocumentIcons.Checked;
                SuperPuTTY.Settings.DockingRestrictFloatingWindows = this.checkRestrictFloatingWindows.Checked;
                SuperPuTTY.Settings.SessionsShowSearch             = this.checkSessionsShowSearch.Checked;
                SuperPuTTY.Settings.PuttyPanelShowNewSessionMenu   = this.checkPuttyEnableNewSessionMenu.Checked;
                SuperPuTTY.Settings.AutoUpdateCheck                = this.checkBoxCheckForUpdates.Checked;
                SuperPuTTY.Settings.PscpHomePrefix                 = this.textBoxHomeDirPrefix.Text;
                SuperPuTTY.Settings.PscpRootHomePrefix             = this.textBoxRootDirPrefix.Text;
                SuperPuTTY.Settings.SessiontreeShowFoldersFirst    = this.checkSessionTreeFoldersFirst.Checked;
                SuperPuTTY.Settings.PersistCommandBarHistory       = this.checkBoxPersistTsHistory.Checked;
                SuperPuTTY.Settings.SaveCommandHistoryDays         = (int)this.numericUpDown1.Value;
                SuperPuTTY.Settings.AllowPlainTextPuttyPasswordArg = this.checkBoxAllowPuttyPWArg.Checked;
                SuperPuTTY.Settings.PuttyDefaultParameters         = this.textBoxPuttyDefaultParameters.Text;

                // save shortcuts
                KeyboardShortcut[] shortcuts = new KeyboardShortcut[this.Shortcuts.Count];
                this.Shortcuts.CopyTo(shortcuts, 0);
                SuperPuTTY.Settings.UpdateFromShortcuts(shortcuts);

                SuperPuTTY.Settings.Save();

                // @TODO - move this to a better place...maybe event handler after opening
                if (OrigSettingsFolder != SuperPuTTY.Settings.SettingsFolder)
                {
                    SuperPuTTY.LoadLayouts();
                    SuperPuTTY.LoadSessions();
                }
                else if (OrigDefaultLayoutName != SuperPuTTY.Settings.DefaultLayoutName)
                {
                    SuperPuTTY.LoadLayouts();
                }

                DialogResult = DialogResult.OK;
            }
            else
            {
                StringBuilder sb = new StringBuilder();
                foreach (string s in errors)
                {
                    sb.Append(s).AppendLine().AppendLine();
                }
                if (MessageBox.Show(sb.ToString(), "Errors", MessageBoxButtons.RetryCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
                {
                    DialogResult = DialogResult.Cancel;
                }
            }
        }
Example #2
0
        /// <summary>
        /// Create/Update a session entry
        /// </summary>
        /// <param name="sender">The toolstripmenuitem control that was clicked</param>
        /// <param name="e">An Empty EventArgs object</param>
        private void CreateOrEditSessionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SessionData session = null;
            TreeNode    node    = null;
            TreeNode    nodeRef = this.nodeRoot;
            bool        isEdit  = false;
            string      title   = null;

            if (sender is ToolStripMenuItem)
            {
                ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
                bool isFolderNode          = IsFolderNode(treeView1.SelectedNode);
                if (menuItem.Text.ToLower().Equals("new") || isFolderNode)
                {
                    session = new SessionData();
                    nodeRef = isFolderNode ? treeView1.SelectedNode : treeView1.SelectedNode.Parent;
                    title   = "Create New Session";
                }
                else if (menuItem == this.createLikeToolStripMenuItem)
                {
                    // copy as
                    session             = (SessionData)((SessionData)treeView1.SelectedNode.Tag).Clone();
                    session.SessionId   = SuperPuTTY.MakeUniqueSessionId(session.SessionId);
                    session.SessionName = SessionData.GetSessionNameFromId(session.SessionId);
                    nodeRef             = treeView1.SelectedNode.Parent;
                    title = "Create New Session Like " + session.OldName;
                }
                else
                {
                    // edit, session node selected
                    session = (SessionData)treeView1.SelectedNode.Tag;
                    node    = treeView1.SelectedNode;
                    nodeRef = node.Parent;
                    isEdit  = true;
                    title   = "Edit Session: " + session.SessionName;
                }
            }

            dlgEditSession form = new dlgEditSession(session, this.treeView1.ImageList);

            form.Text = title;
            form.SessionNameValidator += delegate(string txt, out string error)
            {
                error = String.Empty;
                bool isDupeNode = isEdit ? txt != node.Text && nodeRef.Nodes.ContainsKey(txt) : nodeRef.Nodes.ContainsKey(txt);
                if (isDupeNode)
                {
                    error = "Session with same name exists";
                }
                else if (txt.Contains(SessionIdDelim))
                {
                    error = "Invalid character ( " + SessionIdDelim + " ) in name";
                }
                else if (string.IsNullOrEmpty(txt) || txt.Trim() == String.Empty)
                {
                    error = "Empty name";
                }
                return(string.IsNullOrEmpty(error));
            };

            if (form.ShowDialog(this) == DialogResult.OK)
            {
                /* "node" will only be assigned if we're editing an existing session entry */
                if (node == null)
                {
                    // get the path up to the ref (parent) node
                    if (nodeRoot != nodeRef)
                    {
                        UpdateSessionId(nodeRef, session);
                        session.SessionId = SessionData.CombineSessionIds(session.SessionId, session.SessionName);
                    }
                    SuperPuTTY.AddSession(session);

                    // find new node and select it
                    TreeNode nodeNew = nodeRef.Nodes[session.SessionName];
                    if (nodeNew != null)
                    {
                        this.treeView1.SelectedNode = nodeNew;
                    }
                }
                else
                {
                    // handle renames
                    node.Text             = session.SessionName;
                    node.Name             = session.SessionName;
                    node.ImageKey         = session.ImageKey;
                    node.SelectedImageKey = session.ImageKey;
                    if (session.SessionId != session.OldSessionId)
                    {
                        try
                        {
                            this.isRenamingNode = true;
                            SuperPuTTY.RemoveSession(session.OldSessionId);
                            SuperPuTTY.AddSession(session);
                        }
                        finally
                        {
                            this.isRenamingNode = false;
                        }
                    }
                    ResortNodes();
                    this.treeView1.SelectedNode = node;
                }

                //treeView1.ExpandAll();
                SuperPuTTY.SaveSessions();
            }
        }
Example #3
0
        private void InitNewSessionToolStripMenuItems()
        {
            List <ToolStripMenuItem> tsmi = new List <ToolStripMenuItem>();

            foreach (SessionData session in SuperPuTTY.GetAllSessions())
            {
                ToolStripMenuItem tsmiParent = null;
                foreach (string part in SessionData.GetSessionNameParts(session.SessionId))
                {
                    if (part == session.SessionName)
                    {
                        ToolStripMenuItem newSessionTSMI = new ToolStripMenuItem
                        {
                            Tag  = session,
                            Text = session.SessionName
                        };
                        newSessionTSMI.Click      += new System.EventHandler(newSessionTSMI_Click);
                        newSessionTSMI.ToolTipText = session.ToString();
                        if (tsmiParent == null)
                        {
                            tsmi.Add(newSessionTSMI);
                        }
                        else
                        {
                            tsmiParent.DropDownItems.Add(newSessionTSMI);
                        }
                    }
                    else
                    {
                        if (tsmiParent == null)
                        {
                            tsmiParent = tsmi.FirstOrDefault((item) => string.Equals(item.Name, part));
                            if (tsmiParent == null)
                            {
                                tsmiParent = new ToolStripMenuItem(part)
                                {
                                    Name = part
                                };
                                tsmi.Add(tsmiParent);
                            }
                        }
                        else
                        {
                            if (tsmiParent.DropDownItems.ContainsKey(part))
                            {
                                tsmiParent = (ToolStripMenuItem)tsmiParent.DropDownItems[part];
                            }
                            else
                            {
                                ToolStripMenuItem newSessionFolder = new ToolStripMenuItem(part)
                                {
                                    Name = part
                                };
                                tsmiParent.DropDownItems.Add(newSessionFolder);
                                tsmiParent = newSessionFolder;
                            }
                        }
                    }
                }
            }

            if (InvokeRequired)
            {
                Invoke(new Action(() => {
                    if (newSessionToolStripMenuItem.DropDownItems.Count == 0)
                    {
                        newSessionToolStripMenuItem.DropDownItems.AddRange(tsmi.ToArray());
                    }
                }));
            }
            else
            if (newSessionToolStripMenuItem.DropDownItems.Count == 0)
            {
                newSessionToolStripMenuItem.DropDownItems.AddRange(tsmi.ToArray());
            }
        }
Example #4
0
 private void duplicateSessionToolStripMenuItem_Click(object sender, EventArgs e)
 {
     SuperPuTTY.OpenPuttySession(this.Session);
 }
Example #5
0
        /// <summary>
        /// Open a directory listing on the selected nodes host to allow dropping files
        /// for drag + drop copy.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void fileBrowserToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SessionData session = (SessionData)treeView1.SelectedNode.Tag;

            SuperPuTTY.OpenScpSession(session);
        }
Example #6
0
 private void fileTransferToolStripMenuItem_Click(object sender, EventArgs e)
 {
     SuperPuTTY.OpenScpSession(this.Session);
 }
Example #7
0
        /// <summary>
        /// Create/Update a session entry
        /// </summary>
        /// <param name="sender">The toolstripmenuitem control that was clicked</param>
        /// <param name="e">An Empty EventArgs object</param>
        private void CreateOrEditSessionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SessionData session = null;
            TreeNode    node    = null;
            TreeNode    nodeRef = this.nodeRoot;
            string      title   = null;

            if (sender is ToolStripMenuItem)
            {
                ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
                bool isFolderNode          = IsFolderNode(treeView1.SelectedNode);
                if (menuItem.Text.ToLower().Equals("new") || isFolderNode)
                {
                    session = new SessionData();
                    nodeRef = isFolderNode ? treeView1.SelectedNode : treeView1.SelectedNode.Parent;
                    title   = "Create New Session";
                }
                else if (menuItem == this.createLikeToolStripMenuItem)
                {
                    // copy as
                    session             = (SessionData)((SessionData)treeView1.SelectedNode.Tag).Clone();
                    session.SessionId   = SuperPuTTY.MakeUniqueSessionId(session.SessionId);
                    session.SessionName = SessionData.GetSessionNameFromId(session.SessionId);
                    nodeRef             = treeView1.SelectedNode.Parent;
                    title = "Create New Session Like " + session.OldName;
                }
                else
                {
                    // edit, session node selected
                    // We make a clone of the session since we do not want to directly edit the real object.
                    session = (SessionData)((SessionData)treeView1.SelectedNode.Tag).Clone();
                    node    = treeView1.SelectedNode;
                    nodeRef = node.Parent;
                    title   = "Edit Session: " + session.SessionName;
                }
            }

            dlgEditSession form = new dlgEditSession(session, this.treeView1.ImageList)
            {
                Text = title
            };

            form.SessionNameValidator += delegate(string txt, out string error)
            {
                bool IsValid = ValidateSessionNameChange(nodeRef, node, txt, out error);
                return(IsValid);
            };

            if (form.ShowDialog(this) == DialogResult.OK)
            {
                /* "node" will only be assigned if we're editing an existing session entry */
                if (node == null)
                {
                    // get the path up to the ref (parent) node
                    if (nodeRoot != nodeRef)
                    {
                        UpdateSessionId(nodeRef, session);
                        session.SessionId = SessionData.CombineSessionIds(session.SessionId, session.SessionName);
                    }
                    SuperPuTTY.AddSession(session);

                    // find new node and select it
                    TreeNode nodeNew = nodeRef.Nodes[session.SessionName];
                    if (nodeNew != null)
                    {
                        this.treeView1.SelectedNode = nodeNew;
                    }
                }
                else
                {
                    SessionData RealSession = (SessionData)treeView1.SelectedNode.Tag;
                    RealSession.CopyFrom(session);
                    RealSession.SessionName     = session.SessionName;
                    this.treeView1.SelectedNode = node;
                }

                //treeView1.ExpandAll();
                SuperPuTTY.SaveSessions();
            }
        }
Example #8
0
        public void SessionPropertyChanged(SessionData Session, String PropertyName)
        {
            if (Session == null)
            {
                return;
            }

            if (PropertyName == "SessionName" || PropertyName == "ImageKey")
            {
                TreeNode Node = FindSessionNode(Session.SessionId);
                if (Node == null)
                {
                    // It is possible that the session id was changed before the
                    // session name. In this case, we check to see if we
                    // can find a node with the old session id that is also associated
                    // to the session data.
                    Node = FindSessionNode(Session.OldSessionId);
                    if (Node == null || Node.Tag != Session)
                    {
                        return;
                    }
                }

                Node.Text             = Session.SessionName;
                Node.Name             = Session.SessionName;
                Node.ImageKey         = Session.ImageKey;
                Node.SelectedImageKey = Session.ImageKey;

                bool IsSelectedSession = treeView1.SelectedNode == Node;
                ResortNodes();
                if (IsSelectedSession)
                {
                    // Re-selecting the node since it will be unselected when sorting.
                    treeView1.SelectedNode = Node;
                }
            }
            else if (PropertyName == "SessionId")
            {
                TreeNode Node = FindSessionNode(Session.OldSessionId);
                if (Node == null)
                {
                    // It is possible that the session name was changed before the
                    // session id. In this case, we check to see if we
                    // can find a node with the current session id that is also associated
                    // to the session data.
                    Node = FindSessionNode(Session.SessionId);
                    if (Node == null || Node.Tag != Session)
                    {
                        return;
                    }
                }

                try
                {
                    this.isRenamingNode = true;
                    SuperPuTTY.RemoveSession(Session.OldSessionId);
                    SuperPuTTY.AddSession(Session);
                }
                finally
                {
                    this.isRenamingNode = false;
                }
            }
        }
Example #9
0
        public void BeginGetDirectoryListing(string path, DirListingCallback callback)
        {
            if (m_Session == null)
            {
                callback(RequestResult.SessionInvalid, null);
                return;
            }

            List <FileEntry> files        = new List <FileEntry>();
            Stopwatch        timeoutWatch = new Stopwatch();

            /*
             * Check that we have a username either stored from previous sessions, or loaded
             * from the registry. If PPK Authentication is being used that will override
             * any values entered in the login dialog
             */
            if (String.IsNullOrEmpty(m_Session.Username))
            {
                if (m_Login.ShowDialog(SuperPuTTY.MainForm) == System.Windows.Forms.DialogResult.OK)
                {
                    m_Session.Username = m_Login.Username;
                    m_Session.Password = m_Login.Password;

                    if (m_Login.Remember)
                    {
                        //Session.SaveToRegistry(); // passwords are *never* saved and stored permanently
                        SuperPuTTY.SaveSessions();
                    }
                }
                else
                {
                    Logger.Log("Cancel connection");
                    callback(RequestResult.CancelLogin, null);
                }
            }

            Thread threadListFiles = new Thread(delegate()
            {
                m_processDir = new Process();

                m_processDir.EnableRaisingEvents             = true;
                m_processDir.StartInfo.UseShellExecute       = false;
                m_processDir.StartInfo.RedirectStandardError = true;
                //m_processDir.StartInfo.RedirectStandardInput = true;
                m_processDir.StartInfo.RedirectStandardOutput = true;
                m_processDir.StartInfo.CreateNoWindow         = true;
                m_processDir.StartInfo.FileName = SuperPuTTY.Settings.PscpExe;
                // process the various options from the session object and convert them into arguments pscp can understand
                string args = MakeArgs(m_Session, true, path);
                Logger.Log("Sending Command: '{0} {1}'", m_processDir.StartInfo.FileName, MakeArgs(m_Session, false, path));
                m_processDir.StartInfo.Arguments = args;

                /*
                 * Handle output from spawned pscp.exe process, handle any data received and parse
                 * any lines that look like a directory listing.
                 */
                m_processDir.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e)
                {
                    if (!String.IsNullOrEmpty(e.Data))
                    {
                        if (e.Data.Equals(PUTTY_ARGUMENTS_HELP_HEADER))
                        {
                            m_processDir.CancelOutputRead();
                            m_processDir.Kill();
                            return;
                        }
                        else if (e.Data.StartsWith("Listing directory "))
                        {
                            // This just tells us the current directory, however since we're the ones that requested it
                            // we already have this information. But this traps it so its not sent through the directory
                            // entry parser.
                        }
                        else if (e.Data.Equals(PUTTY_INTERACTIVE_AUTH) || e.Data.Contains("password: "******"Username/Password invalid or not sent");
                            callback(RequestResult.RetryAuthentication, null);
                        }
                        else
                        {
                            timeoutWatch.Reset();
                            lock (files)
                            {
                                FileEntry file;
                                if (TryParseFileLine(e.Data, out file))
                                {
                                    files.Add(file);
                                }

                                if (files.Count > 0)
                                {
                                    callback(RequestResult.ListingFollows, files);
                                }
                            }
                        }
                    }
                };

                m_processDir.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs e)
                {
                    if (!String.IsNullOrEmpty(e.Data))
                    {
                        if (e.Data.Contains(PUTTY_NO_KEY))
                        {
                            m_processDir.CancelErrorRead();
                            m_processDir.Kill();
                            System.Windows.Forms.MessageBox.Show("The key of the host you are attempting to connect to has changed or is not cached \n" +
                                                                 "You must connect to this host with with a PuTTY ssh terminal to accept the key and store it in the cache", "Host Key not found or changed", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Stop);
                        }
                        else
                        {
                            Logger.Log("Error Data:\n\t'{0}'", e.Data.TrimEnd());
                            // 'ssh_init: Host does not exist'
                        }
                    }
                };

                m_processDir.Exited += delegate(object sender, EventArgs e)
                {
                    if (m_processDir.ExitCode != 0)
                    {
                        Logger.Log("Process Exited (Failure): {0}", m_processDir.ExitCode);
                        callback(RequestResult.UnknownError, null);
                        if (m_PuttyClosed != null)
                        {
                            m_PuttyClosed(true);
                        }
                    }
                    else
                    {
                        Logger.Log("Process Exited: {0}", m_processDir.ExitCode);
                        if (m_PuttyClosed != null)
                        {
                            m_PuttyClosed(false);
                        }
                    }
                    m_DirIsBusy = false;
                };

                try
                {
                    m_processDir.Start();
                }
                catch (Win32Exception e)
                {
                    if (e.NativeErrorCode == 2) // File Not Found
                    {
                        Logger.Log(e);
                    }
                    else if (e.NativeErrorCode == 4) // Acess Denied
                    {
                        Logger.Log(e);
                    }
                }

                m_processDir.BeginErrorReadLine();
                m_processDir.BeginOutputReadLine();
                m_processDir.WaitForExit();
            });

            /* Only allow one directory list request at a time */
            if (!m_DirIsBusy)
            {
                m_DirIsBusy                  = true;
                threadListFiles.Name         = "List Remote Directory";
                threadListFiles.IsBackground = true;
                threadListFiles.Start();
            }
            else
            {
                return;
            }

            Thread timeoutThread = new Thread(delegate()
            {
                while (m_DirIsBusy)
                {
                    /*
                     * if no data received in 5 seconds we'll stop the process,
                     * This allows us to capture any interactive prompts/messages
                     * sent to us by putty.
                     */
                    if (timeoutWatch.Elapsed.Seconds >= 5)
                    {
                        Logger.Log("Timeout after {0} seconds", timeoutWatch.Elapsed.Seconds);

                        if (!m_processDir.HasExited)
                        {
                            m_processDir.Kill();
                        }
                        m_processDir.CancelErrorRead();
                        m_processDir.CancelOutputRead();
                        return;
                    }
                    Thread.Sleep(1000);
                }
            });

            timeoutThread.Name         = "Timeout Watcher";
            timeoutThread.IsBackground = true;
            timeoutThread.Start();
            timeoutWatch.Start();
        }
Example #10
0
        /// <summary>Open a new putty window with its settings being passed in a <seealso cref="SessionData"/> object</summary>
        /// <param name="session">The <seealso cref="SessionData"/> object containing the settings</param>
        public static ctlPuttyPanel OpenProtoSession(SessionData session)
        {
            Log.InfoFormat("Opening putty session, id={0}", session == null ? "" : session.SessionId);
            ctlPuttyPanel panel = null;

            if (session != null)
            {
                String Executable = PuttyStartInfo.GetExecutable(session);
                if (String.IsNullOrEmpty(Executable))
                {
                    MessageBox.Show("Error trying to create session: " + session.ToString() +
                                    "\nExecutable not set for " + session.Proto.ToString() + " protocol." +
                                    "\nGo to tools->options->General tab to set the path to the executable."
                                    , "Failed to create a session", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return(null);
                }
                if (!File.Exists(Executable))
                {
                    MessageBox.Show("Error trying to create session: " + session.ToString() +
                                    "\nExecutable not found for " + session.Proto.ToString() + " protocol." +
                                    "\nThe path for the executable was set as \"" + Executable + "\"." +
                                    "\nGo to tools->options->General tab to set the path to the executable."
                                    , "Failed to create a session", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return(null);
                }

                // This is the callback fired when the panel containing the terminal is closed
                // We use this to save the last docking location and to close the panel
                PuttyClosedCallback callback = delegate
                {
                    if (panel != null)
                    {
                        // save the last dockstate (if it has been changed)
                        if (session.LastDockstate != panel.DockState &&
                            panel.DockState != DockState.Unknown &&
                            panel.DockState != DockState.Hidden)
                        {
                            session.LastDockstate = panel.DockState;
                            SuperPuTTY.SaveSessions();
                        }

                        if (panel.InvokeRequired)
                        {
                            panel.BeginInvoke((MethodInvoker) delegate {
                                panel.Close();
                            });
                        }
                        else
                        {
                            panel.Close();
                        }
                    }
                };

                try {
                    panel = new ctlPuttyPanel(session, callback);

                    ApplyDockRestrictions(panel);
                    ApplyIconForWindow(panel, session);
                    panel.Show(MainForm.DockPanel, session.LastDockstate);
                    ReportStatus("Opened session: {0} [{1}]", session.SessionId, session.Proto);

                    if (!String.IsNullOrEmpty(session.SPSLFileName) &&
                        File.Exists(session.SPSLFileName))
                    {
                        ExecuteScriptEventArgs scriptArgs = new ExecuteScriptEventArgs()
                        {
                            Script = File.ReadAllText(session.SPSLFileName), Handle = panel.AppPanel.AppWindowHandle
                        };
                        if (!String.IsNullOrEmpty(scriptArgs.Script))
                        {
                            SPSL.BeginExecuteScript(scriptArgs);
                        }
                    }
                } catch (InvalidOperationException ex)
                {
                    MessageBox.Show("Error trying to create session " + ex.Message, "Failed to create session panel", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return(panel);
        }
Example #11
0
        /// <summary>Open a new putty window with its settings being passed in a <seealso cref="SessionData"/> object</summary>
        /// <param name="session">The <seealso cref="SessionData"/> object containing the settings</param>
        public static ctlPuttyPanel OpenProtoSession(SessionData session)
        {
            Log.InfoFormat("Opening putty session, id={0}", session == null ? "" : session.SessionId);
            ctlPuttyPanel panel = null;

            if (session != null)
            {
                String Executable = PuttyStartInfo.GetExecutable(session);
                if (String.IsNullOrEmpty(Executable))
                {
                    MessageBox.Show("Error trying to create session: " + session.ToString() +
                                    "\nExecutable not set for " + session.Proto.ToString() + " protocol." +
                                    "\nGo to tools->options->General tab to set the path to the executable."
                                    , "Failed to create a session", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return(null);
                }
                if (!File.Exists(Executable))
                {
                    MessageBox.Show("Error trying to create session: " + session.ToString() +
                                    "\nExecutable not found for " + session.Proto.ToString() + " protocol." +
                                    "\nThe path for the executable was set as \"" + Executable + "\"." +
                                    "\nGo to tools->options->General tab to set the path to the executable."
                                    , "Failed to create a session", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return(null);
                }

                // This is the callback fired when the panel containing the terminal is closed
                // We use this to save the last docking location and to close the panel
                PuttyClosedCallback callback = delegate
                {
                    if (panel != null)
                    {
                        // save the last dockstate (if it has been changed)
                        if (session.LastDockstate != panel.DockState &&
                            panel.DockState != DockState.Unknown &&
                            panel.DockState != DockState.Hidden)
                        {
                            session.LastDockstate = panel.DockState;
                            SuperPuTTY.SaveSessions();
                        }

                        if (panel.InvokeRequired)
                        {
                            panel.BeginInvoke((MethodInvoker) delegate {
                                panel.Close();
                            });
                        }
                        else
                        {
                            panel.Close();
                        }
                    }
                };

                try {
                    panel = new ctlPuttyPanel(session, callback);

                    ApplyDockRestrictions(panel);
                    ApplyIconForWindow(panel, session);
                    panel.Show(MainForm.DockPanel, session.LastDockstate);
                    ReportStatus("Opened session: {0} [{1}]", session.SessionId, session.Proto);

                    if (!String.IsNullOrWhiteSpace(session.SPSLFileName))
                    {
                        String fileName = session.SPSLFileName;
                        String script   = String.Empty;

                        if (Regex.IsMatch(fileName, @"^https?:\/\/", RegexOptions.IgnoreCase))
                        {
                            try
                            {
                                HttpWebRequest req      = WebRequest.CreateHttp(fileName);
                                var            response = req.GetResponse();
                                using (var stream = new StreamReader(response.GetResponseStream()))
                                {
                                    script = stream.ReadToEnd();
                                }
                            }
                            catch (Exception)
                            {
                                script = String.Empty;
                            }
                        }
                        else
                        {
                            if (fileName.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
                            {
                                fileName = fileName.Substring("file://".Length);
                            }

                            if (File.Exists(fileName))
                            {
                                script = File.ReadAllText(fileName);
                            }
                        }

                        if (!String.IsNullOrEmpty(script))
                        {
                            ExecuteScriptEventArgs scriptArgs = new ExecuteScriptEventArgs()
                            {
                                Script = script, Handle = panel.AppPanel.AppWindowHandle
                            };
                            SPSL.BeginExecuteScript(scriptArgs);
                        }
                    }
                } catch (InvalidOperationException ex)
                {
                    MessageBox.Show("Error trying to create session " + ex.Message, "Failed to create session panel", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return(panel);
        }