Connection Timeout in C# - c#

I am running an application that loads too many data from the database, I don't have any wrong code or anything but every time I load too many data I get this exception
Timeout expired. The timeout period elapsed prior to completion of the
operation or the server is not responding.
Warning: Null value is eliminated by an aggregate or other SET operation.
Here is my code to load the data in my gridview
private void toolStripCompute_Click(object sender, EventArgs e)
{
//LoadData();
#region Threading Begin
//this.dgvCommision.Enabled = false;
oProgressBar.Visible = true;
lblProgress.Visible = true;
oProgressBar.Value = 0;
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
worker.RunWorkerAsync();
#endregion
// worker_DoWork();
//ComputeCommission();
}
This is worker_DoWork code from worker.DoWork += new DoWorkEventHandler(worker_DoWork)
void worker_DoWork(object sender, DoWorkEventArgs e)
{
try
{
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_elapsed);
timer.Start();
Invoke(new MyDelegate(ShowLabel), "Loading...");
BACS.DateFrom = this.dtFrom.Value.ToShortDateString(); //this.dtFrom.Text;
BACS.DateTo = this.dtTo.Value.ToShortDateString(); //this.dtTo.Text;
BACS.BrokerAgent = BrokerXML;
BACS.Payor = PayorXML;
DS = BACS.GET_SP_BACS_ComputeCommission();
ReadData(DS, this.dgvCommision);
CheckGrid();
Thread.Sleep(1);
timer.Stop();
}
catch
{ }
}
And this is how I load my sp command from DS = BACS.GET_SP_BACS_ComputeCommission(); GET_SP_BACS_ComputeCommission is this
public DataSet GET_SP_BACS_ComputeCommission()
{
SqlParameter[] sqlParam = new SqlParameter[4];
sqlParam[0] = new SqlParameter("#DATEFROM", DateFrom);
sqlParam[1] = new SqlParameter("#DATETO", DateTo);
sqlParam[2] = new SqlParameter("#BROKERAGENT", BrokerAgent);
sqlParam[3] = new SqlParameter("#PAYOR",Payor);
DataSet ds = new DataSet();
if (this.InitDataLayerObject() == true)
{
ds = this.ExecuteQuery("dbo.[SP_BACS_COMMISSION_COMPUTATION]", sqlParam);
}
return ds;
}
Is there any solution in this? I've tried setting up my Connection Timeout=0 I even changed it to Connection Timeout=2500 Still it didn't worked.

Related

C# WPF Dispatcher Timer Tick in Separate Thread

So I have a basic WPF application, that OnStartup creates a DispatcherTimer and has a tick method that runs a basic SQL query to check the status of some arbitrary table.
It is a variable query in terms of how long it takes to execute.
If I am in the main application window, when the background DispatcherTimer runs (DispatcherTimer code being within the App.xaml, not the MainWindow.xaml), the window hangs while the query runs, and as the query runs every 5 seconds, the GUI is unresponsive.
It seems a new thread is the way to go, but I am lost on where to begin. I am relatively new to C#/WPF so it's all a learning curve at the moment. How would I go about invoking my dispatcherTimer_Tickwithin a new thread, to avoid this problem?
DispatcherTimer dispatcherTimer;
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
MainWindow = new MainWindow();
MainWindow.Closing += MainWindow_Closing;
_notifyIcon = new System.Windows.Forms.NotifyIcon();
_notifyIcon.DoubleClick += (s, args) => ShowMainWindow();
_notifyIcon.Icon = BackgroundApplication.Properties.Resources.GTL;
_notifyIcon.Visible = true;
CreateContextMenu();
dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 5);
dispatcherTimer.Start();
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
// Console.WriteLine("Tick");
SqlConnection cnn;
connectionString = #"SOME_DATA_SOURCE";
cnn = new SqlConnection(connectionString);
cnn.Open();
// MessageBox.Show("Connection Open !");
// cnn.Close();
SqlCommand command;
SqlDataReader dataReader;
String sql = "";
Int16 output = 0;
sql = "SOME SQL STATEMENT";
command = new SqlCommand(sql, cnn);
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
output = Int16.Parse(dataReader[""].ToString());
}
if(output > 0)
{
_notifyIcon.Icon = BackgroundApplication.Properties.Resources.RTL;
}
_notifyIcon.Text = "Current Issues: " + output;
}
Make the Tick handler async and await the long-running call:
private async void dispatcherTimer_Tick(object sender, EventArgs e)
{
await Task.Run(() =>
{
// make query here
});
// update the UI outside the Task
_notifyIcon.Text = "Current Issues: " + output;
}
Even better would be to directly call async methods, like
private async void dispatcherTimer_Tick(object sender, EventArgs e)
{
...
dataReader = await command.ExecuteReaderAsync();
...
}

Background worker not starting

I've implemented a background worker onLoad of my window. The code in the Progress_Load is reached but after that the DoWork function is not called. The function excel.Read() reads a quite big excel tabel into a list, this takes about 1.5 min and that's why i want to do it a-syn.
public List<Part> partList = new List<Part>() { };
//boolean that will be set when the backgroundworker is done
public bool listRead = false;
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
_Excel excel = new _Excel();
partList = excel.Read();
backgroundWorker1.ReportProgress(100);
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Message m;
if (e.Cancelled == true)
{
m = new Message("The operation has been canceld!", "Canceled");
this.Close();
}
else if (e.Error != null)
{
Error er = new Error("Error: " + e.Error.Message, "Error!");
this.Close();
}
else
{
listRead = true;
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
//Change the value of the ProgressBar to the BackgroundWorker progress.
progressBar1.Value = e.ProgressPercentage;
//Set the text.
this.Text = e.ProgressPercentage.ToString();
}
private void Progress_Load(object sender, EventArgs e)
{
if (backgroundWorker1 == null)
{
backgroundWorker1 = new BackgroundWorker();
backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
}
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true;
backgroundWorker1.RunWorkerAsync();
}
Probably it's not null when loading the form. You may have added the BackgroundWorker via the designer. If so it's never null, you can hook up the event handlers also from its Properties/Events.
Try this
private void Progress_Load(object sender, EventArgs e)
{
if (backgroundWorker1 == null)
{
backgroundWorker1 = new BackgroundWorker();
}
backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true;
backgroundWorker1.RunWorkerAsync();
}
In WPF Dispatcher.BeginInvoke(DispatcherPriority.Background, workAction); is a another option because report progress is not much useful in your scenario. Here example for Dispatcher and Background worker comparison.

Awesomium freezes / not responding

I have a traffic exchange website and I want to convert it into an windows application using C# winform with Awesomium 1.7.5.
The basic setup is ready but there is a problem with Awesomium.
After visiting a few websites slows down and the freezes entirely ( Not Responding ).
public Form1()
{
InitializeComponent();
Text = "Traffic Exchange";
WindowState = FormWindowState.Maximized;
timer1 = new System.Windows.Forms.Timer();
timer1.Tick += new EventHandler(timer1_Tick);
int user_id = Properties.Settings.Default.user_id;
string user_id_s = user_id.ToString();
toolStripLabel2.Text = user_id_s;
if (Properties.Settings.Default.user_id == 0)
{
toolStripLabel3.Visible = true;
toolStripButton3.Visible = false;
}
else
{
toolStripButton3.Visible = true;
toolStripLabel3.Visible = false;
}
}
private void toolStripButton3_Click_1(object sender, EventArgs e)
{
// starting the traffic traffic exchange
LoadUrl();
StartTimer();
}
private void LoadUrl()
{
try
{
string MyConnection2 = "*******";
string Query = "select * from ****** where status = 1 AND credits > 5 ORDER BY rand() LIMIT 1";
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);
MyConn2.Open();
using (MySqlDataReader DR = MyCommand2.ExecuteReader())
{
while (DR.Read())
{
string WebURL = Convert.ToString(DR.GetValue(*));
string WebSurfSec = Convert.ToString(DR.GetValue(*));
int result = Convert.ToInt32(WebSurfSec);
int sec_to_mil = result * 1000;
toolStripLabel5.Text = WebSurfSec;
//toolStripStatusLabel2.Text = result.ToString();
//toolStripStatusLabel3.Text = sec_to_mil.ToString();
webControl3.Source = new Uri(WebURL);
toolStripTextBox1.Text = WebURL;
toolStripLabel6.Text = toolStripTextBox1.Text;
timer1.Interval = sec_to_mil; // in miliseconds
}
}
MyConn2.Close();
// WebCore.ReleaseMemory();
// webControl3.Update();
// Thread.Sleep(500);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
LoadUrl();
}
private void StartTimer()
{
timer1.Start();
}
So LoadUrl() it's a loop. When the app is started loads in the traffic exchange website, a little bit slow but it works and you can go form a page to another without freezing but when the exchange is in action ( LoadUrl() ) after 5 minutes the app is dead.
I've been searching for a solution all day and ended up with nothing, couldn't find a solution the problem.
The timer should not be recreated each time you loop. What is happening is that you are creating multiple event handlers each time you loop. Creating the handler once in the constructor and starting the timer in the button click routine is the right way.
You can change the interval inside the loop, but avoid adding another Start() method call there.

How to use ProgressBar Control with DataGridView

I want to use a ProgressBar control in C# when my DataGridView is loading data, but when I run my program I get an error:
Cross-thread operation not valid: Control 'dataGridView1' accessed from a thread other than the thread it was created on.
Code:
private readonly BackgroundWorker _bw = new BackgroundWorker();
public workerbloks()
{
InitializeComponent();
progressBar1.MarqueeAnimationSpeed = 30;
// set Visible false before you start long running task
progressBar1.Visible = false;
_bw.DoWork += show_worked_bloks;
_bw.RunWorkerCompleted += BW_RunWorkerCompleted;
}
private void button1_Click(object sender, EventArgs e)
{
progressBar1.Show();
_bw.RunWorkerAsync();
}
private void BW_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
progressBar1.Hide();
}
public void show_worked_bloks(object sender, DoWorkEventArgs doWorkEventArgs)
{
MYDBMS md = new MYDBMS();
DataTable dt = new DataTable();
clsWorkBloks clswb = new clsWorkBloks();
try
{
dt = md.ExecuteSelectSQL(clswb.show_all_worked_bloks());
dataGridView1.DataSource = dt;
}
catch
{
}
}
Execute the specified delegate asynchronously on the thread that the dataGridView1 underlying handle was created on.
dataGridView1.BeginInvoke((MethodInvoker)delegate
{
this.dataGridView1.DataSource = dt;
});
As the progressbar is just marquee display. Simply bring it to front before running background worker.
progressBar1.BringToFront();
progressBar1.Show();
_bw.RunWorkerAsync();

BackgroundWorker WPF difficulties with Progress Bar

I am developing a WPF, C# application and I have to read a very big CSV file and write to a database. This process takes a long time so I want to at least show a progress bar that grows in size as it nears completition.
Now, I have the following code at the top:
private readonly BackgroundWorker worker = new BackgroundWorker();
Then inside the loop I have this:
worker.WorkerReportsProgress = true;
worker.ReportProgress((100 * i) / 10000);
and I have a private sub like this:
private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
prgBar.Value = Math.Min(e.ProgressPercentage, 100);
}
Yet I don't see the progress bar updating or anything happening, program still hangs. Am I doing something wrong?
UPDATE: Tried the MSDN guide here http://msdn.microsoft.com/en-us/library/cc221403%28v=vs.95%29.aspx and I somehow failed to get it working with that example. I adjusted the looping part of course. Heh. It still stays idle and nothing updates. Heck, all I want to do is get a small counter that increases every time a line is read and added.
UPDATED CODE:
private BackgroundWorker bw = new BackgroundWorker();
public Process()
{
bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
// Perform a time consuming operation and report progress.
int d = 0;
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
// Set filter for file extension and default file extension
dlg.DefaultExt = ".csv";
dlg.Filter = "CSV File (*.csv)|*.csv";
dlg.Title = "file";
// Display OpenFileDialog by calling ShowDialog method
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
// Open document
string filename = dlg.FileName;
List<String[]> fileContent = new List<string[]>();
using (FileStream reader = File.OpenRead(#filename)) // mind the encoding - UTF8
using (TextFieldParser parser = new TextFieldParser(reader))
{
using (SqlConnection conn = new SqlConnection(Classes.PublicVariables.Connection))
{
parser.Delimiters = new[] { "," };
parser.HasFieldsEnclosedInQuotes = true;
while (!parser.EndOfData)
{
string[] line = parser.ReadFields();
fileContent.Add(line);
SqlCommand comm = QUERYANDPARAMETERS
d += 1;
comm.ExecuteNonQuery();
worker.ReportProgress((d * 10));
}
}
}
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
lblCount.Content = "Complete";
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.lblCount.Content = (e.ProgressPercentage.ToString() + "%");
}
I am getting an excerption when the worker runs.
An exception of type 'System.NullReferenceException' occurred inSolution.exe but was not handled in user code
Additional information: Object reference not set to an instance of an object.
UPDATE3
Got it working! All I needed was the same code as above but this:
if (bw.IsBusy != true)
{
bw.RunWorkerAsync();
}
else
{
bw_DoWork(null, null);
}
In the event handler for the button press.
This will not compile as-is, but should get you started in the right direction:
private readonly BackgroundWorker worker
= new BackgroundWorker { WorkerReportsProgress = true };
public MainWindow()
{
InitializeComponent();
worker.DoWork += worker_DoWork;
worker.ProgressChanged += worker_ProgressChanged;
}
private void worker_DoWork(object sender, DoWorkEventArgs doWorkEventArgs)
{
// Do some long process, break it up into a loop so you can periodically
// call worker.ReportProgress()
worker.ReportProgress(i); // Pass back some meaningful value
}
private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
prgBar.Value = Math.Min(e.ProgressPercentage, 100);
}
is the varible i int? if it is, the value of (100 * i) / 10000 will return 0 while i < 100. and the param of ReportProgress method should be a precent value. you can change it to worker.ReportProgress(i);,try it.

Categories