Unable to convert these methods to multi-threading in windows form application

  • Thread starter Thread starter samiarja
  • Start date Start date
S

samiarja

Guest
Hi all, I created a windows form application with a start and stop buttons. The application dynamically creates labels, textboxes depend on how element there are in the JSON file, for example, if there was three machine details, three textboxes, labels etc. will be created.

The application basically transfer files from a remote server to a local server (local computer) using SFTP. However, at some points the number of remote server will be huge that the application has to detect if there are within the network and then transfer the files in one go. To do I need to build a multi-thread application that ping each machine, then the one within the network zone will start the transfer in a way that each machine will work in a seperate thread.

The JSON file looks like that, it is an example where two machines exist:

[
{
"Record": 1,
"IPaddress": "192.168.1.10",
"Machinename": "taurus",
"username": "root",
"password": "roo123",
"sourcefolder": "/home/root/data/completed",
"destfolder": "C:\\temp",
"filextension": ".db",
"removedownloaded": 0,
"removecsv": 0,
"removedb": 0,
"eagleIOHost": "sftp.eagle.io",
"eagleIOUsername": "sftp.eagle.io",
"eagleIOpassword": "nautitech260",
"eagleIOdirectory": "/usr/share/tomcat8"
},
{
"Record": 2,
"IPaddress": "192.168.1.11",
"Machinename": "taurus",
"username": "root",
"password": "root567",
"sourcefolder": "/home/root/data/completed",
"destfolder": "C:\\temp",
"filextension": ".txt",
"removedownloaded": 0,
"removecsv": 1,
"removedb": 1,
"eagleIOHost": "sftp.eagle.io",
"eagleIOUsername": "sftp.eagle.io",
"eagleIOpassword": "nautitech200",
"eagleIOdirectory": "/usr/share/tomcat8"
}
]

this is how the application looks like:

1538196.png

This how the information are displayed in the application, and the main part happen in Start button. The code look like below:

private void Start_button_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Are you sure you want to Start", "STARTED", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{

string text = File.ReadAllText(filePath);
var currentList = JsonConvert.DeserializeObject<List<Datalogger>>(text);

System.Windows.Forms.Timer Clock = new System.Windows.Forms.Timer
{
Interval = 2000 //5 seconds
};
Clock.Start();

Clock.Tick += new EventHandler(timer1_Tick);
}
else
{
this.Activate();
}

}
private void timer1_Tick(object sender, EventArgs e)
{
string text = File.ReadAllText(filePath);
var currentList = JsonConvert.DeserializeObject<List<Datalogger>>(text);
foreach (var item in currentList)
{

List<String> hosts = new List<String>();
for (Int32 i = 0; i < 10; ++i) hosts.Add(item.IPaddress);

var average = hosts.AsParallel().WithDegreeOfParallelism(64).
Select(h => new Ping().Send(h).RoundtripTime).Average();
Console.WriteLine("IP:" + item.IPaddress + "," + "time=" + average + "ms");
m_streamWriter.WriteLine("{0} {1} {2}",
DateTime.Now.ToLongTimeString(),
DateTime.Now.ToLongDateString(),
"IP:" + item.IPaddress + "," + "time=" + average + "ms");
m_streamWriter.Flush();

string host = item.IPaddress;
string username = item.username;
string password = item.password;
string remoteDirectory = item.sourcefolder;
string localDirectory = item.destfolder;
string filextension = item.filextension;
string removedownloaded = item.removedownloaded.ToString();
string removecsv = item.removecsv.ToString();
string removedb = item.removedb.ToString();


using (SftpClient sftp = new SftpClient(host, username, password))
{
try
{
sftp.Connect();
var files = sftp.ListDirectory(remoteDirectory);

//Parallel.ForEach(files, file =>
foreach (var file in files)
{
try
{
string remoteFileName = file.Name;
string str = "";
str = remoteFileName.Replace(":", "_");
string Folder_path = item.destfolder;
var files_path = Directory.GetFiles(Folder_path, "*db", SearchOption.AllDirectories);
System.IO.DirectoryInfo local_directory = new DirectoryInfo(Folder_path);
System.IO.DirectoryInfo local_directory_csv = new DirectoryInfo(Folder_path + "/CSV");
string tablename = string.Empty;
string path = remoteDirectory + "/" + str;

if ((file.Name.EndsWith(filextension)) || (file.Name.EndsWith(filextension.ToLower())) || (file.Name.EndsWith(filextension.ToUpper())))
{
using (Stream file1 = File.OpenWrite(Path.Combine(localDirectory, str)))
{
sftp.DownloadFile(path + "/Data", file1);
foreach (var item_db in files_path)
{
var result = item_db.Substring(item_db.Length - 3);
for (var i = 1; i < files_path.Count() + 1; i++)
{
if (result == ".db")
{
tablename = string.Format("DADLoggerTable{0}", i);
DataTable dt = ConverttoDatatable(item_db, tablename);
SaveCsv(dt, Folder_path + "/CSV", tablename);
}
}
}

if (removedownloaded == "1")
{
sftp.Delete(path);

}
else
{
sftp.DownloadFile(path, file1);
}
foreach (FileInfo filedb in local_directory.EnumerateFiles())
{
if (removedb == "1")
{
filedb.Delete();
}
}
foreach (FileInfo filecsv in local_directory_csv.EnumerateFiles())
{
if (removecsv == "1")
{
filecsv.Delete();
}
}
}

}
}
catch (Exception er1)
{
//MessageBox.Show("An exception has been caught " + er1.ToString());
}}
//});
}
catch (Exception entry)
{
MessageBox.Show(entry.Message);
}
}

}

}

This is what happen in this button:


  1. Confirm with the user to start.
  2. Read and deserialize the .JSON file to convert the data to list.
  3. Set the timer to a specific value.
  4. Acticate and start the timer.
  5. Ping each IP address every 2 seconds and write the feedback time on the .txt file with the time and date of its occurrences.
  6. Connect to the SFTP server of each machine.
  7. Read each machine in a parallel process using Parallel.each command.
  8. Download all .db file to Data file.
  9. Loop through all the data and check if it end with .db, if yes then convert all to .csv.
  10. Check if remove download, remove .db, remove .csv radio button is 1, then remove files from designated folder.


How to make this code each machine in multi-threading way?

I appreciate all sort of advice and helps, thanks in advance


Sami Arja

Continue reading...
 
Back
Top