A coworker and I got the task to fix an problem on a SQL-Client.
The error is a System.OutOfMemoryException.
I figured that it could be because of the client has to many connections that doesn't get closed properly.
I tested a bit around but I can't seem to get it working.
Anyone have a suggestion?
This is the code where the error happens:
public void SQLIntoDataGridView(OracleCommand cmd, int startIndex, int maxIndex, int ersteSpalte, int maxSpalten, DataTable datenTabelle, DataGridView dgv, int sqlNr, DataTable dt)
{
OracleConnection test = new OracleConnection();
int i = 0;
int j = 0;
int spalten = ersteSpalte;
int id;
int spaltenZaehler = ersteSpalte;
int maxrows = datenTabelle.Rows.Count;
int readZeile = 0;
int writeZeile = 0;
int startrow = 0;
int startSpalte = 0;
int endSpalte = 0;
Stopwatch watch = new Stopwatch();
watch.Start();
test.ConnectionString = "Data Source=; User ID=; Password=";
using (test)
{
if (test.State == ConnectionState.Closed)
test.Open(); // <-- this is where the error occures
using (OracleDataReader reader = cmd.ExecuteReader())
{
datenTabelle.Load(reader);
dataGridViewErgebnis.DataSource = dt;
dataGridViewTest.DataSource = datenTabelle;
dataGridViewErweitern(sqlNr);
#region Rechnungsempfänger X
if (startIndex == 27 || startIndex == 24)
{
while (j < dataGridViewErgebnis.Rows.Count - 1)
{
id = startIndex;
if (dataGridViewErgebnis.Rows[j].Cells[21].Value.ToString() == "")
{
readZeile++;
i = readZeile;
j++;
writeZeile++;
}
else if (dataGridView1.Rows[startrow].Cells[0].Value.ToString() == dataGridViewErgebnis.Rows[j].Cells[21].Value.ToString())
{
if (startIndex == 24)
{
startSpalte = 7;
endSpalte = 9;
spaltenZaehler = startSpalte;
}
else if (startIndex == 27)
{
startSpalte = 10;
endSpalte = 14;
spaltenZaehler = startSpalte;
}
spaltenZaehler = startSpalte;
maxSpalten = endSpalte;
while (spaltenZaehler <= maxSpalten)
{
i = startrow;
dataGridViewErgebnis.Rows[writeZeile].Cells[id].Value = dgv.Rows[i].Cells[spaltenZaehler].Value.ToString();
spaltenZaehler++;
id++;
}
readZeile++;
i = readZeile;
j++;
writeZeile++;
spaltenZaehler = startSpalte;
startrow = 0;
}
else
{
startrow++;
}
if (i == dt.Rows.Count - 1 && j == datenTabelle.Rows.Count - 1)
{
id = startIndex;
while (id <= maxIndex && spaltenZaehler <= maxSpalten)
{
dataGridViewErgebnis.Rows[writeZeile].Cells[id].Value = dataGridViewTest.Rows[i].Cells[spaltenZaehler].Value.ToString();
id++;
spaltenZaehler++;
}
}
}
}
#endregion
else
{
while (i < dt.Rows.Count - 1)
{
id = startIndex;
if (dataGridViewErgebnis.Rows[i].Cells[0].Value.ToString() == dataGridViewTest.Rows[j].Cells[0].Value.ToString())
{
while (spaltenZaehler <= maxSpalten)
{
dataGridViewErgebnis.Rows[i].Cells[id].Value = dataGridViewTest.Rows[j].Cells[spaltenZaehler].Value.ToString();
spaltenZaehler++;
id++;
}
if (startIndex == 10 && j == datenTabelle.Rows.Count - 1)
{
j--;
j--;
i++;
}
if (j <= datenTabelle.Rows.Count - 1)
{
j++;
}
spaltenZaehler = ersteSpalte;
}
else
{
i++;
while (id <= maxIndex)
{
dataGridViewErgebnis.Rows[i].Cells[id].Value = "";
id++;
}
}
if (i == dt.Rows.Count - 1 && j == datenTabelle.Rows.Count - 1)
{
id = startIndex;
while (id <= maxIndex && spaltenZaehler <= maxSpalten)
{
dataGridViewErgebnis.Rows[i].Cells[id].Value = dataGridViewTest.Rows[j].Cells[spaltenZaehler].Value.ToString();
id++;
spaltenZaehler++;
}
}
else if (j == datenTabelle.Rows.Count && startIndex != 10)
{
j--;
if (i <= dt.Rows.Count - 2)
{
i++;
}
}
}
}
watch.Stop();
StoppUhr(watch);
}
}
}
I would rewrite the code like this.
.
.
.
OracleConnection test = new OracleConnection();
.
.
.
using (OracleConnection test = new OracleConnection("Data Source=; User ID=; Password=")) // <-- SQLconnection here
{
test.Open(); // <-- Only Open connection
using (OracleDataReader reader = cmd.ExecuteReader())
{
.
.
.
}
}
Related
This is my code for the back tracking logic.
private void backtrackLogic()
{
if (m == 0 && n != 0)
{
n--;
m = 8;
if(sudokuArray[n, m] == 0)
{
counter = copyArray[n, m];
copyArray[n, m] = 0;
if(counter == 9)
{
backtrackLogic();
}
}
else
{
backtrackLogic();
}
}
else if (m != 0)
{
m--;
if (sudokuArray[n, m] == 0)
{
counter = copyArray[n, m];
copyArray[n, m] = 0;
if (counter == 9)
{
backtrackLogic();
}
}
else
{
backtrackLogic();
}
}
else
{
Environment.Exit(0);
}
}
This is my code for the rest of the algorithm.
private void SolveButton_Click(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
copyArray[i, j] = sudokuArray[i, j];
Console.Write(sudokuArray[i, j]);
}
}
counter = 1;
bool noOptions = false;
for (n = 0; n < 9; n++)
{
for (m = 0; m < 9; m++)
{
for (counter = 1; counter < 10; counter++)
{
if (sudokuArray[n, m] == 0)
{
if (checkRow(n, m, counter) && checkColumn(n, m, counter) && checkBox(n, m, counter))
{
copyArray[n, m] = counter;
printTextBox(n, m, counter);
Console.Write(counter);
break;
}
else if (counter == 9)
{
noOptions = true;
}
}
if (noOptions)
{
backtrackLogic();
noOptions = false;
}
}
}
}
for (int n = 0; n < 9; n++)
{
for (int m = 0; m < 9; m++)
{
Console.Write(copyArray[n, m]);
}
}
}
When running this code on difficult Sudoku problems, the program times out because of how long it takes to execute. Any help in the execution of the algorithm would be very helpful!
I have a task called Find and Replace in the DataGridView - It's completed.But i want the replaced count in the message box.
Can anyone help me how to achieve this? Below is my Find and Replace code:
private void btnFindandReplace_Click(object sender, EventArgs e)
{
f.cmbColumnCombo.DataSource = cmbList;
f.ShowDialog();
if (recNo > 0)
recNo = recNo - 30;
LoadPage(MyFOrmat, true);
}
public void LoadPage(string Format, bool isFindAndReplace = false)
{
int startRec;
int endRec;
if (currentPage == PageCount)
{
endRec = (int)maxRec;
}
else
{
endRec = (int)pageSize * currentPage;
}
dataGridView1.Rows.Clear();
if (recNo == 0)
{
dataGridView1.Columns.Clear();
}
int rowindex = 0;
startRec = recNo;
for (int RowCount = startRec; RowCount <= endRec; RowCount++)
{
if (datfile[RowCount].ToString() != "" )
{
if (RowCount == 0)
{
string[] column = datfile[RowCount].Split('þ');
for (int i = 0; i < column.Length - 1; i++)
{
if (column[i].ToString() != "") //if (column[i].ToString() != "" && column[i].ToString() != "\u0014")
{
DataGridViewTextBoxColumn dgvtxtcountry = new DataGridViewTextBoxColumn();
dgvtxtcountry.HeaderText = column[i].ToString();
dgvtxtcountry.Name = column[i].ToString();
dataGridView1.Columns.Add(dgvtxtcountry);
cmbList.Add(column[i]);
// dataGridView1.Columns["Sent Date"].DefaultCellStyle.Format = "dd/MM/yyyy";
i += 1;
}
}
}
if (RowCount != 0)
{
dataGridView1.Rows.Add();
string[] column = datfile[RowCount].Split('þ');
int index = 0;
for (int i = 1; i < column.Length - 1; i++)
{
if (column[i].ToString() != "\u0014")
{
//if (i == 3)
//{
// dataGridView1.Rows[rowindex].Cells[index].Value = Convert.ToDateTime(column[i]).ToString(Format);
//}
//else
//{
dataGridView1.Rows[rowindex].Cells[index].Value = column[i].Trim('þ');
//}
if (StaticVar.FnR == true && index == StaticVar.colindx)
{
if ((column[i]).Contains(StaticVar.Find) != null)
dataGridView1.Rows[rowindex].Cells[index].Value = column[i].Replace(StaticVar.Find, StaticVar.Replace);
}
if (StaticVar.DateFormat != "" && StaticVar.DateFormat != null)
{
if (StaticVar.datecolidx == ((i - 1) / 2))
{
dataGridView1.Rows[rowindex].Cells[index].Value = Convert.ToDateTime(column[i]).ToString(StaticVar.DateFormat);
}
}
index += 1;
i += 1;
}
}
rowindex += 1;
}
}
recNo += 1;
}
}
Declare the replaced variable and increment it every time you replace a value. Show a message box at the end of the method.
public void LoadPage(string Format, bool isFindAndReplace = false) {
int replaced = 0;
....
if ((column[i]).Contains(StaticVar.Find) != null) {
dataGridView1.Rows[rowindex].Cells[index].Value = column[i].Replace(StaticVar.Find, StaticVar.Replace);
replaced++;
}
....
if(isFindAndReplace)
MessageBox.Show(string.Format("{0} occurrence(s) replaced.", replaced));
}
Currently, I am doing a log analyzer for my personal project.
My issue here is that I am new to c# and I have an performance issue with my tool.
Everytime the device(iOS) is interacted, I get an output syslog from a library and it comes in to the output handler.
public void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine, iosSyslogger form, string uuid)
{
string currentPath = System.Environment.CurrentDirectory;
bool exit = false;
if (exit == true) return;
try
{
form.BeginInvoke(new Action(() =>
{
form.insertLogText = outLine.Data;
}));
using (System.IO.StreamWriter file = new System.IO.StreamWriter(currentPath + #"\syslog" + uuid + ".txt", true))
{
file.WriteLine(outLine.Data);
}
}
catch
{
return ;
}
//*Most of the logic for outputing the log should be dealt from this output Handler
}
Then, I write the outline.Data to Data grid view. My concern is that I need to be able to search and filter through data gridview.
Curently I am using visibility = false for search filtering ( if the row does not match the given filter specification I set the row to visibility =false)
This requires the program to traverse the entire datagridview to check whether the condition is met.
Will there be any better way to filter and search within ?
(When I have thousands of lines of row, it takes at least 20 seconds to process it)
Below is the code for filtering, and searching through the results function.
private void searchResult(string term)
{
if (term != null)
{
int i = 0;
while (i < dataGridView1.Rows.Count - 1)
{
if (dataGridView1.Rows[i].Cells[3] == null)
{
i++;
continue;
}
if (dataGridView1.Rows[i].Visible == false)
{
i++;
continue;
}
else if (dataGridView1.Rows[i].Cells[2].Value.ToString().Contains(term) || dataGridView1.Rows[i].Cells[3].Value.ToString().Contains(term) || dataGridView1.Rows[i].Cells[4].Value.ToString().Contains(term))
{
string multirow = dataGridView1.Rows[i].Cells[5].Value.ToString();
int count = Convert.ToInt32(multirow);
if (count > 0)
{
int z = 0;
for (z = 0; z <= count; z++)
{
dataGridView1.Rows[i + z].Visible = true;
}
i = i + z;
}
else
{
dataGridView1.Rows[i].Visible = true;
i++;
}
}
else
{
dataGridView1.Rows[i].Visible = false;
i++;
}
}
}
}
public filteringThelist(){
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
dataGridView1.Rows[i].Visible = false;
int count1,count2,count3=0;
count1 = 1;
count2 = 1;
count3 = 1;
int z = 0;
foreach (KeyValuePair<string, string> entry in totalSelected)
{
if (entry.Value == "devicename" && dataGridView1.Rows[i].Cells[1].Value != null)
{
if (dataGridView1.Rows[i].Cells[1].Value.ToString().Trim().Equals(entry.Key.Trim()))
{
string multirow1 = dataGridView1.Rows[i].Cells[5].Value.ToString();
int counts = Convert.ToInt32(multirow1);
if (counts > 0)
{
for (z = 0; z < counts; z++)
{
dataGridView1.Rows[i + z].Visible = true;
}
}
else
{
dataGridView1.Rows[i].Visible = true;
}
}
else if (devicename.CheckedItems.Count > 1&&count1!= devicename.CheckedItems.Count)
{
count1++;
continue;
}
else
{
dataGridView1.Rows[i].Visible = false;
break;
}
}
else if (entry.Value == "process" && dataGridView1.Rows[i].Cells[2].Value != null)
{
if (dataGridView1.Rows[i].Cells[2].Value.ToString().Trim().Equals(entry.Key.Trim()))
{
string multirow1 = dataGridView1.Rows[i].Cells[5].Value.ToString();
int counts = Convert.ToInt32(multirow1);
if (counts > 0)
{
for (z = 0; z < counts; z++)
{
dataGridView1.Rows[i + z].Visible = true;
}
}
else
{
dataGridView1.Rows[i].Visible = true;
}
}
else if (processlistname.CheckedItems.Count > 1 && count2 != processlistname.CheckedItems.Count)
{
count2++;
continue;
}
else
{
dataGridView1.Rows[i].Visible = false;
break;
}
}
else if (entry.Value == "loglevel" && dataGridView1.Rows[i].Cells[3].Value != null)
{
if (dataGridView1.Rows[i].Cells[3].Value.ToString().Trim().Contains(entry.Key.Trim()))
{
string multirow1 = dataGridView1.Rows[i].Cells[5].Value.ToString();
int counts = Convert.ToInt32(multirow1);
if (counts > 0)
{
for (z = 0; z < counts; z++)
{
dataGridView1.Rows[i + z].Visible = true;
}
}
else
{
dataGridView1.Rows[i].Visible = true;
}
continue;
}
else if (loglevelCheckBox.CheckedItems.Count > 1 && count3 != loglevelCheckBox.CheckedItems.Count)
{
count3++;
continue;
}
else
{
dataGridView1.Rows[i].Visible = false;
break;
}
}
// do something with entry.Value or entry.Key
}
string multirow = dataGridView1.Rows[i].Cells[5].Value.ToString();
int count = Convert.ToInt32(multirow);
if (count > 0&& dataGridView1.Rows[i].Visible==false)
{
for (int k = 0; k <= count; k++)
{
dataGridView1.Rows[i + k].Visible = false;
}
}
i = i + z;
}
The performance problem is because your DataGridView is redrawing at each modification.
Don't fill the DataGridView directly from your Data. Rather create a DataTable and bind it to DataGridView with a BindingSource.
Then use the "Filter" property of the binding source to view extracts of dataTable in the DataGridView. The "Filter" property is a string whose content is similar to that of a WHERE SQL clause.
I want to export my DataTable to CSV. DataTable is sort by column "Czas", but when I export it then data in the output file is sort by "Nrkarty".
There you have a fragments of my code:
time1 = dateTimePicker1.Text.ToString() + dateTimePicker3.Text.ToString()+":00";
time2 = dateTimePicker2.Text.ToString() + dateTimePicker4.Text.ToString()+":59";
DataTable DT3 = new DataTable();
{
using (SQLiteTransaction transaction = sql_con.BeginTransaction())
{
using (SQLiteCommand command = sql_con.CreateCommand())
{
command.CommandText = "SELECT IDX, Nrkarty, Czas FROM Zdarzenia WHERE datetime(Czas) BETWEEN datetime('" + time1 + "') AND datetime('" + time2 + "') ORDER BY Nrkarty";
DA = new SQLiteDataAdapter(command);
DA.AcceptChangesDuringFill = false;
DT3.Clear();
DT3.Columns.Clear();
DA.Fill(DT3);
DT3.Columns.Add("Kierunek", typeof(String));
DT3.Columns.Add("Status", typeof(int));
DT3.Columns.Add("Roznica", typeof(TimeSpan));
if (DT3.Rows.Count != 0)
{
DateTime tempczas = DateTime.Parse(DT3.Rows[0]["Czas"].ToString());
long temp = tempczas.Ticks;
long suma = 0;
long indeks = 0;
foreach (DataRow temprow in DT3.Rows)
{
DateTime czas = DateTime.Parse(temprow["Czas"].ToString());
long Ticks = czas.Ticks;
long roznica = Ticks - temp;
if (roznica < 0) { roznica = 0; }
long stala10m = new TimeSpan(0, 10, 0).Ticks;
long stala13h=new TimeSpan(17,0,0).Ticks;//zmiana zakladalem ze trwa 12 dlatego zrobilem 13 okazalo sie ze trwa 16 zrobilem 17
if (roznica < stala10m)
{
temprow["Roznica"] = roznica;
temprow["Kierunek"] = "X";//filtracja ktos nie wiedzial czy przylozyl
if (roznica == 0)//tylko dla pierwszej lini wynikow sortowania roznica =0;
indeks = 1;//domyslnie zakladam ze pierwszy wynik to przyjscie do pracy
}
else if (roznica < stala13h)
{
if (indeks == 0)
{
temprow["Roznica"] = new TimeSpan(0);
temprow["Kierunek"] = "WE";//jezeli parzyste przylozenie to to przylozenie musi byc rozpoczeciem pracy
indeks = 1;
}
else
{
temprow["Roznica"] = roznica;
suma += roznica;
temprow["Kierunek"] = "WY";//jezeli nieparzyste przylozenie to to przylozenie musi byc zakonczenie pracy
indeks = 0;
}
}
else
{
indeks = 1;
temprow["Roznica"] = new TimeSpan(0);
temprow["Kierunek"] = "WE";//jezeli minelo 17h od poprzedniego przylozenia to to przylozenie musi byc rozpoczeciem pracy
}
temp = Ticks;
temprow["Status"] = 0;
}
DT3.DefaultView.Sort = "Czas asc";
dataGridView1.DataSource = DT3;
DT4 = DT3;
TimeSpan ssuma = new TimeSpan(suma);
UInt32 czas_pracy = Convert.ToUInt32(ssuma.TotalMinutes);
UInt32 czas_h = czas_pracy / 60;
UInt32 czas_m = czas_pracy % 60;
textBox1.Text = czas_h.ToString();
textBox2.Text = czas_m.ToString();
try
{
dataGridView1.Columns["Czas"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";
dataGridView1.Columns["IDX"].Visible = true;
dataGridView1.Columns["Nrkarty"].Visible = true;
dataGridView1.Columns["Czas"].Width = 110;
dataGridView1.Columns["Nazwisko"].Width = 120;
dataGridView1.Columns["Imie1"].Width = 120;
//dataGridView1.Columns["Roznica"].DefaultCellStyle.Format = "HH:mm:ss";
}
catch (NullReferenceException)
{
// This happens when settings values are empty
}
}
}
transaction.Commit();
}
}
and export to CSV:
public static void ExportToSpreadsheet(System.Data.DataTable dt, Stream myStream, string CB1)
{
StreamWriter sw = new StreamWriter(myStream);//, System.Text.Encoding.Unicode);
int iColCount = dt.Columns.Count;
if (CB1 != "Wszystko")
{
for (int i = 0; i < iColCount; i++)
{
if ((dt.Columns[i].ColumnName == "Czas") || (dt.Columns[i].ColumnName == "Nazwisko") || (dt.Columns[i].ColumnName == "Imie1") || (dt.Columns[i].ColumnName == "Imie2"))
{
if (dt.Columns[i].ColumnName == "Czas")
{
sw.Write("Data;Czas");
}
else
sw.Write(dt.Columns[i]);
if (i < iColCount - 1)
{
sw.Write(";");
}
}
}
sw.Write(sw.NewLine);
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if ((dt.Columns[i].ColumnName == "Czas") || (dt.Columns[i].ColumnName == "Nazwisko") || (dt.Columns[i].ColumnName == "Imie1") || (dt.Columns[i].ColumnName == "Imie2"))
{
if (!Convert.IsDBNull(dr[i]))
{
/*if (dt.Columns[i].ColumnName == "Czas")
{
string tmp = dr[i].ToString();
StringBuilder s = new StringBuilder(tmp);
char x1 = s[0];
char x2 = s[1];
char x3 = s[6];
char x4 = s[7];
s[0] = x3;
s[1] = x4;
s[6] = x1;
s[7] = x2;
sw.Write(s.ToString());
}
else*/
{
if (dt.Columns[i].ColumnName == "Czas")
{
string x = dr[i].ToString();
string y = x.Replace(' ', ';');
sw.Write(y);
}
else
sw.Write(dr[i].ToString());
}
}
if (i < iColCount - 1)
{
sw.Write(";");
}
}
}
sw.Write(sw.NewLine);
}
}
else
{
{
for (int i = 0; i < iColCount; i++)
{
if ((dt.Columns[i].ColumnName == "Nrkarty") || (dt.Columns[i].ColumnName == "Czas") || (dt.Columns[i].ColumnName == "Kierunek") || (dt.Columns[i].ColumnName == "Status"))
{
if (dt.Columns[i].ColumnName == "Czas")
{
sw.Write("Data;Czas");
}
else
sw.Write(dt.Columns[i]);
if (i < iColCount - 1)
{
sw.Write(";");
}
}
}
sw.Write(sw.NewLine);
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if ((dt.Columns[i].ColumnName == "Nrkarty") || (dt.Columns[i].ColumnName == "Czas") || (dt.Columns[i].ColumnName == "Kierunek") || (dt.Columns[i].ColumnName == "Status"))
{
if (!Convert.IsDBNull(dr[i]))
{
/*if (dt.Columns[i].ColumnName == "Czas")
{
string tmp = dr[i].ToString();
StringBuilder s = new StringBuilder(tmp);
char x1 = s[0];
char x2 = s[1];
char x3 = s[6];
char x4 = s[7];
s[0] = x3;
s[1] = x4;
s[6] = x1;
s[7] = x2;
sw.Write(s.ToString());
}
else*/
{
if (dt.Columns[i].ColumnName == "Czas")
{
string x = dr[i].ToString();
//string x = ((DateTime)dr[i]).ToString("yyyy/MM/dd HH:mm:ss", CultureInfo.InvariantCulture);
string y = x.Replace(' ', ';');
sw.Write(y);
}
else
sw.Write(dr[i].ToString());
}
}
if (i < iColCount - 1)
{
sw.Write(";");
}
}
}
sw.Write(sw.NewLine);
}
}
}
sw.Close();
}
ok..I did it. I had only assign DefaultView to Datatable befor import DataTable to dataGridView.
datatable = datatable.DefaultView.ToTable();
There is an error with that string.compiler thingy and i dont know what to do. i really need some help please
char[] valWord = new char[100];
Console.WriteLine(textBox1.Text);
valWord = textBox1.Text;
int beg = 0;
int val = 0;
int value = 0;
for (int i = 0; i < 100; i++)
{
if (valWord[i] == ' ' || valWord[i] == '\0')
{
char[] temp = new char[100];
for (int j = 0; j < i - beg; j++)
{
temp[j] = valWord[beg + j];
}
temp[i - beg] = '\0';
//there is an error in this if statement: String.Compare
if (String.Compare(temp, "thousand") == 0)
{
value += (val*1000);
val = 0;
}
else if (String.Compare(temp, "hundred") == 0)
{
value += (val*100);
val = 0;
}
else if (String.Compare(temp, "one") == 0)
{
val = 1;
}
else if (String.Compare(temp, "two") == 0)
{
val = 2;
}
if (valWord[i] == '\0')
{
value += val;
break;
}
}
Console.WriteLine(textBox2.Text);
}
else
{
_list.Add(name, new GenericList());
}
You can't compare a string to a char array. They are different types.
Use if (string.Equals(new string(temp),"thousand")) instead.
As per MSDN, there is no such function overload defined for String.Compare