I am currently making a client and server. The server will store people and their location using a dictionary. The client can then lookup a location or update/add a person and their location. For example, I could type 'Lucy', 'School', and the server will add that to the dictionary. If I then type 'Lucy' it should reply with 'School' and if I type in 'Lucy' 'Home' it should up date that to the dictionary.
However, in the arguments, the user may put /h followed by a host name and /p followed by a port number. I'm currently trying to implement this feature in the client, however it doesn't seem to be working at all.
The following is my code. I made a list for the arguments so that if it does have /h or /p followed by the appropriate information, I can reduce the number of arguments so it doesn't effect the other parts of the program.
static void Main(string[] args)
{
String server = "whois.networksolutions.com";
int port = 43;
List<string> list = new List<string>(args);
for (int i = 0; i < args.Length; i++)
{
if (args[i].Trim() == "/h")
{
string serverString = args[i + 1].Trim();
server = args[i + 1];
list.RemoveAt(i);
//remove h from the list
list.RemoveAt(i);
//remove server name from the lst
args = list.ToArray();
//update args array
i = i - 1;
Console.WriteLine("Server changed to " + serverString);
}
else if (args[i].Trim() == "/p")
{
string portString = args[i + 1];
port = Convert.ToInt32(args[i + 1].Trim());
list.RemoveAt(i);
//remove p from the list
list.RemoveAt(i);
//remover port number from list
args = list.ToArray();
//update args array
i = i - 1;
Console.WriteLine("Port changed to " + portString);
}
}
try
{
TcpClient client = new TcpClient();
client.Connect(server, port);
client.ReceiveTimeout = 1000;
client.SendTimeout = 1000;
StreamWriter sw = new StreamWriter(client.GetStream());
StreamReader sr = new StreamReader(client.GetStream());
sw.AutoFlush = true;
sw.WriteLine(args[0]);
if (args.Length == 1)
{
if (args[0] == "514872")
{
Console.WriteLine("514872 is being tested\r\n");
}
else
{
Console.WriteLine("ERROR: no entries found\r\n");
}
}
else if (args.Length == 2)
{
Console.WriteLine(args[0] + " location changed to be is being tested\r\n");
}
}
catch
{
Console.WriteLine("Connection failure.");
}
}
}
Any help would be massively appreciated!
Thank you
Lucy
Related
I stumble on the following problems:
When trying to use the Parallel Function. I need to synchronously wait until the all the information is gathered.
When I put the foreach loop inside the try there are duplicate values.
How can I fix this? I want when I scan a subnet (254 hosts) that I get live results back.
Code:
//Network Information Parallel.ForEach Example
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Net.NetworkInformation;
using System.Text;
namespace AsteRScanneR
{
public class Program1
{
public static void Main()
{
Console.WriteLine("Enter IP Adresses seperated by a comma!");
Console.Write("Enter IP Adresses: ");
List<string> ipAdresses = new List<string>();
ipAdresses = Console.ReadLine().Split(',').ToList();
var firstOrDefault = ipAdresses.FirstOrDefault();
string[] octets = firstOrDefault.Split('.');
if (octets[3] == string.Empty)
{
ipAdresses = new List<String>();
for (int i = 1; i < 255; i++)
{
var result = String.Concat(firstOrDefault, i.ToString());
ipAdresses.Add(result);
}
}
else
{
Console.WriteLine("Multiple IP's Found!");
}
//In case you want to scan a whole subnet, user needs to input only the ABC of the IP adres and leave the D empty. It will scan 255 hosts
//Options
PingOptions pingOptions = new PingOptions(128, true);
int timeout = 1000;
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data);
List<PingReply> pingRepliesList = new();
Parallel.ForEach(ipAdresses, ip =>
{
new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount, CancellationToken = CancellationToken.None };
try
{
Stopwatch sw = new Stopwatch();
sw.Start();
Ping p = new();
lock (pingRepliesList) {
pingRepliesList.Add(p.Send(ip, timeout, buffer, pingOptions));
}
sw.Stop();
//Console.WriteLine("Pinging: "+ip+" took: "+sw.Elapsed.Milliseconds+"ms on Thread:"+ Environment.CurrentManagedThreadId);
}catch (Exception)
{
Console.WriteLine("An Error Occured...");
}
});
Console.WriteLine("");
foreach (var pingvalue in pingRepliesList)
{
if (pingvalue.Status == IPStatus.Success)
{
Console.WriteLine("Pinging " + pingvalue.Address.ToString() + " with " + pingvalue.Buffer.Length + " bytes of data:");
Console.WriteLine("Reply from " + pingvalue.Address.ToString() + ": bytes=" + pingvalue.Buffer.Length + " time" + pingvalue.RoundtripTime + "ms TTL=" + pingvalue.Options.Ttl);
Console.WriteLine("");
}
else
{
Console.WriteLine("Pinging " + pingvalue.Address.ToString() + " with " + pingvalue.Buffer.Length + " bytes of data:");
Console.WriteLine("General failure.");
Console.WriteLine("");
}
}
}
}
}
I found the solution to the problem. This is what I did:
Used the example code from: https://riptutorial.com/csharp/example/3279/parallel-for
Replacing the hard-coded list with for now the user-input. (This will be changed to args user input afterwards.)
Included the piece of code I wrote down below
Console.WriteLine("Enter IP Adresses seperated by a comma!");
Console.Write("Enter IP Adresses: ");
List<string> ipAdresses = new List<string>();
ipAdresses = Console.ReadLine().Split(',').ToList();
var firstOrDefault = ipAdresses.FirstOrDefault();
string[] octets = firstOrDefault.Split('.');
if (octets[3] == string.Empty)
{
ipAdresses = new List<String>();
for (int i = 1; i < 255; i++)
{
var result = String.Concat(firstOrDefault, i.ToString());
ipAdresses.Add(result);
}
}
else
{
Console.WriteLine("Multiple IP's Found!");
Console.WriteLine("");
}
Changed Parallel.For loop to .Count, because I am using a List
Changed some output result.Address.ToString() to ipAdresses[i] because it was creating bugs and displaying the same output over and over again.
Formatted everything in 1 string to not stumble upon problems.
I did format in 1 string on purpose, because when I formatted two strings I to get output mixed.
I need to write and read data from serial port to my device. I've test certain approach where at first, I'm receiving the data using SerialDataReceivedEventArgs and I feel it is hard to read the port where I need to define the command that send where as the command is almost 200 commands.
My first approach is using:-
private void ObjCom_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
if (!ObjCom.IsOpen) return;
byte[] data = new byte[ObjCom.BytesToRead];
ObjCom.Read(data, 0, data.Length);
RaiseEventMsg("Buffer String: " + BitConverter.ToString(data).Replace("-", " "));
}
The RaiseEventMsg is a delegate event to pass current information to Main UI. The second approach is:-
private long lngTickCount = Convert.ToInt64(1000L);
public void StartWriteToPort()
{
byte[] Cmd = null;
string strCmd = string.Empty;
string strMsg = null;
bool bCont = true;
long lngCurrent = 0;
long lngNow = 0;
try
{
RaiseEventMsg("Start Write To Port");
ObjCom.DiscardOutBuffer();
ObjCom.DiscardInBuffer();
GetFullCommandByte(ref Cmd, Convert.ToByte(123)); // Referencing Cmd with return and pass Command List(various set of command)
ObjCom.Write(Cmd, 0, Cmd.Length);
strCmd = ByteArrayToString(Cmd); // Convert byte array to Hex string
RaiseEventMsg("Send: " + strCmd);
bool bTimeout = false;
lngCurrent = DateTime.Now.Ticks;
while (!bTimeout)
{
lngNow = DateTime.Now.Ticks;
if (lngNow > (lngCurrent + (3 * lngTickCount)))
{
bTimeout = true;
break;
}
}
lngCurrent = DateTime.Now.Ticks;
while (ObjCom.BytesToRead <= 0)
{
lngNow = DateTime.Now.Ticks;
if (lngNow > (lngCurrent + (1000 * lngTickCount)))
{
bCont = false;
break;
}
}
if (!bCont)
{
strMsg = "Error - Timeout Hit";
RaiseEventMsg(strMsg);
return;
}
int Idx = 0;
string strASCIIFull = string.Empty;
if ((ObjCom.BytesToRead > 0) & (bCont == true))
{
while (ObjCom.BytesToRead > 0)
{
var strASCII = ObjCom.ReadByte();
var TmpHex = System.Convert.ToString(strASCII, 16).ToUpper();
if (TmpHex.Length == 1)
{
strASCIIFull += (" 0" + TmpHex);
}
else
{
strASCIIFull += (" " + TmpHex);
}
lngCurrent = DateTime.Now.Ticks;
while (ObjCom.BytesToRead <= 0)
{
lngNow = DateTime.Now.Ticks;
if (lngNow > (lngCurrent + (2 * lngTickCount)))
{
bCont = false;
break;
}
}
Idx += 1;
}
}
RaiseEventMsg("Recv: " + strASCIIFull);
}
catch (System.Exception ex)
{
string error = $"Exception on StartWriteToPort. Message: {ex.Message}. StackTrace: {ex.StackTrace}";
}
}
Problem on second approach is when I call this function for second time, the timeout will hit . But for Serial event, it does not have the problem, the protocol for timeout is set to 1 seconds. My device currently connected using USB without converter. The input cable to device is type B port (like standard printer port).
Is the any other way to read directly from port or any improvement on current code?
You need to learn how to layer your code. At the moment you have one long function that tries to do everything.
If you had several smaller functions that did specific things like reading or writing a chunk of information then it would make what you are trying to do simpler.
For example, serial communications generally have some sort of protocol that encapsulates how the packets of information are stored. Say the protocol was "", then you know every packet starts with an STX byte (0x01), a length byte, which tells you how many bytes are in the section, and there must be an ETX byte (0x02) at the end. You could write a function that would return an array of bytes that are just the because the function would interpret the stream and extract the relevant parts.
Then it might be as simple as:
var packet1 = ReadPacket();
WritePacket(outputData);
var packet2 = ReadPacket();
I have searched the web but I am a newbie and I find it hard to understand everything clearly.
Here is the code I have reached so far:
In this part, I am storing the text files I desire to send in variables, the I am storing each mac address of each device along with the text file to be sent to this device in a 2D array.
an array cdevices is created to store the detected devices mac addresses in the range.
//Storing data.
var Sfile = #"C:\Users\Noha\Desktop\Shenawy.txt";
var Mfile = #"C:\Users\Noha\Desktop\Moustafa.txt";
var Nfile = #"C:\Users\Noha\Desktop\Noha.txt";
string[,] array = new string[3, 2]
{
{"7840E4FA48EB", Sfile},
{"502E5CBB1A4A", Mfile},
{"0017AB39CAD3", Nfile}
};
string[] cdevices = new string[3];
int x = 0;
//end of storing data
Here is a foreach loop that detects each device, and once the device is detected, a text file is supposed to be sent to that device.
//Check if the laptop's bluetooth i connectable
if (!BluetoothRadio.IsSupported)
System.Console.WriteLine("No Bluetooth device detected.");
if (BluetoothRadio.PrimaryRadio.Mode == RadioMode.PowerOff)
BluetoothRadio.PrimaryRadio.Mode = RadioMode.Connectable;
System.Console.WriteLine(BluetoothRadio.PrimaryRadio.Name.ToString());
System.Console.WriteLine(BluetoothRadio.PrimaryRadio.Mode.ToString());
BluetoothClient bc = new BluetoothClient();
//BluetoothDeviceInfo[] info = null;
//info = bc.DiscoverDevices(999);
BluetoothDeviceInfo[] devs = bc.DiscoverDevicesInRange();
foreach (BluetoothDeviceInfo device in devs)
{
//lstDevices.Items.Add(device.DeviceName + " - " + device.DeviceAddress);
cdevices[x] = device.DeviceAddress.ToString();
System.Console.WriteLine(device.DeviceName + " " + device.DeviceAddress.ToString());
device.Update();
device.Refresh();
device.SetServiceState(BluetoothService.ObexObjectPush, true);
if (!device.Authenticated)
{
// Use pin "0000" for authentication
if (!BluetoothSecurity.PairRequest(device.DeviceAddress, "0000"))
{
// MessageBox.Show("Request failed");
System.Console.WriteLine("Request failed");
}
}
for (int countOr = 0; countOr < 3; countOr++)
{
for (int countOc = 0; countOc < 3; countOc++){
if (cdevices[x] == array[countOr, countOc])
{
var uri = new Uri("obex://" + device.DeviceAddress + "/" + array[countOr,countOc+1]);
//ObexWebRequest req = new ObexWebRequest(uri);
var request = new ObexWebRequest(uri);
request.ReadFile(array[countOr, 1]);
var response = (ObexWebResponse)request.GetResponse();
System.Console.WriteLine(response.StatusCode.ToString());
//MessageBox.Show(response.StatusCode.ToString());
// check response.StatusCode
response.Close();
break;
}
}
}
x++;
}
However,the devices do not connect to the computer, and it says failure.
Also do I have to manually pair the devices?
Thank you
Okay so in case someone needs it , I have figured out why it gives a failure. The device needs to be already paired with the computer before starting. This has fixed it. However the part for sending the text file to the device is still not working
So i am making an application which can open connections to remote devices and execute different commands. So yesterday before i left work i was debugging when i got an error. But as my application ignored it and proceeded and having not enough time to fix it immedietly i decided to do it today. When i wanted to make connection with my program again it said it couldn't authenticate (note* the parameters did not change).
So i did some checks to determine the problem, after logging in on the server and running netstat i found out that there was an active connection to port 22, which originated from my application.
Somehow the connection did not show up in my SSH manager until i rebooted it TWICE.
So to prevent things like this in a production environment, how do i prevent things like this.
my Program.cs
class Program
{
static void Main(string[] args)
{
var ip="";
var port=0;
var user="";
var pwd="";
var cmdCommand="";
ConnectionInfo ConnNfo;
ExecuteCommand exec = new ExecuteCommand();
SSHConnection sshConn = new SSHConnection();
if (args.Length > 0)
{
ip = args[0];
port = Convert.ToInt32(args[1]);
user = args[2];
pwd = args[3];
cmdCommand = args[4];
ConnNfo = sshConn.makeSSHConnection(ip, port, user, pwd);
exec.executeCMDbySSH(ConnNfo, cmdCommand);
}
else {
try
{
XMLParser parser = new XMLParser();
List<List<string>> configVars = parser.createReader("C:\\Users\\myusername\\Desktop\\config.xml");
Console.WriteLine("this is from program.cs");
//iterate through array
for (int i = 0; i < configVars[0].Count; i++)
{
if ((configVars[0][i].ToString() == "device" && configVars[1][i].ToString() == "device") && (configVars[0][i + 6].ToString() == "device" && configVars[1][i + 6].ToString() == "no value"))
{
string ipAdress = configVars[1][i + 1].ToString();
int portNum = Convert.ToInt32(configVars[1][i + 2]);
string username = configVars[1][i + 3].ToString();
string passwd = configVars[1][i + 4].ToString();
string command = configVars[1][i + 5].ToString();
Console.WriteLine("making connection with:");
Console.WriteLine(ipAdress + " " + portNum + " " + username + " " + passwd + " " + command);
ConnNfo = sshConn.makeSSHConnection(ipAdress, portNum, username, passwd);
Console.WriteLine("executing command: ");
exec.executeCMDbySSH(ConnNfo, command);
}
}
}
catch (Exception e) { Console.WriteLine("Error occurred: " + e); }
}
Console.WriteLine("press a key to exit");
Console.ReadKey();
}
}
my executeCommand class:
public class ExecuteCommand
{
public ExecuteCommand()
{
}
public void executeCMDbySSH(ConnectionInfo ConnNfo, string cmdCommand )
{
try
{
using (var sshclient = new SshClient(ConnNfo))
{
//the error appeared here at sshclient.Connect();
sshclient.Connect();
using (var cmd = sshclient.CreateCommand(cmdCommand))
{
cmd.Execute();
Console.WriteLine("Command>" + cmd.CommandText);
Console.WriteLine(cmd.Result);
Console.WriteLine("Return Value = {0}", cmd.ExitStatus);
}
sshclient.Disconnect();
}
}
catch (Exception e) { Console.WriteLine("Error occurred: " + e); }
}
}
and my class where i make conenction:
public class SSHConnection
{
public SSHConnection() { }
public ConnectionInfo makeSSHConnection(string ipAdress, int port, string user, string pwd)
{
ConnectionInfo ConnNfo = new ConnectionInfo(ipAdress, port, user,
new AuthenticationMethod[]{
// Pasword based Authentication
new PasswordAuthenticationMethod(user,pwd),
}
);
return ConnNfo;
}
}
Note* i have not included my XMLParser class because it is not relevant to the question, nor does it have any connections regarding SSH in general.
EDIT
i found out i had compiled the application and it was running in the commandline. Turns out there is no error with the code
I am writing a program that will live on a "Super PC" in my lab at work. Its job is to constantly query our customers databases proactively looking for common errors that we encounter.
It accomplishes this by using an adjustable timer and simply running down the list of queries and databases and interpreting the results.(Queries and Database connections are added using a Configuration UI)
This program has a TCP client/server connection with another app that I have written that lives on my team members personal machines. Messages get sent from the Server(Query) program to the client program alerting my team of errors found in the Databases.
The problem I keep encountering is occasionally a message gets sent through the socket at the exact same time a DB connection is made or a query is run and it causes the server program to crash with no explanation.
The methods that run the queries is always called in its own thread as well as the server connection is made in its own thread.
In addition I have placed all of the DB methods and Client Server methods in Try/Catch blocks that are setup to catch all exceptions and display the stack trace, but for some reason when it crashes its not hitting any of the catch.
The runQueries Methods is called off a C# .Net System.Timers.Timer which is supposed to launch a new thread on every tick.
Below are my Client/Server Methods and Query Methods
private void serverMeth()
{
try
{
/*conbox.Text = conbox.Text + "The server is running at port 8001..." + Environment.NewLine;
conbox.Text = conbox.Text + "The local End point is :" + myList.LocalEndpoint + Environment.NewLine;
conbox.Text = conbox.Text + "Waiting for a connection....." + Environment.NewLine;*/
msglist.Add("The server is running at port 8001...");
msglist.Add("The local end point is: " + myList.LocalEndpoint);
msglist.Add("Waiting for a connection...");
writeToLog("Listening for connection at "+myList.LocalEndpoint);
/* Start Listeneting at the specified port */
while (true)
{
gatherErrors();
myList.Start();
//Socket s = myList.AcceptSocket();
s = myList.AcceptSocket();
//conbox.Text = conbox.Text + "Connection accepted from " + s.RemoteEndPoint + Environment.NewLine;
msglist.Add("Connection accepted from " + s.RemoteEndPoint);
writeToLog("Connection Established #" + myList.LocalEndpoint);
byte[] b = new byte[20000];
int k = s.Receive(b);
//conbox.Text = conbox.Text + "Recieved..." + Environment.NewLine;
msglist.Add("Recieved...");
writeToLog("Message Recieved from Command Center");
//for (int i = 0; i < k; i++)
//{ conbox.Text = conbox.Text + Convert.ToChar(b[i]); }
string message = ""; //allows it to store the entire message in one line
string dt = DateTime.Now.ToString("MM-dd-yyyy hh:mm:ss");
string eid = "TEST ID";
for (int i = 0; i < k; i++)
{ message = message + Convert.ToChar(b[i]); }
if (message.Contains(uniquekey))
{
writeToLog("Message contains correct passcode");
message = message.Replace(uniquekey, "");
String[] splits = message.Split(',');
message = message.Replace("," + splits[1], "");
writeToLog("Connection from " + splits[1]);
msglist.Add(message); //this takes the completed message and adds it.
//DO IGNORE STUF HERE
if (!message.Equals(""))
{
//Message contains error key
Error erro = null;
for (int i = 0; i < errorss.Count; i++)
{
if (errorss[i].getKey().Equals(message)) {
erro = errorss[i];
}
}
Stage st = null;
if (erro != null)
{
for (int i = 0; i < stages.Count; i++)
{
if (stages[i].errContainCheck(erro))
{
st = stages[i];
}
}
}
if (st != null)
{
st.addIgnore(erro);
writeToLog("Error: " + erro.getKey() + "ignored");
}
}
//conbox.Text = conbox.Text + Environment.NewLine;
msglist.Add(" ");
string msg = "";
string log = "Error(s): ";
for (int i = 0; i < errorss.Count; i++)
{
msg += errorss[i].getTime() + "|"+errorss[i].getMsg()+"|" + errorss[i].getSite()+"|"+errorss[i].getKey();
msg += ",";
log += errorss[i].getKey()+",";
}
log+= "sent to Command Center";
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes(msg));
//conbox.Text = conbox.Text + "\nSent Acknowledgement" + Environment.NewLine;
msglist.Add("\nSent Acknowledgement");
writeToLog(log);
}
else
{
message = "Unauthorized access detected. Disregarding message.";
//.Add(message); //this takes the completed message and adds it.
//conbox.Text = conbox.Text + Environment.NewLine;
msglist.Add(" ");
writeToLog("Passcode mismatch");
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes("Access Denied. Unique key mismatch."));
//conbox.Text = conbox.Text + "\nSent Acknowledgement" + Environment.NewLine;
msglist.Add("\nSent Denial Acknowledgement");
}
/* clean up */
s.Close();
myList.Stop();
if (quit == true)
{
break;
}
}
}
catch (Exception err)
{
//conbox.Text = conbox.Text + "Error..... " + err.StackTrace + Environment.NewLine;
msglist.Add("Error..... " + err.StackTrace);
writeToLog("ERROR: "+err.StackTrace);
}
}
private void sasDownload()
{
int selItemList;
selItemList = saerrlist.SelectedIndex;
saerrlist.Items.Clear(); //clears the list before redownload
saerrgrid.Rows.Clear();
try
{
TcpClient tcpclnt = new TcpClient();
//clibox.Text = clibox.Text + "Connecting....." + Environment.NewLine;
tcpclnt.Connect(staralertip.Text, 8001);
// use the ipaddress as in the server program
//clibox.Text = clibox.Text + "Connected" + Environment.NewLine;
//clibox.Text = clibox.Text + "Enter the string to be transmitted : " + Environment.NewLine;
String str = "982jsdf293jsadd02jkdas20dka2";
Stream stm = tcpclnt.GetStream();
if (ackClick)
{
str += ackKey;
ackClick = false;
}
String name = "User not found";
for (int i = 0; i < users.Count(); i++)
{
if(users[i].sys_id.Equals(SNLists.loggedinuser)){
name = users[i].name;
break;
}
}
str += "," + name;
ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(str);
//clibox.Text = clibox.Text + "Transmitting....." + Environment.NewLine;
stm.Write(ba, 0, ba.Length);
byte[] bb = new byte[20000];
int k = stm.Read(bb, 0, 20000);
string incmsg = "";
for (int i = 0; i < k; i++)
incmsg = incmsg + Convert.ToChar(bb[i]);
string tempmsg = "";
foreach (char c in incmsg)
{
if (c != ',')
{
tempmsg = tempmsg + c;
}
else if (c == ',')
{
saerrlist.Items.Add(tempmsg);
saerrgrid.Rows.Add(tempmsg.Split('|')[0], tempmsg.Split('|')[1], tempmsg.Split('|')[2], tempmsg.Split('|')[3]);
tempmsg = "";
}
}
saerrlist.Items.Add(tempmsg);
//saerrgrid.Rows.Add(tempmsg.Split('|')[0], tempmsg.Split('|')[1], tempmsg.Split('|')[2]);
//MessageBox.Show(incmsg);
tcpclnt.Close();
}
catch (Exception err)
{
//MessageBox.Show("Error..... " + err.StackTrace, "STAR Command Center: Connectivity Error");
staralertTimer.Enabled = false;
MessageBox.Show("Error downloading recent errors from STAR Alert System.\n\nPlease confirm STAR Alert is running " +
"and hit \"Refresh\" in the STAR Alert tab." + "\n" + err, "STAR Command Center: Connectivity Error");
}
saerrlist.SelectedIndex = selItemList;
}
public void runQueries()
{
OracleConnection con = new OracleConnection();
int siteNum = -1;
try
{
writeToLog("Call to runQueries");
List<List<Error>> results = new List<List<Error>>();
for (int i = 0; i < ppreset.getSites().Count(); i++)
{
siteNum = i;
Site s = ppreset.getSites()[i];
if (s.getStatus().Equals("ACTIVE"))
{
//OracleConnection con = new OracleConnection();
String it = "User Id=" + s.getLogin() + ";Password=" + s.getPassword() + ";Data Source=" + s.getDbName();
con.ConnectionString = it;
//con.OpenAsync();
con.Open();
writeToLog("Connection opened for site: " + s.getSite());
List<Error> subResults = new List<Error>();
for (int j = 0; j < s.getQueries().Count(); j++)
{
Query q = s.getQueries()[j];
string sql = q.getCode();
List<string> columns = getColumns(sql);
List<List<String>> mast = new List<List<String>>();
for (int m = 0; m < columns.Count(); m++)
{
mast.Add(new List<String>());
}
OracleCommand cmd = new OracleCommand(sql, con);
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
writeToLog("Execute SQL, Begin Reading results...");
// dr.Read();
//List<String> results = new List<String>();
if (dr.HasRows)
{
//MessageBox.Show("has rows");
while (dr.Read())
{
//string result = "";
for (int p = 0; p < columns.Count(); p++)
{
if (columns.Count() != 0)
{
mast[p].Add(dr[columns[p]].ToString());
}
}
//results.Add(result);
}
}
subResults.AddRange(ruleCheck(mast, q.getRules(), s.getQueries()[j], ppreset.getSites()[i].getSite()));
cmd.Dispose();
writeToLog("Done reading");
}
results.Add(subResults);
// con.Dispose();
con.Close();
writeToLog("Connection Closed for site: " + s.getSite());
}
}
//we now have all of the error strings gathered from running all queries on all sites in the given preset
//lets send them to a method that will change the status' of the modules and makem RAVVEEEEE
//update(results);
if (errors == null && results.Count != 0)
{
//MessageBox.Show("errors = results");
errors = results;
writeToLog("First error found...errors = results");
for (int i = 0; i < results.Count; i++)
{
for (int j = 0; j < results[i].Count; j++)
{
if (foncig.lallerdisc == true)
{
sendLyncMsg(results[i][j].getMsg());
writeToLog("Lync Msg sent");
}
}
}
}
else
{
for (int i = 0; i < results.Count; i++)
{
for (int j = 0; j < results[i].Count; j++)
{
errors[i].Add(results[i][j]);
writeToLog("Error: " + results[i][j].getKey() + " added");
// MessageBox.Show("Error added to errors");
//////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//LYNC STUFF CAN GO HERE///////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/////FOR EACH ERROR ADDED TO MASTER LIST SEND LYNC///////////////////////////
//////////////////////////////////////////////////////////////////////////////
if (foncig.lallerdisc == true)
{
sendLyncMsg(results[i][j].getMsg());
writeToLog("Lync msg sent");
}
}
}
}
}
catch (Exception e)
{//MessageBox.Show("Err: " + e);
badConn[siteNum] += "x";
writeToLog("Connection error strike added to " + ppreset.getSites()[siteNum].getSite());
con.Close();
checkForBadConn();
writeToLog( e.StackTrace);
}
//foncig.errors = errors;
//here we will check all of the errors in results against all of the errors in errors
//if the error is not in errors add it
//errors = results;
}
Query timer initialization
queryTimer = new System.Timers.Timer(120000);
queryTimer.Elapsed += queryTimer_Tick;
queryTimer.Enabled = true;
Tick method for query timer
private void queryTimer_Tick(object sender, EventArgs e)
{
GC.Collect();
try
{
runQueries();
}
catch (OracleException err)
{
// MessageBox.Show("Err: " + err);
}
}
How the server thread is started
server = new Thread(serverMeth);
server.Start();
Does anyone have any idea why this might be happening? Both programs work as described and do what they are supposed to its just when more and more clients begin connecting to the server it becomes more and more likely that a TCP connection and DB connection will occur at the same time.
Update 12:20 9/15/14
So I'm trying to upload a pic of the log from the last crash... but i don't have enough rep points... derp, anyway
This time the last line in the log is from a log purge(deletes log entries older than 24 hours)
However the program will only crash when I have the client program set to auto refresh. IE Client app has a button to request messages from server or user can select auto-refresh which sets request function to timer.
My only other thought is that multiple threads are trying to write to the log file at the same time, however my write to log method uses writeLinesAsync() so that shouldn't be a problem?
This issue turned out to be caused by multiple threads trying to write to the log file at the same time.
I resolved it by following #user469104's advice and creating an internal lock object to lock the writeToLog methods.
Both client and server apps have been running for multiple days now without breaking.
Thanks Everyone!