Foros del Web » Programación para mayores de 30 ;) » .NET »

Problema al cerrar aplicación

Estas en el tema de Problema al cerrar aplicación en el foro de .NET en Foros del Web. Hola a tod@s, Primero os explico el problema y después os pongo todo el código, que por cierto me tiene super rallado no veo el ...
  #1 (permalink)  
Antiguo 27/01/2012, 09:07
 
Fecha de Ingreso: agosto-2006
Mensajes: 19
Antigüedad: 17 años, 8 meses
Puntos: 0
Problema al cerrar aplicación

Hola a tod@s,

Primero os explico el problema y después os pongo todo el código, que por cierto me tiene super rallado no veo el porque por ningún lado.

Resulta que tengo un Formulario MDI que es el que carga Application.Run desde el Main. En el evento load de este formulario tengo un codigo que abre como ventana modal otra ventana en la que tengo unos controles y códigos para un login de usuario. En esta última ventana asigno los valores Cancel u OK a DialogResult en función de lo que ocurra en la comprobación del usuario. Al asignar DialogResult a OK o Cancel se realiza el cierre del formulario. Recordad que la abrí como Modal (ShowDialog) desde el formulario MDI principal. Este formulario principal continua su código después de recibir la respuesta de la ventana Modal. Si devolvió OK hago un Dispose de la venta modal y muestro el formulario MDI, si devolvió algo distinto a OK (Cancel por ejemplo) hago un Dispose de la ventana Modal y un Close al MDI (y se cierra la aplicación sin problemas). Bien ahora viene lo raro, este formulario MDI tiene un menu salir con este codigo en su evento click this.Close(); Se me cierra la ventana principal pero LA APLICACIÓN SIGUE ACTIVA (si abro el Task Manager del windows sale el exe y si lo ejecuto desde Visual Studio me sigue con las ventanas de depuración hasta que le doy a STOP).

Os pongo los códigos de Program.cs y de los dos formularios:

Program.cs
Código:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace Tripmania
{
    static class Program {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main() {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new frmPrincipal());
        }
    }
}
frmPrincipal.js
Código:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Tripmania {
    public partial class frmPrincipal : Form {
        public frmPrincipal() {
            InitializeComponent();
        }

        private void salirToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); }

        private void frmPrincipal_Shown(object sender, EventArgs e) {
            this.Hide();
            frmLogin logWindow = new frmLogin();
            if (logWindow.ShowDialog() != DialogResult.OK) {
                logWindow.Dispose();
                this.Close();
            } else {
                logWindow.Dispose();
                this.Show();
            }
        }
    }
}
frmLogin.cs
Código:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
using MyFunctions;

namespace Tripmania {
    public partial class frmLogin : Form {
        public frmLogin() {
            InitializeComponent();
        }

        private void btnExit_Click(object sender, EventArgs e) {
            if (MessageBox.Show("¿Está seguro que desea salir de la aplicación?", "Salir del Panel", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) this.DialogResult = DialogResult.Cancel;
        }

        private void btnClean_Click(object sender, EventArgs e) {
            txtPass.Text = "";
            txtUser.Text = "";
        }

        private void btnEnter_Click(object sender, EventArgs e) {
            lblStatus.Text = "Conectando ...";
            this.Enabled = false;
            const string title = "Error de Acceso";
            if (this.txtUser.Text == "") {
                lblStatus.Text = "";
                this.Enabled = true;
                MessageBox.Show("Introduzca un nombre de usuario.", title, MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.txtUser.Focus();
            } else if (this.txtPass.Text == "") {
                lblStatus.Text = "";
                this.Enabled = true;
                MessageBox.Show(String.Format("Introduzca la clave del usuario {0}.", this.txtUser.Text.ToUpper()), title, MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.txtPass.Focus();
            } else {
                DataAccess tripmaniaData = new DataAccess("xxxxxx", "xxxxxx", "xxxxxx");
                tripmaniaData.setSSHInfo("xxx.xxx.xxx.xxx", "xxxx", "xxxxxx");
                string[] where = { "user=" + TextManipulation.safeSQL(this.txtUser.Text), "pass=" + TextManipulation.safeSQL(Crypto.getSHA1(this.txtPass.Text)) };
                lblStatus.Text = "Comprobando usuario ...";
                if (tripmaniaData.checkRegistry("logins", where)) {
                    this.DialogResult = DialogResult.OK;
                } else {
                    lblStatus.Text = "";
                    this.Enabled = true;
                    MessageBox.Show("Los datos introducidos no son correctos. Inténtelo de nuevo.", title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void TextBox_TextChanged(object sender, EventArgs e) {
            TextBox modelBox = new TextBox();
            bool activate = false;
            foreach (Control elementForm in this.Controls) if (elementForm.GetType() == modelBox.GetType()) if (elementForm.Text != "") activate = true;
            this.btnClean.Enabled = activate;
        }

        private void TextBox_KeyPress(object sender, KeyPressEventArgs e) {
            string validChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.-_ ";
            if (validChars.IndexOf(e.KeyChar) == -1 && e.KeyChar != Convert.ToChar('\r') && e.KeyChar != Convert.ToChar('\b') && e.KeyChar != Convert.ToChar('\t')) e.Handled = true;
            else e.Handled = false;
        }

        private void TextBox_Enter(object sender, EventArgs e) {
            TextBox model = (TextBox) sender;
            model.SelectAll();
        }

        private void frmLogin_FormClosing(object sender, FormClosingEventArgs e) { if (e.CloseReason == CloseReason.UserClosing || e.CloseReason == CloseReason.TaskManagerClosing || e.CloseReason == CloseReason.WindowsShutDown) this.DialogResult = DialogResult.Cancel; }
    }
}
Como podeis ver, en frmPrincipal.cs el código lo pongo en el evento Shown, si lo pongo en Load hace exactamente lo mismo. Si hago clic en el menú salir he comprobado en debug paso a paso que tras terminar Application.Run no hace nada más y se queda parado pero no termina el programa nunca. Os he MARCADO EN ROJO los trozos de código que están implicados en lo que he explicado, el resto está todo correcto.

Haber si algun@ sois capaz de ver lo que yo no veo.

Última edición por raistlin2912; 27/01/2012 a las 09:21
  #2 (permalink)  
Antiguo 27/01/2012, 11:17
Avatar de ramirezmario7  
Fecha de Ingreso: febrero-2008
Ubicación: Medellín
Mensajes: 336
Antigüedad: 16 años, 2 meses
Puntos: 56
Respuesta: Problema al cerrar aplicación

Hola utiliza Application.Exit()
  #3 (permalink)  
Antiguo 27/01/2012, 12:53
Avatar de alan_69niupi  
Fecha de Ingreso: junio-2011
Mensajes: 200
Antigüedad: 12 años, 11 meses
Puntos: 17
Respuesta: Problema al cerrar aplicación

yo cierro todo de esta manera

Application.ExitThread()

esto cierra el hilo del formulario principal. espero te sirva

Saludos!!!!
  #4 (permalink)  
Antiguo 30/01/2012, 01:22
 
Fecha de Ingreso: agosto-2006
Mensajes: 19
Antigüedad: 17 años, 8 meses
Puntos: 0
Respuesta: Problema al cerrar aplicación

Ya encontré el problema (aunque todavía no lo he podido arreglar), resulta que la aplicación no se cierra porque el tunel SSH que abro entre la aplicación y el servidor de MySQL se queda activo aún cuando he usado el cierre del objeto. En concreto estoy usando las librerías de SharpSSH. Yo sigo investigando, haber si lo veis algun@, os pos pongo el código concreto a ver si lo veis:

Código c#:
Ver original
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Data;
  6. using MySql.Data.MySqlClient;
  7. using Tamir.SharpSsh.jsch;
  8. using MyFunctions;
  9.  
  10. namespace Tripmania {
  11.  
  12.     public class MyUserInfo : UserInfo {
  13.         private String password;
  14.         public String getPassword() { return password; }
  15.         public bool promptYesNo(String str) { return true; }
  16.         public String getPassphrase() { return null; }
  17.         public bool promptPassphrase(String message) { return true; }
  18.         public bool promptPassword(String message) { return true; }
  19.         public void showMessage(String message) { }
  20.     }
  21.  
  22.     public class DataAccess {
  23.         private struct infoSSH {
  24.             public string server;
  25.             public string user;
  26.             public string password;
  27.             public System.Int32 port;
  28.         }
  29.  
  30.         private MySqlConnection connection;
  31.         private MySqlDataAdapter da;
  32.         private MySqlCommandBuilder cb;
  33.         public DataSet data;
  34.         private infoSSH sessionInfo;
  35.         private Session sshSession;
  36.         private bool sshConnection = false;
  37.  
  38.         public DataAccess(string user, string password, string database) { if (!(user == "" || password == "" || database == "")) this.connection = new MySqlConnection(String.Format("Server=localhost;Database={0};Uid={1};Pwd={2};", database, user, password)); }
  39.         public DataAccess(string user, string password, string database, string server) { if (!(user == "" || password == "" || database == "" || server == "")) this.connection = new MySqlConnection(String.Format("Server={0};Database={1};Uid={2};Pwd={3};", server, database, user, password)); }
  40.  
  41.         public void setSSHInfo(string server, string user, string password) {
  42.             this.sessionInfo.server = server;
  43.             this.sessionInfo.user = user;
  44.             this.sessionInfo.password = password;
  45.             this.sessionInfo.port = 22;
  46.             this.sshConnection = true;
  47.         }
  48.         public void setSSHInfo(string server, string user, string password, System.Int32 port) {
  49.             this.sessionInfo.server = server;
  50.             this.sessionInfo.user = user;
  51.             this.sessionInfo.password = password;
  52.             this.sessionInfo.port = port;
  53.             this.sshConnection = true;
  54.         }
  55.  
  56.         public void clearSSHInfo() {
  57.             this.sessionInfo.server = "";
  58.             this.sessionInfo.user = "";
  59.             this.sessionInfo.password = "";
  60.             this.sessionInfo.port = 0;
  61.             this.sshConnection = false;
  62.         }
  63.  
  64.         private bool makeSSHTunnel() {
  65.             if (this.sessionInfo.server == "") return false;
  66.             JSch sshConnection = new JSch();
  67.             this.sshSession = sshConnection.getSession(sessionInfo.user, sessionInfo.server, 22);
  68.             this.sshSession.setHost(sessionInfo.server);
  69.             this.sshSession.setPassword(sessionInfo.password);
  70.             UserInfo ui = new MyUserInfo();
  71.             this.sshSession.setUserInfo(ui);
  72.             this.sshSession.connect();
  73.             this.sshSession.setPortForwardingL(3306, "localhost", 3306);
  74.             return true;
  75.         }
  76.        
  77.         private bool destroySSHTunnel() {
  78.             if (!this.sshSession.isConnected()) return false;
  79.             this.sshSession.delPortForwardingL(3306);
  80.             this.sshSession.disconnect();
  81.             return true;
  82.         }
  83.  
  84.         public bool loadData(string[] fields, string[] tables) {
  85.             if (this.sshConnection) if(!this.makeSSHTunnel()) return false;
  86.             if (fields.Count() == 0 || tables.Count() == 0) {
  87.                 this.destroySSHTunnel();
  88.                 return false;
  89.             }
  90.             string sql = "SELECT " + String.Join(",", fields) + " FROM " + String.Join(",", tables);
  91.             this.connection.Open();
  92.             this.da = new MySqlDataAdapter(sql, this.connection);
  93.             this.cb = new MySqlCommandBuilder(da);
  94.             this.data = new DataSet();
  95.             this.da.FillSchema(data, SchemaType.Mapped);
  96.             this.connection.Close();
  97.             this.destroySSHTunnel();
  98.             return true;
  99.         }
  100.         public bool loadData(string[] fields, string[] tables, string[] conditions) {
  101.             if (this.sshConnection) if (!this.makeSSHTunnel()) return false;
  102.             if (fields.Count() == 0 || tables.Count() == 0 || conditions.Count() == 0) {
  103.                 this.destroySSHTunnel();
  104.                 return false;
  105.             }
  106.             string sql = "SELECT " + String.Join(",", fields) + " FROM " + String.Join(",", tables) + " WHERE " + String.Join(",", conditions);
  107.             this.connection.Open();
  108.             this.da = new MySqlDataAdapter(sql, this.connection);
  109.             this.cb = new MySqlCommandBuilder(da);
  110.             this.data = new DataSet();
  111.             this.da.FillSchema(data, SchemaType.Mapped);
  112.             this.connection.Close();
  113.             this.destroySSHTunnel();
  114.             return true;
  115.         }
  116.         public bool loadData(string[] fields, string[] tables, string[] conditions, string[] orderFields, string selectionOrder = "") {
  117.             if (this.sshConnection) if (!this.makeSSHTunnel()) return false;
  118.             if (fields.Count() == 0 || tables.Count() == 0 || conditions.Count() == 0) {
  119.                 this.destroySSHTunnel();
  120.                 return false;
  121.             }
  122.             string sql = "SELECT " + String.Join(",", fields) + " FROM " + String.Join(",", tables) + " WHERE " + String.Join(",", conditions) + " ORDER BY " + String.Join(",", orderFields);
  123.             selectionOrder = selectionOrder.Trim();
  124.             if (selectionOrder != "ASC" && selectionOrder != "DESC") selectionOrder = "";
  125.             if (selectionOrder != "") sql += " " + selectionOrder;
  126.             this.connection.Open();
  127.             this.da = new MySqlDataAdapter(sql, this.connection);
  128.             this.cb = new MySqlCommandBuilder(da);
  129.             this.data = new DataSet();
  130.             this.da.FillSchema(data, SchemaType.Mapped);
  131.             this.connection.Close();
  132.             this.destroySSHTunnel();
  133.             return true;
  134.         }
  135.  
  136.         public bool updateData() {
  137.             if (this.sshConnection) if (!this.makeSSHTunnel()) return false;
  138.             if (data.Tables.Count == 0) {
  139.                 this.destroySSHTunnel();
  140.                 return false;
  141.             }
  142.             this.connection.Open();
  143.             da.Update(data);
  144.             this.connection.Close();
  145.             this.destroySSHTunnel();
  146.             return true;
  147.         }
  148.  
  149.         public bool unloadData() {
  150.             if (data.Tables.Count == 0) return false;
  151.             data.Tables.Clear();
  152.             return true;
  153.         }
  154.  
  155.         public int executeSQL(string sql) {
  156.             if (this.sshConnection) if (!this.makeSSHTunnel()) return -1;
  157.             if (sql == "") {
  158.                 this.destroySSHTunnel();
  159.                 return -1;
  160.             }
  161.             MySqlCommand cm = new MySqlCommand();
  162.             this.connection.Open();
  163.             cm.Connection = this.connection;
  164.             cm.CommandType = CommandType.Text;
  165.             cm.CommandText = sql;
  166.             int res = cm.ExecuteNonQuery();
  167.             this.connection.Close();
  168.             this.destroySSHTunnel();
  169.             return res;
  170.         }
  171.  
  172.         public bool checkRegistry(string table, string[] condition) {
  173.             if (table == "" || condition.Count() == 0) return false;
  174.             if (this.sshConnection) if (!this.makeSSHTunnel()) return false;
  175.             MySqlCommand cm = new MySqlCommand();
  176.             this.connection.Open();
  177.             cm.Connection = this.connection;
  178.             cm.CommandType = CommandType.Text;
  179.             cm.CommandText = "SELECT COUNT(*) FROM " + table;
  180.             cm.CommandText += " WHERE " + condition[0];
  181.             for (int i = 1; i < condition.Count(); i++) cm.CommandText += " AND " + condition[i];
  182.             int res = Convert.ToInt32(cm.ExecuteScalar());
  183.             this.connection.Close();
  184.             this.destroySSHTunnel();
  185.             if (res > 0) return true;
  186.             else return false;
  187.         }
  188.     }
  189. }
  #5 (permalink)  
Antiguo 14/02/2012, 03:34
 
Fecha de Ingreso: agosto-2006
Mensajes: 19
Antigüedad: 17 años, 8 meses
Puntos: 0
Respuesta: Problema al cerrar aplicación

Resolvi el problema cambiando el componente que usaba para hacer el túnel SSH por otro distinto, y en este no he tenido problema. Por si alguien necesita uno aquí os dejo el enlace: vblog.strutt.org.uk/2011/11/ssh-client-using-powershell/

Etiquetas: cerrar, sql, textbox, visual
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 03:44.