this is my first question in here.
So I have this app that connects to a remote database using Npgsql library.
I have a method that connects to the db, execute a query, and finally it closes the connection.
It work fine, but the problem is that if, while the program is running but not calling the method, I disconnect the WiFi to simulate the inability to connect to the server, and then run the method, the connection method still is able to open the connection. This causes the query to get stuck.
I can't seem to find a way to check if I can connect to server because, even if I disconnect the internet, the NpgsqlConnection.Open() method still opens it.
Sorry about my english
public static NpgsqlConnection ConnectRemote()
{
try
{
remoteConnection = new NpgsqlConnection("Server = " + remoteData.server + "; " +
"Port = " + remoteData.port + "; " +
"User Id = " + remoteData.user + "; " +
"Password = " + remoteData.password + "; " +
"Database = " + remoteData.dataBase + "; ");
remoteConnection.Open();
}
catch (NpgsqlException ex)
{
throw;
}
catch (Exception ex)
{
remoteConnection.Close();
remoteConnection = null;
}
return remoteConnection;
}
public static bool CheckRemote()
{
if (remoteConnection != null)
{
if (remoteConnection.FullState.Equals(ConnectionState.Open))
return true;
return false;
}
return false;
}
public bool AddNewProduct(Product product)
{
try
{
DBManager.ConnectLocal();
DBManager.ConnectRemote();
object[] parameters;
if (DBManager.CheckRemote())
{
if (!DBManager.isSyncronized)
{
DBManager.Syncronize();
}
parameters = new object[8];
parameters[0] = 1;
parameters[1] = product.id;
parameters[2] = product.description;
parameters[3] = (decimal)product.salePrice;
parameters[4] = (decimal)product.cost;
parameters[5] = product.minStock;
parameters[6] = product.providerName;
parameters[7] = product.category;
DBManager.RunFunction(DBManager.remoteConnection, DBProcedures.createProduct, parameters);
}
else
{
string sql = "select * from createproduct(1, " + product.id + ", '" + product.description + "', " + (decimal)product.salePrice + ", "
+ (decimal)product.cost + ", " + product.minStock + ", '" + product.providerName + "', '" + product.category + "'); ";
parameters = new object[1];
parameters[0] = sql;
DBManager.RunFunction(DBManager.localConnection, "addsync", parameters);
DBManager.isSyncronized = false;
}
parameters = new object[6];
parameters[0] = product.description;
parameters[1] = (decimal)product.salePrice;
parameters[2] = (decimal)product.cost;
parameters[3] = product.minStock;
parameters[4] = product.providerName;
parameters[5] = product.category;
DataTable result = DBManager.RunFunction(DBManager.localConnection, DBProcedures.createProduct, parameters);
DBManager.DisconnectLocal();
DBManager.DisconnectRemote();
return true;
}
catch (Npgsql.NpgsqlException ex)
{
return false;
}
}
A few things -- one unrelated, and two related. I am hopeful that some combination of these will help.
First, the unrelated comment. The NpgSqlStringBuilder class is a nice tool to help demystify the connection strings. I realize yours works, but as you have to make edits (as I will suggest in a minute), I find it much easier to use than navigating String.Format, just as Query Parameters are easier (on top of being more secure) than trying to string.Format your way through passing arguments to a query. Also, declare the ApplicationName in your connection string to help diagnose what exactly is happening on the server, like you will read in the next comment.
If you are using connection pooling, When a connection is closed, I don't think it's really closed -- not even on the database. If you open server admin, you will see what I mean -- it kind of dangles out there, waiting to be reused. Try setting pooled=false in your connection string to ensure that when you close a connection you really close it.
If this doesn't work, try a trivial query. The cost will be minimal in cases where you don't need it and will undoubtedly fix your use case when you do need it.
All three suggestions are reflected here:
public static NpgsqlConnection ConnectRemote()
{
NpgsqlConnectionStringBuilder sb = new NpgsqlConnectionStringBuilder();
sb.ApplicationName = "Connection Tester";
sb.Host = remoteData.server;
sb.Port = remoteData.port;
sb.Username = remoteData.user;
sb.Password = remoteData.password;
sb.Database = remoteData.database;
sb.Pooling = false;
remoteConnection = new NpgsqlConnection(sb.ToString());
try
{
remoteConnection.Open();
NpgSqlCommand test = new NpgSqlCommand("select 1", remoteConnection);
test.ExecuteScalar();
}
catch (NpgsqlException ex)
{
throw;
}
catch (Exception ex)
{
remoteConnection.Close();
remoteConnection = null;
}
return remoteConnection;
}
Related
I'm using Mangement class to create a process, but That starts a UI console - I want to console to run in background.
public uint LaunchProcess(string sIPAddress, string sPort)
{
uint iPid = 0;
try
{
logger.AddLog("LaunchProcess : " + sIPAddress + " " + sPort);
object[] PlugInRunnerInfo = { StaticUtils.GetLocation(AgilentPluginCommonConstants.PlugInRunnerPath) + "\\" + "PlugInRunner.exe" + " " + sIPAddress + " " + sPort, null, null, 0 };
//ManagementClass is a part of Windows Management Intrumentation,namespaces. One of its use is to provides access to manage applications.
//Here this class is used to launch PlugInRunner as detached process.By setting the ManagementClass object's property 'CreateFlags' to value 0x00000008
//we can start the PlugInRunner as detached one.
using (var mgmtObject = new ManagementClass("Win32_Process"))
{
var processStartupInfo = new ManagementClass("Win32_ProcessStartup",null);
processStartupInfo.Properties["CreateFlags"].Value = 0x00000008;//DETACHED_PROCESS.
var result = mgmtObject.InvokeMethod("Create", PlugInRunnerInfo);
if (result != null)
{
logger.AddLog("Process id " + Convert.ToUInt32(PlugInRunnerInfo[3]));
iPid = Convert.ToUInt32(PlugInRunnerInfo[3]);
}
}
}
catch (Exception ex)
{
logger.AddLog("Exception " + ex.Message);
}
return iPid;
}
The above code what I have got. Please help me.
I have made a tool that will copy files from a source to a destination. However during the copy, the software came across a virus that was flagged by the anti-virus software (Symantec).
The anti-virus then caused my software to close down, and quarantine the program as a "dropper".
Is there anyway I can gracefully handle this scenario, rather than shutting down my program completely?
I appreciate that the action was the result of the anti-virus, but is there anything I can do to help the situation? For example, Robocopy does not just terminate when it comes across a virus.
Here is my copy code;
void CopyFileExactly(CopyParameterBundle cpb, bool overwrite)
{
string CTP = "", CFP = "";
CFP = cpb.SourcePath;
if (cpb.RenameFile)
CTP = cpb.DestPath ;
else
CTP = cpb.DestPath;
//Check firstly if the file to copy exists
if (!File.Exists(CFP))
{
throw new FileNotFoundException();
}
//Check if destination file exists
//If it does, make it not read only so we can update MAC times
if (File.Exists(CTP))
{
var target = GetFile(CTP);//new FileInfo(CTP);
if (target.IsReadOnly)
target.IsReadOnly = false;
}
var origin = GetFile(CFP);//new FileInfo(CFP);
GetFile(CTP).Directory.Create();
//(new FileInfo(CTP)).Directory.Create();
origin.CopyTo(CTP, (overwrite ? true : false));
if (!File.Exists(CTP))
{
throw new FileNotFoundException("Destination file not found!");
}
var destination = GetFile(CTP);//new FileInfo(CTP);
if (destination.IsReadOnly)
{
destination.IsReadOnly = false;
destination.CreationTime = origin.CreationTime;
destination.LastWriteTime = origin.LastWriteTime;
destination.LastAccessTime = origin.LastAccessTime;
destination.IsReadOnly = true;
}
else
{
destination.CreationTime = origin.CreationTime;
destination.LastWriteTime = origin.LastWriteTime;
destination.LastAccessTime = origin.LastAccessTime;
}
if (performMD5Check)
{
var md5Check = compareFileMD5(CFP, CTP);
cpb.srcMD5Hash = md5Check.Item2;
cpb.dstMD5Hash = md5Check.Item3;
if (!md5Check.Item1)
throw new MD5MismatchException("MD5 Hashes do NOT match!");
}
}
The calling code;
void BeginCopy(int DegreeOfParallelism, int retryCount, int retryDelay)
{
object _lock;
//Setup cancellation token
po.CancellationToken = cts.Token;
//Set max number of threads
po.MaxDegreeOfParallelism = DegreeOfParallelism;
//Exceptio logging queue
var exceptions = new ConcurrentQueue<Exception>();
var completeItems = new ConcurrentQueue<CopyParameterBundle>();
var erroredItems = new ConcurrentQueue<CopyParameterBundle>();
//Logger logger = new Logger(sLogPath);
//logger.Write("Starting copy");
Task.Factory.StartNew(() =>
{
Parallel.ForEach(CopyParameters,
po,
(i, loopState, localSum) =>
{
localSum = retryCount;
do
{
try
{
//Go off and attempt to copy the file
DoWork(i);
//Incrememt total count by 1 if successfull
i.copyResults.TransferTime = DateTime.Now;
i.copyResults.TransferComplete = true;
completeItems.Enqueue(i);
//logger.Write("Copied file from: " + i.SourcePath + "\\" + i.SourceFile + " => " + i.DestPath + "\\" + i.SourceFile);
break;
}
catch (Exception ex)
{
//this.richTextBox1.AppendText("[-] Exception on: " + i.SourcePath + "\\" + i.SourceFile + " => " + ex.Message.ToString() + System.Environment.NewLine);
//Exception was thrown when attempting to copy file
if (localSum == 0)
{
//Given up attempting to copy. Log exception in exception queue
exceptions.Enqueue(ex);
this.SetErrorText(exceptions.Count());
//Write the error to the screen
this.Invoke((MethodInvoker)delegate
{
this.richTextBox1.AppendText("[-] Exception on: " + i.SourcePath + "\\" + i.SourceFile + " => " + ex.Message.ToString() + System.Environment.NewLine);
i.copyResults.TransferComplete = false;
i.copyResults.TransferTime = DateTime.Now;
i.copyResults.exceptionMsg = ex;
erroredItems.Enqueue(i);
//logger.Write("ERROR COPYING FILE FROM : " + i.SourcePath + "\\" + i.SourceFile + " => " + i.DestPath + "\\" + i.SourceFile + " => " + ex.Message.ToString() + " => " + ex.Source);
});
}
//Sleep for specified time before trying again
Thread.Sleep(retryDelay);
localSum--;
}
//Attempt to Repeat X times
} while (localSum >= 0);
//Check cancellation token
po.CancellationToken.ThrowIfCancellationRequested();
Interlocked.Increment(ref TotalProcessed);
this.SetProcessedText(TotalProcessed);
//Update Progress Bar
this.Invoke((MethodInvoker)delegate
{
this.progressBar1.Value = (TotalProcessed);
});
});
//aTimer.Stop();
this.Invoke((MethodInvoker)delegate
{
this.label9.Text = "Process: Writing Log";
});
WriteLog(sLogPath, completeItems, erroredItems);
this.Invoke((MethodInvoker)delegate
{
this.label9.Text = "Process: Done!";
});
if (exceptions.Count == 0)
MessageBox.Show("Done!");
else
MessageBox.Show("Done with errors!");
EnableDisableButton(this.button2, true);
EnableDisableButton(this.button4, false);
});
}
What happened is most likely that the antivirus was aware of the virus file, so when it detected that a change in the file system (moving the file) occurred, it terminated the program because by moving the virus to a different location in your computer, it could cause problems (since it's a virus). It was flagged as dropper, basically a type of program that is designed to install the virus.
Edit: i forgot to mention that to solve the problem you will most likely need to license your program.
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
So, when I connected, or attempt, it runs this code in Database.cs.
Also, I'm using SmartIRC4Net for IRC handling
Now I know this is the error because Init() in Database.cs doesn't even run! If it is, it doesn't create the "trubot.sqlite" file with the tables.
I have no idea why it's doing it, but it is.
Here's the Database.cs code:
public void Init(){
try {
if (File.Exists("trubot.sqlite")) {
dbf = new SQLiteConnection("Data Source=trubot.sqlite;Version=3");
dbf.Open();
String db;
db = "CREATE TABLE IF NOT EXISTS '"+chan+"' (id INTEGER PRIMARY KEY, user TEXT, currency INTEGER DEFAULT 0, subscriber INTEGER DEFAULT 0, battletag TEXT DEFAULT null, uLevel INTEGER DEFAULT 0, mod INTEGER DEFAULT 0, rlvl INTEGER DEFAULT 0);";
using (query = new SQLiteCommand(db, dbf)){
query.ExecuteNonQuery();
}
} else {
SQLiteConnection.CreateFile("trubot.sqlite");
dbf = new SQLiteConnection("Data Source=trubot.sqlite;Version=3");
dbf.Open();
String db;
db = "CREATE TABLE IF NOT EXISTS '"+chan+"' (id INTEGER PRIMARY KEY, user TEXT, currency INTEGER DEFAULT 0, subscriber INTEGER DEFAULT 0, battletag TEXT DEFAULT null, uLevel INTEGER DEFAULT 0, mod INTEGER DEFAULT 0, rlvl INTEGER DEFAULT 0);";
using (query = new SQLiteCommand(db, dbf)){
query.ExecuteNonQuery();
}
}
} catch (Exception s) {
Console.WriteLine("[ERROR] Error in code. " + s.Message);
}
}
public void addUser(String user) {
// add new user
try {
if (!usrExist(user)) {
String db = "INSERT INTO '"+chan+"' (user) VALUES ('"+user+"');";
using (query = new SQLiteCommand(db,dbf)) {
query.ExecuteNonQuery();
}
}
} catch (Exception err) {
Console.WriteLine("addUser is causing an error: " + err.Message);
}
}
and here's the other reason it crashes (which is in Program.cs)
public static void OnJoined(object sender, JoinEventArgs e) {
try {
var conf = new Config();
var db = new Database();
Console.WriteLine("[SELF] ["+conf.Channel+"] > *** "+e.Data.Nick+" has joined the channel!");
if (!db.usrExist(e.Data.Nick)) {
try {
db.addUser(e.Data.Nick);
} catch (Exception er1) {
string lnNum = er1.StackTrace.Substring(er1.StackTrace.Length - 7, 7);
Console.WriteLine("Error: -- Trubot Error "+ er1.Message + " " + er1.Data.ToString()
+ " " + er1.InnerException.Message.ToString()
+ " " + er1.TargetSite.ToString() + " Ln: " + lnNum);
Console.ReadKey();
}
}
} catch (Exception er1) {
string lnNum = er1.StackTrace.Substring(er1.StackTrace.Length - 7, 7);
Console.WriteLine("Error: -- Trubot Error "+ er1.Message + " " + er1.Data.ToString()
+ " " + er1.InnerException.Message.ToString()
+ " " + er1.TargetSite.ToString() + " Ln: " + lnNum);
Console.ReadKey();
}
}
Side note: I'd use MySQL but I need this application to be as portable as possible and run on as many operating systems as possible. I'd rather use SQLite than MSSQL or MySQL.
I fixed it. The problem was when I assigned the channel to the SQL as a Table Name, I needed to remove the "#" from it. So here's the resulting code:
public Database() {
var conf = new Config();
chan = conf.Channel.Replace("#","");
Init();
}
I'm building a form and I'm trying to use threading in order to get some results from a WMI query to display in a textbox without having the form freeze up on the user. However, when I use the code below and use Break-All when debugging, the code just sits on getPrinterThread.Join(). I know I must be missing something.
My aim is to get a thread to run the ObtainPrinterPort method to completion, then get a thread to run the InstallPrinterPort method to completion. I have the code below as inline code in another method. The code isn't in a separate class or anything and I don't have a background worker because all of the examples I've seen, up until now, have only confused me.
Here's my admittedly poor thread attempt:
Thread printThread = new Thread(ObtainPrinterPort);
printThread.Start();
while (!printThread.IsAlive) ;
Thread.Sleep(1);
printThread.Join(); // Form sits and does nothing; Break-all reveals this line as statement being executed.
Thread installThread = new Thread(InstallPrinterPort);
installThread.Start();
while (!installThread.IsAlive);
Thread.Sleep(1);
installThread.Join();
Is there a simple way I can get something to work that is safe and will allow me to display the results that occur in the methods as they happen to the user in the textbox? Hopefully there's a way to do this that will allow me to continue to use the instance variables/methods/code I've written in the form class...otherwise, I'll have to re-write a lot of code if I'm going to implement a "DoWork"-type example (where my methods are called from the DoWork method/constructor or the Worker class).
Please keep in mind that my methods need to return text from the thread to a textbox to display results to the user. I have code that I'm assuming will allow me to return the text from the thread if it works, but I just wanted to make sure that any suggestions/help kept this in mind. The code I'm using is below:
public void AppendTextBox(string value)
{
if (InvokeRequired)
{
this.Invoke(new Action<string>(AppendTextBox), new object[] { value });
return;
}
txtResults.Text += value;
}
For what it's worth, here's my ObtainPrinterPort method and the CreateNewConnection method that accompanies it...the InstallPrinterPort method is extremely similar, so posting it won't really reveal much:
private ManagementScope CreateNewConnection(string server, string userID, string password)
{
string serverString = #"\\" + server + #"\root\cimv2";
ManagementScope scope = new ManagementScope(serverString);
try
{
ConnectionOptions options = new ConnectionOptions
{
Username = userID,
Password = password,
Impersonation = ImpersonationLevel.Impersonate,
EnablePrivileges = true
};
scope.Options = options;
scope.Connect();
}
catch (ManagementException err)
{
MessageBox.Show("An error occurred while querying for WMI data: " +
err.Message);
}
catch (System.UnauthorizedAccessException unauthorizedErr)
{
MessageBox.Show("Connection error (user name or password might be incorrect): " + unauthorizedErr.Message);
}
return scope;
}
private void ObtainPrinterPort()
{
string computerName = "";
string userID = "";
string password = "";
string printerQuery = "SELECT * FROM Win32_Printer WHERE Name = ";
string portQuery = "SELECT * FROM Win32_TCPIPPrinterPort WHERE Name = ";
string search = "";
SelectQuery query;
foreach (var s in lstServer)
{
computerName = s.ServerName;
userID = s.UserID;
password = s.Password;
}
ManagementScope scope = CreateNewConnection(computerName, userID, password);
foreach (Printers p in lstPrinters)
{
AppendTextBox("Obtaining printer/port info for " + p.PrinterName + "\r\n");
search = printerQuery + "'" + p.PrinterName + "'";
query = new SelectQuery(search);
try
{
using (var searcher = new ManagementObjectSearcher(scope, query))
{
ManagementObjectCollection printers = searcher.Get();
if (printers.Count > 0)
{
AppendTextBox("\tStoring printer properties for " + p.PrinterName + "\r\n");
foreach (ManagementObject mo in printers)
{
StorePrinterProperties(p, mo);
}
}
else
{
lstPrinterExceptions.Add("Printer: " + p.PrinterName);
AppendTextBox("\t**Printer " + p.PrinterName + " not found**\r\n");
}
}
}
catch (Exception exception)
{
MessageBox.Show("Error: " + exception.Message, "Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
if (!lstPrinterExceptions.Contains("Printer: " + p.PrinterName)
&& !lstPrinterExceptions.Contains("Port: " + p.PortName))
{
search = portQuery + "'" + p.PortName + "'";
query = new SelectQuery(search);
try
{
using (var searcher = new ManagementObjectSearcher(scope, query))
{
ManagementObjectCollection ports = searcher.Get();
if (ports.Count > 0)
{
AppendTextBox("\tStoring port properties for " + p.PortName + " (" + p.PrinterName + ")\r\n");
foreach (ManagementObject mo in ports)
{
StorePortProperties(p, mo);
}
}
else
{
lstPrinterExceptions.Add("Port: " + p.PortName);
AppendTextBox("\t**Port " + p.PortName + " for " + p.PrinterName + " not found**\r\n");
}
}
}
catch (Exception exception)
{
MessageBox.Show("Error: " + exception.Message, "Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
AppendTextBox("\tSuccessfully obtained printer/port info for " + p.PrinterName + "\r\n");
}
}
}
Thanks.
Your problem is that the Invoke calls are blocking waiting for the main thread to DoEvents so they can be processed, but the main thread is blocking in Thread.Join. You have a deadlock.
This is how you run a thread without blocking the UI thread. Thread.Join blocks until the other thread finishes, so here I am blocking only for max 100ms, then calling DoEvents so the form can respond to messages (including processing your Invoke calls from the other thread), then looping until the background thread is complete.
Thread printThread = new Thread(ObtainPrinterPort);
printThread.Start();
while (printThread.IsAlive) {
Application.DoEvents();
printThread.Join(100);
}
Calling DoEvents in a loop like this is a bit hacky, but it will work.
You can also look into BackgroundWorker, which makes the whole thing a lot safer and easier.
A simple example:
var bw = new BackgroundWorker();
bw.DoWork += (worker, args) => {
ObtainPrinterPort();
};
bw.RunWorkerAsync();