Why is it only outputting Mage? - c#

It only is giving "Mage" even if "Warrior" was selected. I can't seem to know why. Does anyone have ideas?
void OnGUI(){
isMageClass = GUILayout.Toggle(isMageClass, "Mage Class");
isWarriorClass = GUILayout.Toggle(isWarriorClass, "Warrior Class");
if(GUILayout.Button("Create")){
if(isMageClass)
{
newPlayer.PlayerClass = new BaseMageClass();
}else if (isWarriorClass)
{
newPlayer.PlayerClass = new BaseWarriorClass();
}
newPlayer.PlayerLevel = 1;
newPlayer.Stamina = newPlayer.PlayerClass.Stamina;
newPlayer.Endurance = newPlayer.PlayerClass.Endurance;
newPlayer.Intellect = newPlayer.PlayerClass.Intellect;
newPlayer.Strength = newPlayer.PlayerClass.Strength;
Debug.Log("player Class: " + newPlayer.PlayerClass.CharacterClassName);
Debug.Log("player level: " + newPlayer.PlayerLevel);
Debug.Log("player Stamina: " + newPlayer.Stamina);
Debug.Log("player Endurance: " + newPlayer.Endurance);
Debug.Log("player Intellect: " + newPlayer.Intellect);
Debug.Log("player Strength: " + newPlayer.Strength);
}
}

Since 'isMageClass' is defined then it will take the
if(isMageClass)
{
newPlayer.PlayerClass = new BaseMageClass();
}
every time and never even look at the
else if (isWarriorClass)
{
newPlayer.PlayerClass = new BaseWarriorClass();
}
I'm surprised you didn't spot that when stepping through with the debugger (tell me you stepped through with the debugger.... please!)

Related

Can't call playerprefs on other scene

so I'm here want to retrieve the string to text in a different scene with, but after I've tried by my self isn't working, am I do it wrong?
here the google sign script in that script I want to save the string task.result.displayName with Playerprefs
internal void OnAuthenticationFinished(Task<GoogleSignInUser> task)
{
if (task.IsFaulted)
{
using (IEnumerator<Exception> enumerator = task.Exception.InnerExceptions.GetEnumerator())
{
if (enumerator.MoveNext())
{
GoogleSignIn.SignInException error = (GoogleSignIn.SignInException)enumerator.Current;
AddToInformation("Got Error: " + error.Status + " " + error.Message);
}
else
{
AddToInformation("Got Unexpected Exception?!?" + task.Exception);
}
}
}
else if (task.IsCanceled)
{
AddToInformation("Canceled");
}
else
{
AddToInformation("Welcome: " + task.Result.DisplayName + "!");
AddToInformation("Email = " + task.Result.Email);
AddToInformation("Google ID Token = " + task.Result.IdToken);
AddToInformation("Email = " + task.Result.Email);
SignInWithGoogleOnFirebase(task.Result.IdToken);
currEmail = task.Result.DisplayName;
PlayerPrefs.SetString("Username " + currEmail, currEmail);
Debug.Log(currEmail);
}
private void AddToInformation(string str) { infoText.text += "\n" + str; }
after that, I want to call the Playerprefs.GetString to another scene with attaching on text
void Start()
{
displayName();
}
public void displayName()
{
userName.text = PlayerPrefs.GetString("Username " + googleSign.currEmail + "Username ");
}
but why that doesn't work, for your info I don't use DontDestroyOnload on google sign script so I attach on a sign in the scene and main menu scene
Call
PlayerPrefs.Save();
after your SetString method to save data in prefs
Check if googleSign.currEmail has value in debug, also you get your string wrong, it should be
PlayerPrefs.GetString("Username " + googleSign.currEmail)
Without
+ "Username "
at the end

Failed to marshal the objective-c object

I am having a tough time with the following error:
Failed to marshal the Objective-C object 0x17109780 (type:
SMBSC_iOS_EddystoneManagerDelegate). Could not find an existing
managed instance for this object, nor was it possible to create a new
managed instance (because the type
'SMBSC.iOS.EddystoneManagerDelegate' does not have a constructor that
takes one IntPtr argument).
I have added the constructor it is looking for, but the application still crashes with this error.
I am working with the Kontakt Xamarin component.
I am creating a new scan with the following line:
manager = new KTKEddystoneManager(new EddystoneManagerDelegate() { ScanID = ID });
Here is the delegate that is causing the error:
public class EddystoneManagerDelegate : KTKEddystoneManagerDelegate
{
public static int closestRssi { get; set; }
public static string closestInstance { get; set; }
public int ScanID { get; set; }
public EddystoneManagerDelegate()
{
}
public EddystoneManagerDelegate(IntPtr handle) : base(handle)
{
}
public override void DidFailToStartDiscovery(KTKEddystoneManager manager, NSError error)
{
Console.WriteLine("Eddystone discovery failed with error: " + error.Description);
}
public override void DidUpdateEddystone(KTKEddystoneManager manager, KTKEddystone eddystone, KTKEddystoneFrameType frameType)
{
string bkpnt = "";
}
public override void DidDiscoverEddystones(KTKEddystoneManager manager, NSSet<KTKEddystone> eddystones, KTKEddystoneRegion region)
{
try
{
Console.WriteLine("");
Console.WriteLine("------------------------------------------------------------------------");
Console.WriteLine("------------------------------------------------------------------------");
Console.WriteLine("------------------------------------------------------------------------");
int i = 0;
foreach (SavedPoint p in App.discoveredBeaconList)
{
i += 1;
Console.WriteLine("Existing Beacon List: " + p.BeaconInstanceID + " - " + p.BeaconTruckDesc + " - " + p.RSSI);
}
if (App.closestBeaconForTracking != null)
{
Console.WriteLine("Selected Beacon Before Logic: " + App.closestBeaconForTracking.instanceID + " RSSI: " + App.closestBeaconForTracking.RSSI);
}
else
{
Console.WriteLine("Selected Beacon Before Logic: no beacon selected");
}
App.singleOutputValue = "";
Console.WriteLine("Discovered " + eddystones.Count + " eddystones");
App.beaconTimer = DateTime.Now;
App.trackingBeaconTimer = DateTime.Now;
MessagingCenter.Send<App>(App.instance, "Output");
if (eddystones.Count == 1)
{
TimeSpan span = DateTime.Now - EddystoneiOS.StartTime;
Console.WriteLine("First Stone found in " + span.TotalSeconds + " seconds");
App.outputValue += " First Stone found in " + span.TotalSeconds + " seconds; " + ScanID + "; " + DateTime.Now.ToString("HH:mm:ss") + Environment.NewLine;
MessagingCenter.Send<App>(App.instance, "Output");
}
else if (eddystones.Count == 2)
{
TimeSpan span = DateTime.Now - EddystoneiOS.StartTime;
Console.WriteLine("Second Stone found in " + span.TotalSeconds + " seconds");
App.outputValue += " Second Stone found in " + span.TotalSeconds + " seconds; " + ScanID + "; " + DateTime.Now.ToString("HH:mm:ss") + Environment.NewLine;
MessagingCenter.Send<App>(App.instance, "Output");
}
else if (eddystones.Count == 3)
{
TimeSpan span = DateTime.Now - EddystoneiOS.StartTime;
Console.WriteLine("Third Stone found in " + span.TotalSeconds + " seconds");
App.outputValue += " Third Stone found in " + span.TotalSeconds + " seconds; " + ScanID + "; " + DateTime.Now.ToString("HH:mm:ss") + Environment.NewLine;
MessagingCenter.Send<App>(App.instance, "Output");
}
else if (eddystones.Count == 4)
{
TimeSpan span = DateTime.Now - EddystoneiOS.StartTime;
Console.WriteLine("Fourth Stone found in " + span.TotalSeconds + " seconds");
App.outputValue += " Fourth Stone found in " + span.TotalSeconds + " seconds; " + ScanID + "; " + DateTime.Now.ToString("HH:mm:ss") + Environment.NewLine;
MessagingCenter.Send<App>(App.instance, "Output");
}
App.closestBeaconForTracking = null;
foreach (var stone in eddystones)
{
KTKEddystone eddystone = (KTKEddystone)stone;
Console.WriteLine(eddystone.RSSI + ", " + eddystone.EddystoneUID.InstanceID);
App.outputValue += " " + eddystone.RSSI + ", " + ScanID + "; " + eddystone.EddystoneUID.InstanceID + Environment.NewLine;
App.instanceID = eddystone.EddystoneUID.InstanceID;
App.NameSpaceID = eddystone.EddystoneUID.NamespaceID;
App.rssi = eddystone.RSSI.Int32Value;
App.BeaconCount = (int)eddystones.Count;
App.lastBeaconTime = DateTime.Now.ToString();
if (App.isViewingBeacons)
{
MessagingCenter.Send<App>(App.instance, "StoneForBeaconList");
}
MapApp.Beacon beacon = App.Database.GetBeaconByID(eddystone.EddystoneUID.InstanceID.ToLower(), eddystone.EddystoneUID.NamespaceID.ToUpper());
if (beacon != null)
{
beacon.RSSI = eddystone.RSSI.Int32Value;
SavedPoint point = new SavedPoint() { BeaconID = beacon.BeaconID, BeaconInstanceID = beacon.instanceID, BeaconName = beacon.Name, BeaconNameSpaceID = beacon.namespaceID, RSSI = beacon.RSSI, BeaconTruckDesc = beacon.truckDesc };
point.LastSeenTime = DateTime.Now;
if (App.discoveredBeaconList == null)
{
App.discoveredBeaconList = new List<SavedPoint>();
}
if (!App.discoveredBeaconList.Exists(x => x.BeaconInstanceID == point.BeaconInstanceID) && beacon.RSSI != 0)
{
App.discoveredBeaconList.Add(point);
}
else
{
foreach (SavedPoint p in App.discoveredBeaconList)
{
if (p.BeaconInstanceID == point.BeaconInstanceID && beacon.RSSI != 0)
{
p.LastSeenTime = DateTime.Now;
p.RSSI = point.RSSI;
}
}
}
}
if (eddystone.RSSI.Int32Value != 0)
{
if (string.IsNullOrWhiteSpace(App.closestBeaconOutput))
{
App.closestBeaconOutput = eddystone.EddystoneUID.InstanceID + " " + eddystone.RSSI;
closestRssi = (int)eddystone.RSSI;
closestInstance = (string)eddystone.EddystoneUID.InstanceID;
MessagingCenter.Send<App>(App.instance, "topOutput");
}
if (closestInstance == eddystone.EddystoneUID.InstanceID)
{
App.closestBeaconOutput = eddystone.EddystoneUID.InstanceID + " " + eddystone.RSSI;
closestRssi = (int)eddystone.RSSI;
closestInstance = (string)eddystone.EddystoneUID.InstanceID;
MessagingCenter.Send<App>(App.instance, "topOutput");
}
if ((int)eddystone.RSSI > closestRssi)
{
App.closestBeaconOutput = eddystone.EddystoneUID.InstanceID + " " + eddystone.RSSI;
closestRssi = (int)eddystone.RSSI;
closestInstance = (string)eddystone.EddystoneUID.InstanceID;
MessagingCenter.Send<App>(App.instance, "topOutput");
}
//if(App.closestBeaconForTracking == null)
//{
// App.closestBeaconForTracking = App.Database.GetBeaconByID(eddystone.EddystoneUID.InstanceID.ToLower(), eddystone.EddystoneUID.NamespaceID.ToUpper());
// if(App.closestBeaconForTracking != null)
// {
// App.closestBeaconForTracking.RSSI = (int)eddystone.RSSI;
// }
//}
//if (App.closestBeaconForTracking != null)
//{
// if (App.closestBeaconForTracking.instanceID.ToLower() == eddystone.EddystoneUID.InstanceID && App.closestBeaconForTracking.namespaceID.ToLower() == eddystone.EddystoneUID.NamespaceID)
// {
// App.closestBeaconForTracking.RSSI = (int)eddystone.RSSI;
// }
// if (eddystone.RSSI.Int32Value > App.closestBeaconForTracking.RSSI)
// {
// App.closestBeaconForTracking = App.Database.GetBeaconByID(eddystone.EddystoneUID.InstanceID.ToLower(), eddystone.EddystoneUID.NamespaceID.ToUpper());
// if (App.closestBeaconForTracking != null)
// {
// App.closestBeaconForTracking.RSSI = (int)eddystone.RSSI;
// }
// }
//}
}
SavedPoint flipPoint = new SavedPoint();
//if(App.discoveredBeaconList.Count > 1)
//{
// try
// {
// if (App.discoveredBeaconList[0].BeaconInstanceID != App.closestBeaconForTracking.instanceID)
// {
// App.discoveredBeaconList.Insert(1, App.discoveredBeaconList[1]);
// App.discoveredBeaconList[0].BeaconInstanceID = App.closestBeaconForTracking.instanceID;
// App.discoveredBeaconList[0].BeaconNameSpaceID = App.closestBeaconForTracking.namespaceID;
// App.discoveredBeaconList[0].BeaconID = App.closestBeaconForTracking.BeaconID;
// App.discoveredBeaconList[0].RSSI = App.closestBeaconForTracking.RSSI;
// }
// }
// catch (Exception ex)
// {
// throw new Exception("Error in App.discoveredBeaconList.Count > 1");
// }
//}
//if(App.discoveredBeaconList.Count > 1)
//{
// if(App.discoveredBeaconList[0].RSSI > App.closestBeaconForTracking.RSSI)
// {
// App.closestBeaconForTracking.instanceID = App.discoveredBeaconList[0].BeaconInstanceID;
// App.closestBeaconForTracking.namespaceID = App.discoveredBeaconList[0].BeaconNameSpaceID;
// App.closestBeaconForTracking.RSSI = App.discoveredBeaconList[0].RSSI;
// App.closestBeaconForTracking.truckDesc = App.discoveredBeaconList[0].BeaconTruckDesc;
// }
//}
App.singleOutputValue += eddystone.EddystoneUID.InstanceID + " " + eddystone.RSSI.Int32Value + "; ";
}
if (App.discoveredBeaconList.Count > 0)
{
SavedPoint topBeacon = App.discoveredBeaconList.OrderByDescending(c => c.RSSI).First();
MapApp.Beacon convertedBeacon = new MapApp.Beacon();
convertedBeacon.RSSI = topBeacon.RSSI;
convertedBeacon.Name = topBeacon.BeaconName;
convertedBeacon.namespaceID = topBeacon.BeaconNameSpaceID;
convertedBeacon.instanceID = topBeacon.BeaconInstanceID;
convertedBeacon.BeaconID = topBeacon.BeaconID;
convertedBeacon.truckDesc = topBeacon.BeaconTruckDesc;
App.closestBeaconForTracking = convertedBeacon;
}
if (App.closestBeaconForTracking != null)
{
Console.WriteLine("Selected Beacon: " + App.closestBeaconForTracking.instanceID + " RSSI: " + App.closestBeaconForTracking.RSSI);
MapApp.Beacon beacon = App.Database.GetBeaconByID(App.closestBeaconForTracking.instanceID, App.closestBeaconForTracking.namespaceID);
if(!string.IsNullOrWhiteSpace(beacon.truckDesc))
{
App.catchTruckDesc = beacon.truckDesc;
//Insights.Identify(App.catchTruckDesc);
}
}
else
{
Console.WriteLine("Selected Beacon: no beacon selected");
}
Console.WriteLine("------------------------------------------------------------------------");
Console.WriteLine("------------------------------------------------------------------------");
Console.WriteLine("------------------------------------------------------------------------");
Console.WriteLine("");
//if (App.closestBeaconForTracking != null && !string.IsNullOrWhiteSpace(App.closestBeaconForTracking.instanceID))
//{
// App.singleOutputValue = "Beacon found at: " + DateTime.Now + Environment.NewLine + App.closestBeaconForTracking.instanceID + " " + App.closestBeaconForTracking.RSSI;
//}
MessagingCenter.Send<App>(App.instance, "singleOutput");
MessagingCenter.Send<App>(App.instance, "UpdateStartText");
MessagingCenter.Send<App>(App.instance, "Output");
}
catch (Exception ex)
{
if (string.IsNullOrWhiteSpace(App.catchFieldDesc))
{
App.catchFieldDesc = "Null";
}
if (string.IsNullOrWhiteSpace(App.catchTruckDesc))
{
App.catchTruckDesc = "Null";
}
Insights.Report(ex, new Dictionary<string, string>() { { "DidDiscoverEddystone", ex.StackTrace }, { "Field Description", App.catchFieldDesc }, { "Truck Description", App.catchTruckDesc } }, Insights.Severity.Critical);
}
}
I have done some searching on the internet, but I have not found anything that would be relevant to my scenario. I'm sure there is an error with my code, but I do not fully understand this error.
I have read that this error can be caused by the Garbage Collector collecting the object.
What exactly does this error mean and what can I look at to attempt a fix?
Thanks!

Efficient method to increase "code" by 1 - HtmlAgilityPack

I'm working on an app that extracts content from a game page (example), displays it to the user in a textbox and if the user wishes to do so, he/she can save it as a .txt file or .xsl (excel spreadsheet format).
But the main problem I'm facing right now is that you have to manually change the code to "extract" data about another in-game unit.
If you open the link you'll see that I'm currently extracting the "Weapons", "Used", "Survived" and "Casualties" from the Defender side (as for now), but only 1 type of unit (more like only 1 row of that table) is being "extracted", I'm looking for a way to search "tr[1]/td[2]/span[1]" through "tr[45]/td[2]/span[1]" (even if the example page only goes until tr[16]), or maybe a way to automate it to search until it finds no data (nothing) then it would stop.
Sorry for any text mistakes, I'm not a native speaker
private void btnStart_Click(object sender, RoutedEventArgs e)
{
HtmlDocument brPage = new HtmlWeb().Load("http://us.desert-operations.com/world2/battleReport.php?code=f8d77b1328c8ce09ec398a78505fc465");
HtmlNodeCollection nodes = brPage.DocumentNode.SelectNodes("/html[1]/body[1]/div[1]/div[1]/div[3]/div[1]/div[1]/div[1]/div[2]/table[2]");
string result = "";
List<brContentSaver> ContentList = new List<brContentSaver>();
foreach (var item in nodes)
{
brContentSaver cL = new brContentSaver();
/* Here comes the junk handler, replaces all junk for nothing, essentially deleting it
I wish I knew a way to do this efficiently */
cL.Weapons = item.SelectSingleNode("tr[16]/td[1]").InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
cL.Used = item.SelectSingleNode("tr[16]/td[2]/span[1]").InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
cL.Survived = item.SelectSingleNode("tr[16]/td[3]").InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
if (cL.Survived == "0")
{
cL.Casualties = cL.Used;
} else
{
/* int Casualties = int.Parse(cL.Casualties);
* int Used = int.Parse(cL.Used);
* int Survived = int.Parse(cL.Survived);
* Casualties = Used - Survived; */
cL.Casualties = item.SelectSingleNode("tr[16]/td[4]").InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
}
ContentList.Add(cL);
}
foreach (var item in ContentList)
{
result += item.Weapons + " " + item.Used + " " + item.Survived + " " + item.Casualties + Environment.NewLine;
}
brContent.Text = result;
}
Sorry if this sounds silly, but I'm new to programming, especially in C#.
Edit 1: I noticed that "if (cL.Survived == "0")", I was just testing stuff some stuff way earlier and I forgot to change it, but hey, it works
Edit 2: If you are wondering I'm also using this:
public class brContentSaver
{
public string Weapons
{
get;
set;
}
public string Used
{
get;
set;
}
public string Survived
{
get;
set;
}
public string Casualties
{
get;
set;
}
}
I don't have much time to write this but hope it will help if you still need. I find Linq is more handy:
private static void Run()
{
HtmlDocument brPage = new HtmlWeb().Load("http://us.desert-operations.com/world2/battleReport.php?code=f8d77b1328c8ce09ec398a78505fc465");
var nodes = brPage.DocumentNode.Descendants("table").Where(_ => _.Attributes["class"] != null && _.Attributes["class"].Value != null && _.Attributes["class"].Value.Contains("battleReport"));
string result = "";
List<brContentSaver> ContentList = new List<brContentSaver>();
foreach (var item in nodes)
{
if (item.Descendants("th").Any(_ => _.InnerText.Equals("Weapons")))
{
//get all tr nodes except first one (header)
var trNodes = item.Descendants("tr").Skip(1);
foreach (var node in trNodes)
{
brContentSaver cL = new brContentSaver();
var tds = node.Descendants("td").ToArray();
/* Here comes the junk handler, replaces all junk for nothing, essentially deleting it
I wish I knew a way to do this efficiently */
cL.Weapons = tds[0].InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
cL.Used = tds[1].Descendants("span").FirstOrDefault()?.InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
if (string.IsNullOrEmpty(cL.Used))
{
cL.Used = tds[1].InnerText;
}
cL.Survived = tds[2].Descendants("span").FirstOrDefault()?.InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
if (string.IsNullOrEmpty(cL.Survived))
{
cL.Casualties = cL.Used;
}
else
{
/* int Casualties = int.Parse(cL.Casualties);
* int Used = int.Parse(cL.Used);
* int Survived = int.Parse(cL.Survived);
* Casualties = Used - Survived; */
cL.Casualties = tds[3].Descendants("span").FirstOrDefault()?.InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
if (string.IsNullOrEmpty(cL.Casualties))
{
cL.Casualties = tds[3].InnerText;
}
}
ContentList.Add(cL);
}
}
}
foreach (var item in ContentList)
{
result += item.Weapons + " " + item.Used + " " + item.Survived + " " + item.Casualties + Environment.NewLine;
}
var text = result;
}

Input string was not in the correct format with Entity Framework

I'm getting the following exception:
"Input string was not in the correct format."
I'm taking a Json response which is comma delimited and storing it in a database. I'm not sure what is wrong.
Here is the code:
foreach (string s in skaters)
{
skaterData = s.Split(stringSeparator2, StringSplitOptions.None);
Console.WriteLine(skaterData[0] + " " + skaterData[1] + " " + skaterData[2] + " " + skaterData[3] + " " + skaterData[4] + " " + skaterData[5] +
" " + skaterData[6] + " " + skaterData[7] + " " + skaterData[8] + " " + skaterData[9] + " " + skaterData[10] + " " + skaterData[11] + " " + skaterData[12]
+ " " + skaterData[13] + " " + skaterData[14] + " " + skaterData[15]);
try
{
using (var _temp_Player = new FetcherEntities())
{
//int validPlayer;
//int validTeam;
//Skater_Season existingPlayer = _temp_Player.Skater_Season.FirstOrDefault(x => x.player_id == Convert.ToInt32(skaterData[1]) && x.team_id = Convert.ToInt32(skaterData[2]));
// if (existingPlayer != null)
// {
// Console.WriteLine("Existing player: " + existingPlayer.NAME);
// }
// else
// {
_temp_Player.Skater_Season.Add(new Skater_Season
{
player_id = Int32.Parse(skaterData[0]), //stuck here
team_id = Int32.Parse(team),
season_id = season,
Number = Int32.Parse(skaterData[1]),
POS = skaterData[2],
NAME = skaterData[3],
GP = Int32.Parse(skaterData[4]),
G = Int32.Parse(skaterData[5]),
A = Int32.Parse(skaterData[6]),
P = Int32.Parse(skaterData[7]),
plusminus = Int32.Parse(skaterData[8]),
PIM = Int32.Parse(skaterData[9]),
S = Int32.Parse(skaterData[10]),
TOIG = skaterData[11],
PP = Int32.Parse(skaterData[12]),
SH = Int32.Parse(skaterData[13]),
GWG = Int32.Parse(skaterData[14]),
OT = Int32.Parse(skaterData[15])
});
try
{
_temp_Player.SaveChanges();
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e);
}
}
}
catch (DbEntityValidationException forwardDB)
{
foreach (DbEntityValidationResult entityError in forwardDB.EntityValidationErrors)
{
foreach (DbValidationError error in entityError.ValidationErrors)
{
Console.WriteLine("Error Name: {0} : Message: {1}", error.PropertyName, error.ErrorMessage);
return false;
}
}
}
}
Also I've attached some screen shots of what the data looks like.
Its hard to tell you exactly where the error is but that message is being thrown by one of the Int32.Parse methods receiving data that it cant parse.
The best solution is to use TryParse which allows you to gracefully continue if a problem occurs.

C# - Problem with reading XML more that once. Also error check if exists. [XElement]

Updated with the changes suggested below.
I've been trying to de-bug this for about 2 days now for 3-4 hours on and off and haven't gotten far. Any help is appreciated.
Alright, so essentially this runs every time someone dies. If I run it once, it works fine. However, If I run it a second time it returns nothing.
public static string Death(string username)
{
if (File.Exists(path))
{
XElement kd = XElement.Load(path);
Console.WriteLine("[SimplePlugin] Death Recorded for: " + username + "!");
var player = kd.Elements("player").Single(p => p.Attribute("name").Value == username);
int add = int.Parse(player.Element("deaths").Value) + 1; //Dies Here.
player.SetElementValue("deaths", add);
player.Save(path);
kills = int.Parse(player.Element("kills").Value);
deaths = int.Parse(player.Element("deaths").Value);
return (username + " has " + kills + " kills and " + deaths + " deaths.");
}
else
{
Console.WriteLine("[SimpleStats] Writing SimpleConfig.XML...");
XElement kd = new XElement(
"SimpleStats",
new XElement("player",
new XAttribute("name", username),
new XElement("kills", 0),
new XElement("deaths", 0),
new XElement("time", 0)));
kd.Save(path);
Console.WriteLine("[Simple] Done!");
return (username + " has " + kills + " kills and " + deaths + " deaths.");
}
}
My second problem comes when the player name="NAME" in the XML already exists. Even if the username matches, it re-creates it.
Code for this:
public static string Load(string username)
{
if (File.Exists(path))
{
XElement kd = XElement.Load(path);
var player = kd.Elements("player").SingleOrDefault(p => p.Attribute("name").Value == username);
Console.WriteLine(player);
if (player == null)
{
Console.WriteLine("[SimplePlugin] Writing new XML data for " + username + ".");
kd.Add(new XElement("player",
new XAttribute("name", username),
new XElement("kills", 0),
new XElement("deaths", 0),
new XElement("time", 0)));
kd.Save(path);
return (username + " has " + kills + " kills and " + deaths + " deaths.");
}
else
{
kills = int.Parse(player.Element("kills").Value);
deaths = int.Parse(player.Element("deaths").Value);
return (username + " has " + kills + " kills and " + deaths + " deaths.");
}
}
else
{
Console.WriteLine("Doesnt Exist");
Console.WriteLine("[SimpleStats] Writing SimpleConfig.XML...");
XElement player = new XElement(
"SimpleStats",
new XElement("player",
new XAttribute("name", username),
new XElement("kills", 0),
new XElement("deaths", 0),
new XElement("time", 0)));
player.Save(path);
Console.WriteLine("[Simple] Done!");
return (username + " has " + kills + " kills and " + deaths + " deaths.");
}
}
A string is sent to Load(). Load check to see if the xml exists. If not, creates it. If so, creates it. Then check to see if the username exists in the xml data. If it does it reads it and returns that string. If it doesn't, it creates it.
Also: "This question does not show any research effort; it is unclear or not useful"
How?
The second problem: you need to use Value property to get the attribute value.
var player = kd.Elements("player").SingleOrDefault(p => p.Attribute("name").Value == username);
You need to revise your entire code. For example, these lines will give you unexpected results:
kills = (int)player.Element("kills"); // explicit casting XElement to int, will return the pointer value.
deaths = (int)player.Element("deaths");
The correct sequence is
kills = int.Parse(player.Element("kills").Value);
deaths = int.Parse(player.Element("deaths").Value);
For your first issue, do this
player.Element("deaths").Value = Convert.ToInt32(player.Element("deaths").Value) + 1;
As XElement.Value is of type System.String

Categories

Resources