How to update data from child class variables using parent class function? - c#

i'm trying to practise my c# by doing a little exercise creating a basic ORM.
So i have 3 files, my Main program calling my Model:
public Form1()
{
InitializeComponent();
Pessoa mPessoa = new Pessoa();
mPessoa.First();
MessageBox.Show(mPessoa.nome);
}
My child model class:
class Pessoa:Model
{
public int id;
public string nome;
public string telefone;
public Pessoa()
{
Table = "Pessoa";
Conn = "Principal";
}
}
And my parent Model Class:
class Model:Conn
{
protected string Table;
protected string Conn;
public void First()
{
OpenConnection();
string query = "SELECT * from " + Table + " Where id = 1 limit 1";
DataTable oDT = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(query, connection);
da.Fill(oDT);
foreach (var column in oDT.Columns)
{
}
}
The question is: How can i update the child class variables (id, nome and telefone) based on the results from my parent class funcion?
As you can see, i've tried to use dynamic variable names using that foreach with the columns from the result, but i'm stuck because i dont know how to properly set the values.

Related

Get Variable string from Class where Class name matches with CheckedListBox item name

I have few classes in MyApp project under the folder "SQLQueries" as shown below. Each class has SQL query string constant variable named "QUERY".
namespace MyApp.SQLQueries
{
public class Product
{
private const string QUERY = "SELECT * FROM PRODUCT";
}
}
namespace MyApp.SQLQueries
{
public class Order
{
private const string QUERY = "SELECT * FROM ORDER";
}
}
namespace MyApp.SQLQueries
{
public class Customer
{
private const string QUERY = "SELECT * FROM CUSTOMER";
}
}
On my WinForm I've below code where I've CheckedListBox with collection of items with names "Product", "Order" and "Customer" which matches with the class names shown above. I want that when I click on button then I should be able to retrieve query string from the class variable "QUERY" (as shown above) where class name matches with checkedListBox1 item name? Is it anyway possible to do?
namespace MyApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection sqlCon = new SqlConnection(dbCnxStr))
{
sqlCon.Open();
foreach (var item in checkedListBox1.CheckedItems)
{
DataTable dt = new DataTable();
string sql = item.ToString(); // need to retrieve QUERY variable string from the class which matches with checkedListBox1 item name
using (SqlCommand sqlCmd = new SqlCommand(sql, sqlCon))
{
using (SqlDataReader sqlRd = sqlCmd.ExecuteReader())
{
if (sqlRd.HasRows)
{
dt.Load(sqlRd);
}
sqlRd.Close();
}
sqlCmd.Dispose();
}
}
sqlCon.Close();
}
}
}
}
}
I guess you should refactor to be a Dictionary (kami) or a List...
Anyway, if you do not consider it, you must firt instatiate the class by name and then use the property you need.
var type = Type.GetType("sql");
var myObject = Activator.CreateInstance(type);
myObject.QUERY;
NOTE: untested code.
EDIT: Dictionary solution:
Dictionary<string, string> d = new Dictionary<string, string>();
d.Add("Product", "SELECT * FROM PRODUCT");
d.Add("Order", "SELECT * FROM ORDER");
d.Add("Customer", "SELECT * FROM CUSTOMER");
var x = d.Where(kvp => kvp.Key == "Order")
.ToDictionary(item => item.Key, item => item.Value)
.FirstOrDefault();
if(x.Key != null)
{
Console.WriteLine($"{x.Value}"); //this should return "SELECT * FROM ORDER"
}

Deserialize JSON and then insert into table

I want to insert JSON string into table i deserialize json string to object list and then insert into table but not working
My code :
My JSON data
{"data":[{"ID":"1","Personnel_Number":"1001","Employee_Name":"Employee 1","Password":"12345","Gender":"M","Grade":"W5","Designation":"4","SBU_ID":"1","Department":"1","Category":"1","Email_ID_Official":"","Email_ID_Personal":"","Mobile_Number":"","Current_Address":"","Permanent_Address":"","Aadhaar_No":"","DOB":"","DOJ":"","DOM":"","Marital_Status":"","Profile_Pic_Path":"http://iprofileapi.dev.app6.in/UploadedFiles/6365794593150041732018329.jpg","Remarks":"","Status":"Active","Created_By":"dbo","Created_On":"20-09-2017 19:35:13","Updated_By":"3872","Updated_Date":"09-01-2019 12:48:00"},{"ID":"2","Personnel_Number":"1002","Employee_Name":"Employee 2","Password":"12345","Gender":"M","Grade":"W5","Designation":"153","SBU_ID":"6","Department":"28","Category":"1","Email_ID_Official":"","Email_ID_Personal":"","Mobile_Number":"","Current_Address":"","Permanent_Address":"","Aadhaar_No":"","DOB":"","DOJ":"","DOM":"","Marital_Status":"","Profile_Pic_Path":"","Remarks":"","Status":"Active","Created_By":"dbo","Created_On":"20-09-2017 19:35:13","Updated_By":"4957","Updated_Date":"10-02-2018 19:06:58"},{"ID":"3","Personnel_Number":"1003","Employee_Name":"Employee 3","Password":"12345","Gender":"M","Grade":"W5","Designation":"41","SBU_ID":"1","Department":"3","Category":"1","Email_ID_Official":"","Email_ID_Personal":"","Mobile_Number":"","Current_Address":"","Permanent_Address":"","Aadhaar_No":"","DOB":"","DOJ":"","DOM":"","Marital_Status":"","Profile_Pic_Path":"","Remarks":"","Status":"Active","Created_By":"dbo","Created_On":"20-09-2017 19:35:13","Updated_By":"5482","Updated_Date":"05-10-2017 15:36:16"},{"ID":"4","Personnel_Number":"1004","Employee_Name":"Employee 4","Password":"12345","Gender":"M","Grade":"W2","Designation":"120","SBU_ID":"26","Department":"88","Category":"1","Email_ID_Official":"","Email_ID_Personal":"","Mobile_Number":"","Current_Address":"","Permanent_Address":"","Aadhaar_No":"","DOB":"","DOJ":"","DOM":"","Marital_Status":"","Profile_Pic_Path":"","Remarks":"","Status":"Active","Created_By":"dbo","Created_On":"20-09-2017 19:35:13","Updated_By":"6298","Updated_Date":"06-10-2017 13:30:20"},{"ID":"5","Personnel_Number":"1005","Employee_Name":"Employee
And So On......
first i make class for all items in same basis i am not posting all data because it will be too lengthy its a sample data:
public class tblEmployee
{
public string ID { get; set; }
public string Personnel_Number { get; set; }
public string Employee_Name { get; set; }
public string Password { get; set; }
}
Then i create another class for list of items:
public class SalesTransactions
{
public List<tblEmployee> transactions { get; set; }
public int count { get; set; }
}
And then i have create insert data into sql server table on button click
protected void btninsertjsondata_Click(object sender, EventArgs e)
{
var conString = ConfigurationManager.ConnectionStrings["SQLDBConnection1"];
string strConnString = conString.ConnectionString;
SqlConnection conn = new SqlConnection(strConnString);
SqlCommand com;
string data = HttpContent("https://localhost:45333/Retrive_Jsondata.aspx");
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
SalesTransactions table = JsonConvert.DeserializeObject<SalesTransactions>(data);
conn.Open();
com = new SqlCommand("INSERT INTO dbo.tbl_Iprofile_Employee select * from " + table, conn);
com.CommandType = CommandType.Text;
int refId = com.ExecuteNonQuery();
conn.Close();
if (refId > 0)
{
Response.Write("{\"response\":{\"status\":\"success\",\"msg\":\"Details Saved Successfully..\"}}");
}
else
{
Response.Write("{\"response\":{\"status\":\"fail\",\"msg\":\"oops!! something went wrong\"}}");
}
}
While debugging my Code in table i am getting Count 0 and transactions null that's why my sql query is not working and i am getting 'Incorrect syntax near '+'.' In Data i am getting my all JSON string but unable to convert into table form
where i am doing wrong please help me should i add for loop for mapping all column and row ???
Edit:
Check how your query looks like realtime in the debugger. You`re adding to your select statement an object not string with the table name.
foreach (var row in table.transactions)
{
com = new SqlCommand(
string.Format("INSERT INTO dbo.tbl_Iprofile_Employee (ID ,Personnel_Number,Employee_Name,Password )
VALUES ({0},{1},{2},{3});",
row.ID, row.Personnel_Number, row.Employee_Name, row.Password),
conn);
com.CommandType = CommandType.Text;
int refId = com.ExecuteNonQuery();
}
Both code examples (yours and mine) have SQL injection vulnerabilities.
For better readability and sustainability try to extract your DB logic in independent classes and methods first. A common way to do this is the Repository Pattern.
For its implementation try to use a micro ORM like Dapper.
This whole approach will help you out with all these time-consuming things like debugging your, testing and maintaining for your application.

Insert data in comboBox from database

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());
}

DataTable Property - NullReferenceException [duplicate]

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();
}

Trouble with my property using C#

I am having trouble with my property always being null in my app, but I believe that the problem may be deeper than that. The requirement is to have a data layer class that contains my connection string to my access database. This calls another class which pulls the database information and sets it back to the data layer class. I must then use ONLY the data layer class to get my records. The problem is that my property is always null. Here is the code for the data layer class:
{
class CustomerDL
{
OleDbConnection aConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=CIS3341.accdb;");
string names;
public void initializeConnection()
{
Customer.initializeConnection(aConnection);
}
public string getNames
{
get { return names; }
set { names = value; }
}
}
}
And here is the other class:
class Customer
{
static OleDbConnection aConnection = null;
string names;
public static void initializeConnection(OleDbConnection aDbConnection)
{
aConnection = aDbConnection;
aConnection.Open();
getNames();
}
public static void getNames()
{
CustomerDL aCustomer = new CustomerDL();
OleDbDataAdapter myAdapter = new OleDbDataAdapter();
if (aConnection.State == ConnectionState.Closed)
{
aConnection.Open();
}
OleDbCommand cmd = aConnection.CreateCommand();
OleDbDataReader dbReader = null;
cmd.CommandText = "SELECT CustomerName FROM Customer";
dbReader = cmd.ExecuteReader();
while (dbReader.Read())
{
aCustomer.getNames += (string)dbReader["CustomerName"].ToString() + "\r\n";
}
dbReader.Close();
//return aCustomer ;
}
}
Now when i use this code on my form:
public partial class Form1 : Form
{
CustomerDL customer = new CustomerDL();
public Form1()
{
InitializeComponent();
customer.initializeConnection();
string fast = customer.getNames;
richTextBox1.Text = fast;
}
customer.getNames; is always null. Any ideas?
You aren't assigning anything to the proper instance of CustomerDL.
customer.getNames never gets accessed whatsoever. You are initializing your connection, but in that method you use a new CustomerDL: CustomerDL aCustomer = new CustomerDL();. You have to provide that instance to the static method for it to do something.
in CustomerDL the member names has the default value null, you can initialize it with string names = string.Empty;
You really should consolidate the Customer and CustomerDL classes into one class. There is too much duplication. So instead of having CustomerDL call Customer, just put the getnames() code in your CustomerDL class. And scrap all the static modifiers. By your form example, you are instantiating CustomerDL and calling methods on it. Make the class and its methods non-static, and this will work much better for you.
One of the problems that is preventing you from figuring this one out is your naming conventions...
You have both properties and methods named the same (I would leave the word "get" off of properties).
You have a "CustomerDL" object that you named "customer". The problem is you also have a "Customer" class.
You have a static method coded to do what you want, but you are never calling it.
IMHO if you take a little more care in your naming conventions, it will be a lot easier to troubleshoot these kinds of issues....There are a few things wrong with the code, but I quickly gave fixing it a shot. Hope it helps:
class CustomerDL
{
OleDbConnection aConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=CIS3341.accdb;");
public string GetNames()
{
string NamesToReturn = "";
try
{
OleDbDataAdapter myAdapter = new OleDbDataAdapter();
if (aConnection.State == ConnectionState.Closed)
{
aConnection.Open();
}
OleDbCommand cmd = aConnection.CreateCommand();
OleDbDataReader dbReader = null;
cmd.CommandText = "SELECT CustomerName FROM Customer";
dbReader = cmd.ExecuteReader();
while (dbReader.Read())
{
NamesToReturn += (string)dbReader["CustomerName"].ToString() + "\r\n";
}
dbReader.Close();
catch(Exception ex)
{
}
finally
{
aConnection.Close(); //makes sure it closes...
}
return NamesToReturn;
}
}
Then you can do this:
class Customer
{
private CustomerDL customerData = new CustomerDL();
public string Names { get; set; }
public string FillNames()
{
this.Names = customerData.GetNames();
}
}
public partial class Form1 : Form
{
Customer customer = new Customer();
public Form1()
{
InitializeComponent();
customer.FillNames();
richTextBox1.Text = customer.Names;
}
}
Note: This code is very crude and I have not double checked it, but I beleive it will get you pointed in the right direction.

Categories

Resources