Convert code from BGW to Async and Await for DataTabale/MySQLDataAdapter - c#

How can I abandon BGW and use async/wait tasking thing, I am willing to learn the technique as I am using VS 2013.
I looked at the examples online, but still I am unable to do it myself because the examples I came across were using existing functions in .NET which already return a task. I tried to separate the code inside BGW DoWork and create a task, but the compiler kept asking me about await and I could not call the task anyway, I noticed that the lines taking time are:
SQLDataAdapter = new MySqlDataAdapter(SQLcmd);
SQLDataAdapter.Fill(dt);
What I need is: inside a button click to start the task of reading from the database, and then relieve the Form from hanging (suppose I am not using BGW), and then read the result and displaying them in the datagridview.
// code starts here
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.IO;
namespace MySQLProject
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
string stdNo = File.ReadAllText("stdNo.txt").Replace(Environment.NewLine, ",");
const string cs = #"what ever";
MySqlConnection conn = new MySqlConnection(cs);
MySqlDataAdapter SQLDataAdapter = new MySqlDataAdapter(); ;
DataSet ds = new DataSet();
conn.Open();
this.InvokeEx(x => x.textBox1.AppendText(string.Format("MySQL version : {0};", conn.ServerVersion)));
DataTable dt = new DataTable("StudentNamesAndNumbers");
dt.Columns.Add("Student Name", typeof(string));
dt.Columns.Add("Student ID", typeof(string));
dt.Columns.Add("First", typeof(float));
dt.Columns.Add("Second", typeof(float));
dt.Columns.Add("Section", typeof(string));
ds.Tables.Add(dt);
try
{
MySqlCommand SQLcmd = new MySqlCommand();
SQLcmd = conn.CreateCommand();
SQLcmd.CommandText = String.Format(#"Select u.firstname as 'Student Name', u.username as 'Student ID'"
+ ",( select score from gradebook_result g , gradebook_evaluation e "
+ "where g.user_id = u.user_id "
+ "and name = 'First' "
+ "and g.evaluation_id = e.id "
+ "and e.course_code = c.course_code) as 'First' "
+ ",( select score from gradebook_result g , gradebook_evaluation e "
+ "where g.user_id = u.user_id "
+ "and name = 'Second' "
+ "and g.evaluation_id = e.id "
+ "and e.course_code = c.course_code) as 'Second' "
+ ", c.course_code as 'Section'"
+ "from user u, course_rel_user c "
+ "where "
+ "u.username in ({0}) "
+ "and u.username REGEXP '[0-9]+' "
+ "and c.course_code like 'IT102CPLUS%' "
+ "and u.user_id = c.user_id ;", stdNo);
this.InvokeEx(x => x.textBox1.AppendText(SQLcmd.CommandText));
SQLDataAdapter = new MySqlDataAdapter(SQLcmd);
SQLDataAdapter.Fill(dt);
dt.DefaultView.Sort = "Section ASC, Student Name ASC";
this.InvokeEx(x => x.dataGridView1.Columns.Clear());
this.InvokeEx(x => x.dataGridView1.DataSource = ds.Tables["StudentNamesAndNumbers"]);
this.InvokeEx(x => x.dataGridView1.AutoResizeColumns());
this.InvokeEx(x => x.label1.Text = dt.Rows.Count.ToString() + " Students");
// =======================================================
var lines = new List<string>();
string[] columnNames = dt.Columns.Cast<DataColumn>().
Select(column => column.ColumnName).
ToArray();
var header = string.Join(",", columnNames);
lines.Add(header);
var valueLines = dt.AsEnumerable().Select(row => string.Join(",", row.ItemArray));
lines.AddRange(valueLines);
File.WriteAllLines("Export.csv", lines, Encoding.UTF8);
}
catch (MySqlException ex)
{
this.InvokeEx(x => x.textBox1.AppendText(string.Format("Error: {0}\n\n", ex.ToString())));
}
finally
{
if (conn != null)
{
conn.Close();
}
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
button1.Enabled = true;
}
}
}

I have a series on my blog that shows how BackgroundWorker compares to Task.Run.
In general, you should not be using either of these approaches for I/O-bound operations. However, there are some older APIs that have not been upgraded to expose TAP methods. I believe the "data adapter" and "data table" APIs are considered too old to be upgraded, hence there's no "FillAsync" you could use.
So - assuming you want to keep the "data table" approach - you can just use Task.Run as a replacement for BackgroundWorker directly. Note that IProgress<T> is a more modern way of doing any kind of cross-thread invoking for progress updates:
private async void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
var progress = new Progress<string>(update => textBox1.AppendText(update));
var ds = await Task.Run(() => BackgroundWork(progress));
dataGridView1.Columns.Clear();
dataGridView1.DataSource = ds.Tables["StudentNamesAndNumbers"];
dataGridView1.AutoResizeColumns();
label1.Text = dataGridView1.Rows.Count.ToString() + " Students";
button1.Enabled = true;
}
private DataSet BackgroundWork(IProgress<string> progress)
{
string stdNo = File.ReadAllText("stdNo.txt").Replace(Environment.NewLine, ",");
const string cs = #"what ever";
MySqlConnection conn = new MySqlConnection(cs);
MySqlDataAdapter SQLDataAdapter = new MySqlDataAdapter(); ;
DataSet ds = new DataSet();
conn.Open();
if (progress != null)
progress.Report(string.Format("MySQL version : {0};", conn.ServerVersion));
DataTable dt = new DataTable("StudentNamesAndNumbers");
dt.Columns.Add("Student Name", typeof(string));
dt.Columns.Add("Student ID", typeof(string));
dt.Columns.Add("First", typeof(float));
dt.Columns.Add("Second", typeof(float));
dt.Columns.Add("Section", typeof(string));
ds.Tables.Add(dt);
try
{
MySqlCommand SQLcmd = new MySqlCommand();
SQLcmd = conn.CreateCommand();
SQLcmd.CommandText = String.Format(#"Select u.firstname as 'Student Name', u.username as 'Student ID'"
+ ",( select score from gradebook_result g , gradebook_evaluation e "
+ "where g.user_id = u.user_id "
+ "and name = 'First' "
+ "and g.evaluation_id = e.id "
+ "and e.course_code = c.course_code) as 'First' "
+ ",( select score from gradebook_result g , gradebook_evaluation e "
+ "where g.user_id = u.user_id "
+ "and name = 'Second' "
+ "and g.evaluation_id = e.id "
+ "and e.course_code = c.course_code) as 'Second' "
+ ", c.course_code as 'Section'"
+ "from user u, course_rel_user c "
+ "where "
+ "u.username in ({0}) "
+ "and u.username REGEXP '[0-9]+' "
+ "and c.course_code like 'IT102CPLUS%' "
+ "and u.user_id = c.user_id ;", stdNo);
if (progress != null)
progress.Report(SQLcmd.CommandText);
SQLDataAdapter = new MySqlDataAdapter(SQLcmd);
SQLDataAdapter.Fill(dt);
dt.DefaultView.Sort = "Section ASC, Student Name ASC";
var lines = new List<string>();
string[] columnNames = dt.Columns.Cast<DataColumn>().
Select(column => column.ColumnName).
ToArray();
var header = string.Join(",", columnNames);
lines.Add(header);
var valueLines = dt.AsEnumerable().Select(row => string.Join(",", row.ItemArray));
lines.AddRange(valueLines);
File.WriteAllLines("Export.csv", lines, Encoding.UTF8);
return ds;
}
catch (MySqlException ex)
{
if (progress != null)
progress.Report(string.Format("Error: {0}\n\n", ex.ToString()));
}
finally
{
if (conn != null)
{
conn.Close();
}
}
}

You should mark the method as async and await async method when you can.
If there is no async method and you want to run the synchronous method on another thread, await on Task.Run.
private async void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
try
{
//Use an async method when there is one available
string stdNo;
using (var reader = File.OpenText("Words.txt"))
{
stdNo = await reader.ReadToEndAsync();
}
stdNo = stdNo.Replace(Environment.NewLine, ",");
const string cs = #"what ever";
MySqlConnection conn = new MySqlConnection(cs);
MySqlDataAdapter SQLDataAdapter = new MySqlDataAdapter(); ;
DataSet ds = new DataSet();
//Use Task.Run to call a long running code on another thread
//If available you should use await conn.OpenAsync();
await Task.Run(() => conn.Open());
//You don't need invoke, after an await you are back to the synchronization context
textBox1.AppendText(string.Format("MySQL version : {0};", conn.ServerVersion));
DataTable dt = new DataTable("StudentNamesAndNumbers");
dt.Columns.Add("Student Name", typeof(string));
dt.Columns.Add("Student ID", typeof(string));
dt.Columns.Add("First", typeof(float));
dt.Columns.Add("Second", typeof(float));
dt.Columns.Add("Section", typeof(string));
ds.Tables.Add(dt);
//...
}
finally
{
button1.Enabled = true;
}
}

Related

OleDb Update requires Insert Command?

I try to updata a single row, chosen by it ID. But what I got at best is an additional row instead of an updated one.
I made several attempts. Now I got a System.InvalidOperationException claiming that a valid InsertCommand is necessary for an update, if a DataRow listing will get a new row.
To me it is the same again: Why insert? I want to update.
Can anybody give me a hint?
This is my related code:
string selectQuery = $"SELECT * FROM Records";
string updateQuery = $"UPDATE Records SET AnyContent = #AnyContent WHERE [ID] = #ID";
OleDbDataAdapter adapter = null;
OleDbCommand cmd = null;
try
{
adapter = new OleDbDataAdapter(selectQuery, ConnectionString);
cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = updateQuery;
cmd.Parameters.AddWithValue ("#AnyContent", "066066");
cmd.Parameters.AddWithValue("#ID", 2);
try
{
adapter.UpdateCommand = cmd;
nbRowsChanged = adapter.Update(content);
}
finally
{
adapter?.Close();
cmd?.Close();
}
}
catch (OleDbException e)
{
logText += "...Database Exception:\n\n" + e.Message + "\n\n";
isSuccess = false;
}
if (0 < nbRowsChanged)
{
logText += ".... Success: Updated <" + nbRowsChanged.ToString() + "> rows.\n";
isSuccess = true;
}
<<< Update >>>
Originally I tried it with an OleDbCommandBuilder before. But CommandBuilder created an update command, which seems to me like an insert command. This is why I tried it without CommandBuilder above. But inserting seems to follow me.
This is my old code, which is closer to where I want to get as it uses a DataTable instead of parameters:
string selectQuery = $"SELECT * FROM Records WHERE [ID] = ?";
OleDbConnection con = null;
OleDbDataAdapter adapter = null;
OleDbCommandBuilder builder = null;
try
{
adapter = new OleDbDataAdapter();
con = new OleDbConnection(ConnectionString);
adapter.SelectCommand = new OleDbCommand(selectQuery, con);
builder = new OleDbCommandBuilder(adapter);
try
{
con.Open();
nbRowsChanged = adapter.Update(content);
logText += "....InsertCommand: " + builder.GetInsertCommand().CommandText + "\n"; // Just to debug
logText += "....UpdateCommand: " + builder.GetUpdateCommand().CommandText + "\n"; // Just to debug
}
finally
{
con?.Close();
adapter?.Dispose();
}
}
catch (OleDbException e)
{
logText += "...Database Exception:\n\n" + e.Message + "\n\n";
isSuccess = false;
}
if (0 < nbRowsChanged)
{
logText += ".... Success: Updated <" + nbRowsChanged.ToString() + "> rows.\n";
isSuccess = true;
}
logText += tmpText ;
logText += "...Database: Access disposed.\n";
return isSuccess;
And this is the related trace:
LogText:
...Database: Trying to update <1> number of rows in table <Records>
....InsertCommand: INSERT INTO Records (AnyContent) VALUES (?)
....UpdateCommand: UPDATE Records SET AnyContent = ? WHERE ((ID = ?) AND ((? = 1 AND AnyContent IS NULL) OR (AnyContent = ?)))
.... Success: Updated <1> rows.
...Database: Access disposed.
NbRows Before: 5
NbRows After: 6

C# SqlBulkCopy miss a row

I'm using SqlBulkCopy to import data from excel and from another database into 2 different SQL tables.
Everything goes good until I managed that every time a row is missing in the target tables, either the source from the excel or from the other database.
Here is the code snippet for importing data from excel:
public void ImportDataFromExcel(string excelFilePath)
{
string ssqltable = "szip_IncomingAssetData";
string myexceldataquery = "SELECT * FROM ["+ GetExcelSheetNames(excelFilePath)+"]";
try
{
string sexcelconnectionstring = GetExcelConnectionString(excelFilePath);
Logger.Log("Excel Connection String: " + sexcelconnectionstring, false);
OpenDatabaseConnection(1, "ImportDataFromExcel");
OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn);
oledbconn.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
SqlBulkCopy bulkcopy = new SqlBulkCopy(hpamConnection)
{
DestinationTableName = ssqltable
};
SqlBulkCopyColumnMapping mapID = new SqlBulkCopyColumnMapping(System.Configuration.ConfigurationManager.AppSettings["szip_AssetID"], "szip_IncomingAssetID");
SqlBulkCopyColumnMapping mapName = new SqlBulkCopyColumnMapping( System.Configuration.ConfigurationManager.AppSettings["szip_IncomingAssetName"], "szip_IncomingAssetName");
SqlBulkCopyColumnMapping mapSerial = new SqlBulkCopyColumnMapping( System.Configuration.ConfigurationManager.AppSettings["szip_IncomingAssetSerial"], "szip_IncomingAssetSerial");
SqlBulkCopyColumnMapping mapRI = new SqlBulkCopyColumnMapping( System.Configuration.ConfigurationManager.AppSettings["szip_IncomingAssetRI"], "szip_IncomingAssetRI");
SqlBulkCopyColumnMapping mapModel = new SqlBulkCopyColumnMapping( System.Configuration.ConfigurationManager.AppSettings["szip_IncomingAssetModel"],"szip_IncomingAssetModel");
SqlBulkCopyColumnMapping mapVendor = new SqlBulkCopyColumnMapping(System.Configuration.ConfigurationManager.AppSettings["szip_IncomingAssetVendor"],"szip_IncomingAssetVendor");
SqlBulkCopyColumnMapping mapFRU = new SqlBulkCopyColumnMapping( System.Configuration.ConfigurationManager.AppSettings["szip_IncomingAssetFirstRU"], "szip_IncomingAssetFirstRU");
SqlBulkCopyColumnMapping mapLRU = new SqlBulkCopyColumnMapping( System.Configuration.ConfigurationManager.AppSettings["szip_IncomingAssetLastRU"], "szip_IncomingAssetLastRU");
SqlBulkCopyColumnMapping mapLocation = new SqlBulkCopyColumnMapping( System.Configuration.ConfigurationManager.AppSettings["szip_IncomingAssetLocation"], "szip_IncomingAssetLocation");
SqlBulkCopyColumnMapping mapRack = new SqlBulkCopyColumnMapping( System.Configuration.ConfigurationManager.AppSettings["szip_IncomingAssetRack"], "szip_IncomingAssetRack");
SqlBulkCopyColumnMapping mapStatus = new SqlBulkCopyColumnMapping( System.Configuration.ConfigurationManager.AppSettings["szip_IncomingAssetStatus"], "szip_IncomingAssetStatus");
SqlBulkCopyColumnMapping mapConfig = new SqlBulkCopyColumnMapping(System.Configuration.ConfigurationManager.AppSettings["szip_IncomingAssetConfig"], "szip_IncomingAssetConfig");
SqlBulkCopyColumnMapping mapIPDNS = new SqlBulkCopyColumnMapping( System.Configuration.ConfigurationManager.AppSettings["szip_IncomingAssetIP_DNSname"], "szip_IncomingAssetIP_DNSname");
SqlBulkCopyColumnMapping mapArea = new SqlBulkCopyColumnMapping( System.Configuration.ConfigurationManager.AppSettings["szip_IncomingAssetArea"], "szip_IncomingAssetArea");
SqlBulkCopyColumnMapping mapContact = new SqlBulkCopyColumnMapping( System.Configuration.ConfigurationManager.AppSettings["szip_IncomingAssetContact"], "szip_IncomingAssetContact");
SqlBulkCopyColumnMapping mapExtension = new SqlBulkCopyColumnMapping( System.Configuration.ConfigurationManager.AppSettings["szip_IncomingAssetExtension"], "szip_IncomingAssetExtension");
SqlBulkCopyColumnMapping mapHWType = new SqlBulkCopyColumnMapping( System.Configuration.ConfigurationManager.AppSettings["szip_IncomingAssetHardwareType"], "szip_IncomingAssetHardwareType");
SqlBulkCopyColumnMapping mapConnections = new SqlBulkCopyColumnMapping( System.Configuration.ConfigurationManager.AppSettings["szip_IncomingAssetCurrentConnections"], "szip_IncomingAssetCurrentConnections");
SqlBulkCopyColumnMapping mapMaxConnections = new SqlBulkCopyColumnMapping( System.Configuration.ConfigurationManager.AppSettings["szip_IncomingAssetMaxConnections"], "szip_IncomingAssetMaxConnections");
bulkcopy.ColumnMappings.Add(mapID);
bulkcopy.ColumnMappings.Add(mapName);
bulkcopy.ColumnMappings.Add(mapSerial);
bulkcopy.ColumnMappings.Add(mapRI);
bulkcopy.ColumnMappings.Add(mapModel);
bulkcopy.ColumnMappings.Add(mapVendor);
bulkcopy.ColumnMappings.Add(mapFRU);
bulkcopy.ColumnMappings.Add(mapLRU);
bulkcopy.ColumnMappings.Add(mapLocation);
bulkcopy.ColumnMappings.Add(mapRack);
bulkcopy.ColumnMappings.Add(mapStatus);
bulkcopy.ColumnMappings.Add(mapConfig);
bulkcopy.ColumnMappings.Add(mapIPDNS);
bulkcopy.ColumnMappings.Add(mapArea);
bulkcopy.ColumnMappings.Add(mapContact);
bulkcopy.ColumnMappings.Add(mapExtension);
bulkcopy.ColumnMappings.Add(mapHWType);
bulkcopy.ColumnMappings.Add(mapConnections);
bulkcopy.ColumnMappings.Add(mapMaxConnections);
while (dr.Read())
{
bulkcopy.WriteToServer(dr);
}
dr.Close();
oledbconn.Close();
CloseDatabaseConnection(1, "ImportDataFromExcel");
Logger.Log("Data Imported from Excel to Database", false);
}
catch (Exception e)
{
Logger.Log("Cannot Read Excel File: " + e.Message.ToString(), true);
}
connection string is as follows:
private string GetExcelConnectionString(string excelfile)
{
Dictionary<string, string> props = new Dictionary<string, string>
{
["Provider"] = "Microsoft.ACE.OLEDB.12.0",
["Extended Properties"] = "'Excel 12.0 XML;HDR=YES'",
["Data Source"] = excelfile
};
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<string, string> prop in props)
{
sb.Append(prop.Key);
sb.Append('=');
sb.Append(prop.Value);
sb.Append(';');
}
return sb.ToString();
}
In the case of the import from other database into my application database:
public void ImportSmartZoneAssetData()
{
SqlConnection hpamConnection = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["hpamConnectionString"]);
SqlConnection smartZoneConnection = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["szConnectionString"]);
string sqlCommand = "select i.pa_deviceid as DeviceID, " +
"i.pa_displayname as DeviceName, " +
"j.PA_MATERIALIZEDSTRPATH as [Location], " +
"k.PA_CONTAINERTYPEID as ContainerTypeID, " +
"l.PA_CONTAINERTYPEDESCRIPTION as ContainerType, " +
"k.PA_DISPLAYNAME as ContainerName, " +
"i.PA_CONTAINERPOSITION as FirstRU, " +
"(select pa_assetvalue from PA_ASSETLIST where PA_PARENTID = i.PA_DEVICEID and PA_ASSETATTRIBUTEID = 24) as SerialNumber, " +
"(select pa_assetvalue from PA_ASSETLIST where PA_PARENTID = i.PA_DEVICEID and PA_ASSETATTRIBUTEID = 25) as BarCode " +
"from pa_device i " +
"left join PA_LOCATION j on i.pa_locationid = j.PA_LOCATIONID " +
"left join PA_CONTAINER k on i.PA_CONTAINERID = k.PA_CONTAINERID " +
"left join PA_CONTAINERTYPE l on k.PA_CONTAINERTYPEID = l.PA_CONTAINERTYPEID";
string ssqltable = "szip_SmartZoneAssetData";
SqlBulkCopy bulkcopy = new SqlBulkCopy(hpamConnection)
{
DestinationTableName = ssqltable
};
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand(sqlCommand, smartZoneConnection);
hpamConnection.Open();
smartZoneConnection.Open();
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
bulkcopy.WriteToServer(myReader);
}
Logger.Log("Imported Records from SmartZone: " + GetRowsCopied(bulkcopy), false);
myReader.Close();
hpamConnection.Close();
smartZoneConnection.Close();
Logger.Log("Data Imported from SmartZone to Database", false);
}
}
I want to know if there is something wrong in the code and the reason why I always loose one and only one record in both cases.
/**************************
Got rid of the "while (myReader.Read())" on both cases and now it works perfect. New code is:
myReader = myCommand.ExecuteReader();
try
{
bulkcopy.WriteToServer(myReader);
}
catch (Exception e)
{
Logger.Log("Cannot Import SmartZone Device Data: " + e.Message, true);
}
Thanks :-)
As suggested, the while (myReader.Read()) was advancing one register.
I got rid of the "while (myReader.Read())" on both cases and now it works perfect. New code is:
myReader = myCommand.ExecuteReader();
try
{
bulkcopy.WriteToServer(myReader);
}
catch (Exception e)
{
Logger.Log("Cannot Import SmartZone Device Data: " + e.Message, true);
}
Thanks :-)

How to make timer event start on button click in aspx website

i am working on an aspx website in which i am using a timer event.
i just want that timer should run when i click a specific button. now timer is running on page load. in Winforms we use timer.Tick() event to do it. but it is not supporting in website.
Can Anyone help me to sort this Out.
Thanks in Advance....
My Code is Here....
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.ComponentModel;
public partial class Expert : System.Web.UI.Page
{
public static BackgroundWorker worker = new BackgroundWorker();
protected void Page_Load(object sender, EventArgs e)
{
int id;
id = Int32.Parse(Request.QueryString["id"]);
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["LPSConnection"].ConnectionString.ToString());
con.Open();
SqlDataReader rd;
rd = new SqlCommand("Select * from ExpertChat where id=" + id, con).ExecuteReader();
rd.Read();
Image1.ImageUrl = rd["image1"].ToString();
Label8.Text = rd["image1"].ToString();
//Image3.ImageUrl = rd["image1"].ToString();
Label1.Text = rd["SName"].ToString();
Label2.Text = rd["Skills"].ToString();
Label5.Text = rd["rate"].ToString();
Label3.Text = rd["ReviewCount"].ToString();
Label4.Text = rd["Title"].ToString();
Label6.Text = rd["ReviewCount"].ToString();
Label7.Text = rd["Title"].ToString();
Label9.Text = rd["Qualification"].ToString();
Label10.Text = rd["MyServices"].ToString();
Label11.Text = rd["other"].ToString();
Label14.Text = rd["IsLoggedIn"].ToString();
int x = Int32.Parse(rd["IsLoggedIn"].ToString());
if (x == 1)
{
Image2.ImageUrl = "~/online.png";
}
else
{
Image2.ImageUrl = "~/offline.png";
}
rd.Close();
if (Session["User"] == "User")
{
SqlDataReader rd1 = new SqlCommand("Select funds from signup where email='" + Session["email"].ToString() + "'", con).ExecuteReader();
rd1.Read();
Label13.Text = rd1["funds"].ToString();
}
worker.DoWork += new DoWorkEventHandler(DoWork);
worker.WorkerReportsProgress = true;
worker.WorkerSupportsCancellation = true;
con.Close();
}
protected void Button2_Click(object sender, EventArgs e)
{
}
protected void SendButton_Click(object sender, EventArgs e)
{
string messageMask = "{0} # {1} : {2}";
string message = string.Format(messageMask, "yash", DateTime.Now.ToShortTimeString(), NewMessageTextBox.Text);
TextBox1.Text = TextBox1.Text + Environment.NewLine + message;
// Calling the DoWork Method Asynchronously
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myScript", "document.getElementById('" + NewMessageTextBox.ClientID + "').value = '';", true);
ScriptManager.RegisterStartupScript(this, this.GetType(), "TextBox1slide", "buttonClicked();", true);
if (worker.IsBusy != true)
{
worker.RunWorkerAsync(new string[] { message, Label3.Text });
}
}
private static void DoWork(object sender, DoWorkEventArgs e)
{
string[] args = e.Argument as string[];
string value = args[0];
string id = args[1];
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["LPSConnection"].ConnectionString.ToString());
con.Open();
SqlCommand cmd;
cmd = new SqlCommand("Update Chat set Data=#message,Updated1=1 where id=" + Int32.Parse(id), con);
cmd.Parameters.AddWithValue("#message", value);
cmd.ExecuteNonQuery();
con.Close();
}
protected void ChatTextTimer_Tick(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["LPSConnection"].ConnectionString.ToString());
con.Open();
//if (second1.Visible)
//{
// SqlDataReader rd7 = new SqlCommand("Select IsApproved from Chat where id=" + Int32.Parse(Label2.Text) + "'", con).ExecuteReader();
// rd7.Read();
// string str3 = rd7["IsApproved"].ToString();
// rd7.Close();
// if (str3 == "Approved")
// {
// second1.Visible = false;
// }
// else if (str3 == "Canceled")
// {
// second1.Visible = false;
// second3.Visible = true;
// }
//}
//else
//{
int x1 = 0;
SqlDataReader rd;
rd = new SqlCommand("Select UserInitial,Updated from Chat where id =" + Int32.Parse(Label3.Text), con).ExecuteReader();
rd.Read();
string str;
int i;
i = Int32.Parse(rd["Updated"].ToString());
if (i == 1)
{
str = rd["UserInitial"].ToString();
rd.Close();
x1 = x1 + 1;
TextBox1.Text = TextBox1.Text + Environment.NewLine + str;
SqlCommand
cmd = new SqlCommand("Update Chat set Updated=0 where id=" + Int32.Parse(Label3.Text), con);
cmd.ExecuteNonQuery();
}
else
{
rd.Close();
}
con.Close();
ScriptManager.RegisterStartupScript(this, this.GetType(), "TextBox1slide", "buttonClicked();", true);
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
if (Session["User"] != "User")
{
Response.Redirect("signin.aspx");
}
else
{
if (Int32.Parse(Label13.Text) < 20)
{
Response.Redirect("Payment.aspx");
}
else
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["LPSConnection"].ConnectionString.ToString());
con.Open();
SqlDataReader rd = new SqlCommand("Select Booked,email from ExpertChat where id=" + Request.QueryString["id"].ToString(), con).ExecuteReader();
rd.Read();
int x = Int32.Parse(rd["Booked"].ToString());
string str = rd["email"].ToString();
rd.Close();
if (x == 0)
{
//second1.Visible = true;
SqlDataReader mRead1, mRead3, mRead4;
mRead1 = new SqlCommand("insert into chat (ExpertName,UserName,rate,Data,Date,UserInitial) Values ('" + str + "','" + Session["SName"] + "','" + Label5.Text + "','Hello','" + DateTime.Now.ToShortDateString() + "','yash')", con).ExecuteReader();
mRead1.Close();
mRead3 = new SqlCommand("Update ExpertChat Set Booked=1 where SName='" + Label1.Text + "'", con).ExecuteReader();
mRead3.Close();
mRead4 = new SqlCommand("Select top 1 id from Chat where ExpertName='" + str + "' Order by id desc", con).ExecuteReader();
mRead4.Read();
int y = Int32.Parse(mRead4["id"].ToString());
mRead4.Close();
ScriptManager.RegisterStartupScript(this, this.GetType(), "TextBox1slide", "button1Clicked();", true);
ChatTextTimer.Enabled = true;
second3.Visible = false;
second1.Visible = false;
second2.Visible = false;
int id;
id = y;
Label3.Text = id.ToString();
SqlDataReader rd1 = new SqlCommand("Select ExpertName from Chat where id=" + y, con).ExecuteReader();
rd1.Read();
string str23 = rd1["ExpertName"].ToString();
rd1.Close();
SqlDataReader rd3;
rd3 = new SqlCommand("Select * from ExpertChat where email='" + str23 + "'", con).ExecuteReader();
rd3.Read();
string str2;
str2 = rd3["email"].ToString();
Label1.Text = rd3["rate"].ToString();
Image3.ImageUrl = rd3["image1"].ToString();
Label12.Text = rd3["rate"].ToString();
rd3.Close();
con.Close();
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "TextBox1slide", "buttonClicked();", true);
//second2.Visible = true;
}
}
}
}
}
i want to run it when ImageButton1_Click event Fired....
If you're using Visual Studio 2010 up (correct me if I have my versions wrong) you should have access to Intellisense. You can use this to see all of your available methods.
Timer.Start()
http://msdn.microsoft.com/en-us/library/system.timers.timer.start(v=vs.110).aspx

Sum the values of a WPF datagrid column without additional query?

I'm populating the following WPF datagrid:
Using the following method:
private void ButtonFilterWorkflowWhenClick(object sender, RoutedEventArgs e)
{
var db = new DatabaseHandle();
dataGridWorkflow.ItemsSource = db.DisplayHealthIndicator(DateTime.Now, DateTime.Now);
labelWorkflowLastLoaded.Content = "Last Loaded at " + DateTime.Now.ToString(CultureInfo.InvariantCulture) + " with " +
dataGridWorkflow.Items.Count.ToString(CultureInfo.InvariantCulture) + " total events.";
}
Which references the following class object:
public DataView DisplayHealthIndicator(DateTime startDate, DateTime endDate)
{
string queryString = "[marlin].[support_retrieve_workflow_history]";
using (SqlConnection connection = new SqlConnection(GetConnectionString()))
{
using (var cmd = new SqlCommand(queryString, connection))
{
connection.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("date_from", startDate.Date);
cmd.Parameters.AddWithValue("date_to", endDate.Date);
var reader = cmd.ExecuteReader();
var dt = new DataTable();
dt.Load(reader);
connection.Close();
return dt.DefaultView;
}
}
}
I'm trying to find a way that I can find the sum of the total column so I can add it to my label but having no success. I can do this with a second query but I'd like to avoid that wherever possible. How should I approach this problem?
You may have to enumerate the rows in your DataView, something like:
dataGridWorkflow.ItemsSource = db.DisplayHealthIndicator(DateTime.Now, DateTime.Now);
DataView dv = (DataView)dataGridWorkflow.ItemsSource;
DataRowCollection drc = dv.Table.Rows;
IEnumerator rowEnum = drc.GetEnumerator();
int sum = 0;
while (rowEnum.MoveNext())
{
sum += (int)((DataRow)rowEnum.Current)[3];//assuming the 'Total' column has index 3.
}
labelWorkflowLastLoaded.Content = "Last Loaded at " + DateTime.Now.ToString(CultureInfo.InvariantCulture) + " with " + sum.ToString(CultureInfo.InvariantCulture) + " total events.";
Edit: I changed it so that you should be able to just copy and paste into your code.

Is there a bug in .NET ColumnMappings class?

This works:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.OleDb;
public class MyClass
{
public static void Main()
{
OleDbConnection mySqlConnection =new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\data\nwind.Mdb");
OleDbCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText = "SELECT EmployeeID AS MappedID, FirstName, LastName " +
"FROM Employees AS Emp " +
"WHERE EmployeeID = 9";
OleDbDataAdapter mySqlDataAdapter = new OleDbDataAdapter();
mySqlDataAdapter.SelectCommand = mySqlCommand;
DataSet myDataSet = new DataSet();
mySqlConnection.Open();
mySqlDataAdapter.Fill(myDataSet, "Employees");
mySqlConnection.Close();
DataTableMapping myDataTableMapping = mySqlDataAdapter.TableMappings.Add("Employees", "dtEmployee");
myDataSet.Tables["Employees"].TableName = "dtEmployee";
Console.WriteLine("myDataTableMapping.DataSetTable = " + myDataTableMapping.DataSetTable);
Console.WriteLine("myDataTableMapping.SourceTable = " + myDataTableMapping.SourceTable);
myDataTableMapping.ColumnMappings.Add("EmployeeID", "MappedId");
DataTable myDataTable = myDataSet.Tables["dtEmployee"];
foreach (DataRow myDataRow in myDataTable.Rows)
{
Console.WriteLine("ID = " + myDataRow["MappedId"]);
Console.WriteLine("FirstName = " + myDataRow["FirstName"]);
Console.WriteLine("LastName = " + myDataRow["LastName"]);
}
Console.ReadLine();
}
}
Just change "MappedId" to something else like "NewMappedId":
myDataTableMapping.ColumnMappings.Add("EmployeeID", "NewMappedId");
Console.WriteLine("ID = " + myDataRow["NewMappedId"]);
to something else like "NewMappedId" and the program will crash at runtime saying NewMappedId doesn't belong to table dtEmployee. Is this a bug ?!
No bug here.
If you change the contents of a bound dataset, this error is normal since you no longer match the underlying schema you are bound to.

Categories

Resources