Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Auto Connect SQLConnection

Auto Connect SQLConnection

Scheduled Pinned Locked Moved C#
helpdatabasesysadmindata-structurescareer
13 Posts 3 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • M Offline
    M Offline
    Midnight Ahri
    wrote on last edited by
    #1

    So I've been stuck here for 1 week. Everytime I had problem in SQL connection (ex. someone switch of server) my application will show exception message in a messagebox. I don't know when will the connection available except I keep trying to open the connection / execute a query. So I create a wait form that will appear if connection is unavailable, keep trying to open the connection, and close itself when connection is available again. To hide the freeze from user, I use backgroundworker. This is the backgroundworker code

    private void StartLoader(object sender, DoWorkEventArgs e)
    {
    for (int i = 1; i <= 10; i++)
    {
    if (this.par.sqSuccess) //if no error, means connection is available, stop looping
    {
    break;
    }
    else
    {
    i -= 1;
    }

                System.Threading.Thread.Sleep(5000); //report progress every 5 second
            }
    

    This is the backgroundworker progress changed event

            this.cnn = new SqlConnection(this.par.Constr);
    
            try
            {
                this.cnn.Open(); //SqlConnection
    
                this.par.sqSuccess = true; //if no error, then I change this variable
            }
            catch (Exception ex)
            {
                this.par.Exception = ex.Message;
            }
            finally
            {
                if (this.cnn != null) { this.cnn.Dispose(); }
            }
            if (this.par.sqSuccess) { this.Close(); }
    

    After everything is complete, I tried to stop SQL service from services.msc, then I try to connect. The wait form will appear and keep doing its job. A few second after I try to connect, I start the service again and the wait form did close, success. This is the problem, when I wait a little bit longer before I start the service again, the wait form still closed, but it takes a while. After I check everything, it seems like the cnn.open() queue up and the longer I stop the service, the longer it takes for the wait form to close. I searched google and try to add Connect Timeout=3; behind my connection string, as I'm sure my thread.sleep(5000) won't make them queue up, but still not working. I need help to understand how this cnn.open works, why this is not working, what happen in this code that makes I got this problem. While processing the cnn.open(), did my application

    L 1 Reply Last reply
    0
    • M Midnight Ahri

      So I've been stuck here for 1 week. Everytime I had problem in SQL connection (ex. someone switch of server) my application will show exception message in a messagebox. I don't know when will the connection available except I keep trying to open the connection / execute a query. So I create a wait form that will appear if connection is unavailable, keep trying to open the connection, and close itself when connection is available again. To hide the freeze from user, I use backgroundworker. This is the backgroundworker code

      private void StartLoader(object sender, DoWorkEventArgs e)
      {
      for (int i = 1; i <= 10; i++)
      {
      if (this.par.sqSuccess) //if no error, means connection is available, stop looping
      {
      break;
      }
      else
      {
      i -= 1;
      }

                  System.Threading.Thread.Sleep(5000); //report progress every 5 second
              }
      

      This is the backgroundworker progress changed event

              this.cnn = new SqlConnection(this.par.Constr);
      
              try
              {
                  this.cnn.Open(); //SqlConnection
      
                  this.par.sqSuccess = true; //if no error, then I change this variable
              }
              catch (Exception ex)
              {
                  this.par.Exception = ex.Message;
              }
              finally
              {
                  if (this.cnn != null) { this.cnn.Dispose(); }
              }
              if (this.par.sqSuccess) { this.Close(); }
      

      After everything is complete, I tried to stop SQL service from services.msc, then I try to connect. The wait form will appear and keep doing its job. A few second after I try to connect, I start the service again and the wait form did close, success. This is the problem, when I wait a little bit longer before I start the service again, the wait form still closed, but it takes a while. After I check everything, it seems like the cnn.open() queue up and the longer I stop the service, the longer it takes for the wait form to close. I searched google and try to add Connect Timeout=3; behind my connection string, as I'm sure my thread.sleep(5000) won't make them queue up, but still not working. I need help to understand how this cnn.open works, why this is not working, what happen in this code that makes I got this problem. While processing the cnn.open(), did my application

      L Offline
      L Offline
      Lost User
      wrote on last edited by
      #2

      You may like to try the OpenAsync[^] method.

      Veni, vidi, abiit domum

      M 1 Reply Last reply
      0
      • L Lost User

        You may like to try the OpenAsync[^] method.

        Veni, vidi, abiit domum

        M Offline
        M Offline
        Midnight Ahri
        wrote on last edited by
        #3

        It uses System.Threading.Task. Is it possible if I want to use it with backgroundworker?

        L P 2 Replies Last reply
        0
        • M Midnight Ahri

          It uses System.Threading.Task. Is it possible if I want to use it with backgroundworker?

          L Offline
          L Offline
          Lost User
          wrote on last edited by
          #4

          No idea, but I suggest you read the documentation, and try a few experiments.

          Veni, vidi, abiit domum

          M 2 Replies Last reply
          0
          • L Lost User

            No idea, but I suggest you read the documentation, and try a few experiments.

            Veni, vidi, abiit domum

            M Offline
            M Offline
            Midnight Ahri
            wrote on last edited by
            #5

            Oh ok ok. There are no example of code inside but I will try googling. Thank you very much. :)

            1 Reply Last reply
            0
            • M Midnight Ahri

              It uses System.Threading.Task. Is it possible if I want to use it with backgroundworker?

              P Offline
              P Offline
              Pete OHanlon
              wrote on last edited by
              #6

              Why would you want to use BackgroundWorker when the Task is a better choice?

              Chill _Maxxx_
              CodeStash - Online Snippet Management | My blog | MoXAML PowerToys | Mole 2010 - debugging made easier

              M 2 Replies Last reply
              0
              • P Pete OHanlon

                Why would you want to use BackgroundWorker when the Task is a better choice?

                Chill _Maxxx_
                CodeStash - Online Snippet Management | My blog | MoXAML PowerToys | Mole 2010 - debugging made easier

                M Offline
                M Offline
                Midnight Ahri
                wrote on last edited by
                #7

                Thank you very much, I'm new to task and just found it today. But I'll keep searching.

                After calling OpenAsync, State must return Connecting until the returned Task is completed. Then, if the connection was successful, State must return Open. If the connection fails, State must return Closed.

                Sorry that english is not my first language and I'm not that good in programming. So what I understand above is like this.

                this.cnn.OpenASync();

                if (this.cnn.State == ConnectionState.Connecting)
                {
                //cnn is busy connecting
                }

                Then if it's busy, then I will return; instead of OpenASync() again.

                if (this.cnn.State == ConnectionState.Closed)
                {
                //cnn failed to open
                }

                And if it's closed, then I assume cnn failed and finished processing. But it's not working. It's ok, I'll search about task. Thank you very much btw. :)

                1 Reply Last reply
                0
                • P Pete OHanlon

                  Why would you want to use BackgroundWorker when the Task is a better choice?

                  Chill _Maxxx_
                  CodeStash - Online Snippet Management | My blog | MoXAML PowerToys | Mole 2010 - debugging made easier

                  M Offline
                  M Offline
                  Midnight Ahri
                  wrote on last edited by
                  #8

                  This is what I do,

                  static async Task Method(SqlConnection cnn)
                  {
                  await cnn.OpenAsync();
                  return cnn.State;
                  }

                  private void SQLClientLoader_Load(object sender, EventArgs e)
                  {
                  do
                  {
                  this.cnn = new SqlConnection(this.par.Constr);

                              try
                              {
                                  ConnectionState cst = Method(cnn).Result;
                  
                                  if (cst == ConnectionState.Open)
                                  {
                                      this.par.sqSuccess = true;
                                  }
                                  else
                                  {
                  
                                  }
                              }
                              catch (Exception ex)
                              {
                                  this.par.sqSuccess = false;
                  
                                  this.par.Exception = ex.Message;
                              }
                              finally
                              {
                  
                              }
                          } while ((bool)this.par.sqSuccess != true);
                      }
                  

                  It freeze my application everytime I this form load executed. Should I combine Task with BackgroundWorker to prevent freeze? Or maybe something is wrong in my code? Can you explain to me cause I'm new and confuse of this.

                  P 1 Reply Last reply
                  0
                  • M Midnight Ahri

                    This is what I do,

                    static async Task Method(SqlConnection cnn)
                    {
                    await cnn.OpenAsync();
                    return cnn.State;
                    }

                    private void SQLClientLoader_Load(object sender, EventArgs e)
                    {
                    do
                    {
                    this.cnn = new SqlConnection(this.par.Constr);

                                try
                                {
                                    ConnectionState cst = Method(cnn).Result;
                    
                                    if (cst == ConnectionState.Open)
                                    {
                                        this.par.sqSuccess = true;
                                    }
                                    else
                                    {
                    
                                    }
                                }
                                catch (Exception ex)
                                {
                                    this.par.sqSuccess = false;
                    
                                    this.par.Exception = ex.Message;
                                }
                                finally
                                {
                    
                                }
                            } while ((bool)this.par.sqSuccess != true);
                        }
                    

                    It freeze my application everytime I this form load executed. Should I combine Task with BackgroundWorker to prevent freeze? Or maybe something is wrong in my code? Can you explain to me cause I'm new and confuse of this.

                    P Offline
                    P Offline
                    Pete OHanlon
                    wrote on last edited by
                    #9

                    I'm not surprised your app is freezing, you have a tight loop here that's hogging the CPU. In the Load event, you could wrap the while loop inside a Task so that the rest of the app can start up. If, however, you need the database connection immediately, then you have to block.

                    Chill _Maxxx_
                    CodeStash - Online Snippet Management | My blog | MoXAML PowerToys | Mole 2010 - debugging made easier

                    M 1 Reply Last reply
                    0
                    • P Pete OHanlon

                      I'm not surprised your app is freezing, you have a tight loop here that's hogging the CPU. In the Load event, you could wrap the while loop inside a Task so that the rest of the app can start up. If, however, you need the database connection immediately, then you have to block.

                      Chill _Maxxx_
                      CodeStash - Online Snippet Management | My blog | MoXAML PowerToys | Mole 2010 - debugging made easier

                      M Offline
                      M Offline
                      Midnight Ahri
                      wrote on last edited by
                      #10

                      Thank you very much for your instruction, This is what I done.

                      private void SQLClientLoader_Load(object sender, EventArgs e)
                      {
                      this.GetSQLState();
                      }

                      async private System.Threading.Tasks.Task GetStateAsync()
                      {
                      do
                      {
                      this.cts = new CancellationTokenSource();
                      this.cnn = new SqlConnection(this.par.Constr);

                                  try
                                  {
                                      await Task.Delay(2500);
                      
                                      await this.cnn.OpenAsync(cts.Token);
                                  }
                                  catch (Exception ex)
                                  {
                                      cts.Cancel(false);
                      
                                      this.cnn.Dispose();
                                      this.cts.Dispose();
                                  }
                              } while (this.cnn.State != ConnectionState.Open);
                      
                              return this.cnn.State;
                          }
                      

                      async private void GetSQLState()
                      {

                              if (await GetStateAsync() == ConnectionState.Open)
                              {
                                  this.Close();
                              }
                      
                              await Task.Delay(2500);
                          }
                      

                      It's working. I used cancellation token, but why the OpenAsync() is not cancelled and still queue up? Edit : Found my solution. Clear the connection pool, made my day guys. Thank you helping me. :laugh:

                      1 Reply Last reply
                      0
                      • L Lost User

                        No idea, but I suggest you read the documentation, and try a few experiments.

                        Veni, vidi, abiit domum

                        M Offline
                        M Offline
                        Midnight Ahri
                        wrote on last edited by
                        #11

                        Oh cmon, I tried a lot of example and still not working. I'm really really stuck here. I'm not asking someone to do the code for me, at least tell me what is wrong in my code. Please :(

                        L 1 Reply Last reply
                        0
                        • M Midnight Ahri

                          Oh cmon, I tried a lot of example and still not working. I'm really really stuck here. I'm not asking someone to do the code for me, at least tell me what is wrong in my code. Please :(

                          L Offline
                          L Offline
                          Lost User
                          wrote on last edited by
                          #12

                          Midnight Ahri wrote:

                          I tried a lot of example and still not working.

                          So you want us to guess a) what your code is doing, and b) what errors occur.

                          Midnight Ahri wrote:

                          at least tell me what is wrong in my code.

                          As I said before, I have no idea. However, re-reading your original message, it would seem much more sensible to post a message to the user when the connection fails. At least then someone can phone the help desk and alert them of the problem.

                          Veni, vidi, abiit domum

                          M 1 Reply Last reply
                          0
                          • L Lost User

                            Midnight Ahri wrote:

                            I tried a lot of example and still not working.

                            So you want us to guess a) what your code is doing, and b) what errors occur.

                            Midnight Ahri wrote:

                            at least tell me what is wrong in my code.

                            As I said before, I have no idea. However, re-reading your original message, it would seem much more sensible to post a message to the user when the connection fails. At least then someone can phone the help desk and alert them of the problem.

                            Veni, vidi, abiit domum

                            M Offline
                            M Offline
                            Midnight Ahri
                            wrote on last edited by
                            #13

                            Richard MacCutchan wrote:

                            So you want us to guess a) what your code is doing, and b) what errors occur.

                            I've explained everything about my code. I'm just asking about why the sql queue up. By the way, thank you very much. At least you teach me async and await technique. And I appreciate that. I'm not good at programming, so maybe I'll ask you something again. See ya. :thumbsup:

                            1 Reply Last reply
                            0
                            Reply
                            • Reply as topic
                            Log in to reply
                            • Oldest to Newest
                            • Newest to Oldest
                            • Most Votes


                            • Login

                            • Don't have an account? Register

                            • Login or register to search.
                            • First post
                              Last post
                            0
                            • Categories
                            • Recent
                            • Tags
                            • Popular
                            • World
                            • Users
                            • Groups