I am consuming a WCF service in a Windows Forms application. My WCF service has two classes called FulltimeEmployee and ParttimeEmployee. I want to register users into Sql database by using Wcf Service with Windows Fomr Application based on employee type. The user type will come from emu type but I can not compile it and showing following errors ...
Non-invocable member 'EmployeeType.FullTimeEmployee' cannot be used like a method. HalifaxWindowsFormsApplication C:\Users\Khundokar Nirjor\Documents\Visual Studio 2015\Projects\HalifaxWindowsFormsApplication\HalifaxWindowsFormsApplication\ADDEMPLOYEE.cs 38 Active
as shown in the screen shot.
Here is Code for FullTime and PartTime Employee Class..
[DataContract]
public class FullTimeEmployee : Employee
{
public int AnnualSalary { get; set; }
}
[DataContract]
public class PartTimeEmployee : Employee
{
public int HourlyPay { get; set; }
public int HoursWorked { get; set; }
}
Here is the code form class..
[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; }
}
public enum EmployeeType
{
FullTimeEmployee = 1,
PartTimeEmployee = 2
}
}
Here is WCF service code to register employee based on type:
public void SaveEmployee(Employee employee)
{
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spSaveEmployee", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter parameterId = new SqlParameter
{
ParameterName = "#Id",
Value = employee.Id
};
cmd.Parameters.Add(parameterId);
SqlParameter parameterName = new SqlParameter
{
ParameterName = "#Name",
Value = employee.Name
};
cmd.Parameters.Add(parameterName);
SqlParameter parameterGender = new SqlParameter
{
ParameterName = "#Gender",
Value = employee.Gender
};
cmd.Parameters.Add(parameterGender);
SqlParameter parameterDateOfBirth = new SqlParameter
{
ParameterName = "#DateOfBirth",
Value = employee.DateOfBirth
};
cmd.Parameters.Add(parameterDateOfBirth);
SqlParameter parameterEmployeeType = new SqlParameter
{
ParameterName = "#EmployeeType",
Value = employee.Type
};
cmd.Parameters.Add(parameterEmployeeType);
if (employee.GetType() == typeof(FullTimeEmployee))
{
SqlParameter parameterAnnualSalary = new SqlParameter
{
ParameterName = "#AnnualSalary",
Value = ((FullTimeEmployee)employee).AnnualSalary
};
cmd.Parameters.Add(parameterAnnualSalary);
}
else
{
SqlParameter parameterHourlyPay = new SqlParameter
{
ParameterName = "#HourlyPay",
Value = ((PartTimeEmployee)employee).HourlyPay,
};
cmd.Parameters.Add(parameterHourlyPay);
SqlParameter parameterHoursWorked = new SqlParameter
{
ParameterName = "#HoursWorked",
Value = ((PartTimeEmployee)employee).HoursWorked
};
cmd.Parameters.Add(parameterHoursWorked);
}
con.Open();
cmd.ExecuteNonQuery();
}
}
Here is the Windows Form application code:
private void button1_Click(object sender, EventArgs e)
{
MyService.HalifaxServiceClient myservice = new MyService.HalifaxServiceClient("NetTcpBinding_IHalifaxService");
MyService.Employee employee = null;
if (((MyService.EmployeeType)Convert.ToInt32(comboBox2.SelectedValue)) == MyService.EmployeeType.FullTimeEmployee)
{
employee = new MyService.FullTimeEmployee
{
Id = Convert.ToInt32(textBox1.Text),
Name = txtName.Text,
Gender = comboBox1.Text,
DateOfBirth = Convert.ToDateTime(txtDateOfBirth.Text),
Type = MyService.EmployeeType.FullTimeEmployee(comboBox2.SelectedValue),//Error
AnnualSalary = Convert.ToInt32(txtAnnualSalary.Text),
};
myservice.SaveEmployee(employee);
label8.Text = "Employee saved";
}
else if (((MyService.EmployeeType)Convert.ToInt32(comboBox2.SelectedValue)) == MyService.EmployeeType.PartTimeEmployee)
{
employee = new MyService.PartTimeEmployee
{
Id = Convert.ToInt32(textBox1.Text),
Name = txtName.Text,
Gender = comboBox1.Text,
DateOfBirth = Convert.ToDateTime(txtDateOfBirth.Text),
Type = MyService.EmployeeType.PartTimeEmployee(comboBox2.SelectedValue),//Error
HourlyPay = Convert.ToInt32(txtHourlyPay.Text),
HoursWorked = Convert.ToInt32(txtHoursWorked.Text),
};
myservice.SaveEmployee(employee);
label8.Text = "Employee saved";
}
else
{
label8.Text = "Please select Employee Type";
}
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox2.Text == "FullTimeEmployee")
{
txtHourlyPay.Visible = false;
txtHoursWorked.Visible = false;
label6.Visible = false;
label7.Visible = false;
}
else if (comboBox2.Text == "PartTimeEmployee")
{
txtHourlyPay.Visible = true;
txtHoursWorked.Visible = true;
label6.Visible = true;
label7.Visible = true;
}
}
When I click the submit button its shows the error message
and does not insert a new employee into SQL Server database..
Here is screenshot of output:
Please help me to correct this error ...
You'll need to mark your enum with [DataContract] attribute and each enum value with [EnumMember] attribute like this. I also noticed that you've got your enum members as knowntypes on the Employee data contract and not the enum itself.
[DataContract]
public class Car
{
[DataMember]
public string model;
[DataMember]
public CarConditionEnum condition;
}
[DataContract(Name = "CarCondition")]
public enum CarConditionEnum
{
[EnumMember]
New,
[EnumMember]
Used,
[EnumMember]
Rental,
Broken,
Stolen
}
For more information checkout this link
Edit: Here's what you're looking for. You should try something like:
Type = (MyService.EmployeeType) Enum.Parse(typeof(MyService.EmployeeType), comboBox2.SelectedText);
Related
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 am working on a wcf service that connects to database. I had debugged and tested my operation playerregistration and clubregistration. I then tried to test the get functions but i received the error:
Error 1 'WebApplication1.ADOService' does not implement interface member 'WebApplication1.IADOService.newMembership(WebApplication1.playerDetails, WebApplication1.playerDetails, WebApplication1.clubDetails, WebApplication1.memberDetails)' C:\Users\Daniel\Documents\Visual Studio 2013\Projects\Prac4\WebApplication1\ADOService.svc.cs 14 18 WebApplication1
following the error I attempted to remove the get functions however the error remains. Below is the service code
public class ADOService : IADOService
{
public string playerRegistration(playerDetails playerInfo)
{
string Message;
using (SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=c:\\Users\\Daniel\\documents\\visual studio 2013\\Projects\\Prac4\\WebApplication1\\App_Data\\ADODatabase.mdf;Integrated Security=True"))
{
conn.Open();
using (var cmd = new SqlCommand("INSERT into Player(pid, pfname, plname, pphone, paddress, pdob) VALUES (#pid, #pfname, #plname, #pphone, #paddress, #pdob)", conn))
{
cmd.Parameters.AddWithValue("#pid", playerInfo.Pid);
cmd.Parameters.AddWithValue("#pfname", playerInfo.Pfname);
cmd.Parameters.AddWithValue("#plname", playerInfo.Plname);
cmd.Parameters.AddWithValue("#pphone", playerInfo.Pphone);
cmd.Parameters.AddWithValue("#paddress", playerInfo.Paddress);
cmd.Parameters.AddWithValue("#pdob", playerInfo.Pdob);
int result = cmd.ExecuteNonQuery();
if (result == 1)
{
Message = playerInfo.Pid + " Details inserted successfully";
}
else
{
Message = playerInfo.Pid + " Details not inserted successfully";
}
conn.Close();
return Message;
}
}
}
public string clubRegistration(clubDetails clubInfo)
{
string Message;
using (SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=c:\\Users\\Daniel\\documents\\visual studio 2013\\Projects\\Prac4\\WebApplication1\\App_Data\\ADODatabase.mdf;Integrated Security=True"))
{
conn.Open();
using (var cmd = new SqlCommand("INSERT into Club(cid, cname, cfounded, cworldranking) VALUES (#cid, #cname, #cfounded, #cworldranking)", conn))
{
cmd.Parameters.AddWithValue("#cid", clubInfo.Cid);
cmd.Parameters.AddWithValue("#cname", clubInfo.Cname);
cmd.Parameters.AddWithValue("#cfounded", clubInfo.Cfounded);
cmd.Parameters.AddWithValue("#cworldranking", clubInfo.Cworldranking);
int result = cmd.ExecuteNonQuery();
if (result == 1)
{
Message = clubInfo.Cname + " Details inserted successfully";
}
else
{
Message = clubInfo.Cname + " Details not inserted successfully";
}
conn.Close();
return Message;
}
}
}
public List<playerDetails> getplayerInfo(string pfname, string plname)
{
List<playerDetails> playerDetails = new List<playerDetails>();
{
using (SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=c:\\Users\\Daniel\\documents\\visual studio 2013\\Projects\\Prac4\\WebApplication1\\App_Data\\ADODatabase.mdf;Integrated Security=True"))
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Player WHERE pfname LIKE '%'+#pfname+'%' AND plname LIKE '%'+#plname+'%'", conn);
cmd.Parameters.AddWithValue("#pfname", pfname);
cmd.Parameters.AddWithValue("#plname", plname);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
playerDetails playerInfo = new playerDetails();
playerInfo.Pid = Convert.ToInt32(dt.Rows[i]["Pid"].ToString());
playerInfo.Pfname = dt.Rows[i]["Pfname"].ToString();
playerInfo.Plname = dt.Rows[i]["Plname"].ToString();
playerInfo.Pphone = Convert.ToInt32(dt.Rows[i]["Pphone"].ToString());
playerInfo.Paddress = dt.Rows[i]["Paddress"].ToString();
playerInfo.Pdob = DateTime.Parse(dt.Rows[i]["Pdob"].ToString());
playerDetails.Add(playerInfo);
}
}
conn.Close();
}
return playerDetails;
}
}
public List<clubDetails> getclubInfo(string cname)
{
List<clubDetails> clubDetails = new List<clubDetails>();
{
using (SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=c:\\Users\\Daniel\\documents\\visual studio 2013\\Projects\\Prac4\\WebApplication1\\App_Data\\ADODatabase.mdf;Integrated Security=True"))
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Player WHERE cname LIKE '%'+#cname+'%'", conn);
cmd.Parameters.AddWithValue("#cname", cname);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
clubDetails clubInfo = new clubDetails();
clubInfo.Cid = Convert.ToInt32(dt.Rows[i]["Cid"].ToString());
clubInfo.Cname = dt.Rows[i]["Cname"].ToString();
clubInfo.Cfounded = DateTime.Parse(dt.Rows[i]["Cfounded"].ToString());
clubInfo.Cworldranking = Convert.ToInt32(dt.Rows[i]["Cworldranking"].ToString());
clubDetails.Add(clubInfo);
}
}
conn.Close();
}
return clubDetails;
}
}}}
And Iservice code
[ServiceContract]
public interface IADOService
{
[OperationContract]
string playerRegistration(playerDetails playerInfo);
[OperationContract]
string clubRegistration(clubDetails clubInfo);
[OperationContract]
List<playerDetails> getplayerInfo(string pfname, string plname);
[OperationContract]
List<clubDetails> getclubInfo(string cname);
[OperationContract]
string newMembership(playerDetails pfname, playerDetails plname, clubDetails cname, memberDetails memberstart);
}
[DataContract]
public class playerDetails
{
int pid;
string pfname;
string plname;
int pphone;
string paddress;
DateTime pdob;
[DataMember]
public int Pid
{
get { return pid; }
set { pid = value; }
}
[DataMember]
public string Pfname
{
get { return pfname; }
set { pfname = value; }
}
[DataMember]
public string Plname
{
get { return plname; }
set { plname = value; }
}
[DataMember]
public int Pphone
{
get { return pphone; }
set { pphone = value; }
}
[DataMember]
public string Paddress
{
get { return paddress; }
set { paddress = value; }
}
[DataMember]
public DateTime Pdob
{
get { return pdob; }
set { pdob = value; }
}
}
[DataContract]
public class clubDetails
{
int cid;
string cname;
DateTime cfounded;
int cworldranking;
[DataMember]
public int Cid
{
get { return cid; }
set { cid = value; }
}
[DataMember]
public string Cname
{
get { return cname; }
set { cname = value; }
}
[DataMember]
public DateTime Cfounded
{
get { return cfounded; }
set { cfounded = value; }
}
[DataMember]
public int Cworldranking
{
get { return cworldranking; }
set { cworldranking = value; }
}
}
[DataContract]
public class memberDetails
{
int mid;
DateTime memberstart;
DateTime memberend;
int gamesplayed;
[DataMember]
public int Mid
{
get { return mid; }
set { mid = value; }
}
[DataMember]
public DateTime Memberstart
{
get { return memberstart; }
set { memberstart = value; }
}
[DataMember]
public DateTime Memberend
{
get { return memberend; }
set { memberend = value; }
}
[DataMember]
public int Gamesplayed
{
get { return gamesplayed; }
set { gamesplayed = value; }
}
}
}
I am assuming that the get functions are the cause of the problem but not sure how to address the error.
You've defined the following methods in your interface:
string playerRegistration(playerDetails playerInfo);
string clubRegistration(clubDetails clubInfo);
List<playerDetails> getplayerInfo(string pfname, string plname);
List<clubDetails> getclubInfo(string cname);
string newMembership(playerDetails pfname, playerDetails plname, clubDetails cname, memberDetails memberstart);
But only implemented four of them:
playerRegistration
clubRegistration
getplayerInfo
getclubInfo
You haven't actually implemented newMembership in the ADOService class.
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 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).
I am writing code in C# where I want to select data in datagrid from multiple tables with a relation... Here I have a Client & Item_Configuration as parent table and Item_Order as child table which has the foreign keys from Client and Item_Configuration, I just want to fetch data from all three tables and display on a datagrid
My stored procedure is:
ALTER PROC [dbo].[Full_SP]
#clientName varchar(50) = null,
#itemName varchar(50) = null,
#clientId_FK varchar(50) = null,
#operation int
AS
BEGIN
SET NOCOUNT ON;
if #operation = 2
BEGIN
SELECT
Client.clintName, Item_Configuration.itemName,
Item_Order.orderId, Item_Order.orderDate, Item_Order.quantity,
Item_Order.status, Item_Order.totalPrice
FROM
Item_Order
INNER JOIN
Client ON Item_Order.clintId_FK = Client.clientId
JOIN
Item_Configuration ON Item_Order.itemId_FK = Item_Configuration.itemId
END
END
And my function of search to data grid is in C# i.e.
private void btnSrchFull_Click(object sender, EventArgs e)
{
SqlConnection conn1 = new SqlConnection();
try
{
conn1.ConnectionString = "server=.\\ms2k5;database=Info_Connect;Trusted_Connection=true";
conn1.Open();
SqlCommand selectFull = new SqlCommand("Full_SP", conn1);
selectFull.CommandType = CommandType.StoredProcedure;
selectFull.Parameters.Add("#operation", SqlDbType.VarChar);
selectFull.Parameters["#operation"].Value = 2;
SqlDataReader myReader = selectFull.ExecuteReader();
List<FullFill> list = new List<FullFill>();
while (myReader.Read())
{
if (myReader.HasRows)
{
FullFill fullfill = new FullFill();
fullfill = MapFullfill(myReader, fullfill);
list.Add(fullfill);
}
}
myReader.NextResult();
foreach (FullFill ffll in list)
{
if (myReader.Read() && myReader.HasRows)
{
MapClient(myReader, ffll);
}
}
myReader.NextResult();
foreach (FullFill ffll1 in list)
{
if (myReader.Read() && myReader.HasRows)
{
MapItem(myReader, ffll1);
}
}
dataGridView1.DataSource = list;
double totPrice = 0;
for (int i = 0; i < dataGridView1.RowCount; i++)
{
totPrice = totPrice +
Convert.ToDouble(dataGridView1.Rows[i].Cells[5].Value);
totCost.Text = totPrice.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace + MessageBoxIcon.Error);
}
finally
{
if (conn1.State != ConnectionState.Closed)
{
conn1.Close();
}
}
}
private FullFill MapItem(SqlDataReader myReader, FullFill itemName)
{
itemName.ItemName =myReader["itemName"].ToString();
return itemName;
}
private FullFill MapClient(SqlDataReader myReader, FullFill clientName)
{
clientName.ClientName = myReader["clientName"].ToString();
return clientName;
}
private FullFill MapFullfill(SqlDataReader myReader, FullFill fullfill)
{
fullfill.OrderNo = myReader["orderId"].ToString();
fullfill.OrderDate = Convert.ToDateTime(myReader["orderDate"]);
fullfill.Quantity = Convert.ToInt32(myReader["quantity"]);
fullfill.Status = myReader["status"].ToString();
fullfill.TotalPrice = Convert.ToDouble(myReader["totalPrice"]);
return fullfill;
}
and I created a class for property i.e.
class FullFill
{
public string orderNo;
public string clientName;
public DateTime orderDate;
public string itemName;
public int quantity;
public double totCost;
public string status;
public string OrderNo { get { return orderNo; } set { orderNo = value; } }
public string ClientName { get { return clientName; } set { clientName = value; } }
public DateTime OrderDate { get { return orderDate; } set { orderDate = value; } }
public string ItemName { get { return itemName; } set { itemName = value; } }
public int Quantity { get { return quantity; } set { quantity = value; } }
public double TotalPrice { get { return totCost; } set { totCost = value; } }
public string Status { get { return status; } set { status = value; } }
}
}
The problem is that I am only able to find data from child table(Item_Order) I am not getting data from parent Tables.