I am trying to create a chart in my angular application. for that I want to pass dataset as follows in my .Net Web API.
But in my code it pass data set as follows
[{"Column1":1,"_Month":"January","SumOfMonth":-14900.40,"NoOfOutlets":11},{"Column1":2,"_Month":"February","SumOfMonth":-17856.00,"NoOfOutlets":2},{"Column1":3,"_Month":"March","SumOfMonth":-5312.00,"NoOfOutlets":4},{"Column1":4,"_Month":"April","SumOfMonth":-22103.13,"NoOfOutlets":15},{"Column1":6,"_Month":"June","SumOfMonth":-16014.72,"NoOfOutlets":5},{"Column1":7,"_Month":"July","SumOfMonth":-63251.93,"NoOfOutlets":46}
now I want to convert my dataset to the above format to create the graph.
my controller
public class MonthSelloutController : ControllerBase
{
private readonly VantageContext _context;
public MonthSelloutController(VantageContext context)
{
_context = context;
}
//GET: api/AllSellOut
[HttpGet]
public ActionResult<string> Getset(string Year)
{
DataTable dt = new MonthSelloutMgt().Monthsellout(Year, _context);
string json = JsonConvert.SerializeObject(dt);
return json;
}
}
My BL
public DataTable Monthsellout(string Year, VantageContext _context)
{
DataTable dt = new DataTable();
try
{
string conn = _context.Database.GetDbConnection().ConnectionString;
using (SqlConnection con = new SqlConnection(conn))
{
con.Open();
SqlCommand cmd = new SqlCommand("D_MonthSellOut", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#Year", Year));
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
}
}
catch (Exception ex)
{
ex.ToString();
}
return dt;
}
what I can do to convert my dataset as I mentioned in the above image. Any help is much appreciated.
result of my stored procedure
Because you want to get a custom schema for your JSON string, you could try to write a class to carry your data from DataTable as below
public class ViewModel
{
public List<List<object>> SumOfMonth { get; set; } = new List<List<object>>();
public List<List<object>> NoOutlets { get; set; } = new List<List<object>>();
}
Then we can use foreach iterator data from DataTable and fill data in the ViewModel
[HttpGet]
public ActionResult<string> Getset(string Year)
{
DataTable dt = new MonthSelloutMgt().Monthsellout(Year, _context);
ViewModel result = new ViewModel();
foreach (DataRow item in dt.Rows)
{
result.SumOfMonth.Add(new List<object>(){
(decimal)item["SumOfMonth"],
item["_Month"].ToString()
});
}
foreach (DataRow item in dt.Rows)
{
result.NoOfOutlets.Add(new List<object>(){
(int)item["NoOfOutlets"],
item["_Month"].ToString()
});
} string json = JsonConvert.SerializeObject(result);
return json;
}
I would use Sqldatareader to read data result instead of DataTable becasue Sqldatareader migth provide higher performance then DataTable
Related
Trying to return value from GetStage_details() methods and bind it to ViewBag.Stage_details but getting error at var result.
Error msg is :
can't implicitly convert type oracle.ManagedDtaAccessclient.oracledatareader to System.Collection.generic.List<Models.Stage_Details."
Any idea how to resolve it show that correct value return from table and bind to ViewBag.Stage_details will be appreciated.
public class Stage_details
{
public int Stage_Cd { get; set; }
public string Stage_Desc { get; set; }
}
public ActionResult Index_shift()
{
ViewBag.Stage_details = new SelectList(GetStage_details(), "Stage_Cd", "Stage_Desc");
}
private List<Stage_details> GetStage_details()
{
List<Stage_details> Stage_detail = new List<Stage_details>();
OracleConnection conn = new
OracleConnection(ConfigurationManager.ConnectionStrings["Mycon"].ToString());
conn.Open();
string cmdText= "select a.stage_cd,a.stage_desc from Stage_Mst a";
OracleCommand command = new OracleCommand(cmdText,conn);
command.CommandType = CommandType.Text;
var result = command.ExecuteReader();
return result;
}
According to Microsoft documentation, You could read each element from reader and build Stage_detail object inside loop, like the following code :
private List<Stage_details> GetStage_details()
{
List<Stage_details> Stage_detail = new List<Stage_details>();
OracleConnection conn = new
OracleConnection(ConfigurationManager.ConnectionStrings["Mycon"].ToString());
conn.Open();
string cmdText = "select a.stage_cd,a.stage_desc from Stage_Mst a";
OracleCommand command = new OracleCommand(cmdText, conn)
{
CommandType = CommandType.Text
};
using (OracleDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Stage_detail.Add(new Stage_details { Stage_Cd = (int)reader["stage_cd"], Stage_Desc = reader["stage_desc"].ToString() });
}
}
return Stage_detail;
}
I hope you find this helpful.
I want to add all Id from customer table in combobox using class and this is my connection class connectionClass in which I made a function for selecting data from databse.
The second is my Customer form(this is customer form coding customerForm) in which i call a function which i made in connection class .
but it only showing the last id in customer form and i want all id in combobox
In the select() method you are returning a string,instead of that you need to populate
dataset and bind the data to combobox.
reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("customerid", typeof(string));
dt.Columns.Add("contactname", typeof(string));
dt.Load(reader);
regards
chandra
Instead of string return a List of strings as follows:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Fill_Combo();
}
public void Fill_Combo()
{
Connection2DB cst = new Connection2DB();
cmbBoxId.Items.AddRange(cst.Select().ToArray());
}
}
class Connection2DB
{
public List<string> Select()
{
var ids = new List<string>();
try
{
string sqlqry = "select ID from Customer";
SqlCommand cmds = new SqlCommand(sqlqry, _con);
SqlDataReader dr = cmds.ExecuteReader();
while (dr.Read())
{
ids.Add(dr["ID"].ToString());
}
}
catch (Exception ex)
{
// Handle exception here
}
return ids;
}
}
this function only returning only ID from Customer table. I want to multiple data from Customer table using same method. Can you help me in this one??
Normally, this is not how this site works. First, you should ask a specific question, and show what you have done. Then we may help you.
Here I will try to give you two general solutions for working with a database.
Solution 1:
Let`s say you want to display everything retrieved from the database to your windows form.
First, create the DataGridView object let's call it dataGridView1. You can create it using the designer as any other control. then use the codes below:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
dataGridView1.DataSource = GetData();
}
public DataTable GetData()
{
string ConStr = " your connection string "; // Write here your connection string
string query = #"SELECT * FROM Customer"; // or write your specific query
DataTable dataTable = new DataTable();
SqlConnection conn = new SqlConnection(ConStr);
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da = null;
try
{
conn.Open();
// create data adapter
da = new SqlDataAdapter(cmd);
// this will query your database and return the result to your datatable
da.Fill(dataTable);
}
catch (Exception ex)
{
MessageBox.Show($"Cannot read database: {ex.Message}");
}
finally
{
conn.Close();
if (da != null)
da.Dispose();
}
return dataTable;
}
public void FillDataGrid()
{
Connection2DB cst = new Connection2DB();
dataGridView1.DataSource = cst.GetData();
}
}
Solution 2:
Let's say from your database table you want to extract 3 columns: ID (INT), Name (VARCHAR(100)) and Value (VARCHAR(MAX).
First, create a class:
public class Customer
{
public int ID { get; set; }
public string Nmae { get; set; }
public string Value { get; set; }
}
Create the function which returns the list of Customers:
public List<Customer> GetCustomers()
{
var customers = new List<Customer>();
try
{
string sqlqry = "SELECT ID, Name, Value FROM Customer";
SqlCommand cmds = new SqlCommand(sqlqry, _con); // here _con is your predefined SqlConnection object
SqlDataReader dr = cmds.ExecuteReader();
while (dr.Read())
{
customers.Add(new Customer
{
ID = (int)dr["ID"],
Nmae = dr["Name"].ToString(),
Value = dr["Value"].ToString(),
});
}
}
catch (Exception ex)
{
// Handle exception here
}
return customers;
}
Then you can use this data as you want. For example, to fill your ComboBox with IDs you can use this:
public void Fill_Combo()
{
var customers = GetCustomers();
var ids = customers.Select(x => x.ID.ToString());
cmbBoxId.Items.AddRange(ids.ToArray());
}
i was creating a simple rest service in asp.net mvc.my problem is my value is not passing to respository class. i think i miss something can anyone help..?
here is my controller
static LoginRespository repository = new LoginRespository();
public string AddEmployees(Login Emp)
{
//calling EmpRepository Class Method and storing Repsonse
var response = repository.AddEmployees(Emp);
return response;
}
and my respositoryclass like this
public string AddEmployees(Login Emp)
{
SqlCommand com;
SqlConnection con = new SqlConnection(#"Data Source=DOTNET;Initial Catalog=edin;Integrated Security=True;Pooling=False");
try
{
com = new SqlCommand("select * from data where name='" + Emp.username + "'", con);
con.Open();
SqlDataReader dr = com.ExecuteReader();
if (dr.HasRows)
{
return "success";
}
else
{
return "error";
}
con.Close();
}
catch (Exception aa)
{
return aa.ToString();
}
}
and my modelis
public string username { get; set; }
public string password { get; set; }
Pay attention to:
In method AddEmployees instead of passing collection of Employees you pass single employee and suggest change to AddEmployee
Instead of Insert you add Employee with Select
If you receive null Employee in AddEmployee that means that you send null Employee in your controller.
If you calling the AddEmployees on button click event. Try this:
Emp employeeRec = new Emp();
employeeRec.username = txtName.text;
employeeRec.password = txtPassword.text;
AddEmployees(employeeRec);
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
I am writting a programme, which imports data from data base. I want to place all these tables in my own object propeties. All these DataTable properties are filled until Base examBase = Base() is beeing executed, but after this line, the exam.Base.Tests doesnt's exist anymore. What causes the problem?
class Base
{
MySqlConnection myConnection;
MySqlDataAdapter testsDataAdapter;
DataTable testsDataTable;
MySqlDataAdapter questionsDataAdapter;
DataTable questionsDataTable;
MySqlDataAdapter answersDataAdapter;
DataTable answersDataTable;
public Base()
{
string myConnectionString = "Database=Exams;Data Source=localhost;User Id=root;Password=";
myConnection = new MySqlConnection(myConnectionString);
myConnection.Open();
GetTests();
GetQuestions();
GetAnswers();
}
private void GetTests()
{
string testQuery = "SELECT * FROM tests";
testsDataAdapter = new MySqlDataAdapter(testQuery, myConnection);
testsDataTable = new DataTable();
testsDataAdapter.Fill(testsDataTable);
testsDataTable.PrimaryKey = new DataColumn[] { testsDataTable.Columns["TestID"] };
this.Tests = testsDataTable;
}
private void GetQuestions()
{
string questionQuery = "SELECT * FROM questions";
questionsDataAdapter = new MySqlDataAdapter(questionQuery, myConnection);
questionsDataTable = new DataTable();
questionsDataAdapter.Fill(questionsDataTable);
this.Questions = questionsDataTable;
}
private void GetAnswers()
{
string answerQuery = "SELECT * FROM answers";
answersDataAdapter = new MySqlDataAdapter(answerQuery, myConnection);
answersDataTable = new DataTable();
answersDataAdapter.Fill(answersDataTable);
this.Answers = answersDataTable;
}
public DataTable Tests { get; set; }
public DataTable Questions { get; set; }
public DataTable Answers { get; set; }
}
and the exception is firstly seen in GetName() method:
class Test
{
Base examBase;
private List<Question> questions;
public Test(int testID)
{
examBase = new Base();
this.TestID = testID;
GetName();
GetDescription();
GetAuthor();
GetQuestions();
}
private void GetName()
{
this.Name = examBase.Tests.Rows.Find(this.TestID)["Name"].ToString();
}
edit
Ok, the object examBase.Tests exists, but there's something with whis Find() method. In my base, in the table "Tests" I have a primary key (column TestID), but I get the KeyMissing exception. Meybe I use this Find() incorrectly?
I think the "Name" field is null. Do a null check before converting to a string:
Change
this.Name = examBase.Tests.Rows.Find(this.TestID)["Name"].ToString();
To
if(examBase.Tests.Rows.Find(this.TestID)["Name"] != null)
{
this.Name = examBase.Tests.Rows.Find(this.TestID)["Name"].ToString();
}
Failing that
if(examBase.Tests.Rows.Find(this.TestID) != null)
{
this.Name = examBase.Tests.Rows.Find(this.TestID)["Name"].ToString();
}
I have created a database with 1 table "emp" and have some data in it. Now every time i start the app, i want a list to fetch the data from db and save it in list because i want to perform some calculations like tax and Gross-Salary on data at runtime for display only(don't want to save it in db ). I have tried many times but i am unable to understand how this can be done. This is my code:
Main Class:
static void Main(string[] args)
{
empDB empDB1 = new empDB();
List<emplyee> empLST1 = new List<emplyee>();
if (empLST1 == null)
{
empDB1.loadLST(out empLST1);
}
}
empDB Class:
class empDB
{
private string ConnectionString = #"server=localhost;DATABASE=hris;uid=root;Password=123456;";
internal void loadLST(out List<emplyee> loadedLST)
{
string query = "select name, grade from emp";
try
{
MySqlConnection con = new MySqlConnection(ConnectionString);
con.Open();
MySqlDataReader rdr = null;
MySqlCommand cmd = new MySqlCommand(query, con);
rdr = cmd.ExecuteReader();
while(rdr.Read())
{
List<employee> returnedLst = new List<employee>();
returnedLst.Add(rdr["name"].ToString(), rdr["grade"].ToString());
}
loadedLst = returnedLst;
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
I have no idea even if my approach is right or not. I have googled it a few times but i just started working in .net a few days ago so i don't understand how to do it.
Okay i tried this and it also dosn't work:
internal void GetDatabaseList()
{
List<employee> databases = new List<employee>();
MySqlConnection con = new MySqlConnection(ConnectionString);
{
con.Open();
DataTable tbl = con.GetSchema("Databases");
con.Close();
foreach (DataRow row in tbl.Rows)
{
databases.Add(row["hris"].ToString());
}
}
}
static void Main(string[] args)
{
empDB empDB1 = new empDB();
List<emplyee> empLST1 = new List<emplyee>();
**if (empLST1 == null)
{
empDB1.loadLST(out empLST1);
}**
}
this will always be false because you defined empLST1 as a new List, meaning its not null
try this
public class Employee
{
public string Name { get; set; }
public string Grade { get; set; }
}
static void Main(string[] args)
{
empDB empDB1 = new empDB();
List<Employee> empLST1 = new List<Employee>();
empDB1.loadLST(ref empLST1);
}
public class empDB
{
public void loadLst(ref List<Employee> loadedLST)
{
string query = "select name, grade from emp";
try
{
MySqlConnection con = new MySqlConnection(ConnectionString);
con.Open();
MySqlDataReader rdr = null;
MySqlCommand cmd = new MySqlCommand(query, con);
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Employee emp = new Employee();
emp.Name = rdr["name"].ToString();
emp.Grade = rdr["grade"].ToString();
loadedLST.Add(emp);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
Assuming, that that employee class looks like this:
class employee
{
public string Name { get; set; }
public string Grade { get; set; }
}
I'd rewrite loadLST like this:
internal List<employee> loadLST()
{
string query = "select name, grade from emp";
// we should dispose IDisposable implementations:
// connection, command and data reader
using (var con = new MySqlConnection(ConnectionString))
{
con.Open();
using (var cmd = new MySqlCommand(query, con))
using (var rdr = cmd.ExecuteReader())
{
// it is hard to maintain manual mapping
// between query results and objects;
// let's use helper like Automapper to make this easier
Mapper.CreateMap<IDataReader, employee>();
Mapper.AssertConfigurationIsValid();
return Mapper.Map<List<employee>>(rdr);
}
}
}
Improvements:
IDisposable implementations must be disposed explicitly (see this and this)
to avoid manual mapping code, which maps the result from data reader and object (employee instance in your case), the code uses Automapper package
exception handling and out parameter are thrown away. There's no need for exception handling and out parameter here, unless you're writing method like TryToDoSomething (and even in that case your method must return bool to indicate the state of operation, and catch only specific exceptions instead of Exception).
Also note, that your code doesn't match naming guidelines (e.g., employee should be Employee).