I don't get exceptions when I enter invalid inputs - c#

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

Related

Unity3d - IntemDatabase.cs gives an error (FormatException: Input string was not in the correct format)

G'day,
I am currently working on a Unity3d project and get this error while working on the ItemDatabase.cs file. The code looks fine to me but I get the error for some reason. Could I please get some help with fixing the error.
Thanks,
https://i.stack.imgur.com/xUETY.png
ItemDatabase.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
[System.Serializable]
public struct Item
{
public int ID;
public string Name;
public bool Stackable;
public string Slug;
public Item(int id, string name, bool stackable, string slug){
ID = id;
Name = name;
Stackable = stackable;
Slug = slug;
}
}
public class ItemDatabase : MonoBehaviour {
public List<Item> itemDatabase = new List<Item>();
// Use this for initialization
void Start () {
GetDatabase("Assets/Resources/ItemData.txt");
}
// Update is called once per frame
void Update () {
}
void GetDatabase(string path)
{
StreamReader sr = new StreamReader(path);
AddItem:
itemDatabase.Add(new Item(
int.Parse(sr.ReadLine().Replace("id", "")),
sr.ReadLine().Replace("name: ",""),
bool.Parse(sr.ReadLine().Replace("stackable: ","")),
sr.ReadLine().Replace("slug: ","")
));
string c = sr.ReadLine();
if(c == ",")
{
goto AddItem;
}
else if(c == ";")
{
sr.Close();
}
}
}
The error message here is quite explicit in what it's telling you - you're calling int.Parse() on a string that it can't recognise as an integer value here:
itemDatabase.Add(new Item(
int.Parse(sr.ReadLine().Replace("id", "")),
sr.ReadLine().Replace("name: ",""),
bool.Parse(sr.ReadLine().Replace("stackable: ","")),
sr.ReadLine().Replace("slug: ","")
));
You're going to need to double-check what input you are passing to GetDatabase and go from there.

I am attempting to validate user input before uploading to a database. I have linked my Validation and main code, but I keep receiving an error

ERROR:
System.FormatException: 'Input string was not in a correct format.'
I am having the user input into a form, but before it is accepted it must be validated (starting with IsFilledIn()). I have parsed the string from the textbox in the form to an int so it can go into the DB. It seems it is completely skipping validation when I hit submit but have included all that is need (I think).
Current code:
Form1:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Lab5_validation;
using System.Data.SqlClient;
namespace FinalAJG
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnsubmit_Click(object sender, EventArgs e)
{
Character temp = new Character();
//Sets temporary Variables
temp.CharName = txtCharName.Text;
temp.Health = Int32.Parse(txtHealth.Text);
temp.Lvl = Int32.Parse(txtLvl.Text);
temp.Agility = Int32.Parse(txtAgility.Text);
temp.Strength = Int32.Parse(txtStrength.Text);
temp.Stamina = Int32.Parse(txtStamina.Text);
temp.Armor = Int32.Parse(txtArmor.Text);
temp.HoursPlayed = Double.Parse(txtHoursPlayed.Text);
temp.PlayedSince = DateTime.Parse(txtPlayedSince.Text);
temp.Cass = txtClass.Text;
if (!temp.Feedback.Contains("ERROR:"))
{
Feedback.Text = temp.AddARecord();
}
else
{
Feedback.Text = temp.Feedback;
}
}
}
}
Character.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using Lab5_validation;
namespace FinalAJG
{
class Character
{
//Define PRIVATE variables.
bool blnResult;
private string charname;
private string cass;
private int health;
private int lvl;
private int agility;
private int strength;
private int stamina;
private int armor;
private double hoursplayed;
private DateTime playedsince;
private float AvgPlayTime=777;
private int TotalPoints=444;
public string feedback = "";
// Creates Public variables the users can input to, then stores them to private variable if validated correctly.
public string CharName
{
get
{
//Returns private variable to class.
return charname;
}
set
{
//IF-ELSE statement to validate user input.
if (ValidationLibrary.IsItFilledIn(value))
{
// Sets private variable 'fName' to equal user input on public variable.
charname = value;
}
else
{
//If they enter invalid input, the feed back will be set to an error message, and the private variable will not be set.
feedback += "\n\nERROR: Enter your charcters name!!!";
}
}
}
//Public variable to receive user input securly.
public string Cass
{
get
{
//Returns Private variable
return cass;
}
set
{ //IF-ELSE statement to validate user input.
if (ValidationLibrary.IsItFilledIn(value))
{
cass = value; // Sets Private Variable
}
else
{//Feedback gives error IF validation
feedback += "\n\nERROR: Enter your Class!(ONLY OPTIONS ARE, Mage, Assassin, Warrior, Archer, Druid, and Warlock!!";
}
}
}
//Same as previous Public Variables
public int Health
{
get
{
return health;
}
set
{ //Checks for user input, if not true give error feedback.
if (ValidationLibrary.IsItFilledIn(value.ToString()))
{
health = value;
}
else
{
feedback += "\n\nERROR: Enter Characters Health (25-100)!! ";
}
}
}
//Same as previous Public Variables
public int Lvl
{
get
{
return lvl;
}
set
{
if (ValidationLibrary.IsItFilledIn(value.ToString()))
{
lvl = value;
}
else
{
feedback += "\n\nERROR:Enter your Characters level! (1-80)\n ";
}
}
}
//Same as previous Public Variables, except it will not be required to fill it in.
public int Agility
{
get
{
return agility;
}
set
{
if (ValidationLibrary.IsItFilledIn(value.ToString()))
{
agility = value;
}
else
{
feedback += "\n\nERROR:Enter valid Date!! (02-20-2020, 11/11/2011, 06/24/2019)";
}
}
}
//Same as previous Public Variables
public int Strength
{
get
{
return strength;
}
set
{
//Validates to ensure the required length of zipcode is entered
if (ValidationLibrary.IsItFilledIn(value.ToString()))
{
do
{
strength = value;
} while (blnResult == true);
}
else
{
feedback += "\n\nERROR:Enter Characters strength!! (1-25) ";
}
}
}
//Same as previous Public Variables
public int Stamina
{
get
{
return stamina;
}
set
{
if (ValidationLibrary.IsItFilledIn(value.ToString()))
{
stamina = value;
}
}
}
//Same as previous Public Variables except the validation checks for valid characters and the correct length
public int Armor
{
get
{
return armor;
}
set
{
if (ValidationLibrary.IsItFilledIn(value.ToString()))
{
armor = value;
}
else
{
feedback += "\n\nERROR:Enter Valid armor rating!! (10-50) ";
}
}
}
//Same as previous Public Variables
public double HoursPlayed
{
get
{
return hoursplayed;
}
set
{
if (ValidationLibrary.IsItFilledIn(value.ToString()))
{
hoursplayed = value;
}
else
{
feedback += "\n\nERROR:Enter Valid Number!!(.5, 2.3, 6.4, 92)";
}
}
}
//Same as previous Public Variables except checks for required characters for a valid Email.
public DateTime PlayedSince
{
get
{
return playedsince;
}
set
{
if (ValidationLibrary.IsItFilledIn(value.ToString()))
{
playedsince = value;
}
else
{
feedback += "\n\nERROR:Enter valid Date!! (02-20-2020, 11/11/2011, 06/24/2019)";
}
}
}
// Feedback variable to display results or error message.
public string Feedback
{
get
{
return feedback;
}
set
{ // IF feedback contains 'ERROR' then leave it blank and display which input was incorrect
if (feedback.Contains("ERROR:"))
{
feedback += "";
}
//ELSE, store and display the results.
else
{
feedback = value;
}
}
}
public string AddARecord()
{
//Init string var
string strResult = "";
//Make a connection object
SqlConnection Conn = new SqlConnection();
//Initialize it's properties
Conn.ConnectionString = ********************";//Set the Who/What/Where of DB
//Sends command to SQL Server
string strSQL = "INSERT INTO Chars (CharName, Class, Health, Lvl, Agility, Strength, Stamina, Armor, HoursPlayed, PlayedSince, AvgPlayTime, TotalPoints) VALUES (#CharName, #Class, #Health, #Level, #Agility, #Strength, #Stamina, #Armor, #HoursPlayed, #PlayedSince, #AvgPlayTime, #TotalPoints)";
// Sends out Command
SqlCommand comm = new SqlCommand();
comm.CommandText = strSQL; //Commander knows what to say
comm.Connection = Conn; //Where's the phone? Here it is
// Adds all parameters.
comm.Parameters.AddWithValue("#CharName", CharName);
comm.Parameters.AddWithValue("#Class", Cass);
comm.Parameters.AddWithValue("#Health", Health);
comm.Parameters.AddWithValue("#Level", Lvl);
comm.Parameters.AddWithValue("#Agility", Agility);
comm.Parameters.AddWithValue("#Strength", Strength);
comm.Parameters.AddWithValue("#Stamina", Stamina);
comm.Parameters.AddWithValue("#Armor", Armor);
comm.Parameters.AddWithValue("#HoursPlayed", HoursPlayed);
comm.Parameters.AddWithValue("#PlayedSince", PlayedSince);
comm.Parameters.AddWithValue("#AvgPlayTime", AvgPlayTime);
comm.Parameters.AddWithValue("#TotalPoints", TotalPoints);
//Attempts to connect to the Database server
try
{
//Calls to the database server, like dialing a phone.
Conn.Open();
int intRecs = comm.ExecuteNonQuery();
//Output to rhe user the success of inserting records
strResult = $"SUCCESS: Inserted {intRecs} records.";
//Close the Connection to Database Server
Conn.Close();
}
//This will catch any errors if we run into issues connecting.
catch (Exception err)
{
//Displays The Error.
strResult = "ERROR: " + err.Message;
}
finally
{
}
return strResult;
}
public DataSet SearchPerson(String strCharName, String strCharID)
{
//Create a dataset to return filled
DataSet ds = new DataSet();
//Create a command for our SQL statement
SqlCommand comm = new SqlCommand();
//Write a Select Statement to perform Search
String strSQL = "SELECT CharID, CharName, Class, Health, Level, Agility, Strength, Armor, HoursPlayed, PlayedSince, AvgPlayTime, TotalPoints FROM Chars WHERE 0=0";
//If the First/Last Name is filled in include it as search criteria
if (strCharName.Length > 0)
{
strSQL += " AND CharName LIKE #CharName";
comm.Parameters.AddWithValue("#CharName", "%" + strCharName + "%");
}
if (strCharID.Length > 0)
{
strSQL += " AND CharID LIKE #CharID";
comm.Parameters.AddWithValue("#CharID", "%" + strCharID + "%");
}
//Create DB tools and Configure
//*********************************************************************************************
SqlConnection conn = new SqlConnection();
//Create the who, what where of the DB
string strConn = #GetConnected();
conn.ConnectionString = strConn;
//Fill in basic info to command object
comm.Connection = conn; //tell the commander what connection to use
comm.CommandText = strSQL; //tell the command what to say
//Create Data Adapter
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm; //commander needs a translator(dataAdapter) to speak with datasets
//*********************************************************************************************
//Get Data
conn.Open(); //Open the connection (pick up the phone)
da.Fill(ds, "Chars_Temp"); //Fill the dataset with results from database and call it "EBooks_Temp"
conn.Close(); //Close the connection (hangs up phone)
//Return the data
return ds;
}
private string GetConnected()
{
return ************************
}
// Initialize Public Class from person().
public Character()
{
charname = "";
cass = "";
health = 25;
lvl = 1;
agility = 1;
strength = 1;
stamina = 1;
armor = 10;
hoursplayed = 0;
playedsince = DateTime.Now;
feedback = "";
}
}
}
Validation:
//Allen J. Gawlowicz
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lab5_validation
{
public class ValidationLibrary
{
bool result = false;
string temp;
//Validates for alphabetical input only.
public static bool Goodchar(string temp)
{
bool result = false;
string strGoodChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// FOR EACH charcacter in Variable, check to make sure it is Alphabetical
foreach (char ch in strGoodChars.ToUpper())
{//If the variable contains only alphabetical, result= true.
if (temp.Contains(ch))
{
result = true;
}
}
return result;
}
//Checks to see if user inputs a bad word.
public static bool GotBadWords(string temp)
{
bool result = false;
//Array which holds all bad words to ever exist!!
string[] strBadwords = { "POOP", "HOMEWORK", "CACA" };
// FOR EACH word in the array it checks to see if input value matches.
foreach (string strBW in strBadwords)
{
if (temp.Contains(strBW))
{
result = true;
}
}
return result;
}
//Function which checks if user inputs.
public static bool IsItFilledIn(string temp)
{
bool result = false;
//If the number of characters entered is greater than 0 (then obviously), it is filled in (true).
if (temp.Length > 0)
{
result = true;
}
return result;
}
//Function which checks if user input is a future date.
public static bool IsAFutureDate(DateTime temp)
{
bool blnResult;
//IF usrr input is today or before, then blnRes = false.
if (temp <= DateTime.Now)
{
blnResult = false;
}
else
{
blnResult = true;
}
return blnResult;
}
//Function which checks user email input for '#' and '.'.
public static bool IsValidEmail(string temp)
{
bool blnResult = true;
int atLocation = temp.IndexOf("#");
int NexttatLocation = temp.IndexOf("#", atLocation + 1);
int periodLocation = temp.LastIndexOf(".");
if (temp.Length < 8)
{
blnResult = false;
}
else if (atLocation < 2)
{
}
else if (periodLocation + 2 > (temp.Length))
{
blnResult = false;
}
return blnResult;
}
//Function which checks for '.' in the input URL.
public static bool IsValidUrl(string temp)
{
bool blnResult = true;
int NexttatLocation = temp.IndexOf(".");
int periodLocation = temp.LastIndexOf(".");
if (temp.Length < 10)
{
blnResult = false;
}
else if (periodLocation + 2 > (temp.Length))
{
blnResult = false;
}
return blnResult;
}
//Function which checks user input for a specific length. ('min' will changed depending on variable in main program).
public static bool IsMinimumAmount(string temp, int min)
{
bool blnResult;
if (temp.Length >= min)
{
blnResult = true;
}
else
{
blnResult = false;
}
return blnResult;
}
public static bool IsMinimumAmount(double temp, double min)
{
bool blnResult;
if (temp >= min)
{
blnResult = true;
}
else
{
blnResult = false;
}
return blnResult;
}
}
}
Program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using Lab5_validation;
namespace FinalAJG
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
Your Parse methods cannot accept an empty string. Instead, I suggest TryParse, which will try to parse the string, and if it fails then you will get the default value for the assignment target. So if you do this:
int.TryParse(txtHealth.Text, out temp.Health);
The value of temp.Health will be the parsed value of the string, or it will be the default (which is 0 for int).
The same approach can be used for double and DateTime, so:
double.TryParse(txtHoursPlayed.Text, out temp.HoursPlayed);
DateTime.TryParse(txtPlayedSince.Text, out temp.PlayedSince);
Alternatively, you can check if the input string IsNullOrWhiteSpace and assign a default if that's true:
temp.Health = string.IsNullOrWhiteSpace(txtHealth.Text) ? 0 : int.Parse(txtHealth.Text);
But of course the TryParse methods are generally cleaner.

Multiple foreach passes to different class lists

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.

I am trying to access data in a C# packet I've created, however I keep getting null as a response. What am I doing wrong?

Okay, so I'm working with custom network code for pretty much the first time. I have a packet created to transfer some game information back and forth, however beyond the initial content if I try to access some of the commands, I get "null" - though on the server side, it's showing as properly populated.
I have a feeling that this has to do with the setup in receiving the data. The code for the packet follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public enum DataIdentifier
{
Message,
Command,
LogIn,
LogOut,
Null
}
public class Packet
{
private DataIdentifier dataIdentifier;
private string name;
private string player;
private string playerData;
private string message;
private string command;
private string x;
private string y;
private string z;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public string Player
{
get
{
return player;
}
set
{
player = value;
}
}
public string Message
{
get
{
return message;
}
set
{
message = value;
}
}
public string Command
{
get
{
return command;
}
set
{
command = value;
}
}
public DataIdentifier DataIdentifier
{
get
{
return dataIdentifier;
}
set
{
dataIdentifier = value;
}
}
public string PlayerData
{
get
{
return playerData;
}
set
{
playerData = value;
}
}
public string X
{
get
{
return x;
}
set
{
x = value;
}
}
public string Y
{
get
{
return y;
}
set
{
y = value;
}
}
public string Z
{
get
{
return z;
}
set
{
z = value;
}
}
public Packet()
{
this.DataIdentifier = DataIdentifier.Null;
this.message = null;
this.name = null;
this.player = null;
this.playerData = null;
this.x = null;
this.y = null;
this.z = null;
this.command = null;
}
public Packet(byte[] dataStream)
{
// Read the data identifier from the beginning of the stream (4 bytes)
this.DataIdentifier = (DataIdentifier)BitConverter.ToInt32(dataStream, 0);
// Read the length of the name (4 bytes)
int nameLength = BitConverter.ToInt32(dataStream, 4);
// Read the length of the message (4 bytes)
int msgLength = BitConverter.ToInt32(dataStream, 8);
// Read the name field
if (nameLength > 0)
this.name = Encoding.UTF8.GetString(dataStream, 12, nameLength);
else
this.name = null;
// Read the message field
if (msgLength > 0)
this.message = Encoding.UTF8.GetString(dataStream, 12 + nameLength, msgLength);
else
this.message = null;
}
public byte[] GetDataStream()
{
List<byte> dataStream = new List<byte>();
// Add the dataIdentifier
dataStream.AddRange(BitConverter.GetBytes((int)this.DataIdentifier));
// Add the name length
if (this.name != null)
dataStream.AddRange(BitConverter.GetBytes(this.name.Length));
else
dataStream.AddRange(BitConverter.GetBytes(0));
// Add the message length
if (this.message != null)
dataStream.AddRange(BitConverter.GetBytes(this.message.Length));
else
dataStream.AddRange(BitConverter.GetBytes(0));
// Add the name
if (this.name != null)
dataStream.AddRange(Encoding.UTF8.GetBytes(this.name));
// Add the message
if (this.message != null)
dataStream.AddRange(Encoding.UTF8.GetBytes(this.message));
if (this.playerData != null)
{
dataStream.AddRange(Encoding.UTF8.GetBytes(this.playerData));
}
if (this.command != null)
{
dataStream.AddRange(Encoding.UTF8.GetBytes(this.command));
}
if (this.x != null)
{
dataStream.AddRange(Encoding.UTF8.GetBytes(this.x));
}
if (this.y != null)
{
dataStream.AddRange(Encoding.UTF8.GetBytes(this.y));
}
if (this.z != null)
{
dataStream.AddRange(Encoding.UTF8.GetBytes(this.z));
}
return dataStream.ToArray();
}
}
This is how the packet is recieved:
// Receive all data
this.clientSocket.EndReceive(AR);
// Initialise a packet object to store the received data
Packet receivedData = new Packet(this.dataStream);
// Evaulate command played
if (PacketDelegate != null)
{
PacketDelegate(receivedData);
}
// Reset data stream
this.dataStream = new byte[8142];
// Continue listening for broadcasts
clientSocket.BeginReceiveFrom(this.dataStream, 0, this.dataStream.Length, SocketFlags.None, ref epServer, new AsyncCallback(this.ReceiveCallback), null);
And this is the delegate function responsible for handling a packet:
public void RecievePacket(Packet Communication)
{
// Check and manipulate the contents of the packet here //
}
I have confirmed that I can get name, DataIdentifier, and Message, but it's the additional information I've added to the packet itself - player/data, command, x,y,z, I can't seem to get.
My thought is that the problem exists in establishing Packet(byte[] dataStream). However, I'm not quite sure how to calculate or add the additional variables to this. Can anyone give me some tips on how to do so?

Parse.Com and getting the relational data

I have the following code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using OpenFridge.Portable.Data.Interfaces.Entities;
using OpenFridge.Portable.Data.Parse.Entities;
using Parse;
using AutoMapper;
namespace OpenFridge.Portable.Data.Parse.Entities
{
[ParseClassName("_User")]
public class ParseUserEntity : ParseUserEntityBase, IUserEntity
{
private string _password;
[ParseFieldName("password")]
public new string Password
{
get { return _password; }
set
{
_password = value;
base.Password = value;
}
}
Lazy<IEnumerable<IBankAccountEntity>> _bankAccounts;
[ParseFieldName("bankAccounts")]
public Lazy<IEnumerable<IBankAccountEntity>> BankAccounts
{
get
{
var relation = GetRelation<ParseBankAccountEntity>("BankAccount");
if (relation == null) return null;
var result = relation.Query.FindAsync().Result;
var _bankAccounts = new Lazy<IEnumerable<IBankAccountEntity>>(() => relation.Query.FindAsync().Result);
return _bankAccounts;
}
set
{
_bankAccounts = value;
}
}
}
}
And it all seems to work quite fine, however.. once I use the .BankAccounts property I get the following exception:
Must specify a ParseObject class name when creating a ParseQuery.\r\nParameter name: className
Which I find strange since there is no way for me to define a classname with in that line of code:
(That line of code beeing:)
relation.Query.FindAsync().Result
So.. is this a bug?.. Am I doing something wrong or using it wrong?
Any ideas?
Br,
Inx

Categories