Click here to Skip to main content
15,921,793 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello, I'm trying to insert some data into MySQL database using Backgroundworker, now the case is the data is actually a multiple files selected by user in OpenFileDialog which I converted them to byte array before I send them to the database so in order to prevent UI (usually happens when user selected more than 3 files) from not responding I use Backgroundworker and if insert is successful then it will displays the image in picturebox.

My main is problem is lets say if the user selected more than one files it will only inserts one file into the database, and this is because the I'm trying to use the same Backgroundworker for multiple operations at the same time.

Here's my code (This will open FileDialog and let user pick image):

String getName;
  String retrieved;
  String varDate;
  String nameTable;
  Object keyVal;

  int itemCurr;
  String panName;
  Bitmap picImage;

  int curFilesCount;

  private void _mainFileGenerator(int AccountType_, String _AccountTypeStr_) {
      OpenFileDialog open = new OpenFileDialog();
      open.Filter = "All Files|*.*|Images Files|*.jpg;*.jpeg;*.png;.bmp|";
      open.Multiselect = true;
      varDate = DateTime.Now.ToString("dd/MM/yyyy");

      int curFilesCount = flowLayoutPanel1.Controls.Count;
      if (open.ShowDialog() == DialogResult.OK) {
          foreach (var selectedItems in open.FileNames) {
              _filValues.Add(Path.GetFileName(selectedItems));

                  get_ex = open.FileName;
                  getName = Path.GetFileName(selectedItems);
                  retrieved = Path.GetExtension(selectedItems);

                  if (retrieved == ".png" || retrieved == ".jpeg" || retrieved == ".jpg" || retrieved == ".ico" || retrieved == ".bmp" || retrieved == ".svg") {
                      itemCurr++;
                      nameTable = "file_info";
                      var getImg = new Bitmap(selectedItems);

                      var imgWidth = getImg.Width;
                      var imgHeight = getImg.Height;
                      if (retrieved != ".ico") {
                          using (MemoryStream ms = new MemoryStream()) {
                              getImg.Save(ms,System.Drawing.Imaging.ImageFormat.Png);
                              var setupImg = ms.ToArray();
                              keyVal = setupImg;
                              panName = "PanImg";
                              picImage = getImg;
                          }
                      }
                      else {
                          Image retrieveIcon = Image.FromFile(selectedItems);
                          byte[] dataIco;
                          using (MemoryStream msIco = new MemoryStream()) {
                              retrieveIcon.Save(msIco, System.Drawing.Imaging.ImageFormat.Png);
                              dataIco = msIco.ToArray();
                          }
                      }
                  }
              }
          }

          if (backgroundWorker1.IsBusy) {
              backgroundWorker1.CancelAsync();
          }
          else {
              if (guna2ProgressBar1.Value == guna2ProgressBar1.Maximum) {
                  guna2ProgressBar1.Value = guna2ProgressBar1.Minimum;
              }
              backgroundWorker1.RunWorkerAsync(guna2ProgressBar1.Value);
          }
      }


Insert data (DoWork):

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) {

    int percentFinished = (int)e.Argument;
    while(!backgroundWorker1.CancellationPending && percentFinished < 100) {
        percentFinished++;
        backgroundWorker1.ReportProgress(percentFinished);
        //System.Threading.Thread.Sleep(50);
    }
    e.Result = percentFinished;

    String insertTxtQuery = "INSERT INTO " + nameTable + "(CUST_FILE_NAME,UPLOAD_DATE,CUST_FILE) VALUES (@CUST_FILE_PATH,@UPLOAD_DATE,@CUST_FILE)";
    command = new MySqlCommand(insertTxtQuery, con);

    command.Parameters.Add("@CUST_FILE_NAME", MySqlDbType.Text);
    command.Parameters.Add("@UPLOAD_DATE", MySqlDbType.VarChar, 255);

    command.Parameters["@CUST_FILE_NAME"].Value = getName;
    command.Parameters["@UPLOAD_DATE"].Value = varDate;

    command.Parameters.Add("@CUST_FILE", MySqlDbType.LongBlob);
    command.Parameters["@CUST_FILE"].Value = keyVal;
    command.ExecuteNonQuery();
}

Update progress bar value (ProgressChanged):

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) {
           guna2ProgressBar1.Value = e.ProgressPercentage;
       }


Backgroundworker completed and display image in Picturebox (RunWorkerCompleted):

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
          guna2ProgressBar1.Value = 0;
          int top = 275;
          int h_p = 100;
          var panelTxt = new Guna2Panel() {
              Name = panName + itemCurr,
              Width = 240,
              Height = 262,
              BorderRadius = 8,
              FillColor = ColorTranslator.FromHtml("#121212"),
              BackColor = Color.Transparent,
              Location = new Point(600, top)
          };

          top += h_p;
          flowLayoutPanel1.Controls.Add(panelTxt);
          var mainPanelTxt = ((Guna2Panel)flowLayoutPanel1.Controls[panName + itemCurr]);

          var textboxPic = new Guna2PictureBox();
          mainPanelTxt.Controls.Add(textboxPic);
          textboxPic.Name = "TxtBox" + itemCurr;
          textboxPic.Width = 240;
          textboxPic.Height = 164;
          textboxPic.BorderRadius = 8;
          textboxPic.SizeMode = PictureBoxSizeMode.CenterImage;
          textboxPic.Enabled = true;
          textboxPic.Visible = true;
          textboxPic.Image = picImage;

          Label titleLab = new Label();
          mainPanelTxt.Controls.Add(titleLab);
          titleLab.Name = "LabVidUp" + itemCurr;
          titleLab.Font = new Font("Segoe UI Semibold", 12, FontStyle.Bold);
          titleLab.ForeColor = Color.Gainsboro;
          titleLab.Visible = true;
          titleLab.Enabled = true;
          titleLab.Location = new Point(12, 182);
          titleLab.Width = 220;
          titleLab.Height = 30;
          titleLab.Text = getName;


          Label dateLabTxt = new Label();
          mainPanelTxt.Controls.Add(dateLabTxt);
          dateLabTxt.Name = "LabTxtUp" + itemCurr;
          dateLabTxt.Font = new Font("Segoe UI Semibold", 12, FontStyle.Bold);
          dateLabTxt.ForeColor = Color.DarkGray;
          dateLabTxt.Visible = true;
          dateLabTxt.Enabled = true;
          dateLabTxt.Location = new Point(12, 208);
          dateLabTxt.Width = 1000;
          dateLabTxt.Text = varDate;
      }


What I have tried:

I've read a method on backgroundworker in foreach loop but none of those fixed/related to my current problem.
Posted
Updated 16-Jan-23 0:38am

1 solution

The simplest solution is to create a new background worker each time, and pass it the data it needs to send to SQL. Me? I'd pass it a string collection and let it deal with converting it to bytes and then transfering that to the DB.

If each file is to be sent separately, then do that and pass your Image back to the UI thread via the UserState parameter of the BackgroundWorker.ReportProgress method. The UI can then update the picture box, and the worker continues to transfer data.
 
Share this answer
 
Comments
Dan Sep2022 16-Jan-23 6:58am    
Do you have sample code for your 'create a new background worker each time'? I'm kinda lost.
OriginalGriff 16-Jan-23 7:14am    
You are kidding, right?
BackgroundWorker work = new BackgroundWorker();
Dan Sep2022 16-Jan-23 11:46am    
Ok now when I'm not able to upload the last selected file, say if the user selected 3 files only 2 files will be uploaded and display.
OriginalGriff 16-Jan-23 12:06pm    
And what does the debugger show you is happening in the code I can't see?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900