Show MySQL query data on LiveCharts 2 PieChart WPF? - c#

I am having trouble to show MySQL query data on LiveCharts 2 PieChart. The issue is the values does not appears on the chart. I already tried a lot of possible solutions but It still did not succeed.
My code:
public ObservableCollection<ISeries> InvestedMoney { get; set; } //to XAML binding
private ObservableCollection<PieChartModel> pieChartData = new ObservableCollection<PieChartModel>();
pieChartData = dbConnect.GetPieChartData();
InvestedMoney = new ObservableCollection<ISeries>
{
new PieSeries<PieChartModel>
{
Values = pieChartData,
Fill = new SolidColorPaint(SKColors.Red),
}
};
DataContext = this;
My dbConnect class:
public ObservableCollection<PieChartModel> GetPieChartData()
{
ObservableCollection<PieChartModel> pieChartData = new ObservableCollection<PieChartModel>();
if (Connect())
{
string query = "SELECT name, SUM(moneyInvested) AS moneyInvested FROM investments GROUP BY name;";
MySqlCommand cmd = new MySqlCommand(query, con);
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
pieChartData.Add(new PieChartModel
{
name = reader.GetString(0),
moneyAmount = reader.GetDouble(1),
});
}
Connect_Close();
}
return pieChartData;
}
And the PieChartModel:
public string name { get; set; }
public double moneyAmount { get; set; }
I would like to refresh the PieChart everytime when new record is added to the database.

Related

How to fetch Record in a faster manner from SQLDataReader In C#

we have a stored procedure , which results data as below.
testCol1 testCol2 testCol3 testCol4 testCol5
124 1234 4543 4532 5564
123 1235 4546 4537 5565
it has 190,000 records.
I am trying to fetch data in List<TestData> type and then pass it to third party.
below is the code:
public class TestData
{
public int testCol1 { get; set; }
public int testCol2 { get; set; }
public string testCol3 { get; set; }
public double? testCol4 { get; set; }
public int testCol5 { get; set; }
}
var inputs = new List<TestData>();
using (SqlConnection con = new SqlConnection(fitchConnectionString))
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = "dbo.ReadAll_ForTest";
cmd.CommandTimeout = 0;
con.Open();
using (SqlDataReader dr = new SqlDataReader(cmd.ExecuteReader()))
{
while (dr.Read())
{
inputs.Add(new TestData()
{
testCol1 = (int)dr["testCol1"];
testCol2 = (int)dr["testCol2"];
testCol3 =(string)dr["testCol3"];
testCol4 = (double)dr["testCol4"];
testCol5 = (int)dr["testCol5"];
});
}
}
}
//pass to third party
var output = thirdparty.Convert(inputs).ToArray();
its working fine , however is taking lots of time to fetch the data.
is there is a way we can fetch data in faster manner?
One way is to specify types explicitly, so that the framework doesn't have to figure out what you mean. Get the ordinals (indices) in advance, and extract the exact type from the column:
using (var dr = cmd.ExecuteReader())
{
var testCol1Idx = dr.GetOrdinal("testCol1");
var testCol2Idx = dr.GetOrdinal("testCol2");
var testCol3Idx = dr.GetOrdinal("testCol3");
var testCol4Idx = dr.GetOrdinal("testCol4");
var testCol5Idx = dr.GetOrdinal("testCol5");
while (dr.Read())
{
inputs.Add(new TestData()
{
testCol1 = dr.GetInt32(testCol1Idx);
testCol2 = dr.GetInt32(testCol2Idx);
testCol3 = dr.GetString(testCol3Idx);
testCol4 = dr.GetDouble(testCol4Idx);
testCol5 = dr.GetInt32(testCol5Idx);
});
}
}
Other than that, 100K+ are a lot of records. Do you really need all of them? Try to work with a subset of the data, or aggregate data before using them.

display more than one database query in .net MVC

I am creating my first project using asp.net MVC - I have successfully connected to the database and displayed the information on the index page. My question is how do I get more than one query result on the one index page
for e.g
SELECT student ID,first name,surname FROM STUDENT Notes WHERE student ID = 7
Do I need to create new controllers/models for each query or need to add to the current and if I add to the current how would I do it? Below is the code I currently have in my controller.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
//int sNumber = 1;
List<CustomerModel> customers = new List<CustomerModel>();
string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
string query = "SELECT title, `first name`, surname FROM `STUDENT REGISTER`";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Connection = con;
con.Open();
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(new CustomerModel
{
// CustomerId = Convert.ToInt32(sdr["Student Number"]),
Title = sdr["title"].ToString(),
Name = sdr["first name"].ToString(),
Surname = sdr["surname"].ToString()
});
}
}
con.Close();
}
}
return View(customers);
}
Create a view model with two result set for e.g. Student and Marks
public class Result
{
public Student Student { get; set; }
public Marks Marks { get; set; }
}
Load/Construct this Result view model in controller /service with appropriate data and pass this view model to view.
I hope this helps!
You have to create a new class with all the properties you want to display in your View.
Example:
public class StudentModel {
public int Id { get; set; }
public string Title { get; set; }
public string Name { get; set; }
public strign Surname { get; set; }
}
public class MarkModel {
public int Id { get; set; }
public int StudentId { get; set; }
public int SubjectId { get; set; }
public int Mark { get; set; }
}
public class ResultModel
{
public StudentModel Student { get; set; }
public List<MarkModel> Marks { get; set; }
}
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
//int sNumber = 1;
var model= new ResultModel{
Student = new StudentModel(),
Marks = new List<MarkModel>();
}
string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
string queryStudent = "SELECT id, title, `first name`, surname FROM `STUDENT` WHERE Id=1";
using (MySqlCommand cmd = new MySqlCommand(queryStudent))
{
cmd.Connection = con;
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
model.student.Id = Convert.ToInt32(sdr["id"]),
model.student.Title = sdr["title"].ToString(),
model.student.Name = sdr["first name"].ToString(),
model.student.Surname = sdr["surname"].ToString()
}
}
}
string queryMarks = "SELECT Id, `StudentId`, StudentId,Mark FROM `MARK` WHERE StudentId=1";
using (MySqlCommand cmd = new MySqlCommand(queryMarks))
{
cmd.Connection = con;
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
model.Marks.Add(new MarkModel
{
Id = Convert.ToInt32(sdr["Id"]),
StudentId = Convert.ToInt32(sdr["StudentId"]),
StudentId = Convert.ToInt32(sdr["StudentId"]),
Mark = Convert.ToInt32(sdr["Mark"]),
});
}
}
}
}
return View(model);
}
You should create a new ViewModel class with all the properties you want to display in your View. Then you model your View after it.
From the properties you provided so far, the class should look like this:
public class StudentViewModel {
public int Id { get; set; }
public string Title { get; set; }
public string Name { get; set; }
public strign Surname { get; set; }
}
Then you do the value x property assignment
string query = "SELECT title, `first name`, surname FROM `STUDENT REGISTER`";
List<StudentViewModel> model = new List<StudentViewModel>();
using (MySqlCommand cmd = new MySqlCommand(query)) {
cmd.Connection = con;
con.Open();
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
model.Add(new StudentViewModel
{
Id = Convert.ToInt32(sdr["StudentNumber"]),
Title = Convert.ToString(sdr["title"]),
Name = Convert.ToString(sdr["first name"]),
Surname = Convert.ToString(sdr["surname"])
});
}
}
con.Close();
}
return View(model);

MVC DataReader Timeout Error

I have this problem with error timeout, always when it suppose to get data from database it bounce error. I am trying to retrieve video from database with this code:
Repository.cs
public List<videoTble> Video()
{
var model = new List<videoTble>();
string ConStr = "Data Source="";Connect Timeout=60";
using (SqlConnection con = new SqlConnection(ConStr))
{
string str = "SELECT * FROM videoTbles";
con.Open();
SqlCommand cmd = new SqlCommand(str, con);
cmd.CommandTimeout = 60;
SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
var v = new videoTble();
v.Name = rd["Name"].ToString();
v.Data = (byte[])rd["Data"];
v.ContentType = rd["ContentType"].ToString();
v.ArtistName = rd["ArtistName"].ToString();
v.Expirydate = (DateTime)rd["Expirydate"];
model.Add(v);
}
con.Close();
}
return model;
}
Controller.cs
public ActionResult Download()
{
Repository res = new Repository();
ViewBag.Video = res.Video();
return View();
}
Model.cs
public partial class videoTble
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string ContentType { get; set; }
public byte[] Data { get; set; }
public string ArtistName { get; set; }
public DateTime Expirydate { get; set; }
}
The timeout Error I got, when i run application
It looks like you are storing your video as raw data in your database. I highly advise against this. Store the video files on your file system, and store the paths to the video files in your database.

Display Data to spesific column Grid control devexpress using oracle data reader

I have tried display data from spesific column ListView in C# and it was successfull. But I couldn't display it into spesific column in GridControl DevExpress.
This my code in ListView:
OracleCommand cmd = new OracleCommand();
OracleDataReader dr;
cmd.CommandText = #"SELECT * FROM PERMOHONANDETAIL WHERE PERMOHONANFK = '" + buka.txtID.Text + "'";
cmd.Connection = koneksi_manual.con;
dr = cmd.ExecuteReader();
while (dr.Read())
{
ListViewItem list = new ListViewItem(dr["PEKERJAAN"].ToString());
list.SubItems.Add(dr["KODEPEKERJAAN"].ToString());
list.SubItems.Add(dr["PEKERJAAN"].ToString());
list.SubItems.Add(dr["JOBFORM"].ToString());
list.SubItems.Add(dr["QTYORDER"].ToString());
list.SubItems.Add(dr["TARGETPERHARI"].ToString());
list.SubItems.Add(Convert.ToDateTime(dr["TANGGALSTART"]).ToString("dd/MM/yyyy"));
list.SubItems.Add(Convert.ToDateTime(dr["TANGGALEND"]).ToString("dd/MM/yyyy"));
list.SubItems.Add(dr["DURASIHARI"].ToString());
list.SubItems.Add(dr["NOTES"].ToString());
buka.listView1.Items.Add(list);
}
dr.Close();
buka.Focus();
buka.ShowDialog();
How can I do it into spesific column GridControl in DevExpress?
How can I solve this??
You can create a class for your rows and use the List<YourClass> as DataSource for your GridControl.
For example, you can create this class:
public class GridControlItem
{
public string KODEPEKERJAAN { get; set; }
public string PEKERJAAN { get; set; }
public string JOBFORM { get; set; }
public string QTYORDER { get; set; }
public string TARGETPERHARI { get; set; }
public string TANGGALSTART { get; set; }
public string TANGGALEND { get; set; }
public string DURASIHARI { get; set; }
public string NOTES { get; set; }
}
And use it in your GridControl as follows:
OracleCommand cmd = new OracleCommand();
OracleDataReader dr;
cmd.CommandText = #"SELECT * FROM PERMOHONANDETAIL WHERE PERMOHONANFK = '" + buka.txtID.Text + "'";
cmd.Connection = koneksi_manual.con;
dr = cmd.ExecuteReader();
var list = new List<GridControlItem>();
while (dr.Read())
{
var item = new GridControlItem();
item.KODEPEKERJAAN = dr["KODEPEKERJAAN"].ToString();
item.PEKERJAAN = dr["PEKERJAAN"].ToString();
item.JOBFORM = dr["JOBFORM"].ToString();
item.QTYORDER = dr["QTYORDER"].ToString();
item.TARGETPERHARI = dr["TARGETPERHARI"].ToString();
item.TANGGALSTART = Convert.ToDateTime(dr["TANGGALSTART"]).ToString("dd/MM/yyyy");
item.TANGGALEND = Convert.ToDateTime(dr["TANGGALEND"]).ToString("dd/MM/yyyy");
item.DURASIHARI = dr["DURASIHARI"].ToString();
item.NOTES = dr["NOTES"].ToString();
list.Add(item)
}
dr.Close();
gridControl1.DataSource = list;

How can I select items from my table in to a List<T>?

How can I get the results from my data reader into a List<String>?
Here is my code so far:
public List<string> Item_Getall()
{
List<string> data = new List<string>();
SqlCommand cmd = new SqlCommand("c_get_all_item",oo.conn);
cmd.CommandType = CommandType.StoredProcedure;
oo.conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
data.Add(rdr["item_name_id_pk"].ToString());
data.Add(rdr["item_name_arabic"].ToString());
data.Add(rdr["item_componant"].ToString());
data.Add(rdr["item_componant_arabic"].ToString());
data.Add(rdr["item_price"].ToString());
data.Add(rdr["item_image"].ToString());
data.Add(rdr["item_category_name_id_fk"].ToString());
}
oo.conn.Close();
return data;
}
You better use your custom type list instead of string and store your custom type object in list
List<YourCustomType> data = new List<YourCustomType>();
Custom type
public class YourCustom
{
public string ItemName {get; set;}
//Similarly all the properties.
}
Reading values from data Reader and adding in Custom Type List
while (rdr.Read())
{
data.Add(new YourCustom()
{
Id = rdr["item_name_id_pk"].ToString(),
Name = rdr["item_name_arabic"].ToString()
//Similarly all other properties could be set
}
}
I think you will want to create a custom class and return a list of this class:
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
}
Reading would go as:
var data = new List<Item>();
while (rdr.Read())
{
data.Add(new Item()
{
Id = int.Parse(rdr["item_name_id_pk"]),
Name = rdr["item_name_arabic"].ToString()
}
}
return data;
Also, look into the using() statement which will make your code more robust in the eye of exceptions during database calls.
Using a DataAdapter and a custom type:
SqlCommand cmd = new SqlCommand("c_get_all_item",oo.conn);
cmd.CommandType = CommandType.StoredProcedure;
oo.conn.Open();
var adapter = new SqlDataAdapter(cmd);
DataTable dt;
adapter.Fill(dt);
oo.Close()
//Convert DataTable to a list of YourType
List<YourType> data = dt.AsEnumerable().Select(s=>
new YourType {
item_name_id_pk = s.Field<FieldDataType>("item_name_id_pk"),
item_name_arabic = s.Field<FieldDataType>("item_name_arabic"),
...
})
.ToList();
Your custom type would be like;
public class YourType
{
//Replace the DataType with correct datatype to match with FieldDataType
public DataType item_name_id_pk {get; set;}
public DataType item_name_arabic {get; set;}
...
}

Categories