I'm having trouble using setters and getters. When I tried to call a private var from a class to another class, I do not get the value of the var.
Here are some snippets of my code for you guys to check out.
This is my setter getter for the variable.
class PlayerStats
private string _pName;
public string pName
{ get { return _pName; } set { _pName = value; } }
}
This is where I want to show my var.
public void Welcome()
{
PlayerStats pStats = new PlayerStats();
Header();
Console.WriteLine("Hello!");
Console.WriteLine(pStats.pName);
}
This is the method where I inserted a value on my var (this method is executed first before the method welcome)
public void Username()
{
PlayerStats pStats = new PlayerStats();
string name;
Header();
Console.Write("\nChoose your USERNAME: ");
name = Console.ReadLine();
pStats.pName = name;
}
None of this are running from the main method. I thought of doing my program by just calling out different methods from different classes in the main method so it kinda looks like this:
static void Main(string[] args)
{
Jobs jobCl = new Jobs();
GUI gui = new GUI();
gui.Header();
gui.StartPage();
gui.Username();
gui.ChoosepJob();
gui.Welcome();
Console.ReadLine();
}
When I call the var from the username method, I have no problem printing it but I cant make it to print if I am to call it from other methods.
Thank you for any help you can provide. Also if you can suggest a different way of doing this, please don't hesitate to say it to me
Don't make a new PlayerStats every method, make it once outside of the methods then pass it in to each one. You likely have the same problem with Jobs and that likely needs to be passed in to ChoosepJob
static void Main(string[] args)
{
PlayerStats pStats = new PlayerStats();
Jobs jobCl = new Jobs();
GUI gui = new GUI();
gui.Header();
gui.StartPage();
gui.Username(pStats);
gui.ChoosepJob(jobCl);
gui.Welcome(pStats);
Console.ReadLine();
}
public void Welcome(PlayerStats pStats)
{
Header();
Console.WriteLine("Hello!");
Console.WriteLine(pStats.pName);
}
public void Username(PlayerStats pStats)
{
string name;
Header();
Console.Write("\nChoose your USERNAME: ");
name = Console.ReadLine();
pStats.pName = name;
}
Your printing method here is creating a new instance of PlayerStats
public void Welcome()
{
PlayerStats pStats = new PlayerStats();
Header();
Console.WriteLine("Hello!");
Console.WriteLine(pStats.pName);
}
The one you're creating in here is not being used in Welcome() method
public void Username()
{
PlayerStats pStats = new PlayerStats();
string name;
Header();
Console.Write("\nChoose your USERNAME: ");
name = Console.ReadLine();
pStats.pName = name;
}
Create one instance in your main to follow through like the following:
public string Username()
{
Header();
Console.Write("\nChoose your USERNAME: ");
name = Console.ReadLine();
return name;
}
public void Welcome(PlayerStats pStats)
{
Header();
Console.WriteLine("Hello!");
Console.WriteLine(pStats.pName);
}
static void Main(string[] args)
{
PlayerStats pStats = new PlayerStats();
Jobs jobCl = new Jobs();
GUI gui = new GUI();
gui.Header();
gui.StartPage();
pStats.pName = gui.Username();
gui.ChoosepJob();
gui.Welcome(pStats);
Console.ReadLine();
}
Related
I need to use OptionSet to get args in the console. However I am quite struggling to understand the documentation and the examples I found. LIke this when I am debuging and set the debug to init of OptionSet I see an exception " Incorrect number or types of arguments (Parameter 'arguments') "Could you please advise how to pass the parameters?
http://www.ndesk.org/doc/ndesk-options/NDesk.Options/OptionSet.html
static async Task Main(string[] args)
{
var dessert = new string[] {PhoneNum = 123456,"Cake","Candy"};
await Test(dessert);
}
private static CommandLineOptions GetOptions(string[] args)
{
CommandLineOptions options = new CommandLineOptions();
var os = new OptionSet
{
{ "PhoneNum=", PhoneNum => options.PhoneNumn = PhoneNum },
};
os.Parse(args);
return options;
}
static async Task Test(string[] args)
{
var test = GetOptions(args);
Console.WriteLine(test.PhoneNum);
}
public class CommandLineOptions
{
public string PhoneNum { get;set; }
}
First, you need to add a List<string> property in CommandLineOptions to store the rest of the command line arguments (Candy and Cake), which will be returned by os.Parse.
public class CommandLineOptions
{
public string PhoneNum { get; set; }
public List<string> Rest { get; set; }
}
Then, set Rest when you parse the args:
private static CommandLineOptions GetOptions(string[] args)
{
CommandLineOptions options = new CommandLineOptions();
var os = new OptionSet
{
{ "PhoneNum=", PhoneNum => options.PhoneNum = PhoneNum },
};
options.Rest = os.Parse(args); // Here!
return options;
}
To pass the PhoneNum option, you need to prefix with a hyphen (that's how command line arguments work):
var dessert = new string[] { "-PhoneNum=123456", "Cake", "Candy" };
Then in Test, you can get the Rest of the arguments:
static void Test(string[] args)
{
var test = GetOptions(args);
Console.WriteLine(test.PhoneNum);
foreach (var arg in test.Rest) {
Console.WriteLine(arg);
}
}
I have no idea why you made Test and Main async.
I'm trying to map CSV file into class object with C#. My problem is that i have 3 different files, but I want to fallow DRY principles. Can someone tell me how to change 'ParseLine' method to make it possible?
C# consol app.
This is how my FileReader looks like:
public class FileReader<T> : IFileReader<T> where T : Entity
{
private readonly ITransactionReader<T> _transactionReader;
public FileReader(ITransactionReader<T> transactionReader)
{
_transactionReader = transactionReader;
}
public List<T> GetInfoFromFile(string filePath)
{
var lines = File.ReadAllLines(filePath);
var genericLines = new List<T>();
foreach (var line in lines)
{
genericLines.Add(_transactionReader.ParseLine(line));
}
return genericLines;
}
}
public interface IFileReader<T> where T : Entity
{
List<T> GetInfoFromFile(string filePath);
}
This is how the object should look like.
public class TransactionReader : ITransactionReader<Transaction>
{
public Transaction ParseLine(string line)
{
var fields = line.Split(";");
var transaction = new Transaction()
{
Id = fields[0],
Month = int.Parse(fields[1]),
Day = int.Parse(fields[2]),
Year = int.Parse(fields[3]),
IncomeSpecification = fields[4],
TransactionAmount = int.Parse(fields[5])
};
return transaction;
}
}
public interface ITransactionReader<T>
{
T ParseLine(string line);
}
This is how I run it for test purposes.
class Program
{
private static readonly string filePath = "C:/Users/<my_name>/Desktop/C# Practice/ERP/ERP/CsvFiles/Transaction.csv";
static void Main(string[] args)
{
ITransactionReader<Transaction> transactionReader = new TransactionReader();
IFileReader<Transaction> fileReader = new FileReader<Transaction>(transactionReader);
List<Transaction> Test()
{
var obj = fileReader.GetInfoFromFile(filePath);
return obj;
}
var list = Test();
}
}
I'm looking to modify that line:
genericLines.Add(_transactionReader.ParseLine(line));
and method arguments to make it open for any CSV fil.
I don't mind to change that composition into something more effective.
Some classes to start, I'm writing them all so you can reproduce my problem:
public class PermissionObject
{
public string permissionName;
public string permissionObject;
public bool permissionGranted;
public PermissionObject()
{
permissionName = "";
permissionObject = "";
permissionGranted = true;
}
public PermissionObject(string name, string obj, bool granted)
{
permissionName = name;
permissionObject = obj;
permissionGranted = granted;
}
}
public class Config
{
public string cmsDataPath = "";
public string cmsIP = "";
public List<UserClass> usersCMS = new List<UserClass>();
static public string pathToConfig = #"E:\testconpcms.xml";
public string cardServerAddress = "";
public void Save()
{
XmlSerializer serializer = new XmlSerializer(typeof(Config));
using (Stream fileStream = new FileStream(pathToConfig, FileMode.Create))
{
serializer.Serialize(fileStream, this);
}
}
public static Config Load()
{
if (File.Exists(pathToConfig))
{
XmlSerializer serializer = new XmlSerializer(typeof(Config));
try
{
using (Stream fileStream = new FileStream(pathToConfig, FileMode.Open))
{
return (Config)serializer.Deserialize(fileStream);
}
}
catch (Exception ex)
{
return new Config();
}
}
else
{
return null;
}
}
}
public class UserClass
{
public string Name;
public string Login;
public string Password;
public PCMS2 PermissionsList; // OR new PCMS1, as I will explain in a bit
public UserClass()
{
this.Name = "Admin";
this.Login = "61-64-6D-69-6E";
this.Password = "61-64-6D-69-6E";
this.PermissionsList = new PCMS2(); // OR new PCMS1, as I will explain in a bit
}
}
The problematic bit: consider two implementations of PCMS class, PCMS1 and PCMS2:
public class PCMS1
{
public PermissionObject p1, p2;
public PCMS1()
{
p1 = new PermissionObject("ImportConfigCMS", "tsmiImportCMSConfigFile", true);
p2 = new PermissionObject("ExportConfigCMS", "tsmiExportCMSConfigFile", true);
}
}
public class PCMS2
{
public List<PermissionObject> listOfPermissions = new List<PermissionObject>();
public PCMS2()
{
listOfPermissions.Add(new PermissionObject("ImportConfigCMS", "tsmiImportCMSConfigFile", true));
listOfPermissions.Add(new PermissionObject("ExportConfigCMS", "tsmiExportCMSConfigFile", true));
}
}
And finally main class:
public partial class Form1 : Form
{
private Config Con;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Con = Config.Load();
if (Con == null)
{
Con = new Config();
Con.cmsDataPath = #"E:\testconpcms.xml";
Con.Save();
}
if (Con.usersCMS.Count == 0)
{
UserClass adminDefault = new UserClass();
Con.usersCMS.Add(adminDefault);
Con.Save();
}
}
}
Now, using either PCMS1 or PCMS2, the config file generates properly - one user with 2 permissions.
However, when config file is present, calling Con = Config.Load() in the main class gives different results.
Using PCMS1, the Con object is as expected - 1 user with 2 permissions.
However, using PCMS2, the Con object is 1 user with 4 (four) permissions. It doubles that field (it's basically p1, p2, p1, p2). Put a BP to see Con after Load().
I guess the list (PCMS2) implementation is doing something wonky during load which I'm not aware of, but I can't seem to find the issue.
You creates your permission objects in constructor of PMCS2 you do it in the constructor of PMCS1 too, but there you do have two properties that will be overwritten by serializer.
In case of of PMCS2 your constructor adds two items to List and than serializer adds the items it has deserilized to the same list.
I don't know exactly your usecase but i would suggest to move init of the permissions to separated method:
public class PCMS1
{
public PermissionObject p1, p2;
public void Init()
{
p1 = new PermissionObject("ImportConfigCMS", "tsmiImportCMSConfigFile", true);
p2 = new PermissionObject("ExportConfigCMS", "tsmiExportCMSConfigFile", true);
}
}
public class PCMS2
{
public List<PermissionObject> listOfPermissions = new List<PermissionObject>();
public void Init()
{
listOfPermissions.Add(new PermissionObject("ImportConfigCMS", "tsmiImportCMSConfigFile", true));
listOfPermissions.Add(new PermissionObject("ExportConfigCMS", "tsmiExportCMSConfigFile", true));
}
}
after that you could call it, if you want to get initial settings:
if (Con.usersCMS.Count == 0)
{
UserClass adminDefault = new UserClass();
adminDefault.PermissionsList.Init();
Con.usersCMS.Add(adminDefault);
Con.Save();
}
I am trying to get some data for a specified user using ebay's getFeedback API and ended up with this code.
namespace one
{
class Program
{
private static ApiContext apiContext = null;
static void Main(string[] args)
{
ApiContext apiContext = GetApiContext();
GeteBayOfficialTimeCall apiCall = new GeteBayOfficialTimeCall(apiContext);
GetFeedbackCall call = new GetFeedbackCall(apiContext);
call.UserID = "abc";
Console.WriteLine(call.GetFeedback().ToString());
Console.ReadKey();
}
static ApiContext GetApiContext()
{
if (apiContext != null)
{
return apiContext;
}
else
{
apiContext = new ApiContext();
apiContext.SoapApiServerUrl = ConfigurationManager.AppSettings["Environment.ApiServerUrl"];
ApiCredential apiCredential = new ApiCredential();
apiCredential.eBayToken = ConfigurationManager.AppSettings["UserAccount.ApiToken"];
apiContext.ApiCredential = apiCredential;
apiContext.Site = SiteCodeType.US;
return apiContext;
}
}
}
}
It prints the following line in console
eBay.Service.Core.Soap.FeedbackDetailTypeCollection
How can I get the original data?
call.GetFeedback() returning collection of FeedbackDetailType members, so you can use foreach to retrieve informations (such as feedback score and other stuff) about all particular feedback.
see complete members list of FeedbackDetailType members
here!
e.g
foreach (FeedbackDetailType feedback in call.GetFeedback())
{
Console.WriteLine(feedback.CommentText);
//and other stuff
}
Or you can use something like that
call.GetFeedback();
Console.WriteLine(call.FeedbackScore);
I'm having trouble using a third party API that has outdated documentation, so I'm trying to figure out why this piece of ##$! isn't working. And by ##$! i mean "code", of course :)
So as far as i know WAPISoap is a public interface that I have obtained by adding a web reference in visual studio.
I also know the Describe() method accepts two parameters, a string and an object of type credential and it returns a string. Any help would be greatly appreciated :)
Here's what i got so far:
using WAPIClient;
using System;
using Project1.WsWWDAPI;
namespace WAPIClient
{
class ResellerAPI
{
public void CallDescribe()
{
String sReturnXml;
Credential m_Crededential = new Project1.WsWWDAPI.Credential();
m_Crededential.Account = "account";
m_Crededential.Password = "password";
String sCLTRID = System.Guid.NewGuid().ToString();
sReturnXml = WAPISoap.Describe(sCLTRID, m_Crededential);
Console.WriteLine(sReturnXml);
}
static void Main(string[] args)
{
ResellerAPI reseller = new ResellerAPI();
reseller.CallDescribe();
}
}
}
The Describe method is not static, which means you need to call it on an instance of the WAPI class:
WsWWDAPI.WAPI m_WAPIObj = null;
WsWWDAPI.Credential m_Crededential = null;
public void Init()
{
m_WAPIObj = new WsWWDAPI.WAPI();
m_Crededential = new WsWWDAPI.Credential();
m_Crededential.Account = "account";
m_Crededential.Password = "password";
}
public void CallDescribe()
{
String sReturnXml;
String sCLTRID = System.Guid.NewGuid().ToString();
sReturnXml = m_WAPIObj.Describe(sCLTRID, m_Crededential);
Console.WriteLine( sReturnXml );
}
static void Main(string[] args)
{
ResellerAPI reseller = new ResellerAPI();
reseller.Init();
reseller.CallDescribe();
}
See: http://products.secureserver.net/guides/wsapiquickstart.pdf
The error is because you use non-static method in static context - you should have instance of the WAPISoap in order to call member function which is not static
It sounds like you need to create an instance of WAPISoap and then call Describe on that instance.