I am trying to insert data into a database using a three-tier architecture, but I am stuck and I cannot proceed further.
This is my code
First is UI part:
public void assignField()
{
string maritalCondition = "";
string sex = "";
assignObj.Registered_Date = dateTimePicker1_Date.Value;
assignObj.First_Name = txt_FirstName.Text;
if (comboBox2_MaritalStatus.SelectedIndex == 0)
{
maritalCondition = "Single";
}
else
maritalCondition = "Married";
assignObj.Marital_Status = maritalCondition;
if (RadioButton_Male.Checked == true)
sex = "Male";
else
sex = "Female";
assignObj.Gender = sex;
this.txt_Age.Text = Convert.ToInt32(age).ToString();
}
private void btnRegister_Click(object sender, EventArgs e)
{
assignField();
}
Next is the middle tier:
public class CustomerDataType
{
private DateTime registered_Date;
private string first_Name;
private int age;
private string marital_Status;
private string gender;
public DateTime Registered_Date
{
get { return registered_Date; }
set { registered_Date = value; }
}
public string First_Name
{
get { return first_Name; }
set { first_Name = value; }
}
public int Age
{
get { return age; }
set { age = value; }
}
public string Marital_Status
{
get { return marital_Status; }
set { marital_Status = value; }
}
public string Gender
{
get { return gender; }
set { gender = value; }
}
public void insertInfo()
{
CustomerDataAccess insertObj = new CustomerDataAccess(Registered_Date, First_Name, Age, Marital_Status, Gender);
insertObj.insertCustomerInfo();
}
}
and last is the data access tier:
public class CustomerDataAccess
{
public CustomerDataAccess(DateTime Registered_Date, string First_Name, int Age, string Marital_Status, string Gender)
{
this.registrationDate = Registered_Date;
this.fName = First_Name;
this.userAge = Age;
this.marriageStatus = Marital_Status;
this.userGender = Gender;
}
SqlConnection con;
SqlCommand cmd;
DateTime registrationDate;
string fName = "";
int userAge;
string marriageStatus;
string userGender;
public void insertCustomerInfo()
{
try
{
con = new SqlConnection("Data Source=LAKHE-PC;Initial Catalog=Sahakari;Integrated Security=True");
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = "sp_registerCust";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Registered_Date", SqlDbType.DateTime);
cmd.Parameters["#Registered_Date"].Value = registrationDate;
cmd.Parameters.Add("#First_Name", SqlDbType.VarChar);
cmd.Parameters["#First_Name"].Value = fName;
cmd.Parameters.Add("#Age", SqlDbType.Int.ToString());
cmd.Parameters["#Age"].Value = userAge;
cmd.Parameters.Add("#Marital_Status", SqlDbType.VarChar);
cmd.Parameters["#Marital_Status"].Value = marriageStatus;
cmd.Parameters.Add("#Gender", SqlDbType.VarChar);
cmd.Parameters["#Gender"].Value = userGender;
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Here with the stored procedure, there is no problem and and from SQL Server I can insert data into table easily. But from windows form, it does not insert data in table. Plz help me.
I'll do something like below
UI
CustomerHandler custHandler = new CustomerHandler();
// create Customer object and pass to insert method
if (custHandler.InsertCustomer(new Customer(){
FirstName = txt_FirstName.Text, Registered_Date =dateTimePicker1_Date.Value,
//decalare other parameters....
))
{
// insert Success, show message or update label with succcess message
}
In my BL
public class CustomerHandler
{
// in BL you may have to call several DAL methods to perform one Task
// here i have added validation and insert
// in case of validation fail method return false
public bool InsertCustomer(Customer customer)
{
if (CustomerDataAccess.Validate(customer))
{
CustomerDataAccess.insertCustomer(customer);
return true;
}
return false;
}
}
In MY DAL
// this is the class you going to use to transfer data across the layers
public class Customer
{
public DateTime Registered_Date { get; set; }
public string FirstName { get; set; }
//so on...
}
public class CustomerDataAccess
{
public static void insertCustomer(Customer customer)
{
using (var con = new SqlConnection("Data Source=LAKHE-PC;Initial Catalog=Sahakari;Integrated Security=True"))
using (var cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = "sp_registerCust";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Registered_Date", customer.Registered_Date);
cmd.Parameters.AddWithValue("#FirstName", customer.FirstName);
// so on...
cmd.ExecuteNonQuery();
}
}
internal static bool Validate(Customer customer)
{
// some validations before insert
}
}
Your middle tier consists of classes holding the values you require in properties. Instead of writing the data access manually, try using the Entity Framework (EF) which does that for you.
Here (at MSDN) you can find a quickstart example which shows you how you can use it.
Instead of mapping the fields manually and executing a query, the Entity Framework does that which means you just have to assign the values to the object's properties and call SaveChanges() - the SQL code is created and executed automatically by the EF.
For further reading, there is also a lot to find here (at Stackoverflow).
Related
i have ran into some problems with my insert function.
i am trying to make my the string listing_ID an auto increment int with no input needed, however when coding for the button submit i included all the inputs for all the other values but not listing_ID , this gave me the error below. below are all the images and these are the codes for the insert function.
public class Carlisting
{
private string _listID = "";
private string _car_model = "";
private string _brand_name = "";
private string _car_description = "";
private string _car_condition = "";
private string _price = "";
private string _inspection_date = "";
string _connStr = ConfigurationManager.ConnectionStrings["roadbnb.mdf"].ConnectionString;
public Carlisting(string listID, string car_model, string brand_name, string car_description, string car_condition, string price, string inspection_date)
{
_listID = listID;
_car_model = car_model;
_brand_name = brand_name;
_car_description = car_description;
_car_condition = car_condition;
_price = price;
_inspection_date = inspection_date;
}
public Carlisting()
{
}
public string listing_ID
{
get { return _listID; }
set { _listID = value; }
}
public string car_model
{
get { return _car_model; }
set { _brand_name = value; }
}
public string brand_name
{
get { return _brand_name; }
set { _brand_name = value; }
}
public string car_description
{
get { return _car_description; }
set { _car_description = value; }
}
public string car_condition
{
get { return _car_condition; }
set { _car_condition = value; }
}
public string price
{
get { return _price; }
set { _price = value; }
}
public string inspection_date
{
get { return _inspection_date; }
set { _inspection_date = value; }
}
protected void btn_submit_Click(object sender, EventArgs e)
{
int result = 0;
Carlisting car = new Carlisting(tb_model.Text, tb_brand.Text, tb_description.Text, dl_condition.Text, tb_price.Text, tb_date.Text);
result = car.ListingInsert();
if (result > 0)
{
Response.Write("<script>alert('You have succesfully added listing , PLease wait for approval');</script>");
}
else
{
Response.Write("<script>alert('Error : PLease contact helpdesk');</script>");
}
}
public int ListingInsert()
{
int result = 0;
string queryStr = "INSERT INTO Carlisting(car_model, brand_name, car_description, car_condition , price, inspection_date)"
+"VALUES (#car_model, #brand_name, #car_description, #car_condition, #price, #inspection_date)";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
cmd.Parameters.AddWithValue("#car_model", this.car_model);
cmd.Parameters.AddWithValue("#brand_Name", this.brand_name);
cmd.Parameters.AddWithValue("#car_description", this.car_description);
cmd.Parameters.AddWithValue("#car_condition", this.car_condition);
cmd.Parameters.AddWithValue("#price", this.price);
cmd.Parameters.AddWithValue("#inspection_date", this.inspection_date);
conn.Open();
result += cmd.ExecuteNonQuery();
conn.Close();
return result;
}
Does anyone know how should fix it in order to get the results i wan? Thank you in advance
As per your screenshot, you are getting compilation error. To Fix it, create another constructor. Currently your code want to invoke constructor which does not take listId as parameter.
public Carlisting(string listID, string car_model, string brand_name, string car_description, string car_condition, string price, string inspection_date)
: this(car_model, brand_name, car_description, car_condition, price, inspection_date)
{
_listID = listID;
}
public Carlisting(string car_model, string brand_name, string car_description, string car_condition, string price, string inspection_date)
{
_car_model = car_model;
_brand_name = brand_name;
_car_description = car_description;
_car_condition = car_condition;
_price = price;
_inspection_date = inspection_date;
}
With above the 1st constructor invokes the another constructor with other required parameters. And for your code, the 2nd constructor will be invoked and you won't have compilation error.
I am consuming wcf service into console application . I am trying to retrieve account information based on account number . But the problem is when i enter the account number and hit enter ,its only displaying account number and rest of the fields are empty.
Here is the base class.
[DataContract]
public class Current_Account_Details
{
string account_creation_date;
string account_type;
string branch_sort_code;
string account_fees;
string account_balance;
string over_draft_limit;
string account_holder_id;
[DataMember]
public string Account_Creation_Date
{
get { return account_creation_date; }
set { account_creation_date = value; }
}
[DataMember]
public string Account_Type
{
get { return account_type; }
set { account_type = value; }
}
[DataMember]
public string Branch_Sort_Code
{
get { return branch_sort_code; }
set { branch_sort_code = value; }
}
[DataMember]
public string Account_Fees
{
get { return account_fees; }
set { account_fees = value; }
}
[DataMember]
public string Account_Balance
{
get { return account_balance; }
set { account_balance = value; }
}
[DataMember]
public string Over_Draft_Limit
{
get { return over_draft_limit; }
set { over_draft_limit = value; }
}
[DataMember]
public string Account_Holder_Id
{
get { return account_holder_id; }
set { account_holder_id = value; }
}
}
}
Here is the inherited class.
[DataContract]
public class AccountBalanceRequest : Current_Account_Details
{
string account_number;
[DataMember]
public string Account_Number
{
get { return account_number; }
set { account_number = value; }
}
}
}
Here is the Interface .
[OperationContract]
AccountBalanceRequest AccountBalanceCheek(AccountBalanceRequest accountNumber);
Here is my Method .
public AccountBalanceRequest AccountBalanceCheek(AccountBalanceRequest accountNumber)
{
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
//use top 1 since you are only getting one record.
//let us use string interpolation, if you are working below C#6
//replace it with your previous value
var cmd = new SqlCommand($#"SELECT TOP 1
*
FROM
Current_Account_Details
WHERE
Account_Number ='{accountNumber.Account_Number}'", conn);
cmd.CommandType = CommandType.Text;
//use ExecuteReader to execute sql select
//ExecuteNonQuery is for update, delete, and insert.
var reader = cmd.ExecuteReader();
//read the result of the execute command.
while (reader.Read())
{
//assuming that your property is the same as your table schema. refer to your table schema Current_Account_Details
//assuming that your datatype are string... just do the conversion...
accountNumber.Account_Balance = reader["Account_Balance"].ToString();
accountNumber.Account_Fees = reader["Account_Fees"].ToString();
accountNumber.Account_Balance = reader["Account_Balance"].ToString();
accountNumber.Over_Draft_Limit = reader["Over_Draft_Limit"].ToString();
}
return accountNumber;
}
}
Here is the code in Console Application .
public static void Balance()
{
MyService.HalifaxCurrentAccountServiceClient currentAccount = new MyService.HalifaxCurrentAccountServiceClient("NetTcpBinding_IHalifaxCurrentAccountService");
MyService.AccountBalanceRequest cs = new MyService.AccountBalanceRequest();
string AccountNumber;
Console.WriteLine("\nEnter your Account Number--------:");
AccountNumber = Console.ReadLine();
cs.Account_Number = AccountNumber;
// MyService.AccountBalanceRequest cs1 = currentAccount.AccountBalanceCheek(AccountNumber);
MyService.AccountBalanceRequest AccountBalance = currentAccount.AccountBalanceCheek(cs);//error on this line
Console.WriteLine("Account Number is :" + cs.Account_Number);
Console.WriteLine("Account creation date :" + cs.Account_Creation_Date);
Console.WriteLine("Account Type :" + cs.Account_Type);
Console.WriteLine("Branch_Sort_Code:" + cs.Branch_Sort_Code);
Console.WriteLine("Account_Fee:" + cs.Account_Fees);
Console.WriteLine("Account Account_Balance :" + cs.Account_Balance);
Console.WriteLine("Account Over Draft Limit :" + cs.Over_Draft_Limit);
Console.Write("--------------------------");
Console.ReadLine();
//Console.Clear();
}
Here is the screen shot of the database.click here to record
Here is the screen shot when i run the applicationClick here to see the result.In this screen shot only the account number is displaying and rest of the fields are empty
your Current_Account_Details is the base class and AccountBalanceRequest is derived class from your question posted.
If we have classes related by inheritance, the wcf service generally accepts and returns the base type. If you expect the service to accept and return inherited types, then use KnownType attribute.
So its enough if you decorate the base class with contracts and try.
[KnownType(typeof(AccountBalanceRequest))]
[DataContract]
public class Current_Account_Details
{
string account_creation_date;
string account_type;
string branch_sort_code;
string account_fees;
string account_balance;
string over_draft_limit;
string account_holder_id;
[DataMember]
public string Account_Creation_Date
{
get { return account_creation_date; }
set { account_creation_date = value; }
}
[DataMember]
public string Account_Type
{
get { return account_type; }
set { account_type = value; }
}
[DataMember]
public string Branch_Sort_Code
{
get { return branch_sort_code; }
set { branch_sort_code = value; }
}
[DataMember]
public string Account_Fees
{
get { return account_fees; }
set { account_fees = value; }
}
[DataMember]
public string Account_Balance
{
get { return account_balance; }
set { account_balance = value; }
}
[DataMember]
public string Over_Draft_Limit
{
get { return over_draft_limit; }
set { over_draft_limit = value; }
}
[DataMember]
public string Account_Holder_Id
{
get { return account_holder_id; }
set { account_holder_id = value; }
}
}
}
public class AccountBalanceRequest : Current_Account_Details
{
string account_number;
public string Account_Number
{
get { return account_number; }
set { account_number = value; }
}
}
Just check whether account number that you read from console is passed in the accountnumber variable.
var cmd = new SqlCommand("SELECT * FROM Current_Account_Details WHERE Account_Number = '" + accountNumber + "'", conn);
Edit 1: Your service is failing to retrieve records because you are passing the AccountBalanceRequest object and the changes made to the object is not reflected outside the method.
MyService.AccountBalanceRequest cs = new MyService.AccountBalanceRequest();
Change it to.
public AccountBalanceRequest AccountBalanceCheek(AccountBalanceRequest accountNumber)
{
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
//use top 1 since you are only getting one record.
//let us use string interpolation, if you are working below C#6
//replace it with your previous value
var cmd = new SqlCommand($#"SELECT TOP 1
*
FROM
Current_Account_Details
WHERE
Account_Number ='{accountNumber.Account_Number}'", conn));
cmd.CommandType = CommandType.Text;
//use ExecuteReader to execute sql select
//ExecuteNonQuery is for update, delete, and insert.
var reader = cmd.ExecuteReader();
//read the result of the execute command.
while(reader.Read())
{
//assuming that your property is the same as your table schema. refer to your table schema Current_Account_Details
//assuming that your datatype are string... just do the conversion...
accountNumber.Account_Balance = reader["Account_Balance"].ToString();
accountNumber.Account_Fee = reader["Account_Fee"].ToString();
accountNumber.Account_Balance = reader["Account_Balance"].ToString();
accountNumber.Over_Draft_Limit = reader["Over_Draft_Limit"].ToString();
}
return accountNumber;
}
}
In your console retrieve it,
MyService.AccountBalanceRequest AccountBalance =currentAccount.AccountBalanceCheek(cs);
Console.WriteLine("Your Account Number is :" + cs.Account_Number)
...
I think your problem is that you're passing a reference to the WCF service method and changing it there instead of returning. The documentation says that:
Each operation has a return value and a parameter, even if these are void. However, unlike a local method, in which you can pass references to objects from one object to another, service operations do not pass references to objects. Instead, they pass copies of the objects.
Try to change your code so the method returns the changed object. At the end of AccountBalanceCheek method instead of returning true return accountNumber.
And then in Balance method - remove if statement and change to:
....
cs = currentAccount.AccountBalanceCheek(cs);
Console.WriteLine("Your Account Number is :" + cs.Account_Number);
Console.WriteLine("Your Account Type :" + cs.Account_Balance);
....
To read more about it: Is it possible to pass parameters by reference with WCF
I am consuming Wcf Service in Windows Form Application . I am trying to create user login system based on user emu type from sql database .When I enter the value 1 into textbox it should return full time employee method else value 2 into textbox it should return part time employee method but Its is not working according expectation ..
Here is Employee class code ....
[KnownType(typeof(FullTimeEmployee))]
[KnownType(typeof(PartTimeEmployee))]
[DataContract(Namespace = "http://pragimtech.com/Employee")]
public class Employee
{
private int _id;
private string _name;
private string _gender;
private DateTime _dateOfBirth;
[DataMember(Order = 1)]
public int Id
{
get { return _id; }
set { _id = value; }
}
[DataMember(Order = 2)]
public string Name
{
get { return _name; }
set { _name = value; }
}
[DataMember(Order = 3)]
public string Gender
{
get { return _gender; }
set { _gender = value; }
}
[DataMember(Order = 4)]
public DateTime DateOfBirth
{
get { return _dateOfBirth; }
set { _dateOfBirth = value; }
}
[DataMember(Order = 5)]
public EmployeeType Type { get; set; }
}
[DataContract(Name = "EmployeeType")]
public enum EmployeeType
{
[EnumMember]
FullTimeEmployee = 1,
[EnumMember]
PartTimeEmployee = 2
}
}
Here is my Full time and part time employee class inherit from Employee class...
public class FullTimeEmployee : Employee
{
public int AnnualSalary { get; set; }
}
public class PartTimeEmployee : Employee
{
public int HourlyPay { get; set; }
public int HoursWorked { get; set; }
}
Here is Method to Get Employee method to access employee based on employee type...
public Employee GetEmployee(int Id)
{
Employee employee = null;
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spGetEmployee1", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter parameterId = new SqlParameter();
parameterId.ParameterName = "#EmployeeType";
parameterId.Value = Id;
cmd.Parameters.Add(parameterId);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
if ((EmployeeType)reader["EmployeeType"] == EmployeeType.FullTimeEmployee)
{
return employee;
} }
else if ((EmployeeType)reader["EmployeeType"] == EmployeeType.PartTimeEmployee)
{
return employee;
}
}
}
return employee;
}
Here is my Windows Form Application ......
private void button1_Click(object sender, EventArgs e)
{
MyService.HalifaxServiceClient myservice = new MyService.HalifaxServiceClient("NetTcpBinding_IHalifaxService");
MyService.Employee employee = myservice.GetEmployee(Convert.ToInt32(txt1.Text));
MyService.FullTimeEmployee ft = new MyService.FullTimeEmployee();
if (employee == myservice.GetEmployee(Convert.ToInt32(txt1.Text).CompareTo(employee.Type)))
{
FulltimeEmployeeLinkActivites();
}
else if (employee == myservice.GetEmployee(Convert.ToInt32(txt1.Text).CompareTo(employee.Type)))
{
PartTimeEmployeeActivities();
}
else
{
label4.Text = "No infomation found";
}
}
Here is screen shot when I run the application ...
The problem I see with your if / else is that the conditional statements are exactly the same. One way that you can branch based on the type of an object is with the is keyword.
if (employee is FullTimeEmployee)
{
FulltimeEmployeeLinkActivites();
}
else if (employee is PartTimeEmployee)
{
PartTimeEmployeeActivities();
}
else
{
label4.Text = "No information found";
}
I would also add that this is not necessarily best practice, however it should get you what you are asking for.
In addition to that, your method that returns the employee instance never returns an employee of a valid type. It doesn't appear that the GetEmployee method ever instantiates an employee instance. It looks like it is always returning null. Try returning instances of the proper type. You will also need to populate the instances with the data you need.
if ((EmployeeType)reader["EmployeeType"] == EmployeeType.FullTimeEmployee)
{
return new FullTimeEmployee();
}
else if ((EmployeeType)reader["EmployeeType"] == EmployeeType.PartTimeEmployee)
{
return new PartTimeEmployee();
}
You have a confusing naming in your elements and "employee" class does not seems to be populated in your data reader.
"FullTimeEmployee" is the name one of your classes and also the name of one of your enums. So is not safe to set your condition
(EmployeeType)reader["EmployeeType"] == EmployeeType.FullTimeEmployee
I can not be sure without the code of your spGetEmployee, but if it returns values from your table with those same names it could be safer to declare
while(reader.Read())
{
employee= new employee();
employee.Id= reader.GetInt32(0);
employee.Name= reader.GetString(1);
...
employee.EmployeeType=(EmployeeType)reader.GetInt32(4);
if(employee.EmployeeType== EmployeeType.FullTimeEmployee)
{
//Do extra work for this type of employee
...
return employee;
}
}
I want to update some information when a save button is clicked.
I got an error
On : command.Parameters.Add("#doctorID", SqlDbType.Int).Value =
resident.Doctor.DoctorID; Saying: Object reference not set to an
instance of an object.
Im guessing I need to create some kind of object?
Button code:
private void btnSave_Click(object sender, RoutedEventArgs e)
{
Resident hello = new Resident();
hello.Doctor = new Doctor();
Resident residentID;
txtAdditionalInformation.Text = hello.addtionalInformation;
txtForename.Text = hello.FirstName;
txtSurname.Text = hello.Surname;
txtTitle.Text = hello.Title;
ResidentData.Update(hello);
}
update code (ResidentData Class):
public static void Update(Resident resident, SqlConnection connection, SqlTransaction transaction)
{
StringBuilder sqlString = new StringBuilder();
SqlCommand command;
sqlString.Append("UPDATE [Resident] SET ");
sqlString.Append("title = #title, ");
sqlString.Append("firstName = #firstName, ");
sqlString.Append("surname = #surname, ");
sqlString.Append("dateOfBirth = #dateOfBirth, ");
sqlString.Append("photo = #photo, ");
sqlString.Append("doctorID = #doctorID, ");
sqlString.Append("roomID = #roomID, ");
sqlString.Append("allergies = #allergies, ");
sqlString.Append("additionalInformation = #additionalInformation ");
sqlString.Append("WHERE residentID = #residentID ");
command = new SqlCommand(sqlString.ToString(), connection);
if ((transaction != null)) command.Transaction = transaction;
command.Parameters.Add("#residentID", SqlDbType.Int).Value = resident.ResidentID;
command.Parameters.Add("#title", SqlDbType.VarChar, 50).Value = Helper.GetValue(resident.Title);
command.Parameters.Add("#firstName", SqlDbType.VarChar, 100).Value = Helper.GetValue(resident.FirstName);
command.Parameters.Add("#surname", SqlDbType.VarChar, 100).Value = Helper.GetValue(resident.Surname);
command.Parameters.Add("#dateOfBirth", SqlDbType.DateTime).Value = Helper.GetValue(resident.DateOfBirth);
command.Parameters.Add("#photo", SqlDbType.Image, 2147483647).Value = Helper.GetValue(resident.Photo);
command.Parameters.Add("#doctorID", SqlDbType.Int).Value = resident.Doctor.DoctorID;
command.Parameters.Add("#roomID", SqlDbType.Int).Value = resident.Room.RoomID;
command.Parameters.Add("#allergies", SqlDbType.NText).Value = resident.Allergies;
command.Parameters.Add("#additionalInformation", SqlDbType.NText).Value = resident.addtionalInformation;
int rowsAffected = command.ExecuteNonQuery();
if (!(rowsAffected == 1))
{
throw new Exception("An error has occurred while updating Resident details.");
}
}
*Residence Class:
{
public class Resident
{
private int residentID;
private string title;
private string firstName;
private string surname;
private string searchText;
private System.DateTime dateOfBirth;
private byte[] photo;
private Room room;
private Doctor doctor;
private string nhs;
private string residentBarcode;
private string allergies;
private string additionalInformation;
public Resident()
: base()
{
}
public Resident(int newResidentID, string newTitle, string newFirstName, string newSurname, string newSearchText, System.DateTime newDateOfBirth, byte[] newPhoto, Room newRoom, Doctor newDoctor, string newNhs, string newResidentBarcode, string newAllergies, string newAdditionalInformation)
: base()
{
residentID = newResidentID;
title = newTitle;
firstName = newFirstName;
surname = newSurname;
searchText = newSearchText;
dateOfBirth = newDateOfBirth;
photo = newPhoto;
room= newRoom;
doctor = newDoctor;
nhs = newNhs;
residentBarcode = newResidentBarcode;
allergies = newAllergies;
additionalInformation = newAdditionalInformation;
}
public int ResidentID
{
get { return residentID; }
set { residentID = value; }
}
public string Title
{
get { return title; }
set { title = value; }
}
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
public string Surname
{
get { return surname; }
set { surname = value; }
}
public string SearchText
{
get { return searchText; }
set { searchText = value; }
}
public System.DateTime DateOfBirth
{
get { return dateOfBirth; }
set { dateOfBirth = value; }
}
public byte[] Photo
{
get { return photo; }
set { photo = value; }
}
public Room Room
{
get { return room; }
set { room = value; }
}
public Doctor Doctor
{
get { return doctor; }
set { doctor = value; }
}
public string NHS
{
get { return nhs; }
set { nhs = value; }
}
public string ResidentBarcode
{
get { return residentBarcode; }
set { residentBarcode = value; }
}
public string Allergies
{
get { return allergies; }
set { allergies = value; }
}
public string addtionalInformation{
get { return additionalInformation; }
set { additionalInformation = value; }
}
}
}
Looking at the way you've created your Resident:
Resident hello = new Resident();
ucMedicationCheckIn.SaveCheckedInMedication();
ResidentData.Update(hello);
ucMedicationCheckIn.HideDetails();
you probably haven't assigned it a doctor which is why it fails on this line:
command.Parameters.Add("#doctorID", SqlDbType.Int).Value = resident.Doctor.DoctorID;
You need to initialize the Doctor type
Edit*
After seeing your Resident class I can see that you haven't initialized Room either.
You could provide a constructor to initialize these to default values:
public Resident()
{
this.Doctor = new Doctor();
this.Room = new Room();
//etc...
}
Though to do anything meaningful you will probably want to set these up with actual data before saving.
That is because your Doctor and Room are not initialized anyhere:
Resident hello = new Resident();
hello.Doctor = new Doctor();
hello.Room = new Room();
but that update will probably fail as there is no meaningful data in resident and rowsAffected will return 0 probably.
I am facing problem while i am inserting new record from GUI part to database table. I have created database table Patient with id, name, age etc....id is identity primary key. My problem is while i am inserting duplicate name in table the control should go to else part, and display the message like...This name is already exits, pls try with another name...
but in my coding not getting..... Here is all the code...pls somebody point me out whats wrong or how do this???
GUILayer:
protected void BtnSubmit_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
return;
int intResult = 0;
string name = TxtName.Text.Trim();
int age = Convert.ToInt32(TxtAge.Text);
string gender;
if (RadioButtonMale.Checked)
{
gender = RadioButtonMale.Text;
}
else
{
gender = RadioButtonFemale.Text;
}
string city = DropDownListCity.SelectedItem.Value;
string typeofdisease = "";
foreach (ListItem li in CheckBoxListDisease.Items)
{
if (li.Selected)
{
typeofdisease += li.Value;
}
}
typeofdisease = typeofdisease.TrimEnd();
PatientBAL PB = new PatientBAL();
PatientProperty obj = new PatientProperty();
obj.Name = name;
obj.Age = age;
obj.Gender = gender;
obj.City = city;
obj.TypeOFDisease = typeofdisease;
try
{
intResult = PB.ADDPatient(obj);
if (intResult > 0)
{
lblMessage.Text = "New record inserted successfully.";
TxtName.Text = string.Empty;
TxtAge.Text = string.Empty;
RadioButtonMale.Enabled = false;
RadioButtonFemale.Enabled = false;
DropDownListCity.SelectedIndex = 0;
CheckBoxListDisease.SelectedIndex = 0;
}
else
{
lblMessage.Text = "Name [<b>" + TxtName.Text + "</b>] alredy exists, try another name";
}
}
catch (Exception ex)
{
lblMessage.Text = ex.Message.ToString();
}
finally
{
obj = null;
PB = null;
}
}
BAL layer:
public class PatientBAL
{
public int ADDPatient(PatientProperty obj)
{
PatientDAL pdl = new PatientDAL();
try
{
return pdl.InsertData(obj);
}
catch
{
throw;
}
finally
{
pdl=null;
}
}
}
DAL layer:
public class PatientDAL
{
public string ConString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
public int InsertData(PatientProperty obj)
{
SqlConnection con = new SqlConnection(ConString);
con.Open();
SqlCommand com = new SqlCommand("LoadData",con);
com.CommandType = CommandType.StoredProcedure;
try
{
com.Parameters.AddWithValue("#Name", obj.Name);
com.Parameters.AddWithValue("#Age",obj.Age);
com.Parameters.AddWithValue("#Gender",obj.Gender);
com.Parameters.AddWithValue("#City", obj.City);
com.Parameters.AddWithValue("#TypeOfDisease", obj.TypeOFDisease);
return com.ExecuteNonQuery();
}
catch
{
throw;
}
finally
{
com.Dispose();
con.Close();
}
}
}
Property Class:
public class PatientProperty
{
private string name;
private int age;
private string gender;
private string city;
private string typedisease;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public int Age
{
get
{
return age;
}
set
{
age = value;
}
}
public string Gender
{
get
{
return gender;
}
set
{
gender = value;
}
}
public string City
{
get
{
return city;
}
set
{
city = value;
}
}
public string TypeOFDisease
{
get
{
return typedisease;
}
set
{
typedisease = value;
}
}
}
This is my stored Procedure:
CREATE PROCEDURE LoadData
(
#Name varchar(50),
#Age int,
#Gender char(10),
#City char(10),
#TypeofDisease varchar(50)
)
as
insert into Patient(Name, Age, Gender, City, TypeOfDisease)values(#Name,#Age, #Gender, #City, #TypeofDisease)
GO
Are you sure your LoadData stored proc is doing an insert instead of an update?
looks like your throwing the error, so it jumps down to your catch block.
You'll need to handle the error coming back from PB.ADDPatient and not the value
Does the record duplicated in the database? I am afraid you did not add the unique constraint for Names in the database!
If this is the case, and you are using SQL Server, check this:
SQL Server 2005 How Create a Unique Constraint?