Should I use public methods or writeonly properties in my class? - c#

I have a class library that contains a class. The class is responsible to form a connection between the program and the database and provide me with the connection string :
public class DBcon
{
private string pass = "";
private string dbName = "";
OleDbConnection con = new OleDbConnection();
public string setdbName
{
set { dbName = value; }
}
public string setpass
{
set { pass = value; }
}
public OleDbConnection getsetcon
{
set { createcon(); }
get { return con; }
}
private void createcon()
{
PathFinder dbPath = new PathFinder(); // just another class
string DBPath = "";
dbPath.dbFilesPath = "db";
dbPath.setDBName = dbName;
DBPath = dbPath.dbFilesPath;
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + DBPath + ";" +
"Persist Security Info = False;Jet OLEDB:Database Password=" + pass + "";
}
}
Firstly, I wanted to use a public method ie. createcon, to avoid all the properties but then I read that's a bad practice.
Then I decided to use write only properties but they are also considered bad practices.
Can anyone tell me what to do to make my class a well structured class. I am using write only properties as I don't want to return strings. I just want the OledbConnection.
Any help will be appreciated even if it changes the structure of the class.

public class DBConnection
{
private string pass = string.Empty;
private string dbName = string.Empty;
private OleDbConnection connection;
public void DBConnection(string dbName, string pass)
{
this.dbName = dbName;
this.pass = pass;
this.Initialize();
}
public OleDbConnection Connection
{
get {return this.connection;}
}
private void Initialize()
{
//all the initialization
var connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + DBPath + ";" +
"Persist Security Info = False;Jet OLEDB:Database Password=" + pass + "";
this.connection = new OleDbConnection(connString);
}
}
p.s. instead of using string concatenation, use appropriate string builder for connection path.

Related

I want to call a method from a different form

I want my TextBox to take information and run the code from a business object from a different form. I want it to run whenever the button is clicked.
I am having problems initializing the code. In theStudent.cs form it works fine I just want to pull the SelectDB() method into the StudentForm.
namespace SchoolReg{
public partial class StudentForm : Form
{
public StudentForm()
{
InitializeComponent();
}
private void StudentForm_Load(object sender, EventArgs e)
{
//ignore
}
private void StudentButton_Click(object sender, EventArgs e)
{
Student s1;
s1 = new Student();
txtboxIDStu.Text = s1.SelectDB(int);
}
private void txtboxIDStu_TextChanged(object sender, EventArgs e)
{
//ignore
}
}
namespace SchoolReg{
class Student : person
{
private double gpa;
//constructors
public Student():base()
{
gpa = 0;
}
public Student(int id, string fn, string ln, Address a1, string em, double gp) : base(id,fn,ln,a1,em)
{
gpa = gp;
}
//behaviors
public void setgpa(double gp) { gpa = gp; }
public double getgpa() { return gpa; }
//display
public void Display()
{
base.display();
Console.WriteLine("===================================");
Console.WriteLine("Gpa = " + gpa);
Console.WriteLine("===================================");
}
public System.Data.OleDb.OleDbDataAdapter OleDbDataAdapter2;
public System.Data.OleDb.OleDbCommand OleDbSelectCommand2;
public System.Data.OleDb.OleDbCommand OleDbInsertCommand2;
public System.Data.OleDb.OleDbCommand OleDbUpdateCommand2;
public System.Data.OleDb.OleDbCommand OleDbDeleteCommand2;
public System.Data.OleDb.OleDbConnection OleDbConnection2;
public string cmd;
public Student(int id)
{
SelectDB(id);
}
public void DBSetup()
{
OleDbDataAdapter2 = new System.Data.OleDb.OleDbDataAdapter();
OleDbSelectCommand2 = new System.Data.OleDb.OleDbCommand();
OleDbInsertCommand2 = new System.Data.OleDb.OleDbCommand();
OleDbUpdateCommand2 = new System.Data.OleDb.OleDbCommand();
OleDbDeleteCommand2 = new System.Data.OleDb.OleDbCommand();
OleDbConnection2 = new System.Data.OleDb.OleDbConnection();
OleDbDataAdapter2.DeleteCommand = OleDbDeleteCommand2;
OleDbDataAdapter2.InsertCommand = OleDbInsertCommand2;
OleDbDataAdapter2.SelectCommand = OleDbSelectCommand2;
OleDbDataAdapter2.UpdateCommand = OleDbUpdateCommand2;
OleDbConnection2.ConnectionString = "Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Registry Path=;Jet OLEDB:Database L" +
"ocking Mode=1;Data Source=C:\\Users\\nicho\\OneDrive\\Desktop\\Database c#\\RegistrationMDB.mdb;J" +
"et OLEDB:Engine Type=5;Provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:System datab" +
"ase=;Jet OLEDB:SFP=False;persist security info=False;Extended Properties=;Mode=S" +
"hare Deny None;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Create System Database=False;Jet " +
"OLEDB:Don't Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica Repai" +
"r=False;User ID=Admin;Jet OLEDB:Global Bulk Transactions=1";
}
public void SelectDB(int id)
{
DBSetup();
cmd = "Select * from Students where ID =" + id;
OleDbDataAdapter2.SelectCommand.CommandText = cmd;
OleDbDataAdapter2.SelectCommand.Connection = OleDbConnection2;
Console.WriteLine(cmd);
try
{
OleDbConnection2.Open();
System.Data.OleDb.OleDbDataReader dr;
dr = OleDbDataAdapter2.SelectCommand.ExecuteReader();
dr.Read();
Id = id;
setfname(dr.GetValue(1) + "");
setlname(dr.GetValue(2) + "");
Address a1 = new Address(dr.GetValue(3) + "", dr.GetValue(4) + "", dr.GetValue(5) + "", long.Parse(dr.GetValue(6)+""));
setAddr(a1);
setemail(dr.GetValue(7) + "");
setgpa(Double.Parse(dr.GetValue(8) + ""));
}
catch(Exception ex)
{
Console.WriteLine(ex);
}
finally
{
OleDbConnection2.Close();
}
Console.WriteLine("===================================");
getSchedule();
Console.WriteLine("===================================");
}
/I think I am messing up in the StudentForm form. I'm sorry in advance because I feel like the answer is simple. Also for the messy layout, I don't usually post./
Okay, you're pretty close here, but you're missing a few steps
private void StudentButton_Click(object sender, EventArgs e)
{
Student s1;
s1 = new Student();
txtboxIDStu.Text = s1.SelectDB(int);
}
should be something like this
private void StudentButton_Click(object sender, EventArgs e)
{
string studentIdString = this.TEXTBOXNAME.Text; // This fetches the string from the input box and stores it. Replace TEXTBOXNAME with the name of your textbox that holds the ID.
bool inputIsNumber = Int32.TryParse(studentIdString , out studentIdInt); //Int32 TryParse tries to convert a given string into an integer. If it works inputIsNumber will be true, and the studentIdInt will be available as a variable.
if(inputIsNumber == false){
txtboxIDStu.Text = "Please enter a valid number";
return; //Bail out if we can't turn the string into a number
}
Student s1 = new Student(studentIdInt); //We're going to use the ID we created to build the student using the constructor
txtboxIDStu.Text = s1.fname + " " + s1.lastname; // By the time we've gotten here the constructor has fired, which also fired SelectDB() on that student. This just prints the name of the student, but if you want to improve this look up "Overrides" and create a ToString() override on your Student class.
}
You already have a constructor for student that takes an Id, which is exactly what we need.
public Student(int id)
{
SelectDB(id);
}

How to add data into MSQL database by using c# programming?

Good day!
Using visual studio 2012, I have created a Student class with get and set codes, and i need to complete the StudentDAO class to create insert coding that will use to store data to database student table. this action is perform by a windows form button click event.
what i need to create a button click code and then insert into database code,
//Student.cs class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SRSJason
{
class Student
{
private string S_Student_id;
private string S_Full_name;
private DateTime S_Dob;
private string S_Address;
private int S_Contact;
private string S_Username;
private string S_Password;
public Student() //Default constructor
{
}
public Student(string Student_id, string Full_name, DateTime Dob, string Address, int Contact, string Username, string Password) //Overloadign
{
S_Student_id = Student_id;
S_Full_name = Full_name;
S_Dob = Dob;
S_Address = Address;
S_Contact = Contact;
S_Username = Username;
S_Password = Password;
}
public void setID(string Student_id)
{
S_Student_id = Student_id;
}
public string getID()
{
return S_Student_id;
}
public void setName(string Full_name)
{
S_Full_name = Full_name;
}
public string getName()
{
return S_Full_name;
}
public void setDob(DateTime Dob)
{
S_Dob = Dob;
}
public DateTime getDob()
{
return S_Dob;
}
public void setAddress(string Address)
{
S_Address = Address;
}
public string getAddress()
{
return S_Address;
}
public void setContact(int Contact)
{
S_Contact = Contact;
}
public int getContact()
{
return S_Contact;
}
public void setUsername(string Username)
{
S_Username = Username;
}
public string getUsername()
{
return S_Username;
}
public void setPassword(string Password)
{
S_Password = Password;
}
public string getPassword()
{
return S_Password;
}
}
}`
//StudentDAO class (please help me to complete this code)
`class StudentDAO
{
static string constring = "Data Source=JAZE;Initial Catalog=srsjason;Integrated Security=True";
SqlConnection m_con = new SqlConnection(constring);
}`
//button click from the form (please help me to complete this code as well)
private void submitstudent(object sender, EventArgs e)
{
}
please help me to complete this coding
First of all when you create private properties u cant access them in your forms, you have to create a method instead inside the same class then use it in your form. second you should know about the ORM - Object Relational Mapping that you are using.
Here I'll list them:
ADO.NET
LINQ to SQL
ADO.NET Entity Framework
When you picked one of those. next step would be learning about how they work and whats the syntax.
However knowing that you kinda showed a syntax of ADO.NET Here is an Example how you can insert the data in your data base using ADO.NET. If you want to add data directly from code-behind without a method. so basically on click event of your button.
private void btn_Click(object sender, EventArgs e)
{
try
{
//create object of Connection Class..................
SqlConnection con = new SqlConnection();
// Set Connection String property of Connection object..................
con.ConnectionString = "Data Source=KUSH-PC;Initial Catalog=test;Integrated Security=True";
// Open Connection..................
con.Open();
//Create object of Command Class................
SqlCommand cmd = new SqlCommand();
//set Connection Property of Command object.............
cmd.Connection = con;
//Set Command type of command object
//1.StoredProcedure
//2.TableDirect
//3.Text (By Default)
cmd.CommandType = CommandType.Text;
//Set Command text Property of command object.........
cmd.CommandText = "Insert into Registration (Username, password) values ('#user','#pass')";
//Assign values as `parameter`. It avoids `SQL Injection`
cmd.Parameters.AddWithValue("user", TextBox1.text);
cmd.Parameters.AddWithValue("pass", TextBox2.text);
//Execute command by calling following method................
//1.ExecuteNonQuery()
//This is used for insert,delete,update command...........
//2.ExecuteScalar()
//This returns a single value .........(used only for select command)
//3.ExecuteReader()
//Return one or more than one record.
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Saved");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
con.Close();
}
}
Be sure that you've included your ConnectionString in your config file.

C# Error: “Fill: SelectCommand.Connection property has not been initialized.”

I have problem with this error:
C# Error: “Fill: SelectCommand.Connection property has not been
initialized.”
I lloked ower others threads, but people have it built their clients little different and it didnt help.
I dont know, why this error showed. And I suppose its wrong somewhere at SelectOsoba.
I need to show data in DataGridView.
my code is :
class Vrstva
{
public static SqlConnection myConnection;
public static string connstr;
static DataTable t;
public static void createConnect1()
{
connstr = ConfigurationSettings.AppSettings["local1"];
Vrstva.myConnection = new SqlConnection(connstr);
}
public static void createConnect2()
{
connstr = ConfigurationSettings.AppSettings["local2"];
Vrstva.myConnection = new SqlConnection(connstr);
}
public static void createConnect3()
{
connstr = ConfigurationSettings.AppSettings["local3"];
Vrstva.myConnection = new SqlConnection(connstr);
}
public static void openConn()
{
Vrstva.myConnection.Open();
}
public static void closeConn()
{
Vrstva.myConnection.Close();
}
public static SqlDataAdapter Query(string command)
{
return new SqlDataAdapter(command, Vrstva.myConnection);
}
public static void NonQuery(string command)
{
SqlCommand Command = new SqlCommand(command, Vrstva.myConnection);
Command.ExecuteNonQuery();
}
public static bool login1(string login, string password)
{
string login1 = ConfigurationSettings.AppSettings["login1"];
string password1 = ConfigurationSettings.AppSettings["password1"];
if (login == login1 && password == password1)
{
return true;
}
return false;
}
public static bool login2(string login, string password)
{
string login1 = ConfigurationSettings.AppSettings["login2"];
string password1 = ConfigurationSettings.AppSettings["password2"];
if (login == login1 && password == password1)
{
return true;
}
return false;
}
public static bool login3(string login, string password)
{
string login1 = ConfigurationSettings.AppSettings["login3"];
string password1 = ConfigurationSettings.AppSettings["password3"];
if (login == login1 && password == password1)
{
return true;
}
return false;
}
////vypis tabulku prislusniku
public static DataTable SelectOsoba()
{
t = new DataTable();
Query("Select * from Osoba;").Fill(t);
return t;
}
//Insert
public static void PridejOsoba(string Jmeno, string Prijmeni, string Povolani, int Poc_Det)
{
NonQuery("Insert into Osoba(Jmeno,Prijmeni,Povolani,Poc_Det) values('" + Jmeno + "','" + Prijmeni + "','" + Povolani + "','" + Poc_Det + "');");
}
}
This error is most likely being thrown because your connection in this line:
return new SqlDataAdapter(command, Vrstva.myConnection);
has not been initialized.
You have to call one of your createConnectX() methods before trying to query.

How can I pass my getters and setters parameters to connection class?

I assigned the textbox inputs to getters and setters also created one connection class. How can I pass my getters and setters parameters to connection class so I can use it inside my mainform.
MemberClass
private string srDatabase = "";
private string srID = "";
private string srPass = "";
public string SDB
{
get
{
return srDatabase;
}
set
{
srDatabase= value;
}
}
public string SID
{
get
{
return srID ;
}
set
{
srID = value;
}
}
public string SPassword
{
get
{
return srPass ;
}
set
{
srPass = value;
}
}
ConnectionClass
class Connection
{
public static OracleConnection GetConnection(string dataSource, string userName, string password)
{
OracleConnection con = null;
if(!string.IsNullOrWhiteSpace(dataSource) && !string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password))
{
con = new OracleConnection("Data Source=" + dataSource + ";User Id=" + userName.ToUpper() + ";Password=" + password + ";");
return con;
}
return con;
}
}
MainForm
UserMembers = new UserMembers();
txtSrcUserDatabase.Text = src.srDatabase ;
txtSrcUserID.Text=src.srID.ToUpper();
txtSrcUserPassword.Text = src.srPass;
OracleConnection conn1 = Connection.GetConnection() // **here error**
conn1.Open();
using (OracleCommand Names = new OracleCommand("SELECT TABLE_NAME FROM USER_TABLES ORDER BY TABLE_NAME", conn1))
{
using (OracleDataReader reader = Names.ExecuteReader())
{
while (reader.Read())
{
//Do something
}
}
}
Your method GetConnection requires three parameters. You need to pass them to the method.
UserMembers src = new UserMembers();
src.srDatabase =txtSrcUserDatabase.Text;
src.srID = txtSrcUserID.Text.ToUpper();
src.srPass = txtSrcUserPassword.Text;
OracleConnection conn1 = Connection.GetConnection(src.srDatabase, src.srID, src.srPass)
conn1.Open();
......
Or you could pass the instance of UserMembers to the GetConnection method creating an overload of GetConnection like this
class Connection
{
// the first overload that takes 3 string parameters
public static OracleConnection GetConnection(string dataSource, string userName, string password)
{
....
}
// The second overload that takes an instance of UserMembers
public static OracleConnection GetConnection(UserMembers src )
{
OracleConnection con = null;
if(!string.IsNullOrWhiteSpace(sr.srDatabase) && !string.IsNullOrWhiteSpace(sr.srID) && !string.IsNullOrWhiteSpace(sr.srPass))
{
con = new OracleConnection("Data Source=" + sr.srDatabase + ";User Id=" + sr.srID.ToUpper() + ";Password=" + sr.Pass + ";");
}
return con;
}
}
As a side note. If you need the srID member to be always in upper case then move this logic in the setter property, and you could stop to worry about the proper formatting of this member when you try to read it back
public string SID
{
get { return srID ; }
set { srID = value.ToUpper(); }
}

LINQ Database

I have a system that supports multiple products. Each product has its own database with the same exact schema.
When I pass in the connection string as a parameter to my Data Context constructor it always uses the default database listed in the connection string, or the default database of the user connecting if I do not provide an Initial Catalog in the connection string.
I would like to be able to have the system utilize a database without having to change the connection string and by passing in the database name as a parameter.
Here is an example of the code I am using:
class Program
{
static void Main(string[] args)
{
var d = new Data("Data Source=(LOCAL);Initial Catalog=Database1;Integrated Security=true;");
var d1 = new Data("Data Source=(LOCAL);Initial Catalog=Database2;Integrated Security=true;");
Console.ReadLine();
}
}
internal class Data
{
public Data(string connection)
{
using (var ctx = new DataClassDataContext(connection))
{
var query = from c in ctx.MyTable select c;
try
{
Console.WriteLine(query.Count());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
If this code gets executed, then the first result will pull from Database1 and the second result will pull from Database2. I would like it to have the ability to pull from a database that is not provided in the connection string. The reason for this is because the database could change based on a specific scenario but the connection string will remain the same.
Here is an example of what I am using to "fake" it, but I don't really think this is the best solution for this:
class oConnection
{
public string Server { get; set; }
public string Database { get; set; }
public bool IntegratedSecurity { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
class Program
{
static void Main(string[] args)
{
var d = new Data(new oConnection
{
Database = "Database1",
Server = "(Local)",
IntegratedSecurity = true
});
var d1 = new Data(new oConnection
{
Database = "Database2",
Server = "(Local)",
IntegratedSecurity = true
});
Console.ReadLine();
}
}
internal class Data
{
private static string BuildConnection(oConnection connection)
{
var sb = new StringBuilder();
sb.Append("Data Source=" + connection.Server + ";Initial Catalog=" + connection.Database + ";");
if(connection.IntegratedSecurity)
{
sb.Append("Integrated Security=true;");
}
else
{
sb.Append("user id=" + connection.UserName + ";password=" + connection.Password);
}
return sb.ToString();
}
public Data(oConnection connection)
{
using (var ctx = new DataClassDataContext(BuildConnection(connection)))
{
var query = from c in ctx.MyTable select c;
try
{
Console.WriteLine(query.Count());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
Another note: the goal of this is really to be able to support not having multiple different connection strings when running queries that will span across multiple databases. For example: If I want to query the account records from a database and then query some sort of lookup data from another database, I would have to create a new connection string for the context.
Any help would be appreciated.
Thanks
Use the constructor that receives System.Data.IDbConnection connection. You can use the same connection string, and call connection.ChangeDatabase("mydb") before passing it to the constructor. Alternatively you can add a new constructor on the partial class, so the calling call doesn't has to deal with that.
you can use the SqlConnectionStringBuilder
class

Categories