public void Cancel() { using (var cmd = new NpgsqlCommand("SELECT pg_sleep(5)", Conn)) { Task.Factory.StartNew(() => { Thread.Sleep(300); cmd.Cancel(); }); Assert.That(() => cmd.ExecuteNonQuery(), Throws.TypeOf<NpgsqlException>() .With.Property("Code").EqualTo("57014") ); } }
public void CancelCrossCommand() { using (var cmd1 = CreateSleepCommand(Conn, 2)) using (var cmd2 = new NpgsqlCommand("SELECT 1", Conn)) { var cancelTask = Task.Factory.StartNew(() => { Thread.Sleep(300); cmd2.Cancel(); }); Assert.That(() => cmd1.ExecuteNonQuery(), Throws.Nothing); cancelTask.Wait(); } }
//public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords) public MembershipUserCollection GetAllUsers(string providerName, string applicationname, int pageIndex, int pageSize) { MembershipUserCollection users = new MembershipUserCollection(); using (NpgsqlConnection conn = new NpgsqlConnection(GetConnectionString())) { string query = string.Format( QRY_GET_ALL_USER_BY_APPLICATION, applicationname); using (NpgsqlCommand cmd = new NpgsqlCommand(query, conn)) { NpgsqlDataReader reader = null; try { conn.Open(); reader = cmd.ExecuteReader(); int counter = 0; int startIndex = pageSize * pageIndex; int endIndex = startIndex + pageSize - 1; while (reader.Read()) { if (counter >= startIndex) { MembershipUser u = GetUserFromReader(providerName, reader); users.Add(u); } if (counter >= endIndex) cmd.Cancel(); ++counter; } } catch (NpgsqlException ex) { Logger.Instance.Write (TrackProtect.Logging.LogLevel.Error, ex, "GetAllUsers<NpgsqlException>"); } finally { if (reader != null) reader.Close(); conn.Close(); } } } return users; }
public MembershipUserCollection FindUsersByName(string providerName, string usernameToMatch, string applicationname, int pageIndex, int pageSize, out int totalRecords) { MembershipUserCollection users = new MembershipUserCollection(); using (NpgsqlConnection conn = new NpgsqlConnection(GetConnectionString())) { string query = string.Format( QRY_SELECT_USER_COUNT_BY_NAME, usernameToMatch, applicationname); using (NpgsqlCommand cmd = new NpgsqlCommand(QRY_SELECT_USER_COUNT_BY_NAME, conn)) { NpgsqlDataReader reader = null; try { conn.Open(); totalRecords = (int)cmd.ExecuteScalar(); if (totalRecords <= 0) { return users; } query = string.Format( QRY_GET_USER_BY_NAME_AND_APPLICATION_ORDERED, usernameToMatch, applicationname); cmd.CommandText = query; reader = cmd.ExecuteReader(); int counter = 0; int startIndex = pageSize * pageIndex; int endIndex = startIndex + pageSize - 1; while (reader.Read()) { if (counter >= startIndex) { MembershipUser u = GetUserFromReader(providerName, reader); users.Add(u); } if (counter >= endIndex) { cmd.Cancel(); } counter++; } } catch (NpgsqlException e) { if (WriteExceptionsToEventLog) { WriteToEventLog(e, "FindUsersByName"); throw new ProviderException(EXCEPTION_MESSAGE); } else { throw e; } } finally { if (reader != null) { reader.Close(); } conn.Close(); } } } return users; }
private void timer_Tick(object sender, System.Timers.ElapsedEventArgs e) { timer.Enabled = false; CustomBase.Rec rec = new CustomBase.Rec(); L.Log(LogType.FILE, Log.LogLevel.INFORM, "Service Started"); string readQuery = null; PostGreConnection pgc = new PostGreConnection(); NpgsqlDataReader readReader = null; NpgsqlCommand command = null; try { if (!reg_flag) { if (!Read_Registry()) { L.Log(LogType.FILE, Log.LogLevel.ERROR, "Error on Reading the Registry "); return; } else if (!Initialize_Logger()) { L.Log(LogType.FILE, Log.LogLevel.ERROR, "Error on Intialize Logger on McaffeeEpo Recorder functions may not be running"); return; } reg_flag = true; } if (fromend) { if (!Set_LastPosition()) L.Log(LogType.FILE, Log.LogLevel.INFORM, "Error on setting last position see eventlog for more details"); fromend = false; } readQuery = "Select kayit_tarih,kayit_saat,kullanici_ip,kullanici_name,table_name,prev_data,current_data,url,kodu from loglar where kodu > " + last_position.ToString() + " ORDER BY kodu"; //readQuery = "Select * from loglar"; L.Log(LogType.FILE, Log.LogLevel.DEBUG, " Query for EventLogTable is " + readQuery); pgc.OpenPostGreConnection(remote_host, user, password, mcdb_name); command = new NpgsqlCommand(); readReader = pgc.ExecutePostGreQuery(readQuery, ref command); //if (readReader.Read() != false) //{ // L.Log(LogType.FILE, Log.LogLevel.INFORM, "timer_Tick() ----> Query Which Was Executed Bring Data"); //} int i = 0; while (readReader.Read()) { rec.LogName = "NetCadPostGre Recorder"; string date = ""; string time = ""; string date_time = ""; date = readReader[0].ToString(); time = readReader[1].ToString(); string saat = time.Split(' ')[0].Trim(); string zamanDilimi = time.Split(' ')[1].Trim(); if (zamanDilimi == "AM") time = saat + ":00"; else time = (Convert.ToInt32(saat.Split(':')[0]) + 12).ToString() + ":" + saat.Split(':')[1] + ":00"; date = date.Split('/')[1] + "/" + date.Split('/')[0] + "/" + date.Split('/')[2]; date_time = date + " " + time; try { rec.Datetime = Convert.ToDateTime(date_time).AddMinutes(zone).ToString("yyyy/MM/dd HH:mm:ss.fff"); } catch (Exception ex) { rec.Datetime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff"); L.Log(LogType.FILE, Log.LogLevel.ERROR, "In timer_Tick()-->> An Error Occured While Parsing kayit_tarih and kayit_saat " + ex.Message); } //L.Log(LogType.FILE, Log.LogLevel.INFORM, "rec.Datetime is : " +rec.Datetime); string kullaniciIP = ""; kullaniciIP = readReader[2].ToString(); try { rec.CustomStr1 = System.Net.IPAddress.Parse(kullaniciIP).ToString(); } catch (Exception ex) { L.Log(LogType.FILE, Log.LogLevel.ERROR, "In timer_Tick()-->> An Error Occured While Parsing kullanici_ip " + ex.Message); rec.CustomStr1 = kullaniciIP; L.Log(LogType.FILE, Log.LogLevel.ERROR, "In timer_Tick()-->> kullnici_ip olduðu gibi atandý. " + kullaniciIP); } // L.Log(LogType.FILE, Log.LogLevel.INFORM, "rec.CustomStr1 is (kullanici_ip) : " +rec.CustomStr1); string kullaniciAdý = ""; kullaniciAdý = readReader[3].ToString(); try { rec.UserName = kullaniciAdý; } catch (Exception ex) { L.Log(LogType.FILE, Log.LogLevel.ERROR, "In timer_Tick()-->> An Error Occured While Parsing kullanici_name " + ex.Message); } //L.Log(LogType.FILE, Log.LogLevel.INFORM, "rec.UserName is (kullanici_name) : " + rec.UserName); string tableName = ""; tableName = readReader[4].ToString(); try { L.Log(LogType.FILE, Log.LogLevel.INFORM, "CustomStr7 Is : " + tableName); rec.CustomStr7 = tableName; } catch (Exception ex) { L.Log(LogType.FILE, Log.LogLevel.ERROR, "In timer_Tick()-->> An Error Occured While Parsing table_name " + ex.Message); } //L.Log(LogType.FILE, Log.LogLevel.INFORM, "rec.CustomStr7 (table_name) is : " + rec.CustomStr7); string url = ""; url = readReader[7].ToString(); try { rec.CustomStr6 = url; } catch (Exception ex) { L.Log(LogType.FILE, Log.LogLevel.ERROR, "In timer_Tick()-->> An Error Occured While Parsing url " + ex.Message); } //L.Log(LogType.FILE, Log.LogLevel.INFORM, "rec.CustomStr6 (url) is : " + rec.CustomStr6); string tempCurrentData = ""; tempCurrentData = readReader[6].ToString(); //L.Log(LogType.FILE, Log.LogLevel.INFORM, " (current_data) is : " + tempCurrentData); try { string[] permanentCurrentData = new string[4]; for (int f = 0; f < permanentCurrentData.Length; f++) { permanentCurrentData[f] = ""; } if (tempCurrentData != "") { permanentCurrentData = parseCurrentData(tempCurrentData); } if (permanentCurrentData[0].Length > 900) { rec.CustomStr9 = permanentCurrentData[0].Substring(0,850); rec.CustomStr10 = permanentCurrentData[0].Substring(851, 850); } else { rec.CustomStr9 = permanentCurrentData[0]; } rec.CustomStr4 = permanentCurrentData[1]; rec.CustomStr5 = permanentCurrentData[2]; rec.CustomStr8 = permanentCurrentData[3]; L.Log(LogType.FILE, Log.LogLevel.INFORM, "rec.CustomStr4 Is : " + rec.CustomStr4); L.Log(LogType.FILE, Log.LogLevel.INFORM, "rec.CustomStr5 Is : " + rec.CustomStr5); } catch (Exception ex) { L.Log(LogType.FILE, Log.LogLevel.ERROR, "In timer_Tick()-->> An Error Occured While Parsing current_data " + ex.Message); } string tempPrevData = ""; tempPrevData = readReader[5].ToString(); //L.Log(LogType.FILE, Log.LogLevel.INFORM, " (tempPrevData) is : " + tempPrevData); string permanentPrevData = ""; if (tempPrevData != "") { permanentPrevData = parsePrevData(tempPrevData); } rec.CustomStr2 = permanentPrevData; long recordID = Convert.ToInt64(readReader[8].ToString()); L.Log(LogType.FILE, Log.LogLevel.DEBUG, "Start sending Data"); if (usingRegistry) { CustomServiceBase s = base.GetInstanceService("Security Manager Sender"); s.SetData(rec); } else { CustomServiceBase s = base.GetInstanceService("Security Manager Remote Recorder"); s.SetData(Dal, virtualhost, rec); } L.Log(LogType.FILE, Log.LogLevel.DEBUG, "Finish Sending Data"); last_position = recordID; last_recdate = rec.Datetime; L.Log(LogType.FILE, Log.LogLevel.DEBUG, "Record Number is " + last_position.ToString()); i++; if (i > max_record_send) { command.Cancel(); L.Log(LogType.FILE, Log.LogLevel.DEBUG, "max_record_send < " + i.ToString() + " and command canceled"); return; } lastDb = mcdb_name; if (usingRegistry) SetNetCadPostGre_Registry(last_position.ToString()); else { CustomServiceBase s = base.GetInstanceService("Security Manager Remote Recorder"); s.SetReg(Id, last_position.ToString(), "", lastDb, "", last_recdate); } } L.Log(LogType.FILE, Log.LogLevel.DEBUG, "Finish getting the data"); } catch (Exception er) { L.Log(LogType.FILE, Log.LogLevel.ERROR, er.ToString()); } finally { timer.Enabled = true; L.Log(LogType.FILE, Log.LogLevel.INFORM, "Service Stopped"); if (command != null) { command.Dispose(); } pgc.ClosePostGreConnection(); } }
public void DoWork() { using (NpgsqlConnection conn = new NpgsqlConnection(GlobalUtils.TopSecret.PostgresCS)) using (NpgsqlCommand command = new NpgsqlCommand()) { try { conn.Open(); //conn.StatisticsEnabled = true; command.Connection = conn; } catch (Exception e) { Console.Error.WriteLine(e.Message); return; } try { using (NpgsqlTransaction sqlTran = conn.BeginTransaction()) { command.Transaction = sqlTran; NpgsqlDataReader reader; List<string> commands = GetCommands(com); foreach (string c in commands) { command.CommandText = c; using (reader = command.ExecuteReader()) { ShowResultSet(reader); while (reader.NextResult()) ShowResultSet(reader); } } //var stats = conn.RetrieveStatistics(); //using (TextWriter tw = new StreamWriter(path + ".stats")) //{ // tw.WriteLine("Execution time: {0} sec, rows selected: {1}, rows affected: {2}", // Math.Round((double)(long)stats["ExecutionTime"] / 1000, 2), // stats["SelectRows"], // stats["IduRows"]); //} } } catch (Exception e) { Console.Error.WriteLine(e.Message); if (command != null) command.Cancel(); } } }
/* function name AddStudents_Click inputs: query outputs: add student studying lesson and cancel student studying lesson errors: */ private void AddStudents_Click(object sender, EventArgs e) { string str = "Uid=postgres; Password=123; server=localhost; port=5432; Database=classmanagement;"; NpgsqlConnection conn = new NpgsqlConnection(str); conn.Open(); foreach (DataGridViewRow dr in dataGridView1.Rows) { int n = dr.Index; if (dr.Cells[0].Value != null) { String insert = ""; String select1 = "SELECT studentname FROM attendance WHERE studentname='" + dataGridView1.Rows[n].Cells[1].Value + "'AND subjectname='" + comboBox1.Text + "'"; NpgsqlCommand select_command1 = new NpgsqlCommand(select1, conn); NpgsqlDataReader read = select_command1.ExecuteReader(); if (read.Read()) { MessageBox.Show("Error message", "error", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { insert = "INSERT into attendance VALUES('" + dataGridView1.Rows[n].Cells[2].Value + "','" + dataGridView1.Rows[n].Cells[3].Value + "','" + comboBox1.Text + "')"; NpgsqlCommand command = new NpgsqlCommand(insert, conn); command.ExecuteNonQuery(); command.Cancel(); String select = "SELECT name,start_time,start_minute,finish_time,finish_minute FROM subject WHERE name='" + comboBox1.Text + "'"; NpgsqlCommand select_command = new NpgsqlCommand(select, conn); NpgsqlDataReader reader1 = select_command.ExecuteReader(); NpgsqlCommand baba = new NpgsqlCommand(); if (reader1.Read()) { int num1 = Convert.ToInt32(reader1[1]); int num2 = Convert.ToInt32(reader1[2]); int num3 = Convert.ToInt32(reader1[3]); int num4 = Convert.ToInt32(reader1[4]); String ins = "INSERT into startfinish VALUES('" + comboBox1.Text.ToString() + "','" + dataGridView1.Rows[n].Cells[2].Value + "','" + dataGridView1.Rows[n].Cells[3].Value + "','" + num1 + "','" + num2 + "','" + num3 + "','" + num4 + "')"; baba = new NpgsqlCommand(ins, conn); } reader1.Close(); baba.ExecuteNonQuery(); insert = "INSERT into homework VALUES('" + dataGridView1.Rows[n].Cells[2].Value + "','" + dataGridView1.Rows[n].Cells[3].Value + "','" + comboBox1.Text.ToString() + "')"; NpgsqlCommand comm = new NpgsqlCommand(insert, conn); comm.ExecuteNonQuery(); insert = "INSERT into grade VALUES('" + comboBox1.Text.ToString() + "','" + dataGridView1.Rows[n].Cells[2].Value + "','" + dataGridView1.Rows[n].Cells[3].Value + "')"; NpgsqlCommand comm1 = new NpgsqlCommand(insert, conn); comm1.ExecuteNonQuery(); //MessageBox.Show("success."); } read.Close(); } else { String delete = "DELETE FROM attendance WHERE studentname='" + dataGridView1.Rows[n].Cells[2].Value + "' AND subjectname='"+comboBox1.Text+"'"; NpgsqlCommand comm = new NpgsqlCommand(delete, conn); comm.ExecuteNonQuery(); delete = "DELETE FROM startfinish WHERE student_name='" + dataGridView1.Rows[n].Cells[2].Value + "' AND lesson_name='"+comboBox1.Text+"'"; NpgsqlCommand comm1 = new NpgsqlCommand(delete, conn); comm1.ExecuteNonQuery(); delete = "DELETE FROM homework WHERE studentname='" + dataGridView1.Rows[n].Cells[2].Value + "' AND subjectname='" + comboBox1.Text + "'"; NpgsqlCommand comm2 = new NpgsqlCommand(delete, conn); comm2.ExecuteNonQuery(); delete = "DELETE FROM grade WHERE student_name='" + dataGridView1.Rows[n].Cells[2].Value + "' AND lesson='" + comboBox1.Text + "'"; NpgsqlCommand comm3 = new NpgsqlCommand(delete, conn); comm3.ExecuteNonQuery(); } } conn.Close(); }