I am trying to create a web service for updating a simple database table. I have an update method which takes a parameter an object of type Employee. I have included a reference of namespace where Employee class belongs. For a reason that I can't understand I receive the following error:
Inconsistent accessibility: parameter type 'EmployeeDBApplication.Employee' is less accessible than method 'EmployeeStoreWS.EmployeeStoreService.update(EmployeeDBApplication.Employee)'
class Employee
{
private int id;
public int Id
{
get { return id; }
set { id = value; }
}
private double salary;
public double Salary
{
get { return salary; }
set { salary = value; }
}
private string address;
public string Address
{
get { return address; }
set { address = value; }
}
private string firstname;
public string Firstname
{
get { return firstname; }
set { firstname = value; }
}
private string lastname;
public string Lastname
{
get { return lastname; }
set { lastname = value; }
}
public override string ToString() {
string x;
x = "Employee ID:" + this.id + "\tName:" + this.firstname + "\t" + this.lastname + "\n\tSalary:" + this.salary + "\t Address:" + this.address;
return x;
}
}
And the web service:
public class EmployeeStoreService : System.Web.Services.WebService
{
//id int(11) NO PRI 0
//firstname varchar(255) YES
//lastname varchar(255) YES
//address varchar(255) YES
//salary double YES
[WebMethod]
public MySqlConnection getConnection()
{
return new MySqlConnection("Database=sakila;Data Source=localhost;User Id=root;Password=george 01");
}
[WebMethod]
public void update(Employee employee)
{
MySqlConnection connection = null;
try
{
connection = getConnection();
connection.Open();
MySqlCommand myCommand = new MySqlCommand("UPDATE employee SET (?id,?firstname,?lastname,?address,?salary) WHERE employee.id = ?id");
myCommand.Prepare();
myCommand.Parameters.AddWithValue("?id", employee.Id);
myCommand.Parameters.AddWithValue("?firstname", employee.Firstname);
myCommand.Parameters.AddWithValue("?lastname", employee.Lastname);
myCommand.Parameters.AddWithValue("?address", employee.Address);
myCommand.Parameters.AddWithValue("?salary", employee.Salary);
myCommand.ExecuteNonQuery();
connection.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if (connection != null)
connection.Close();
}
}
}
You need to make your class public.
public class Employee
It's complaining that some of your class members are public while the class itself is not. classes are Internal by default
Try changing this
class Employee
{
private int id;
//...
To this
public class Employee
{
private int id;
//...
Unless you have a specific reason not to, define Employee as public.
Your update method is public where as your class is internal. hence the message. When you dont specify an access modifier, it is internal.
Related
I am trying to create a class that contains a header for my list-box. I have two classes that I will be inserting in the listbox. The first class runs fine, but the second one I am making so that the array is entirely of strings is telling me that a method must have a value return type. What does this mean exactly? The error at hand is "HeaderItems."
namespace RETAILITEMSBLAKE
{
class HeaderClass
{
string HeaderDescription;
string HeaderPrice;
string HeaderUnitsonHand;
public HeaderItems(string HeaderDescription, string HeaderUnitsonHand, string HeaderPrice)
{
this.HeaderDescription = HeaderDescription;
this.HeaderUnitsonHand = HeaderUnitsonHand;
this.HeaderPrice = HeaderPrice;
}
public string HeaderDescriptions
{
get
{
return HeaderDescription;
}
set
{
HeaderDescription = value;
}
}
public string HeaderUnits
{
get
{
return HeaderUnitsonHand;
}
set
{
HeaderUnitsonHand = value;
}
}
public string HeaderPrices
{
get
{
return HeaderPrice;
}
set
{
HeaderPrice = value;
}
}
}
Here is my first class that is working correctly:
namespace RETAILitemsBLAKE
{
class ItemizedClass
{
string description;
int unitsonhand;
double price;
public ItemizedClass(string description,int unitsonhand,double price)
{
this.description = description;
this.unitsonhand = unitsonhand;
this.price = price;
}
public string Description
{
get
{
return description;
}
set
{
description = value;
}
}
public double Price
{
get
{
return price;
}
set
{
price = value;
}
}
public int Quantity
{
get
{
return unitsonhand;
}
set
{
unitsonhand = value;
}
}
}
}
So, my goal is to have the HeaderClass so that I can place them as headers in my Listbox. Is there an alternate way to do such? I want to place it on top of the code here:
namespace RETAILitemsBLAKE
{
public partial class FrmItemList : Form
{
ItemizedClass[] items;
public FrmItemList()
{
InitializeComponent();
ItemizedArray();
}
private void ItemizedArray()
{
ItemizedClass jackets = new ItemizedClass("Jackets", 12, 59.95);
ItemizedClass jeans = new ItemizedClass("Jeans", 40, 34.95);
ItemizedClass shirts = new ItemizedClass("Shirts", 20, 24.95);
items = new ItemizedClass[] { jackets, jeans, shirts };
foreach (ItemizedClass RetailData in items)
{
lstRetailitems.Items.Add(RetailData.Description + "\t\t" + RetailData.Quantity + "\t" + "$" + RetailData.Price);
}
}
}
}
Would anyone be of assistance? Thank you!
You are using construct method which needs as same as class name and it didn't need to set return data type, so the method name needs to write HeaderClass in HeaderClass class otherwise it needs to set return data type to be a normal method.
class HeaderClass
{
string HeaderDescription;
string HeaderPrice;
string HeaderUnitsonHand;
public HeaderClass(string HeaderDescription, string HeaderUnitsonHand, string HeaderPrice)
I have a problem with a class that I wrote. When I try to call it I get an exception. See the code below for more clarity.
I have the class:
using System;
using System.Data;
namespace People
{
class Person
{
// Auto prop + field
public string Name
{
get { return this.Name; }
private set
{
if (string.IsNullOrEmpty(value))
{
throw new NoNullAllowedException("Name is mandatory");
}
else
{
this.Name = value;
}
}
}
// Auto prop + field
public int Age
{
get { return this.Age; }
private set
{
if (value <= 0 || value > 100)
{
throw new Exception("Age must be between 1 and 100");
}
else
{
this.Age = value;
}
}
}
// Auto prop + field
public string Email
{
get { return this.Email; }
private set { this.Email = value; }
}
// Constructor 1
public Person(string name, int age, string email)
{
this.Name = name;
this.Age = age;
this.Email = email;
}
// Constructor 2
public Person(string name, int age) : this(name,age,"")
{
}
// Write to console
public override string ToString()
{
return string.Format("Name: {0} \nAge: {1} \nEmail: {2}" ,Name,Age,Email);
}
}
}
And when I call this class:
Person someone = new Person("First Someone",51,"someone#gmail.com");
Console.WriteLine(someone);
I get:
Process is terminated due to StackOverflowException.
I can't see the problem.
Thank you in advance.
The problem is that when you try to get or set any of the properties, say, Name, there is a code path that calls the setter of the same property:
public string Name
{
get { return this.Name; } // <<<<====== HERE
private set
{
if (string.IsNullOrEmpty(value))
{
throw new NoNullAllowedException("Name is mandatory");
}
else
{
this.Name = value; // <<<<==== HERE
}
}
}
this.Name means "call getter/setter of Name with the value of value". This creates infinite recursion, causing stack overflow.
To implement properties with conditions like that you need to define fields that store the actual data. A common approach is to make these fields private, and name them with the same name as the property, except the first letter should not be capitalized:
private string name; // <<<<==== Add this
public string Name
{
get { return name; } // <<<<====== change
private set
{
if (string.IsNullOrEmpty(value))
{
throw new NoNullAllowedException("Name is mandatory");
}
else
{
name = value; // <<<<==== change
}
}
}
change
get { return this.Name; }
to
get;
the same goes for the Age property.
This is because this.Name is using the get method you are overriding, thus creating the glorious StackOverflowException! If you need a field for name and age you have to create one yourself like:
private string name;
public string Name
{
get { return this.name; }
private set
{
if (string.IsNullOrEmpty(value))
{
throw new NoNullAllowedException("Name is mandatory");
}
else
{
this.name = value;
}
}
}
Trying to learn to program and once again losing all confidence because I think I've internalised a simple concept but something seemingly extraordinary is happening or it is just flying right over my head.
When I run the program I get a StackOverFlowException if I access the property by assigning a string to FirstName or SecondName
My Customer Class:
class Customer : ICustomer
{
public string FirstName
{
get
{
return FirstName;
}
set
{
FirstName = value;
}
}
public string fName
{
get
{
return fName;
}
set
{
fName = value;
}
}
public string SecondName
{
get
{
return SecondName;
}
set
{
SecondName = value;
}
}
public string sName
{
get
{
return sName;
}
set
{
sName = value;
}
}
public int ID
{
get
{
return ID;
}
set
{
ID = value;
}
}
public int mId
{
get
{
return mId;
}
set
{
mId = value;
}
}
public int GetID()
{
return mId;
}
public void SetID(int id)
{
mId = ID;
}
public void SetName(string fName, string sName)
{
fName = FirstName;
sName = SecondName;
}
}
and the main program
class Program
{
/// <summary>
/// Create unique string code based off current date and time.
/// </summary>
/// <returns>code string</returns>
static string generateUniqueCode()
{
string characters = "abcdefghijklmnopqrstuvqxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
string ticks = DateTime.UtcNow.Ticks.ToString();
var code = "";
for (var i = 0; i < characters.Length; i += 2)
{
if ((i + 2) <= ticks.Length)
{
var number = int.Parse(ticks.Substring(i, 2));
if (number > characters.Length - 1)
{
var one = double.Parse(number.ToString().Substring(0, 1));
var two = double.Parse(number.ToString().Substring(1, 1));
code += characters[Convert.ToInt32(one)];
code += characters[Convert.ToInt32(two)];
}
else
code += characters[number];
}
}
return code;
}
/// <summary>
/// Creates unique integer code based off current date and time.
/// </summary>
/// <returns>integer code</returns>
static int generateUniqueCode(int seed)
{
string characters = "0123456789";
Random randInt = new Random(seed);
var ticks = randInt.Next();
int code = 0;
for (var i = 0; i < characters.Length; i += 2)
{
if ((i + 2) <= ticks)
{
var number = ticks;
if (number > characters.Length - 1)
{
var one = double.Parse(number.ToString().Substring(0, 1));
var two = double.Parse(number.ToString().Substring(1, 1));
code += characters[Convert.ToInt32(one)];
code += characters[Convert.ToInt32(two)];
}
else
code += characters[number];
}
}
return code;
}
static void Main(string[] args)
{
Customer customer = new Customer();
int generatedIntCode = generateUniqueCode(1);
customer.FirstName = "Conor";
customer.SecondName = "MacFirbhisigh";
customer.SetID(generatedIntCode);
Console.WriteLine("{0}, {1} {2}", customer.ID, customer.FirstName, customer.SecondName);
//Console.ReadKey();
}
}
In the getter and setter of FirstName (and all others), you are calling the same property over and over again. The endless loop you created will result in a StackOverflowException.
If you don't want to add custom logic to your properties, just use auto-implemented properties:
public string FirstName
{
get;
set;
}
If you did want to implement the property on your own, creating your own backing fields, this is what it should look like (this is effectively the same as what the above code would generate):
private string firstName; // backing field
public string FirstName
{
get
{
return this.firstName; // return the backing field
}
set
{
this.firstName = value; // set the backing field
}
}
You left out a few important parts
Firstly, you always need to declare you variables,
public - for outside get and set, thus no need for the get-set methods.
private - get/set methods are necessary for data retrieval modification.
Also, see the SetName method.
Hope it helps :p
This should do the trick:
class Customer : ICustomer
{
private string firstName;
private string name;
private string secondName;
private string sName;
private int iD;
private int mId;
public string FirstName
{
get
{
return firstName;
}
set
{
firstName = value;
}
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public string SecondName
{
get
{
return secondName;
}
set
{
secondName = value;
}
}
public string SName
{
get
{
return sName;
}
set
{
sName = value;
}
}
public int ID
{
get
{
return iD;
}
set
{
iD = value;
}
}
public int MId
{
get
{
return mId;
}
set
{
mId = value;
}
}
public void SetName(string fName, string sName)
{
FirstName = fName;
SecondName = sName ;
}
}
I'm trying to save two lists of my custom objects the first list of type List<Vechicle>.
XmlSerializer SerializerObjVechicle = new XmlSerializer(typeof(List<Vechicle>));
Then I get the error
"An unhandled exception of type
'System.Windows.Markup.XamlParseException' occurred in
PresentationFramework.dll"
This is my vechicle class
[Serializable]
public class Vechicle
{
private int _Id;
private String _Registration;
public Vechicle(int id,String registration)
{
Id = id;
Registration = registration;
}
public override string ToString()
{
return Id.ToString() + " " + Registration;
}
#region getters/setters
public int Id{
get { return _Id; }
set { _Id = value; }
}
public String Registration
{
get { return _Registration; }
set { _Registration = value; }
}
#endregion
}
}
bogza.anton's answer is right, you need to provide a constructor without parameters, I give a sample like this:
[Serializable]
public class Vechicle
{
private int _Id;
private String _Registration;
public Vechicle()
{
_Id = 1;
_Registration = "default name";
}
public Vechicle(int id, String registration)
{
Id = id;
Registration = registration;
}
public override string ToString()
{
return Id.ToString() + " " + Registration;
}
#region getters/setters
public int Id
{
get { return _Id; }
set { _Id = value; }
}
public String Registration
{
get { return _Registration; }
set { _Registration = value; }
}
#endregion
}
private void button1_Click(object sender, EventArgs e)
{
List<Vechicle> vList = new List<Vechicle>()
{
new Vechicle(),
new Vechicle(),
new Vechicle{Id=2, Registration="hello"},
new Vechicle{Id = 100, Registration="world"}
};
XmlSerializer SerializerObjVechicle = new XmlSerializer(vList.GetType());
FileStream fs = new FileStream("d:\\test.xml", FileMode.OpenOrCreate);
SerializerObjVechicle.Serialize(fs, vList);
}
result of my test is below:
Need to add a constructor without parameters.
Or inherit class from interface ISerializable.
http://msdn.microsoft.com/en-us/library/vstudio/ms233843(v=vs.110).aspx
i was need to write 2 methods in my student class which do the following
hasPassed() Should return True if the student has a year mark >= 40 or
false if the marks is <40
toString() Should return a single string containing a summary of the
student details held within the class
e.g.
“12345 Basil Fawlty, 23/08/1946”
here's the code i have for the above to methods, is what i have correct for what its asking for the above?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CourseWork
{
public class Student
{
private static string firstname;
private string secondname;
private string dateofbirth;
private string course;
private int matricnumber;
private double yearmark;
public bool hasPassed()
{
if (yearmark >= 40)
return true;
else
return false;
}
public void toString()
{
firstname = "Basil";
secondname = "Fawlty";
dateofbirth = "23/08/1946";
course = "MA Hotel Management";
matricnumber = 12345;
yearmark = 55;
}
public Student()
{
}
public string FirstName
{
get { return firstname; }
set { firstname = value; }
}
public string SecondName
{
get { return secondname; }
set { secondname = value; }
}
public string DateOfBirth
{
get { return dateofbirth; }
set { dateofbirth = value; }
}
public string Course
{
get { return course; }
set { course = value; }
}
public int MatricNumber
{
get { return matricnumber; }
set
{
if (value <= 99999 && value >= 10000)
{
matricnumber = value;
}
else
{
Console.WriteLine("Invalid Matric Number: {0}", value);
}
matricnumber = value;
}
}
public double YearMark
{
set
{
if (value <= 100 && value >= 0)
{
yearmark = value;
}
else
{
Console.WriteLine("Invalid Year Mark: {0}", value);
}
yearmark = value;
}
}
}
i then need the above methods to be used in a get button that does the following
Get: Uses the values of the Student class methods to update the text boxes. The
Student.hasPassed() method should be used to update the pass/fail label. The
Student details summary should be updated by using Student.toString ().
but I'm having trouble coding it and i cant seam to call hasPassed() method or toString() method from my student class
so I've doing something wrong but cant see what it is
any ideas how to go about fixing this?
In order the methods to be visible, you need to create an instance of the class Student. ex,
Student _student = new Student();
bool _x = _student.hasPassed();
if you want the members to be access without instantiating, make the member static,
public static bool hasPassed()
{
if (yearmark >= 40)
return true;
else
return false;
}
but bear in mind that static members cannot see non-static members. In that case, it won;t compile because yearmark cannot be found.