assistance with optimization - c#

not sure if stackoverflow is normally used for stuff like this but i'm looking for assistance in optimizing my code. I am running a method to query a count from a database which is fast and works fine. and a timer that is set to run this every 5 minutes. When i implement the timer in my main window after initialization it freezes when opening the window for 30+ seconds. It didn't do that before I added the timers. Any help optimizing this or tips on improving the way this works would be great!
Method that runs SQL query:
public string SQLDataTotalCalls()
{
DateTime dte = DateTime.Today;
string fixedStartDate = String.Format("{0:yyyy-MM-dd " + "05:00:00.000" + "}", dte);
string fixedEndDate = String.Format("{0:yyyy-MM-dd " + "05:00:00.000" + "}", dte.AddDays(1));
SqlConnection connection = null;
using (connection)
{
try
{
var dataSet = new DataSet();
connection = new SqlConnection("Data Source=QL1OADB1;Initial Catalog=OADB;User Id=;Password=");
connection.Open();
var command = new SqlCommand("SELECT COUNT(SOURCEID) AS 'MYCOUNT' "
+ "FROM [OADB].[oadb].[CmsCallHistory] "
+ "WHERE disposition = 2 and DISPSPLIT in (" + SkillNumber + ") AND SEGSTOP BETWEEN '" + fixedStartDate + "' and '" + fixedEndDate + "'",
connection)
{
CommandType = CommandType.Text
};
var dataAdapter = new SqlDataAdapter { SelectCommand = command };
dataAdapter.Fill(dataSet);
return dataSet.Tables[0].Rows[0]["MYCOUNT"].ToString();
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
finally
{
if (connection != null)
{
connection.Close();
}
}
}
}
Timer that triggers the method every 5 minutes:
public async Task RunPeriodicQueryTotalCalls()
{
TimeSpan interval = TimeSpan.FromMinutes(5);
while (true)
{
await Task.Delay(interval);
string result = await Task.Run((Func<string>)SQLDataTotalCalls);
TotalDailyCalls = result;
}
}
This is where i initialize the window. please note that I run these querys also when the application first launches before the timer runs otherwise the numbers will not post until it runs 5 minutes later:
public ScoreBoardBigViewWindow()
{
InitializeComponent();
string value = "Enter Skill Number Here";
if (Tmp.InputBox("New document", "New document name:", ref value) == System.Windows.Forms.DialogResult.OK)
{
SkillNumber = value;
}
TotalDailyLast7Days = SQLDataSevenPastCalls();
TotalDailyCalls = SQLDataTotalCalls();
TotalDailyAbandon = SQLDataAbandonCalls();
RunPeriodicQueryTotalCalls();
RunPeriodicQueryAbandonCalls();
}
If i remove RunPeriodicQueryTotalCalls(); and RunPeriodicQueryAbandonCalls(); then the performance issue goes away.
If stackoverflow is not the right place to ask this type of question please let me know and I'll reach out to other avenues for further assistance.

Related

Mysql update query works without using parameters but doesn't when using them

Good day,
In c#, I am trying to run a MySQL update query to update one record, based on its id. Everything goes well as long as I'm not using parameters.
I'm experiencing the issue once I am adding one or several parameters. I have made the test with only one parameter and same problem here.
What am I missing here ?
Thank you very much for your help.
public static void editCustomerTest(ClsCustomerTest pTest)
{
MySqlConnection l_Connection = null;
string l_SpName = string.Empty;
MySqlCommand l_MyCommand = null;
try
{
l_Connection = ClsIconEnv.getDataAccess().MySqlConnection;
ClsDataAccess.OpenConnection(l_Connection);
l_SpName = "update tbTestCustomers " +
"set sName = '#sLastName', " +
"sFirstName = '#sFirstName', " +
"sAddress = '#sAddress' " +
"Where id = #id);";
l_MyCommand = new MySqlCommand(l_SpName, l_Connection);
l_MyCommand.Parameters.Add("#sLastName", pTest.Last_Name);
l_MyCommand.Parameters.Add("#sFirstName", pTest.First_name);
l_MyCommand.Parameters.Add("#sAddress", pTest.Address);
l_MyCommand.Parameters.Add("#id", pTest.id);
l_MyCommand.ExecuteNonQuery(); // <----- This is the line at which the execution stops
ClsDataAccess.CloseConnection(l_Connection);
}
catch (Exception exc)
{
ClsIconErrorManager.manageException(exc);
}
finally
{
}
}
You do not need to wrap your params into the string and you have to use AddWithValue instead of Add if you don't want to explicitly specify the type, like this
l_SpName = "update tbTestCustomers " +
"set sName = #sLastName, " +
"sFirstName = #sFirstName, " +
"sAddress = #sAddress" +
"Where id = #id);";
l_MyCommand.Parameters.AddWithValue("#sLastName", pTest.Last_Name);
l_MyCommand.Parameters.AddWithValue("#sFirstName", pTest.First_name);
l_MyCommand.Parameters.AddWithValue("#sAddress", pTest.Address);
l_MyCommand.Parameters.AddWithValue("#id", pTest.id);
Like this:
l_SpName = #"update tbTestCustomers
set sName = #sLastName,
sFirstName = #sFirstName,
sAddress = #sAddress
Where id = #id";
l_MyCommand = new MySqlCommand(l_SpName, l_Connection);
l_MyCommand.Parameters.AddWithValue("#sLastName", pTest.Last_Name);
l_MyCommand.Parameters.AddWithValue("#sFirstName", pTest.First_name);
l_MyCommand.Parameters.AddWithValue("#sAddress", pTest.Address);
l_MyCommand.Parameters.AddWithValue("#id", pTest.id);
l_MyCommand.ExecuteNonQuery();

When I can't reach Mysql server ip, winform GUI freezes

I am working on a project about data acquisition. I get data via RasPi3b+ from machines. Data is held Mysql on Raspi server. To track data, I have made a dashborad by using C# winforms. Sometimes machines are shut down and I can't reach Mysql server. When that happens winforms freezes. I don't want it to freeze (maybe a green indicator turns red but it should not affect GUI ). How can I fix this ?
This is my timer code that is triggered every 2 second.
private void timer1_Tick(object sender, EventArgs e)
{
for (int i = 0; i < (IpAndNames.Count ); i++)
{
string today = DateTime.Now.ToString("yyyy-MM-dd");
_lblListOpen[i].Text = "open: " + _machineDal.SpenTime(today, IpAndNames[i].Ip, "Logs", "Machine","open").ToString();
_lblListClose[i].Text = "close: " + _machineDal.SpendTime(today, IpAndNames[i].Ip, "Logs", "Machine","close").ToString();
string lastState = _machineDal.LastDateAndState(IpAndNames[i].Ip, "Machine", "Logs").LastState;
DateTime lastTime = _machineDal.LastDateAndState(IpAndNames[i].Ip, "Machine", "Logs").LastDate;
TimeSpan spendTime= DateTime.Now - lastTime;
_lblListWorkingTime[i].Text = lastState +" "+ spendTime.ToString("h'h 'm'm 's's'");
}
}
This is my data layer code
public TimeSpan SpendTime(string date, string ip, string tableName, string db, string state)
{
TimeSpan openTime= new TimeSpan(0, 0, 0);
string connString = "server=" + ip + ";user=root;database=" + db + ";port=3306;password=root;Connection Timeout=1";
try
{
using (_conn = new MySqlConnection(connString))
{
string query = "SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(time ) ) ) AS timeSum FROM " + tableName + " " +
"WHERE Laststate='" + state + "' " +
"and date like \"" + date + "%\"";
using (MySqlCommand cmd = new MySqlCommand(query, _conn))
{
_conn.Open();
using (MySqlDataReader reader = cmd.ExecuteReader())
{
reader.Read();
if (!reader.IsDBNull(0))
{
openTime= reader.GetTimeSpan(0);
}
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
return openTime;
}

Stop a thread working with DB

I'm working on an autocomplete script.
When user stop typing, his input is send to the server which will look for some matches in DB.
Eg: If looking for people "Obam" should return "Barack Obama".
I want this search to be limited to ~500ms. If it takes longer, I want to abort the search and only return results found in time.
I start by looking for a perfect match (this one won't be interrupted), then I am looking for a partial match (this one can be interrupted) :
private static MySqlConnection conn = new MySqlConnection(ConfigurationManager.AppSettings["CxMySql"].ToString());
protected void Page_Load(object sender, EventArgs e)
{
conn.Open();
SearchTerm(table,term,domaine);
conn.Close(); // TimeoutException HERE
conn.Dispose();
}
private void SearchTerm(string table,string term,string domaine)
{
Dictionary<int, Scoring> results = new Dictionary<int, Scoring>();
var requete = "SELECT m.id, m.nom as label FROM marque m WHERE m.nom = '" + term + "'";
var Cmd = new MySqlCommand(requete, conn);
using (var Rd = Cmd.ExecuteReader())
{
while (Rd.Read())
{
results.Add(int.Parse(Rd["id"].ToString()), new Scoring()
{
score = 1000,
value = Rd["label"].ToString()
});
}
}
// Here it should be 500, but I put 1 to force troubles to appear.
RunWithTimeout(() => FindOtherBrands(term, ref results), TimeSpan.FromMilliseconds(1));
var resultsList = results.ToList();
resultsList.Sort(
delegate(KeyValuePair<int, Scoring> firstPair,
KeyValuePair<int, Scoring> nextPair)
{
return nextPair.Value.score - firstPair.Value.score;
}
);
}
private void FindOtherBrands(string term, ref Dictionary<int, Scoring> results)
{
MySqlCommand Cmd;
string requete;
requete = "SELECT m.id, m.nom as label FROM marque m WHERE m.nom LIKE '" + term + "%'";
Cmd = new MySqlCommand(requete, conn);
var Rd = Cmd.ExecuteReader(); // NullReferenceException HERE
while (Rd != null && Rd.Read())
{
int id = int.Parse(Rd["id"].ToString());
if (!results.ContainsKey(id))
{
results.Add(id, new Scoring()
{
score = 100,
value = Rd["label"].ToString()
});
}
}
Rd.Close();
requete = "SELECT m.id, m.nom as label FROM marque m WHERE m.nom LIKE '%" + term + "%'";
Cmd = new MySqlCommand(requete, conn);
Rd = Cmd.ExecuteReader();
while (Rd != null && Rd.Read())
{
int id = int.Parse(Rd["id"].ToString());
if (!results.ContainsKey(id))
{
results.Add(id, new Scoring()
{
score = 10,
value = Rd["label"].ToString()
});
}
}
Rd.Close();
}
I found the RunWithTimeout method here : stop executing code in thread after 30s
bool RunWithTimeout(ThreadStart threadStart, TimeSpan timeout)
{
Thread workerThread = new Thread(threadStart);
workerThread.Start();
bool finished = true;
if (!workerThread.Join(timeout))
{
workerThread.Abort();
finished = false;
}
return finished;
}
Scoring is a struct for an easy sorting of results
private struct Scoring
{
public string value;
public int score;
}
The aim is to have results (not necessarily all) fast.
PROBLEMS
I randomly get Timeoutexception after ~30s on the conn.Close(); line.
I randomly get NullReferenceException on the first Cmd.ExecuteReader(); call in FindOtherBrands.
Can anyone explain me why ?
Am I doing something wrong or is there a workaround ?
I guess the TimeoutException is because I am trying to close connection during command execution, can I drop/cancel that query ?
I would take a different approach. Since you're querying a database, which is naturally asynchronous, you can use async-await for querying the data. With that, you can pass a CancellationToken which is set to a timeout, which you'll monitor with every read:
For example:
private async Task FindOtherBrands(string term,
Dictionary<int, Scoring> results,
CancellationToken cancellationToken)
{
MySqlCommand cmd;
string requete;
requete = "SELECT m.id, m.nom as label
FROM marque m
WHERE m.nom LIKE '" + term + "%'";
cmd = new MySqlCommand(requete, conn);
var Rd = await cmd.ExecuteReaderAsync();
while (Rd != null && await Rd.ReadAsync())
{
cancellationToken.ThrowIfCancellationRequested();
int id = int.Parse(Rd["id"].ToString());
if (!results.ContainsKey(id))
{
results.Add(id, new Scoring()
{
score = 100,
value = Rd["label"].ToString()
});
}
}
Rd.Close();
requete = "SELECT m.id, m.nom as label
FROM marque m
WHERE m.nom LIKE '%" + term + "%'";
cmd = new MySqlCommand(requete, conn);
Rd = await Cmd.ExecuteReaderAsync();
while (Rd != null && await Rd.ReadAsync())
{
cancellationToken.ThrowIfCancellationRequest();
int id = int.Parse(Rd["id"].ToString());
if (!results.ContainsKey(id))
{
results.Add(id, new Scoring()
{
score = 10,
value = Rd["label"].ToString()
});
}
}
Rd.Close();
}
And when you invoke it, all you need is to wrap it in a try-catch and pass a CancellationToken:
private async Task<bool> RunWithTimeoutAsync(TimeSpan timeout)
{
bool finished;
try
{
var cancellationTokenSource = new CancellationTokenSource(timeout);
await FindOtherBrandsAsnyc(term,
results,
cancellationTokenSource.CancellationToken);
finished = true;
}
catch (OperationCanceledException e)
{
// Handle
}
return finished;
}
Side note - Your query is prone to SQL Injection. You shouldn't used string concatenation. Use query parameters instead.

Displaying a progressbar while executing an SQL Query

I want to inform the user while data is being read from an SQL database
and I decided to create a form with a progressbar but it doesn't work - maybe because a thread is needed. I want to create the form programmatically
ProgressBar pb = new ProgressBar();
pb.MarqueeAnimationSpeed = 30;
pb.Style = ProgressBarStyle.Marquee;
pb.Dock = DockStyle.Fill;
progressForm.ClientSize = new Size(200, 50);
progressForm.FormBorderStyle = FormBorderStyle.FixedDialog;
progressForm.StartPosition = FormStartPosition.CenterScreen;
progressForm.Controls.Add(pb);
progressForm.ControlBox = false;
progressForm.TopMost = true;
progressForm.Show();
//do data processes here (all queries and executes)
progressForm.close();
How do I modify the code above to achieve my stated goals?
edit: Btw, I want to use this progressbar form in every data functions in my project. For example: fillGrid, runQuery..
#Will thank you very much for your answers. I meant how can I use a function of class for example my gridFill function is in that connection class:
class ConnectionClass
{
public static SqlConnection connection = new SqlConnection();
public string sorgu;
public static string server;
public static string userId;
public static string catalog;
public static string password;
public static string accessMethod;
public DataSet ds = new DataSet();
Form progressForm = new Form();
public bool Open()
{
try
{
if (connection.State != ConnectionState.Open)
{
connection.ConnectionString = "Data Source = " + server + ";" +
"Initial Catalog=" + catalog + ";" +
"User ID=" + userId + ";" +
"Password=" + password + ";" +
"Connect Timeout=0";
connection.Open();
return true;
}
else
{
return true;
}
}
catch (Exception ex)
{
MessageBox.Show("System message:" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
public DataTable Dt(string query)
{
DataTable dt = new DataTable();
if (Open())
{
SqlDataAdapter da = new SqlDataAdapter(query, connection);
try
{
//progressForm.Showdialog() is this possible???
da.Fill(dt);
//progressForm.close(); ??
}
catch (Exception ex)
{
MessageBox.Show("Sistem Mesajı:" + ex.Message, "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
return dt;
}
public bool Run(string query, string hataMsj)
{
Form activeForm = Form.ActiveForm;
query = " SET DATEFORMAT DMY " + query;
SqlCommand sc = new SqlCommand(query, connection);
try
{
Open();
sc.ExecuteNonQuery();
return true;
}
catch (Exception )
{
return false;
}
}
public void fillComboBox(string sorgu, ComboBox cb, string text, string value)
{
DataTable dt = Dt(sorgu);
cb.DisplayMember = text;
cb.ValueMember = value;
cb.DataSource = dt;
if (cb.Items.Count > 0)
{
cb.SelectedIndex = 0;
}
}
public int fillGridView(string sorgu, DataGridView dgv)
{
DataTable dtGrvw = Dt(sorgu);
dgv.DataSource = dtGrvw;
return 1;
}
}
and example queries from another form(class)
ConnectionClass cc = new ConnectionClass();
query= " INSERT INTO tblPersonel (" +
" [sqlUserName] " +
",[personelNo] " +
",[ad] " +
",[soyad] " +
",[departmanId] " +
",[emailadres] " +
",[tcKimlikNo],[kangurubu],[dokumaciNo])VALUES" +
"('" + tbSqlUserName.Text +
"','" + tbPersonelNo.Text +
"','" + tbAd.Text +
"','" + tbSoyad.Text +
"','" + cbDepartman.SelectedValue.ToString() +
"','" + tbMail.Text +
"','" + tbKimlikno.Text +
"','" + tbKangrubu.Text +
"','" + tbDokumaciNo.Text + "' ) ";
if (cc.Run(query, "Unexpected error on insert new person"))
{
fillGrid();
this.Close();
}
public void fillGrid()
{
query= " select * from View_Personel order by personelNo desc";
cc.fillGridView(query, gridviewPersonel);
}
and I cant imagine how can I use it in bw_DoWork event. because my function has parameters.(query, gridview) when I call it from another class I can use it with parameters...
p.s. : this Method is pretty good for me but it didnt worked. I didnt understand the problem
Use the BackgroundWorker class to fill your DataGrid.
Form progressForm;
public void func() {
BackgroundWorker bw = new BackgroundWorker ();
bw.DoWork += new DoWorkEventHandler (bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler (bw_RunWorkerCompleted);
progressForm = new Form ();
ProgressBar pb = new ProgressBar ();
pb.MarqueeAnimationSpeed = 30;
pb.Style = ProgressBarStyle.Marquee;
pb.Dock = DockStyle.Fill;
progressForm.ClientSize = new Size (200, 50);
progressForm.FormBorderStyle = FormBorderStyle.FixedDialog;
progressForm.StartPosition = FormStartPosition.CenterScreen;
progressForm.Controls.Add (pb);
progressForm.ControlBox = false;
progressForm.TopMost = true;
progressForm.Show ();
string queryString = "SELECT ...."; // fill query string here
var params = new KeyValuePair<GridControl, string>(sorgu, queryString);
bw.RunWorkerAsync (params);
}
void bw_DoWork (object sender, DoWorkEventArgs e) {
KeyValuePair<GridControl, string> params = e.Argument as KeyValuePair<GridControl, string>;
ConnectionClass cc = new Connection Class();
cc.fillGrid(params.Value, params.Key);
}
void bw_RunWorkerCompleted (object sender, RunWorkerCompletedEventArgs e) {
progressForm.Close (); //
}
It is possible to send a parameter to the BackgroundWorker. If you need more than one parameter, you can send a Tuple which contains any objects you need.
EDIT: If you're on 3.5, you can use a KeyValuePair instead. Code is updated for that.
Just as Ash Burlaczenko recommended, you'll have to use a BackgroundWorker for that purpose.
Since, however, you'd like to tie it in with a ProgressBar, I'd recommend looking at this article on CodeProject: ProgressWorker.
It's fairly easy to use and it updates the progress bar for you automatically. All you'll have to do is remember to call the ProgressWorker.ReportProgress method from time to time in order to update the associated progress bar.

ADO.NET connection error "System.Data.OleDb.OleDbException"

I am getting this error while trying to connect my web site.
Unspecified error Description: An
unhandled exception occurred during
the execution of the current web
request. Please review the stack trace
for more information about the error
and where it originated in the code.
Exception Details:
System.Data.OleDb.OleDbException:
Unspecified error.
Maybe I am doing something wrong while opening and closing connections. I always get this error if 5-10 user enter same time to site. When a user enter site I am updating or inserting new records for statistics.
I am using db class for connect:
public OleDbConnection baglan()
{
OleDbConnection baglanti = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + Server.MapPath("~/App_Data/manisaweb.mdb"));
baglanti.Open();
return (baglanti);
}
//********************************************************************
//Sql Sorgu Çalıştırma
public int cmd(string sqlcumle)
{
OleDbConnection baglan = this.baglan();
OleDbCommand sorgu = new OleDbCommand(sqlcumle, baglan);
int sonuc = 0;
try
{
sonuc = sorgu.ExecuteNonQuery();
}
catch (OleDbException ex)
{
throw new Exception(ex.Message + " (" + sqlcumle + ")");
}
finally
{
sorgu.Connection.Close();
}
return (sonuc);
}
//********************************************************************
//Kayıt Sayısı Bulma
public string GetDataCell(string sql)
{
DataTable table = GetDataTable(sql);
if (table.Rows.Count == 0)
return null;
return table.Rows[0][0].ToString();
}
//Kayıt Çekme
public DataRow GetDataRow(string sql)
{
DataTable table = GetDataTable(sql);
if (table.Rows.Count == 0) return null;
return table.Rows[0];
}
//DataTable ye veri çekme
public DataTable GetDataTable(string sql)
{
OleDbConnection baglan = this.baglan();
OleDbDataAdapter adapter = new OleDbDataAdapter(sql, baglan);
DataTable dt = new DataTable();
try
{
adapter.Fill(dt);
}
catch (OleDbException ex)
{
throw new Exception(ex.Message + " (" + sql + ")");
}
finally
{
adapter.Dispose();
baglan.Close();
}
return dt;
}
//Datasete veri çekme
public DataSet GetDataSet(string sql)
{
OleDbConnection baglan = this.baglan();
OleDbDataAdapter adapter = new OleDbDataAdapter(sql, baglan);
DataSet ds = new DataSet();
try
{
adapter.Fill(ds);
}
catch (OleDbException ex)
{
throw new Exception(ex.Message + " (" + sql + ")");
}
finally
{
ds.Dispose();
adapter.Dispose();
baglan.Close();
}
return ds;
}
And for STATISTICS in main.master.cs every page_load event
public void Istatistik()
{
string IpAdres = Request.ServerVariables["REMOTE_ADDR"].ToString();//Ip Adresini alıyoruz.
string Tarih = DateTime.Now.ToShortDateString();
lblOnlineZiyaretci.Text = Application["OnlineUsers"].ToString();//Online ziyaretçi
//Ogüne Ait Hit Bilgi Güncelleme
DataRow drHit = GetDataRow("Select * from SayacHit Where Tarih='" + Tarih + "'");
if (drHit == null)
{
//Bugüne ait kayıt yoksa bugunün ilk siftahını yap
cmd("Insert into SayacHit(Tarih,Tekil,Cogul) values('" + Tarih + "',1,1)");
}
else
{
string SayfaAdi = Page.ToString().Replace("_aspx", ".aspx").Remove(0, 4); //Sayfa adını alıyoruz.
if (SayfaAdi == "default.aspx")//Güncelleme işlemini sadece anasayfadaysa yapıyoruz
{
//Bugüne ait kayıt varsa Çoğulu 1 artırıyoruz.
cmd("Update SayacHit set Cogul=Cogul+1 Where Tarih='" + Tarih + "'");
}
//Tekil artımı için önce Ip kontrolü yapıyoruz.
DataRow drIpKontrol = GetDataRow("select * from SayacIp Where Ip='" + IpAdres + "'");
if (drIpKontrol == null)
{ //Eğer ip yoksa tekilide artırabiliriz. Ip kayıtlı ise artırma işlemi yapmıyoruz.
cmd("Update SayacHit set Tekil=Tekil+1 Where Tarih='" + Tarih + "'");
}
}
//Giren Kişinin IP sini Kaydetme
DataRow drIp = GetDataRow("Select * from SayacIp Where Ip='" + IpAdres + "'");
if (drIp == null)
{
cmd("Insert into SayacIp(Ip,Tarih) values('" + IpAdres + "','" + Tarih + "')");
}
//Ekrana Bilgileri Yazdırabiliriz
DataRow drSonuc = GetDataRow("Select * from SayacHit Where Tarih='" + Tarih + "'");
lblBugunTop.Text = drSonuc["Cogul"].ToString();
//lblBugunTekil.Text = drSonuc["Tekil"].ToString();
//Dün Bilgilerini Çekme
//DataRow drDun = GetDataRow("Select * from SayacHit Where Tarih='" + DateTime.Now.AddDays(-1).ToShortDateString() + "'");
DataRow drGenel = GetDataRow("Select SUM(Tekil) as Toplam from SayacHit");
//if (drDun != null)
//{
// lblDunTop.Text = drDun["Tekil"].ToString();
//}
//else
//{
// lblDunTop.Text = "0";
//}
lblGenelTop.Text = drGenel["Toplam"].ToString();
lblIPAdresi.Text = IpAdres;
}
And then there is 2 section in Default.aspx; it loads at the page load event for news and articles.
db veri = new db();
rptNews.DataSource = veri.GetDataTable("select top 5 KullaniciAdiSoyadi,Ozet,Baslik,Tarih,IcerikID,Icerik from Icerik a inner join Kullanici d on a.KullaniciID=d.KullaniciID where KategoriID = 1 and Durum = 1 Order by IcerikID Desc ");
rptNews.DataBind();
rptArticle.DataSource = veri.GetDataTable("select top 5 Ozet,Baslik,Tarih,IcerikID,Icerik from Icerik where KategoriID = 2 and Durum = 1 Order by IcerikID Desc ");
rptArticle.DataBind();
So there is so many UPDATE, INSERT and SELECT queries in every page load event. If this is my problem, is there another way of doing this?
It would help if you showed a bit more of the code. With this much information it could be anything. I'll take 2 guesses:
1) You have a limit of 5 connections, either on your Db or in ConnectionPooling
2) You forgot to close (Dispose) one or more Database objects
I would second Henk's #2 suggestion: failure to properly close database connections. If you are using DataSets or DataReaders, sending inline SQL or calling stored procedures, you must close the connections in code when you are through with them. If you don't close the connection, the number of available connections is gradually maxed out, and no new database requests can be made. It is only after enough users' sessions time out and the connections are released that other users can obtain a connection.
You have the exact symptom of unclosed connections: everything works fine for the first few users. But gradually, as more users log in, or as the original users move about the web app, opening ever more database connections, that everything locks up.
One way to diagnose this would be to use a database profiler tool (Profiler for SQL Server) to examine the database connections as they are opened and closed.

Categories