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
Related
I'm ruunig a code that take 10 ip in one time - check ping
and if there is ping ,
he is writing the rime to the MySQL
but on every run - he get stuck after 100 runs
why?
MySql.Data.MySqlClient.MySqlException (0x80004005): error connecting: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.
at MySql.Data.MySqlClient.MySqlPool.GetConnection()
at MySql.Data.MySqlClient.MySqlConnection.Open()
at PIng_Parallel.Program.Main(String[] args) in C:\Users\Computer\Documents\Visual Studio 2015\Projects\PIng_Parallel\PIng_Parallel\Program.cs:line 48
this is the code I'm running (I'm sure i can make it better , will ty latter)
I was ask here and someone told me how to make the code run in a better why - to put the Ip in a magazine and "shoot" 10 IP every time .
if someone want to show me what I need to do - you are most welcome
"-)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.NetworkInformation;
using System.Net;
using System.Net.Sockets;
using MySql.Data.MySqlClient;
using System.IO;
namespace PIng_Parallel
{
class Program
{
static void Main(string[] args)
{
List<string> Online = new List<string>();//save the IP that were Online
List<string> Top3 = new List<string>(); //save just 10 IP every time
List<string> ListIPs = new List<string>();//save the IP from the sql
string[] RouterData = new string[14]; //save the data from the router
List<string> Answer = new List<string>();//save the IP from the sql
int running = 0;
string IP;
string time;
again:
Online.Clear();
ListIPs.Clear();
running++;
MySqlConnection con = new MySqlConnection("Server=10.0.0.249;UserID=Home;password=1234567890;database=sample;SslMode=none");
string sql = "Select IP From sample.table1 where LastOnline <='20/05/2018' OR LastOnLine='none' ";
MySqlCommand cmd = new MySqlCommand(sql, con);
try
{
con.Open();
}
catch (Exception e)
{
Console.WriteLine(e);
Console.ReadKey();
Environment.Exit(0);
}
MySqlDataReader reader = cmd.ExecuteReader();
try
{
while (reader.Read())
{
IP = reader["IP"].ToString();
ListIPs.Add(IP);
}
con.Clone();
}
catch (Exception e)
{
Console.WriteLine(e);
Console.ReadKey();
}
Console.WriteLine("We have - " + ListIPs.Count + " router to check ");
//*********************************************//
int Size = 10; //how may sessions in 1 time
int num = (ListIPs.Count / Size);
int part = (ListIPs.Count % Size);
int RunTime = 0;
MySqlConnection conn2 = new MySqlConnection("Server=10.0.0.249;UserID=Home;password=1234567890;database=sample;SslMode=none");
for (int i = 0; i < ListIPs.Count; i++)//want to run the command for only 3 in each time
{
RunTime++;
Top3 = ListIPs.GetRange(i, Size-1);
System.Threading.Tasks.Parallel.ForEach(Top3, site =>
{
try
{
Ping p = new Ping();
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 200;
PingReply reply = p.Send(site, timeout, buffer);
if (reply.Status == IPStatus.Success)
{
time = DateTime.Now.ToString();
// Online.Add(site + "," + reply.Status.ToString() + " , " + reply.RoundtripTime.ToString()+ " - " + time);
Online.Add("Update table1 SET LastOnline='" + time + "'" + "Where IP='" + site + "'");
// RouterData = GetData(site);
// foreach (string h in RouterData)
// {
// Answer.Add(h);
// }
}
}
catch (Exception e)
{
Console.WriteLine(site);
Console.WriteLine(e);
Console.ReadKey();
}
finally
{ }
});///end of Threading
// string sql2 = ("Update table1 SET LastOnline='" + time + "'" + "Where IP='" + site + "'");
try
{
foreach (string sql2 in Online)
{
MySqlCommand write = new MySqlCommand(sql2, conn2);
conn2.Open();
write.ExecuteNonQuery(); //something like "send command";
conn2.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
finally
{ }
Console.WriteLine(RunTime);
if (RunTime == num)//the last call
{
i = i + part;
}
else
{
i = i +(Size-1);
}
Top3.Clear();
} //end of cutting the list to 10 each time
Console.WriteLine("Finish");
foreach (var t in Online) //print just the Online IP
{
Console.WriteLine(t);
}
Console.WriteLine("the program run for " + running + "times");
goto again;
// Console.ReadKey();
}
I've created a simple server in raspberry pi 3 running Windows 10 IOT Core with uwp(Universal Windows Platform) with this class>
using System;
using System.Diagnostics;
using System.Text;
using Windows.Networking;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
namespace UWP_Server
{
public class StreamSocketManager
{
private StreamSocket ConnectionSocket;
public static bool IsServer { get; set; }
private string ServerPort = "8590";
public void Open()
{
StreamSocketListener DataListener = new StreamSocketListener();
DataListener.ConnectionReceived += ConnectionReceived;
DataListener.BindServiceNameAsync(ServerPort).AsTask().Wait();
}
private async void ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
DataReader reader;
StringBuilder sb;
string receivedData = null;
using (reader = new DataReader(args.Socket.InputStream))
{
sb = new StringBuilder();
reader.InputStreamOptions = InputStreamOptions.Partial;
reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
reader.ByteOrder = ByteOrder.LittleEndian;
await reader.LoadAsync(256);
while (reader.UnconsumedBufferLength > 0)
{
sb.Append(reader.ReadString(reader.UnconsumedBufferLength));
await reader.LoadAsync(256);
}
reader.DetachStream();
receivedData = sb.ToString();
}
if (receivedData != null)
{
if (IsServer)
{
MainPage.Current.Show("[SERVER] I've received " + receivedData + " from " +
args.Socket.Information.RemoteHostName);
Debug.WriteLine("[SERVER] I've received " + receivedData + " from " +
args.Socket.Information.RemoteHostName +
"\r\nIp: " + args.Socket.Information.LocalAddress + ":" +
args.Socket.Information.LocalPort +
"\r\nProtectionLevel: " + args.Socket.Information.ProtectionLevel +
"\r\nRemoteHostName: " + args.Socket.Information.RemoteHostName +
"\r\nRemoteIP: " + args.Socket.Information.RemoteAddress + ":" +
args.Socket.Information.RemotePort +
"\r\nRemoteServiceName: " + args.Socket.Information.RemoteServiceName
);
Debug.WriteLine("");
Debug.WriteLine("");
SentResponse(args.Socket.Information.RemoteAddress, "Hello " + args.Socket.Information.RemoteHostName);
}
else
{
Debug.WriteLine("[CLIENT] I've received " + receivedData + " from "
+ args.Socket.Information.RemoteHostName +
"\r\nIp: " + args.Socket.Information.LocalAddress + ":" +
args.Socket.Information.LocalPort +
"\r\nProtectionLevel: " + args.Socket.Information.ProtectionLevel +
"\r\nRemoteHostName: " + args.Socket.Information.RemoteHostName +
"\r\nRemoteIP: " + args.Socket.Information.RemoteAddress + ":" +
args.Socket.Information.RemotePort +
"\r\nRemoteServiceName: " + args.Socket.Information.RemoteServiceName
);
Debug.WriteLine("");
Debug.WriteLine("");
}
}
else
Debug.WriteLine("Received data was empty. Check if you sent data.");
}
public async void SentResponse(HostName address, string message)
{
try
{
Debug.WriteLine("Connecting to " + address + Environment.NewLine);
ConnectionSocket = new StreamSocket();
await ConnectionSocket.ConnectAsync(address, ServerPort);
DataWriter SentResponse_Writer = new DataWriter(ConnectionSocket.OutputStream);
string content = message;
byte[] data = Encoding.UTF8.GetBytes(content);
SentResponse_Writer.WriteBytes(data);
await SentResponse_Writer.StoreAsync();
SentResponse_Writer.DetachStream();
SentResponse_Writer.Dispose();
Debug.WriteLine("Connection has been made and your message " + message + " has been sent." + Environment.NewLine);
ConnectionSocket.Dispose();
ConnectionSocket = new StreamSocket();
}
catch (Exception ex)
{
Debug.WriteLine("Failed to connect ");
ex.Exception("SentResponse");
ConnectionSocket.Dispose();
ConnectionSocket = null;
}
}
}
}
everything seems OK and It's worked in as Server.
I run this code in my Windows 10 mobile (as client) and I can received and send messages between my raspberry pi and windows mobile.
Now I want to send and receive message from my android phone.
I tested a-lot of codes but none of them worked to connect android to raspberry pi.
for android I used this nuget package >
https://github.com/rdavisau/sockets-for-pcl
here is my code:
void Send()
{
var client = new TcpClient();
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse("Ramtin"), 8590);
try
{
client.Connect(ipEndPoint);
if (client.Connected)
{
Debug.WriteLine("Connected to server" + "\n");
var reader = new StreamReader(client.GetStream());
var writer = new StreamWriter(client.GetStream());
writer.AutoFlush = true;
WriteLine("Connected: " + client.Connected);
if (client.Connected)
{
writer.WriteLine("HEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEy");
}
else
{
Debug.WriteLine("send failed !");
}
}
}
catch (Exception ex)
{
ex.Exception("Send");
}
}
"Ramtin" is my raspberry pi host name.
How can I solve this?
Thanks.
Note: I tried to create android as Server and other phones as clients and it's works fine(sending/receiving message). but I don't want android as a server!
I tried to create a simple twitchBot using Visual Studio C#, but it won't show up in chat. I could connect with mIRC manually without problems.
I don't recieve any error messages, so it's hard for me to pinpoint the problem.
Any ideas are appreciated.
class Program
{
static void Main(string[] args)
{
IrcClient irc = new IrcClient("irc.chat.twitch.tv", 6667, "gruhlumbot", "oauth:g49tpwj1czs200RETAINED");
irc.joinRoom("gruhlumbot");
while(true)
{
string message = irc.readMessage();
if (message.Contains("!test"))
{
irc.sentChatMessage("response");
}
}
}
}
class IrcClient
{
private string userName;
private string channel;
private TcpClient tcpClient;
private StreamReader inputStream;
private StreamWriter outputStream;
public IrcClient(string ip, int port, string userName, string password)
{
this.userName = userName;
tcpClient = new TcpClient(ip, port);
inputStream = new StreamReader(tcpClient.GetStream());
outputStream = new StreamWriter(tcpClient.GetStream());
outputStream.WriteLine("PASS " + password);
outputStream.WriteLine("NICK " + userName);
outputStream.WriteLine("USER " + userName + " 8 * :" + userName);
outputStream.Flush();
}
public void joinRoom(string channel)
{
this.channel = channel;
outputStream.WriteLine("JOIN #" + channel);
outputStream.Flush();
}
public void sentChatMessage(string message)
{
sendIrcMessage(":" + userName + "!" + userName + "#" + userName + ".tmi.twitch.tv PRIVMSG #" + channel + " :" + message);
}
public string readMessage()
{
string message = inputStream.ReadLine();
return message;
}
}
Can you try adding the character "/" before the command join?
As I remember when I was using Irc all commands where using the "/" character before the command.
Something like this.
outputStream.WriteLine("/JOIN #" + channel);
Share with us the results. Thanks.
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!
can someone please help me with this?
i need to check through the System DSN for my ODBC connection to the AS400 servier and create a System DSN if a particular one does not exist.
i've tried googling and have not been able to find anything good for me.
btw, i am quite new to programming. any help will be much appreciated.
thank you
After going through the few less complicated examples available online, this is what i managed to come up with (and it works fine for me).
using System;
using System.Runtime.InteropServices;
public class ODBC_Manager
{
[DllImport("ODBCCP32.dll")]
public static extern bool SQLConfigDataSource(IntPtr parent, int request, string driver, string attributes);
[DllImport("ODBCCP32.dll")]
public static extern int SQLGetPrivateProfileString(string lpszSection, string lpszEntry, string lpszDefault, string #RetBuffer, int cbRetBuffer, string lpszFilename);
private const short ODBC_ADD_DSN = 1;
private const short ODBC_CONFIG_DSN = 2;
private const short ODBC_REMOVE_DSN = 3;
private const short ODBC_ADD_SYS_DSN = 4;
private const short ODBC_CONFIG_SYS_DSN = 5;
private const short ODBC_REMOVE_SYS_DSN = 6;
private const int vbAPINull = 0;
public void CreateDSN(string strDSNName)
{
string strDriver;
string strAttributes;
try
{
string strDSN = "";
string _server = //ip address of the server
string _user = //username
string _pass = //password
string _description = //not required. give a description if you want to
strDriver = "iSeries Access ODBC Driver";
strAttributes = "DSN=" + strDSNName + "\0";
strAttributes += "SYSTEM=" + _server + "\0";
strAttributes += "UID=" + _user + "\0";
strAttributes += "PWD=" + _pass + "\0";
strDSN = strDSN + "System = " + _server + "\n";
strDSN = strDSN + "Description = " + _description + "\n";
if (SQLConfigDataSource((IntPtr)vbAPINull, ODBC_ADD_SYS_DSN, strDriver, strAttributes))
{
Console.WriteLine("DSN was created successfully");
}
else
{
Console.WriteLine("DSN creation failed...");
}
}
catch (Exception ex)
{
if (ex.InnerException != null)
{
Console.WriteLine(ex.InnerException.ToString());
}
else
{
Console.WriteLine(ex.Message.ToString());
}
}
}
public int CheckForDSN(string strDSNName)
{
int iData;
string strRetBuff = "";
iData = SQLGetPrivateProfileString("ODBC Data Sources", strDSNName, "", strRetBuff, 200, "odbc.ini");
return iData;
}
}
... and then call the methods from your application.
static void Main(string[] args)
{
ODBC_Manager odbc = new ODBC_Manager();
string dsnName = //Name of the DSN connection here
if (odbc.CheckForDSN(dsnName) > 0)
{
Console.WriteLine("\n\nODBC Connection " + dsnName + " already exists on the system");
}
else
{
Console.WriteLine("\n\nODBC Connection " + dsnName + " does not exist on the system");
Console.WriteLine("\n\nPress 'Y' to create the connection?");
string cont = Console.ReadLine();
if (cont == "Y" || cont == "y")
{
odbc.CreateDSN(dsnName);
Environment.Exit(1);
}
else
{
Environment.Exit(1);
}
}
}