I'm working on a "bank application" in C# WPF where I came upon error:CS0052
Inconsistent accessibility: field type 'List' is less
accessible than field 'Customer.CustomerAccountsList'
The idea is that the method bool DoseThisAccountExistAlready() should check all customers one by one and see if his/her accounts have the same data as the account that is about to be created.
However CustomerAccountsList must be public or DoseThisAccountExistAlready() can't access the accounts data.
How do I fix this error?
//main window
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Uppgift2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public List<Customer> ListOfAllCustomers = new List<Customer>();
public bool Login(string fornamn, string efternamn, string pin)
{
foreach (Customer c in ListOfAllCustomers)
{
if (c.firstname == fornamn && c.lastname == efternamn && c.pinKod == pin)
{
MessageBox.Show("Login succesfull. Welcome " + c.firstname + " " + c.lastname);
WindowAccountOperations LoggedInUser = new WindowAccountOperations();
LoggedInUser.ShowDialog();
return true;
}
else
{
MessageBox.Show("Det finns inte ett sånt användare. Kontrolera användarnamn och pin");
return false;
}
}
return false;
}
//Customer pin could be remade into a rondom generator with an if() that forces it to be a four digit number
/*
* Random randomPin = new Random();
randomPin.Next(x, y);
if(randomPin.ToString().Length!=4)
{
}
*/
public bool CreateNewCustomer(string fornamn, string efternamn, string telefon, string customerAdress, string customerPin)
{
//Is there already such customer?
foreach (Customer c in ListOfAllCustomers)
{
if ((c.firstname == fornamn && c.lastname == efternamn && c.adress == customerAdress))
{
MessageBox.Show("Kunden med ett sånt förnamn, efternamn och adress redan finns");
return false;
}
if(c.pinKod == customerPin)
{
MessageBox.Show("Kunden med ett sånt pinkod redan finns");
return false;
}
else
{
ListOfAllCustomers.Add(new Customer(TBFirstNameNyKund.Text, TBSecondNameLogin.Text, TBTelNyKund.Text, TBAdressNyKund.Text, TBPinNyKund.Text));
MessageBox.Show("Registration complete. Du kan nu logga in");
TBFirstNameNyKund.Clear(); TBSecondNameLogin.Clear(); TBAdressNyKund.Clear(); TBPinNyKund.Clear();//clear login textboxes
return true;
}
}
return false;
}
public bool DoseThisAccountExistAlready(string kontoNummer, string kontotyp)
{
foreach (Customer c in ListOfAllCustomers )
{
foreach(Account a in c.CustomerAccountsList)
{
if(a.accountType==kontotyp)//Does customer c try to create another type of account he already has?
{
return true;
}
if(a.accountNumber==kontoNummer)
{
return true;
}
}
return false;
}
return false;
}
private void ButtonLogin_Click(object sender, RoutedEventArgs e)
{
Login(TBFirstNameLogin.Text, TBSecondNameLogin.Text, TBPinLogin.Text);
}
private void ButtonSkapaKund_Click(object sender, RoutedEventArgs e)
{
CreateNewCustomer(TBFirstNameNyKund.Text, TBSecondNameNyKund.Text, TBTelNyKund.Text, TBAdressNyKund.Text, TBPinNyKund.Text);
}
}
}
//customer class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Uppgift2
{
public class Customer
{
public string adress;
public string celphone;
public string firstname;
public string lastname;
public string pinKod;
public List<Account> CustomerAccountsList = new List<Account>();//Error apears here.
public Customer(string fname,string lname, string tel, string customerAdress,string customerPin)
{
adress = customerAdress;
celphone = tel;
firstname = fname;
lastname = lname;
pinKod = customerPin;
}
}
}
//account base class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Uppgift2
{
abstract class Account //The abstract modifier indicates that the thing being modified has a missing or incomplete implementation=base class for other classes
{
public double payoutAmmount;
protected double payoutTax;
public bool creditPosible;
public string accountNumber;
public string accountType;
public double balance;
protected double interest; //customer shouldent be able to modify interest %
//constructor
public Account(string kontoNummer, double KontoStartsaldo,string kontoTyp, double ranta, bool finsdetkredit,double uttagPris)
{
accountNumber = kontoNummer;
balance = KontoStartsaldo;
accountType = kontoTyp;
creditPosible = finsdetkredit;
payoutTax = uttagPris;
}
public double InsertMoney(int chosenAccount, double payout) //int chosenAccount becouse i thought to use a combo box index
{
payoutAmmount = payout;
balance = balance - payout + (payout * payoutTax);
return balance;
}
}
}
You can't have a public List<Account> because the Account class has no access modifier so it is defaulted by the compiler to be internal. You can't have a public property of an internal type. You need to make it public for this to work.
Related
Ok, so I am trying to figure out why I am having a looping issue. The intention of the method GetNewDvdInfo() is to return a new dvd class with 5 properties and will be passed on to DvdController.cs in the CreateDvd() method and will then display all the dvds and the dvd the user added. The problem is that the GetNewDvdInfo() method is repeating itself, but when I was returning null instead, it was not looping.
DvdView.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DvdManager.Models;
/*
GetMenuChoice() : int
GetNewDvdInfo(): Dvd
DisplayDvd(Dvd dvd) : void
EditDvdInfo(Dvd dvd) : Dvd
SearchDvd() : int
ConfirmRemoveDvd(Dvd) : boolean
*/
namespace DvdManager.View
{
public class DvdView
{
public int GetMenuChoice()
{
string input;
int choice;
Console.Clear();
Console.WriteLine("Press 1 to display movies");
Console.WriteLine("Press 2 to add movie");
input = Console.ReadLine();
if (int.TryParse(input, out choice))
{
switch (choice)
{
case 1:
break;
case 2:
break;
default:
Console.WriteLine("Invalid input");
break;
}
}
return choice;
}
public Dvd GetNewDvdInfo() //looping here
{
string inputReleaseYear;
string inputRating;
int id = 4;
string readTitle;
int readReleaseYear;
string readDirector;
float readRating;
Console.WriteLine("What is the Title of the DVD?");
readTitle = Console.ReadLine();
Console.WriteLine("What is the Release Year of the DVD?");
inputReleaseYear = Console.ReadLine();
int.TryParse(inputReleaseYear, out readReleaseYear);
Console.WriteLine("Who is the Director of the DVD?");
readDirector = Console.ReadLine();
Console.WriteLine("What is the star rating of the DVD?");
inputRating = Console.ReadLine();
float.TryParse(inputRating, out readRating);
var dvd = new Dvd(id, readTitle, readReleaseYear, readDirector, readRating);
Dvd newDvd = GetNewDvdInfo();
return dvd;
}
public void DisplayDvd(Dvd dvd)
{
}
public Dvd EditDvdInfo(Dvd dvd)
{
return null;
}
public int SearchDvd()
{
return 0;
}
public Boolean ConfirmRemoveDvd(Dvd dvd)
{
return false;
}
}
}
DvdController.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DvdManager.Models;
using DvdManager.Data;
using DvdManager.View;
/*
Run() : void
Private CreateDvd(): void
Private DisplayDvds(): void
Private SearchDvds(): void
Private EditDvd() : void
Private RemoveDvd() : void
*/
namespace DvdManager.Controllers
{
public class DvdController
{
public DVDList _dvds = new DVDList();
public void Run()
{
Console.WriteLine("Welcome To Dvd Manager");
DvdView view = new DvdView();
var pass = view.GetMenuChoice();
if (pass == 1)
{
CreateDvd();
}
else if (pass == 2)
{
view.GetNewDvdInfo();
CreateDvd();
}
else
Console.WriteLine("Invalid.");
}
private void CreateDvd() //Create
{
var myView = new DvdView();
var dvdInfos = myView.GetNewDvdInfo();
List<Dvd> Dvds = _dvds.GetList();
Dvds.Add(new Dvd(0, "Batman", 2010, "Bruce", 4));
Dvds.Add(new Dvd(1, "Superman", 2009, "John", 4));
Dvds.Add(new Dvd(2, "Wonderwoman", 2012, "Omar", 4));
Dvds.Add(dvdInfos);
DisplayDvds();
}
private void DisplayDvds() //Read List<Dvd> dvds
{
List<Dvd> Dvds = _dvds.GetList();
for (int i = 0; i < Dvds.Count; i++)
{
Console.WriteLine(Dvds[i]);
}
RemoveDvd();
}
private void SearchDvds() //List
{
}
private void EditDvd(int id, Dvd dvd) //Update
{
}
private void RemoveDvd() //Delete int id
{
List<Dvd> Dvds = _dvds.GetList();
//Dvds.RemoveAt(Dvds[1]);
Dvds.Remove(Dvds.Single(x => x.Id == 1));
Console.WriteLine("Removed movie from list:");
for (int i = 0; i < Dvds.Count; i++)
{
Console.WriteLine(Dvds[i]);
}
}
}
}
You are making a recursive call at the end of GetNewDvdInfo(), just remove it.
You are calling this method recursively here:
var dvd = new Dvd(id, readTitle, readReleaseYear, readDirector, readRating);
Dvd newDvd = GetNewDvdInfo(); //!!!
return dvd;
Hence the looping. It seems like this line of code is not needed.
I am trying to learn web services. My problem is I have created a class "Item" as follows,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WebServiceTaxCalc
{
public enum Type { BASIC, IMPORTED, EXEMPT}
public class Item
{
string name;
double basePrice;
int quantity;
Type TaxType;
public Item(string name, double price, int quantity, Type type)
{
this.basePrice = price;
this.name = name;
this.quantity = quantity;
this.TaxType = type;
}
public string getName()
{
return name;
}
public double getPrice()
{ return basePrice; }
public int getQuantity()
{ return quantity; }
public Type getType() { return TaxType; }
}
}
and another class for calculating the tax:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WebServiceTaxCalc
{
public class ShoppingBasket
{
double itemsTotalPrice = 0.0;
double totalTax = 0.0;
public void addItem(List<Item> i)
{
foreach (Item a in i)
{
totalTax += taxPerItem(a);
double eachItemPrice = (a.getPrice() + taxPerItem(a));
itemsTotalPrice += eachItemPrice;
//Console.WriteLine(a.getQuantity() + " " + a.getName() + ": " + eachItemPrice);
}
//Console.WriteLine("sales tax: " + totalTax);
//Console.WriteLine("total cost: "+itemsTotalPrice);
}
public double taxPerItem(Item i)
{
double tax = 0;
if (i.getType() == Type.BASIC)
{
tax = i.getPrice() * 5 / 100;
return tax;
}
else if (i.getType() == Type.EXEMPT)
{
tax = 0;
return tax;
}
else
{
tax = i.getPrice() * 15 / 100;
return tax;
}
}
}
}
I am trying to pass the values to the web service and let the web service call the classes.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace WebServiceTaxCalc
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public ShoppingBasket Calc(string name, double price, int quantity, Type catg)
{
List<Item> l1 = new List<Item>();
Item i1 = new Item(name, price, quantity,catg);
l1.Add(i1);
ShoppingBasket sb = new ShoppingBasket();
sb.addItem(l1);
return sb;
}
}
}
I am giving the input like this,
input image:
and after invoking I am just getting this:
Output image
I am not getting the document tree of what I passed.
I have seen a useful post here https://stackoverflow.com/a/12039010/3768995
But I couldn't solve my problem.
Please guide me through this.
Add a [DataContract] attribute to ShoppingBasket and a [DataMember] attribute to the properties that need to be included when the response is sent. (And as was said, make them public properties.)
I have a problem with my code. When I enter an invalid input it should give me an exception but it doesn't, instead it returns me the value as if its correct.
Here is my class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Mail;
namespace Lecture_1_Homework
{
public class Person
{
private string name;
private int age;
private string email;
public string Name
{
get
{
return this.name;
}
set
{
if (!ValidateName(name))
{
throw new ArgumentException("You need to enter your name.");
}
this.name = value;
}
}
public int Age
{
get
{
return this.age;
}
set
{
if (!ValidateAge(age))
{
throw new ArgumentException("Your age must be between 1 and 100");
}
this.age = value;
}
}
public string Email
{
get
{
return this.email;
}
set
{
if (!ValidateEmail(email))
{
throw new ArgumentException("Invalid email input");
}
this.email = value;
}
}
private bool ValidateName(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return false;
}
return true;
}
private bool ValidateAge(int age)
{
if (age > 100 || age < 1)
{
return false;
}
return true;
}
private bool ValidateEmail(string email)
{
try
{
MailAddress mail = new MailAddress(email);
return true;
}
catch (FormatException)
{
return false;
}
}
public Person(string name, int age, string email)
{
this.name = name;
this.age = age;
this.email = email;
}
public Person(string name, int age)
{
this.name = name;
this.age = age;
}
public void ToString()
{
Console.Write("Name:{0}\nAge:{1}\nEmail:{2}\n",this.name,this.age,string.IsNullOrWhiteSpace(this.email) ? "no email given" : this.email);
}
}
}
Here is my main
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lecture_1_Homework
{
class Persons_main
{
static void Main()
{
Person Peter = new Person("Peter", 18, "test123#yahoo.com");
Person Jake = new Person("Jake", 19);
Peter.ToString();
Jake.ToString();
}
}
}
If I enter an number greater than 100 or lower than 1 it should give me an exception but it doesn't.
if I don't enter a name it should give me an exception but it doesn't.
And if I enter a wrong format for my email it should give me and exception but it doesn't.
For example if I enter for my email "test123mail.com" this should give me an exception but it doesn't.
And if I enter a " " for my name it should give me an exception but it doesn't.
I can't find my mistake and I would appreciate some help.
Two things...
First of all, you're validating the variable before it's been set:
ValidateName(name)
I think you want to validate the incoming value for the property instead:
ValidateName(value)
Second, you're setting the backing variables directly without validating them:
this.name = name;
The validation is in the property setter, so use that instead:
this.Name = name;
you need to validate the value being passed in, not the property.
ValidateName(value)
instead of
ValidateName(name)
And when assigning the value to the property, use
this.Name = value; // instead of this.name
when i run a method within my WCF service i get "An unhandled exception of type 'System.StackOverflowException' occurred in developer1SVC.dll".
No infinite loops exist and no infinite recursion is occurring. Any ideas to why this may be happening? when i run the method through wcf test client. I get the results back correctly however, hooking it up to my console app and running it breaks the application. The other methods run fine. It is this one method. Just trying to get the feel for WCF services. The service breaks right after i return accounts from the "generateMultiplAccounts" method.
Much help appreciated.
Service
using developer1.Core.ServiceContracts;
using developer1.Core.Data;
using developer1.Core.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using developer1.Core.Dto.Account;
namespace developer1.Core.Service
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite == null)
{
throw new ArgumentNullException("composite");
}
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
Console.WriteLine(composite.StringValue + composite.BoolValue);
return composite;
}
public List<AccountDto> GenerateMultipleAccounts(int count)
{
List<AccountDto> accounts = new List<AccountDto>();
for (int i = 0; i < count; i++)
{
AccountDto newAccount = new AccountDto() { AccountId = Guid.NewGuid()};
accounts.Add(newAccount);
}
return accounts;
}
}
}
Console Application
using developer1.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using developer1.Core.Service;
using developer1.Core.Dto.Account;
using developer1.Core.ServiceContracts;
using AccountServiceClient = developer1.TestConsole.ServiceReference1.Service1Client;
namespace developer1.TestConsole
{
class Program
{
static void Main(string[] args)
{
try
{
AccountServiceClient AccountServiceClient = new AccountServiceClient();
Guid testGuid = Guid.NewGuid();
List<AccountDto> newAccounts = new List<AccountDto>(AccountServiceClient.GenerateMultipleAccounts(2));
Console.WriteLine(testGuid);
CompositeType testDataContract = new CompositeType() { StringValue = "test", BoolValue = true };
testDataContract = AccountServiceClient.GetDataUsingDataContract(testDataContract);
Console.WriteLine(AccountServiceClient.GetData(6));
Console.WriteLine(testDataContract.StringValue);
//foreach (var item in newAccounts)
//{
// Console.WriteLine(item.AccountId);
//}
}
catch(Exception e) {
Console.WriteLine(e);
}
Console.Read();
}
}
}
Data Contract
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;
namespace developer1.Core.Dto.Account
{
[DataContract]
public class AccountDto
{
[DataMember]
public Guid AccountId { get; set; }
//get { return this.AccountId; }
//set { this.AccountId = this.AccountId == Guid.Empty ? Guid.NewGuid() : value; }
[DataMember]
public Guid UserId { get; set; }
[DataMember]
public string AccountName { get; set; }
[DataMember]
public string BankName { get; set; }
//get { return this.BankName; }
//set { this.BankName = this.BankName == null ? "Unspecified" : value; }
}
}
ANSWER!!!!!!!
So I have solved this dreaded issue. You must create a WCF Service Library instead of a WCF Service Application. My god that is stupid that the application wont let you split your components outside of the interface.
Please help me with this error! Here ResultValue is an enumeration.
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS0019: Operator '==' cannot be applied to operands of type 'string' and 'Answer.ResultValue'
Source Error:
Line 38: Answer a = (Answer)al[i];
Line 39:
Line 40: if (a.Result == Answer.ResultValue.Correct)
Line 41: correct=correct+1;
Line 42: }
=================================
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class results : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ArrayList al = (ArrayList)Session["AnswerList"];
if (al == null)
{
Response.Redirect("History.aspx");
}
resultGrid.DataSource = al;
resultGrid.DataBind();
// Save the results into the database.
if (IsPostBack == false)
{
// Calculate score
double questions = al.Count;
double correct = 0.0;
for (int i = 0; i < al.Count; i++)
{
Answer a = (Answer)al[i];
if (a.Result == Answer.ResultValue.Correct)
correct=correct+1;
}
double score = (correct / questions) * 100;
SqlDataSource studentQuizDataSource = new SqlDataSource();
studentQuizDataSource.ConnectionString =
ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
studentQuizDataSource.InsertCommand = "INSERT INTO UserQuiz ([QuizID],
[DateTimeComplete], [Score], [UserName]) VALUES (#QuizID, #DateTimeComplete,
#Score, #UserName)";
studentQuizDataSource.InsertParameters.Add("QuizID",
Session["QuizID"].ToString());
studentQuizDataSource.InsertParameters.Add("Score", score.ToString());
studentQuizDataSource.InsertParameters.Add("UserName", User.Identity.Name);
studentQuizDataSource.InsertParameters.Add("DateTimeComplete",
DateTime.Now.ToString());
int rowsAffected = studentQuizDataSource.Insert();
if (rowsAffected == 0)
{
errorLabel.Text = "There was a problem saving your quiz results into our
database. Therefore, the results from this quiz will
not be displayed on the list on the main menu.";
}
}
}
protected void resultGrid_SelectedIndexChanged(object sender, EventArgs e)
{
SqlDataSource1.FilterExpression = "QuestionOrder=" + resultGrid.SelectedValue;
}
}
code for Answer.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Answer : System.Web.UI.Page
{
private string m_QuestionID;
private string m_CorrectAnswer;
private string m_UserAns;
private string m_Result;
public string QuestionID
{
get
{
return m_QuestionID;
}
set
{
m_QuestionID = value;
}
}
public string CorrectAnswer
{
get
{
return m_CorrectAnswer;
}
set
{
m_CorrectAnswer = value;
}
}
public string UserAns
{
get
{
return m_UserAns;
}
set
{
m_UserAns = value;
}
}
public string Result
{
get
{
if (m_UserAns == m_CorrectAnswer)
{
return "Correct";
}
else
{
return "Incorrect";
}
}
}
public enum ResultValue
{
Correct,
Incorrect
}
}
It's pretty obvious you're trying to compare Enumeration Types with Strings, which aren't the same and can't be compared like that. Instead, I think you should try replacing this bit of code:
public string Result
{
get
{
if (m_UserAns == m_CorrectAnswer)
{
return "Correct";
}
else
{
return "Incorrect";
}
}
}
with
public ResultValue Result
{
get
{
if (m_UserAns == m_CorrectAnswer)
{
return ResultValue.Correct;
}
else
{
return ResultValue.Incorrect;
}
}
}
Try evaluating this :-
if (a.Result == Answer.ResultValue.Correct.ToString())