Saturday, February 28, 2015

Save Exceptions into Sql Database using C#

  1. Create  Database named: ExceptionDatabase into sql an than create ExceptionDetails Table in it
  2. Create a new class named: Exceptionfunction and add below function in it
  3.  public static void connecttion(Exception exdb)
            {
                SqlConnection con = new SqlConnection();
                con.ConnectionString = @"Data Source=MCS000009-PC\SQL;Initial Catalog=ExceptionDatabase; Trusted_Connection=True;";

                string query1 = "insert into ExceptionDetails (ExceptionMsg,ExceptionType)   values( '" + exdb.Message.ToString() + "',  '" + exdb.GetType().Name.ToString() + "')";
                SqlCommand cmd1 = new SqlCommand(query1, con);
                con.Open();
                cmd1.ExecuteNonQuery();
                con.Close();
            }
  4. Now create a new Webform and add text boxes and a button
  5. On buttom click add function to do Sum of two integers from textboxes
  6. protected void Button1_Click(object sender, EventArgs e)
            {
                try
                {
                    int a = Convert.ToInt32(TextBox1.Text);
                    int b = Convert.ToInt32(TextBox2.Text);
                    int c = a + b;
                    Response.Write(c);
                }
                catch (Exception ex)
                {
                    ExceptionFunction.connecttion(ex);
                }}
  7. In catch add call function of Exceptionfunction class.

No comments:

Post a Comment