Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

ArgumentNullException: Argument cannot be null. Simple login

Discussion in 'Scripting' started by michalides, Apr 11, 2017.

  1. michalides

    michalides

    Joined:
    Jan 9, 2017
    Posts:
    15
    Hi,
    I have a problem with simple login (from here https://github.com/bdodroid/SimpleScripts-LoginSystem)
    Everything works fine but when i want to log in it says:

    ArgumentNullException: Argument cannot be null.
    Parameter name: s
    System.Int32.Parse (System.String s) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System/Int32.cs:629)
    Login+<WWWSubmit>c__Iterator13.MoveNext () (at Assets/xxx/Demo/Login.cs:119)

    upload_2017-4-11_14-24-19.png

    Please help me, i have the same code as here so you can check
    https://github.com/bdodroid/SimpleScripts-LoginSystem

    Login.cs
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using UnityEngine.UI;
    4. using JSONhandler;
    5.  
    6. public class Login : MonoBehaviour {
    7.     //fields and toggles using unitys new UI system. Create an InputField in the editor (right-click->ui->inputFiled) then attach it from the Hierachy.
    8.     public InputField email;
    9.     public InputField pass;
    10.     public InputField pass2;
    11.     public InputField secQ;//I just use an input field for simplicity but you could easily change this to a drop down selection box or something.
    12.     public InputField secA;
    13.     public Toggle autoLogin;
    14.  
    15.     public GameObject responseText; //a ui text filed we update with information we plan on showing the user, ie. Login Success!/Email not found!
    16.  
    17.     //variables we want to keep during the enitre session, like PlayerID and Username, etc.
    18.     public static int userID;
    19.     public static string userEmail;
    20.  
    21.     public string URL = ""; //add the address to your php file in this line or the editor (editor overwrites whats here). example: http://yoursite.com/login.php
    22.     public string hash = "theHashCode"; //this is a secret hashcode that needs to match the one you set in your php page. See login.php for example
    23.  
    24.     public void Start(){
    25.         CheckToggle ();
    26.         StartCoroutine(CheckConnection());//check the connection then run FirstRun function
    27.     }
    28.  
    29.     private IEnumerator CheckConnection() {
    30.         Ping pingServer = new Ping("8.8.8.8");
    31.         float startTime = Time.time;
    32.         while (!pingServer.isDone && Time.time < startTime + 2.0f) {
    33.             yield return new WaitForSeconds(0.1f);
    34.         }
    35.         if(pingServer.isDone) {
    36.             LoginSetup(true);//function we run if we have a connection
    37.         } else {
    38.             LoginSetup(false);//function if we do not have a connection
    39.         }
    40.     }
    41.  
    42.     private void LoginSetup(bool connected){
    43.         if (connected) {
    44.             //check player prefs and login if auto-login is checked
    45.             if(PlayerPrefs.HasKey("email") && PlayerPrefs.HasKey("pass")){
    46.                 if(PlayerPrefs.GetInt("autoLogin") == 1){
    47.                     email.text = PlayerPrefs.GetString("email");
    48.                     pass.text = PlayerPrefs.GetString("pass");
    49.                     LoginAccount();
    50.                 }else{
    51.                     email.text = PlayerPrefs.GetString("email");
    52.                 }
    53.             }
    54.         } else {
    55.             if(PlayerPrefs.HasKey("userID") && PlayerPrefs.HasKey("email")){//check for stored login data
    56.                 userID = PlayerPrefs.GetInt("userID");
    57.                 userEmail = PlayerPrefs.GetString("email");
    58.             }else{//if we have no stored data we create a guest user and continue on to the game.
    59.                 userID = -1;
    60.                 userEmail = "guest@guest.guest";
    61.                 PlayerPrefs.SetInt("userID", userID);
    62.                 PlayerPrefs.SetString("email", userEmail);
    63.             }
    64.             //to game scene because we are not using
    65.         //    Application.loadedLevel(1);
    66.         }
    67.     }
    68.  
    69.     //used for Unity UI button presses.
    70.     public void LoginAccount(){
    71.         StartCoroutine(WWWSubmit("false"));
    72.     }
    73.     public void CreateAccount(){
    74.         StartCoroutine(WWWSubmit("true"));
    75.     }
    76.     public void ToggleAutoLogin(){
    77.         var toggleValue = 0;
    78.         if (autoLogin.isOn) {
    79.             toggleValue = 1;
    80.         } else {
    81.             toggleValue = 0;
    82.         }
    83.         PlayerPrefs.SetInt("autoLogin", toggleValue);
    84.     }
    85.  
    86.     private void CheckToggle(){//check if we want to auto login
    87.         if (PlayerPrefs.HasKey ("autoLogin")) {
    88.             var toggleStatus = PlayerPrefs.GetInt ("autoLogin");
    89.             if (toggleStatus == 1) {
    90.                 autoLogin.isOn = true;
    91.             }
    92.         }
    93.     }
    94.  
    95.     IEnumerator WWWSubmit(string creatingAccount) {
    96.         var form = new WWWForm(); //create a new form for submiting
    97.  
    98.         //here we add all the fields we want to send over. They must match the $_POST["namehere"] in your php script
    99.         form.AddField( "hash", hash ); //hash code must be sent! it is the only thing really securing yout login attempt
    100.         form.AddField( "email", email.text );
    101.         form.AddField( "pass", pass.text );
    102.         form.AddField("pass2", pass2.text);
    103.         form.AddField("securityQuestion", secQ.text);
    104.         form.AddField("securityAnswer", secA.text);
    105.         form.AddField ("creatingAccount", creatingAccount);
    106.  
    107.         var phpData = new WWW(URL, form); //here we create a variable that submits the form data and returns the response from our php page.
    108.  
    109.         yield return phpData; //we wait for the response from the server before continuing.
    110.  
    111.         if (phpData.error != null) {
    112.             responseText.GetComponent<Text>().text = phpData.error; //if for some reason the www failes we report it out here.
    113.         } else {
    114.             //this is assuming you return a JSON string. You can return a single string if you want but JSON is much more flexible, especially when dealing with arrays.
    115.             var parsedData = JSON.Parse(phpData.text);
    116.             if(parsedData != null){//if we get a JSON string back
    117.                 userEmail = parsedData[1]["email"]; //an issue where JSON keeps returning slot 0 as empty. Working on it, but in the mean time 1 is the first slot.
    118.                 userID = int.Parse(parsedData[1]["ID"]);
    119.                 responseText.GetComponent<Text>().text = "CONNECTED";
    120.                 SetPlayerPrefs();
    121.             }else{//if we dont get a JSON string back
    122.                 responseText.GetComponent<Text>().text = phpData.text; //show the returned string. Login/Failed etc.
    123.             }
    124.             phpData.Dispose(); //clear the stored form data
    125.         }
    126.     }
    127.  
    128.     private void SetPlayerPrefs(){//add whatever variables you want to store on the device itself here. Im using it here to store auto login detials.
    129.         PlayerPrefs.SetInt("userID", userID);
    130.         PlayerPrefs.SetString("email", userEmail);
    131.         PlayerPrefs.SetString("pass", pass.text);
    132.     }
    133. }
    JSONhandler.cs
    Code (CSharp):
    1. #if !UNITY_WEBPLAYER
    2. #define USE_FileIO
    3. #endif
    4.  
    5. using System;
    6. using System.Collections;
    7. using System.Collections.Generic;
    8. using System.Linq;
    9.  
    10.  
    11. namespace JSONhandler
    12. {
    13.     public enum JSONBinaryTag
    14.     {
    15.         Array            = 1,
    16.         Class            = 2,
    17.         Value            = 3,
    18.         IntValue         = 4,
    19.         DoubleValue      = 5,
    20.         BoolValue        = 6,
    21.         FloatValue       = 7,
    22.     }
    23.  
    24.     public class JSONNode
    25.     {
    26.         #region common interface
    27.         public virtual void Add(string aKey, JSONNode aItem){ }
    28.         public virtual JSONNode this[int aIndex]   { get { return null; } set { } }
    29.         public virtual JSONNode this[string aKey]  { get { return null; } set { } }
    30.         public virtual string Value                { get { return "";   } set { } }
    31.         public virtual int Count                   { get { return 0;    } }
    32.    
    33.         protected JSONBinaryTag valueType = JSONBinaryTag.Value;
    34.    
    35.         public virtual void Add(JSONNode aItem)
    36.         {
    37.             Add("", aItem);
    38.         }
    39.    
    40.         public virtual JSONNode Remove(string aKey) { return null; }
    41.         public virtual JSONNode Remove(int aIndex) { return null; }
    42.         public virtual JSONNode Remove(JSONNode aNode) { return aNode; }
    43.    
    44.         public virtual IEnumerable<JSONNode> Childs { get { yield break;} }
    45.         public IEnumerable<JSONNode> DeepChilds
    46.         {
    47.             get
    48.             {
    49.                 foreach (var C in Childs)
    50.                     foreach (var D in C.DeepChilds)
    51.                         yield return D;
    52.             }
    53.         }
    54.    
    55.         public virtual IEnumerable<string> Keys { get { yield break; } }
    56.    
    57.         public override string ToString()
    58.         {
    59.             return "JSONNode";
    60.         }
    61.         public virtual string ToString(string aPrefix)
    62.         {
    63.             return "JSONNode";
    64.         }
    65.    
    66.         #endregion common interface
    67.    
    68.         #region typecasting properties
    69.         public virtual int AsInt
    70.         {
    71.             get
    72.             {
    73.                 int v = 0;
    74.                 if (int.TryParse(Value,out v))
    75.                     return v;
    76.                 return 0;
    77.             }
    78.             set
    79.             {
    80.                 Value = value.ToString();
    81.                 valueType = JSONBinaryTag.IntValue;
    82.             }
    83.         }
    84.         public virtual float AsFloat
    85.         {
    86.             get
    87.             {
    88.                 float v = 0.0f;
    89.                 if (float.TryParse(Value,out v))
    90.                     return v;
    91.                 return 0.0f;
    92.             }
    93.             set
    94.             {
    95.                 Value = value.ToString();
    96.                 valueType = JSONBinaryTag.FloatValue;
    97.             }
    98.         }
    99.         public virtual double AsDouble
    100.         {
    101.             get
    102.             {
    103.                 double v = 0.0;
    104.                 if (double.TryParse(Value,out v))
    105.                     return v;
    106.                 return 0.0;
    107.             }
    108.             set
    109.             {
    110.                 Value = value.ToString();
    111.                 valueType = JSONBinaryTag.DoubleValue;
    112.             }
    113.         }
    114.         public virtual bool AsBool
    115.         {
    116.             get
    117.             {
    118.                 bool v = false;
    119.                 if (bool.TryParse(Value,out v))
    120.                     return v;
    121.                 return !string.IsNullOrEmpty(Value);
    122.             }
    123.             set
    124.             {
    125.                 Value = (value)?"true":"false";
    126.                 valueType = JSONBinaryTag.BoolValue;
    127.             }
    128.         }
    129.         public virtual JSONArray AsArray
    130.         {
    131.             get
    132.             {
    133.                 return this as JSONArray;
    134.             }
    135.         }
    136.         public virtual JSONClass AsObject
    137.         {
    138.             get
    139.             {
    140.                 return this as JSONClass;
    141.             }
    142.         }
    143.    
    144.    
    145.         #endregion typecasting properties
    146.    
    147.         #region operators
    148.         public static implicit operator JSONNode(string s)
    149.         {
    150.             return new JSONData(s);
    151.         }
    152.         public static implicit operator string(JSONNode d)
    153.         {
    154.             return (d == null)?null:d.Value;
    155.         }
    156.         public static bool operator ==(JSONNode a, object b)
    157.         {
    158.             if (b == null && a is JSONLazyCreator)
    159.                 return true;
    160.             return System.Object.ReferenceEquals(a,b);
    161.         }
    162.    
    163.         public static bool operator !=(JSONNode a, object b)
    164.         {
    165.             return !(a == b);
    166.         }
    167.         public override bool Equals (object obj)
    168.         {
    169.             return System.Object.ReferenceEquals(this, obj);
    170.         }
    171.         public override int GetHashCode ()
    172.         {
    173.             return base.GetHashCode();
    174.         }
    175.    
    176.    
    177.         #endregion operators
    178.    
    179.         internal static string Escape(string aText)
    180.         {
    181.             string result = "";
    182.             foreach(char c in aText)
    183.             {
    184.                 switch(c)
    185.                 {
    186.                 case '\\' : result += "\\\\"; break;
    187.                 case '\"' : result += "\\\""; break;
    188.                 case '\n' : result += "\\n" ; break;
    189.                 case '\r' : result += "\\r" ; break;
    190.                 case '\t' : result += "\\t" ; break;
    191.                 case '\b' : result += "\\b" ; break;
    192.                 case '\f' : result += "\\f" ; break;
    193.                 default   : result += c     ; break;
    194.                 }
    195.             }
    196.             return result;
    197.         }
    198.    
    199.         public static JSONNode Parse(string aJSON)
    200.         {
    201.             Stack<JSONNode> stack = new Stack<JSONNode>();
    202.             JSONNode ctx = null;
    203.             int i = 0;
    204.             string Token = "";
    205.             string TokenName = "";
    206.             bool QuoteMode = false;
    207.             while (i < aJSON.Length)
    208.             {
    209.                 switch (aJSON[i])
    210.                 {
    211.                 case '{':
    212.                     if (QuoteMode)
    213.                     {
    214.                         Token += aJSON[i];
    215.                         break;
    216.                     }
    217.                     stack.Push(new JSONClass());
    218.                     if (ctx != null)
    219.                     {
    220.                         TokenName = TokenName.Trim();
    221.                         if (ctx is JSONArray)
    222.                             ctx.Add(stack.Peek());
    223.                         else if (TokenName != "")
    224.                             ctx.Add(TokenName,stack.Peek());
    225.                     }
    226.                     TokenName = "";
    227.                     Token = "";
    228.                     ctx = stack.Peek();
    229.                     break;
    230.                
    231.                 case '[':
    232.                     if (QuoteMode)
    233.                     {
    234.                         Token += aJSON[i];
    235.                         break;
    236.                     }
    237.                
    238.                     stack.Push(new JSONArray());
    239.                     if (ctx != null)
    240.                     {
    241.                         TokenName = TokenName.Trim();
    242.                         if (ctx is JSONArray)
    243.                             ctx.Add(stack.Peek());
    244.                         else if (TokenName != "")
    245.                             ctx.Add(TokenName,stack.Peek());
    246.                     }
    247.                     TokenName = "";
    248.                     Token = "";
    249.                     ctx = stack.Peek();
    250.                     break;
    251.                
    252.                 case '}':
    253.                 case ']':
    254.                     if (QuoteMode)
    255.                     {
    256.                         Token += aJSON[i];
    257.                         break;
    258.                     }
    259.                     if (stack.Count == 0)
    260.                         throw new Exception("JSON Parse: Too many closing brackets");
    261.                
    262.                     stack.Pop();
    263.                     if (Token != "")
    264.                     {
    265.                         TokenName = TokenName.Trim();
    266.                         if (ctx is JSONArray)
    267.                             ctx.Add(Token);
    268.                         else if (TokenName != "")
    269.                             ctx.Add(TokenName,Token);
    270.                     }
    271.                     TokenName = "";
    272.                     Token = "";
    273.                     if (stack.Count>0)
    274.                         ctx = stack.Peek();
    275.                     break;
    276.                
    277.                 case ':':
    278.                     if (QuoteMode)
    279.                     {
    280.                         Token += aJSON[i];
    281.                         break;
    282.                     }
    283.                     TokenName = Token;
    284.                     Token = "";
    285.                     break;
    286.                
    287.                 case '"':
    288.                     QuoteMode ^= true;
    289.                     break;
    290.                
    291.                 case ',':
    292.                     if (QuoteMode)
    293.                     {
    294.                         Token += aJSON[i];
    295.                         break;
    296.                     }
    297.                     if (Token != "")
    298.                     {
    299.                         if (ctx is JSONArray)
    300.                             ctx.Add(Token);
    301.                         else if (TokenName != "")
    302.                             ctx.Add(TokenName, Token);
    303.                     }
    304.                     TokenName = "";
    305.                     Token = "";
    306.                     break;
    307.                
    308.                 case '\r':
    309.                 case '\n':
    310.                     break;
    311.                
    312.                 case ' ':
    313.                 case '\t':
    314.                     if (QuoteMode)
    315.                         Token += aJSON[i];
    316.                     break;
    317.                
    318.                 case '\\':
    319.                     ++i;
    320.                     if (QuoteMode)
    321.                     {
    322.                         char C = aJSON[i];
    323.                         switch (C)
    324.                         {
    325.                         case 't' : Token += '\t'; break;
    326.                         case 'r' : Token += '\r'; break;
    327.                         case 'n' : Token += '\n'; break;
    328.                         case 'b' : Token += '\b'; break;
    329.                         case 'f' : Token += '\f'; break;
    330.                         case 'u':
    331.                         {
    332.                             string s = aJSON.Substring(i+1,4);
    333.                             Token += (char)int.Parse(s, System.Globalization.NumberStyles.AllowHexSpecifier);
    334.                             i += 4;
    335.                             break;
    336.                         }
    337.                         default  : Token += C; break;
    338.                         }
    339.                     }
    340.                     break;
    341.                
    342.                 default:
    343.                     Token += aJSON[i];
    344.                     break;
    345.                 }
    346.                 ++i;
    347.             }
    348.             if (QuoteMode)
    349.             {
    350.                 throw new Exception("JSON Parse: Quotation marks seems to be messed up.");
    351.             }
    352.             return ctx;
    353.         }
    354.    
    355.         public virtual void Serialize(System.IO.BinaryWriter aWriter) {}
    356.    
    357.         public void SaveToStream(System.IO.Stream aData)
    358.         {
    359.             var W = new System.IO.BinaryWriter(aData);
    360.             Serialize(W);
    361.         }
    362.    
    363.         #if USE_SharpZipLib
    364.         public void SaveToCompressedStream(System.IO.Stream aData)
    365.         {
    366.             using (var gzipOut = new ICSharpCode.SharpZipLib.BZip2.BZip2OutputStream(aData))
    367.             {
    368.                 gzipOut.IsStreamOwner = false;
    369.                 SaveToStream(gzipOut);
    370.                 gzipOut.Close();
    371.             }
    372.         }
    373.    
    374.         public void SaveToCompressedFile(string aFileName)
    375.         {
    376.             #if USE_FileIO
    377.             System.IO.Directory.CreateDirectory((new System.IO.FileInfo(aFileName)).Directory.FullName);
    378.             using(var F = System.IO.File.OpenWrite(aFileName))
    379.             {
    380.                 SaveToCompressedStream(F);
    381.             }
    382.             #else
    383.             throw new Exception("Can't use File IO stuff in webplayer");
    384.             #endif
    385.         }
    386.         public string SaveToCompressedBase64()
    387.         {
    388.             using (var stream = new System.IO.MemoryStream())
    389.             {
    390.                 SaveToCompressedStream(stream);
    391.                 stream.Position = 0;
    392.                 return System.Convert.ToBase64String(stream.ToArray());
    393.             }
    394.         }
    395.    
    396.         #else
    397.         public void SaveToCompressedStream(System.IO.Stream aData)
    398.         {
    399.             throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
    400.         }
    401.         public void SaveToCompressedFile(string aFileName)
    402.         {
    403.             throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
    404.         }
    405.         public string SaveToCompressedBase64()
    406.         {
    407.             throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
    408.         }
    409.         #endif
    410.    
    411.         public void SaveToFile(string aFileName)
    412.         {
    413.             #if USE_FileIO
    414.             System.IO.Directory.CreateDirectory((new System.IO.FileInfo(aFileName)).Directory.FullName);
    415.             using(var F = System.IO.File.OpenWrite(aFileName))
    416.             {
    417.                 SaveToStream(F);
    418.             }
    419.             #else
    420.             throw new Exception("Can't use File IO stuff in webplayer");
    421.             #endif
    422.         }
    423.         public string SaveToBase64()
    424.         {
    425.             using (var stream = new System.IO.MemoryStream())
    426.             {
    427.                 SaveToStream(stream);
    428.                 stream.Position = 0;
    429.                 return System.Convert.ToBase64String(stream.ToArray());
    430.             }
    431.         }
    432.         public static JSONNode Deserialize(System.IO.BinaryReader aReader)
    433.         {
    434.             JSONBinaryTag type = (JSONBinaryTag)aReader.ReadByte();
    435.             switch(type)
    436.             {
    437.             case JSONBinaryTag.Array:
    438.             {
    439.                 int count = aReader.ReadInt32();
    440.                 JSONArray tmp = new JSONArray();
    441.                 for(int i = 0; i < count; i++)
    442.                     tmp.Add(Deserialize(aReader));
    443.                 return tmp;
    444.             }
    445.             case JSONBinaryTag.Class:
    446.             {
    447.                 int count = aReader.ReadInt32();            
    448.                 JSONClass tmp = new JSONClass();
    449.                 for(int i = 0; i < count; i++)
    450.                 {
    451.                     string key = aReader.ReadString();
    452.                     var val = Deserialize(aReader);
    453.                     tmp.Add(key, val);
    454.                 }
    455.                 return tmp;
    456.             }
    457.             case JSONBinaryTag.Value:
    458.             {
    459.                 return new JSONData(aReader.ReadString());
    460.             }
    461.             case JSONBinaryTag.IntValue:
    462.             {
    463.                 return new JSONData(aReader.ReadInt32());
    464.             }
    465.             case JSONBinaryTag.DoubleValue:
    466.             {
    467.                 return new JSONData(aReader.ReadDouble());
    468.             }
    469.             case JSONBinaryTag.BoolValue:
    470.             {
    471.                 return new JSONData(aReader.ReadBoolean());
    472.             }
    473.             case JSONBinaryTag.FloatValue:
    474.             {
    475.                 return new JSONData(aReader.ReadSingle());
    476.             }
    477.            
    478.             default:
    479.             {
    480.                 throw new Exception("Error deserializing JSON. Unknown tag: " + type);
    481.             }
    482.             }
    483.         }
    484.    
    485.         #if USE_SharpZipLib
    486.         public static JSONNode LoadFromCompressedStream(System.IO.Stream aData)
    487.         {
    488.             var zin = new ICSharpCode.SharpZipLib.BZip2.BZip2InputStream(aData);
    489.             return LoadFromStream(zin);
    490.         }
    491.         public static JSONNode LoadFromCompressedFile(string aFileName)
    492.         {
    493.             #if USE_FileIO
    494.             using(var F = System.IO.File.OpenRead(aFileName))
    495.             {
    496.                 return LoadFromCompressedStream(F);
    497.             }
    498.             #else
    499.             throw new Exception("Can't use File IO stuff in webplayer");
    500.             #endif
    501.         }
    502.         public static JSONNode LoadFromCompressedBase64(string aBase64)
    503.         {
    504.             var tmp = System.Convert.FromBase64String(aBase64);
    505.             var stream = new System.IO.MemoryStream(tmp);
    506.             stream.Position = 0;
    507.             return LoadFromCompressedStream(stream);
    508.         }
    509.         #else
    510.         public static JSONNode LoadFromCompressedFile(string aFileName)
    511.         {
    512.             throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
    513.         }
    514.         public static JSONNode LoadFromCompressedStream(System.IO.Stream aData)
    515.         {
    516.             throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
    517.         }
    518.         public static JSONNode LoadFromCompressedBase64(string aBase64)
    519.         {
    520.             throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
    521.         }
    522.         #endif
    523.    
    524.         public static JSONNode LoadFromStream(System.IO.Stream aData)
    525.         {
    526.             using(var R = new System.IO.BinaryReader(aData))
    527.             {
    528.                 return Deserialize(R);
    529.             }
    530.         }
    531.         public static JSONNode LoadFromFile(string aFileName)
    532.         {
    533.             #if USE_FileIO
    534.             using(var F = System.IO.File.OpenRead(aFileName))
    535.             {
    536.                 return LoadFromStream(F);
    537.             }
    538.             #else
    539.             throw new Exception("Can't use File IO stuff in webplayer");
    540.             #endif
    541.         }
    542.         public static JSONNode LoadFromBase64(string aBase64)
    543.         {
    544.             var tmp = System.Convert.FromBase64String(aBase64);
    545.             var stream = new System.IO.MemoryStream(tmp);
    546.             stream.Position = 0;
    547.             return LoadFromStream(stream);
    548.         }
    549.     } // End of JSONNode
    550.  
    551.     public class JSONArray : JSONNode, IEnumerable
    552.     {
    553.         private List<JSONNode> m_List = new List<JSONNode>();
    554.         public override JSONNode this[int aIndex]
    555.         {
    556.             get
    557.             {
    558.                 if (aIndex<0 || aIndex >= m_List.Count)
    559.                     return new JSONLazyCreator(this);
    560.                 return m_List[aIndex];
    561.             }
    562.             set
    563.             {
    564.                 if (aIndex<0 || aIndex >= m_List.Count)
    565.                     m_List.Add(value);
    566.                 else
    567.                     m_List[aIndex] = value;
    568.             }
    569.         }
    570.         public override JSONNode this[string aKey]
    571.         {
    572.             get{ return new JSONLazyCreator(this);}
    573.             set{ m_List.Add(value); }
    574.         }
    575.         public override int Count
    576.         {
    577.             get { return m_List.Count; }
    578.         }
    579.         public override void Add(string aKey, JSONNode aItem)
    580.         {
    581.             m_List.Add(aItem);
    582.         }
    583.         public override JSONNode Remove(int aIndex)
    584.         {
    585.             if (aIndex < 0 || aIndex >= m_List.Count)
    586.                 return null;
    587.             JSONNode tmp = m_List[aIndex];
    588.             m_List.RemoveAt(aIndex);
    589.             return tmp;
    590.         }
    591.         public override JSONNode Remove(JSONNode aNode)
    592.         {
    593.             m_List.Remove(aNode);
    594.             return aNode;
    595.         }
    596.         public override IEnumerable<JSONNode> Childs
    597.         {
    598.             get
    599.             {
    600.                 foreach(JSONNode N in m_List)
    601.                     yield return N;
    602.             }
    603.         }
    604.         public IEnumerator GetEnumerator()
    605.         {
    606.             foreach(JSONNode N in m_List)
    607.                 yield return N;
    608.         }
    609.         public override string ToString()
    610.         {
    611.             string result = "[ ";
    612.             foreach (JSONNode N in m_List)
    613.             {
    614.                 if (result.Length > 2)
    615.                     result += ", ";
    616.                 result += N.ToString();
    617.             }
    618.             result += " ]";
    619.             return result;
    620.         }
    621.         public override string ToString(string aPrefix)
    622.         {
    623.             string result = "[ ";
    624.             foreach (JSONNode N in m_List)
    625.             {
    626.                 if (result.Length > 3)
    627.                     result += ", ";
    628.                 result += "\n" + aPrefix + "   ";            
    629.                 result += N.ToString(aPrefix+"   ");
    630.             }
    631.             result += "\n" + aPrefix + "]";
    632.             return result;
    633.         }
    634.         public override void Serialize (System.IO.BinaryWriter aWriter)
    635.         {
    636.             aWriter.Write((byte)JSONBinaryTag.Array);
    637.             aWriter.Write(m_List.Count);
    638.             for(int i = 0; i < m_List.Count; i++)
    639.             {
    640.                 m_List[i].Serialize(aWriter);
    641.             }
    642.         }
    643.     } // End of JSONArray
    644.  
    645.     public class JSONClass : JSONNode, IEnumerable
    646.     {
    647.         private Dictionary<string,JSONNode> m_Dict = new Dictionary<string,JSONNode>();
    648.         public override JSONNode this[string aKey]
    649.         {
    650.             get
    651.             {
    652.                 if (m_Dict.ContainsKey(aKey))
    653.                     return m_Dict[aKey];
    654.                 else
    655.                     return new JSONLazyCreator(this, aKey);
    656.             }
    657.             set
    658.             {
    659.                 if (m_Dict.ContainsKey(aKey))
    660.                     m_Dict[aKey] = value;
    661.                 else
    662.                     m_Dict.Add(aKey,value);
    663.             }
    664.         }
    665.         public override JSONNode this[int aIndex]
    666.         {
    667.             get
    668.             {
    669.                 if (aIndex < 0 || aIndex >= m_Dict.Count)
    670.                     return null;
    671.                 return m_Dict.ElementAt(aIndex).Value;
    672.             }
    673.             set
    674.             {
    675.                 if (aIndex < 0 || aIndex >= m_Dict.Count)
    676.                     return;
    677.                 string key = m_Dict.ElementAt(aIndex).Key;
    678.                 m_Dict[key] = value;
    679.             }
    680.         }
    681.         public override int Count
    682.         {
    683.             get { return m_Dict.Count; }
    684.         }
    685.    
    686.    
    687.         public override void Add(string aKey, JSONNode aItem)
    688.         {
    689.             if (!string.IsNullOrEmpty(aKey))
    690.             {
    691.                 if (m_Dict.ContainsKey(aKey))
    692.                     m_Dict[aKey] = aItem;
    693.                 else
    694.                     m_Dict.Add(aKey, aItem);
    695.             }
    696.             else
    697.                 m_Dict.Add(Guid.NewGuid().ToString(), aItem);
    698.         }
    699.    
    700.         public override JSONNode Remove(string aKey)
    701.         {
    702.             if (!m_Dict.ContainsKey(aKey))
    703.                 return null;
    704.             JSONNode tmp = m_Dict[aKey];
    705.             m_Dict.Remove(aKey);
    706.             return tmp;    
    707.         }
    708.         public override JSONNode Remove(int aIndex)
    709.         {
    710.             if (aIndex < 0 || aIndex >= m_Dict.Count)
    711.                 return null;
    712.             var item = m_Dict.ElementAt(aIndex);
    713.             m_Dict.Remove(item.Key);
    714.             return item.Value;
    715.         }
    716.         public override JSONNode Remove(JSONNode aNode)
    717.         {
    718.             try
    719.             {
    720.                 var item = m_Dict.Where(k => k.Value == aNode).First();
    721.                 m_Dict.Remove(item.Key);
    722.                 return aNode;
    723.             }
    724.             catch
    725.             {
    726.                 return null;
    727.             }
    728.         }
    729.    
    730.         public override IEnumerable<JSONNode> Childs
    731.         {
    732.             get
    733.             {
    734.                 foreach(KeyValuePair<string,JSONNode> N in m_Dict)
    735.                     yield return N.Value;
    736.             }
    737.         }
    738.    
    739.         public override IEnumerable<string> Keys
    740.         {
    741.             get
    742.             {
    743.                 foreach (var key in m_Dict.Keys)
    744.                     yield return key;
    745.             }
    746.         }
    747.    
    748.         public IEnumerator GetEnumerator()
    749.         {
    750.             foreach(KeyValuePair<string, JSONNode> N in m_Dict)
    751.                 yield return N;
    752.         }
    753.         public override string ToString()
    754.         {
    755.             string result = "{";
    756.             foreach (KeyValuePair<string, JSONNode> N in m_Dict)
    757.             {
    758.                 if (result.Length > 2)
    759.                     result += ", ";
    760.                 result += "\"" + Escape(N.Key) + "\":" + N.Value.ToString();
    761.             }
    762.             result += "}";
    763.             return result;
    764.         }
    765.         public override string ToString(string aPrefix)
    766.         {
    767.             string result = "{ ";
    768.             foreach (KeyValuePair<string, JSONNode> N in m_Dict)
    769.             {
    770.                 if (result.Length > 3)
    771.                     result += ", ";
    772.                 result += "\n" + aPrefix + "   ";
    773.                 result += "\"" + Escape(N.Key) + "\" : " + N.Value.ToString(aPrefix+"   ");
    774.             }
    775.             result += "\n" + aPrefix + "}";
    776.             return result;
    777.         }
    778.         public override void Serialize (System.IO.BinaryWriter aWriter)
    779.         {
    780.             aWriter.Write((byte)JSONBinaryTag.Class);
    781.             aWriter.Write(m_Dict.Count);
    782.             foreach(string K in m_Dict.Keys)
    783.             {
    784.                 aWriter.Write(K);
    785.                 m_Dict[K].Serialize(aWriter);
    786.             }
    787.         }
    788.     } // End of JSONClass
    789.  
    790.     public class JSONData : JSONNode
    791.     {
    792.         private string m_Data;
    793.         public override string Value
    794.         {
    795.             get { return m_Data; }
    796.             set { m_Data = value; }
    797.         }
    798.         public JSONData(string aData)
    799.         {
    800.             m_Data = aData;
    801.         }
    802.         public JSONData(float aData)
    803.         {
    804.             AsFloat = aData;
    805.         }
    806.         public JSONData(double aData)
    807.         {
    808.             AsDouble = aData;
    809.         }
    810.         public JSONData(bool aData)
    811.         {
    812.             AsBool = aData;
    813.         }
    814.         public JSONData(int aData)
    815.         {
    816.             AsInt = aData;
    817.         }
    818.    
    819.         public override string ToString()
    820.         {
    821.             bool asString = false;
    822.             switch (valueType) {
    823.             default:
    824.                 asString = true;
    825.                 break;
    826.             case JSONBinaryTag.BoolValue:
    827.             case JSONBinaryTag.IntValue:
    828.             case JSONBinaryTag.DoubleValue:
    829.             case JSONBinaryTag.FloatValue:
    830.                 asString = false;
    831.                 break;
    832.             }
    833.        
    834.             if (asString) {
    835.                 return "\"" + Escape(m_Data) + "\"";
    836.             }
    837.             else {
    838.                 return m_Data;
    839.             }
    840.         }
    841.         public override string ToString(string aPrefix)
    842.         {
    843.             return ToString ();
    844.         }
    845.    
    846.         public override void Serialize (System.IO.BinaryWriter aWriter)
    847.         {
    848.             var tmp = new JSONData("");
    849.        
    850.             tmp.AsInt = AsInt;
    851.             if (tmp.m_Data == this.m_Data)
    852.             {
    853.                 aWriter.Write((byte)JSONBinaryTag.IntValue);
    854.                 aWriter.Write(AsInt);
    855.                 return;
    856.             }
    857.             tmp.AsFloat = AsFloat;
    858.             if (tmp.m_Data == this.m_Data)
    859.             {
    860.                 aWriter.Write((byte)JSONBinaryTag.FloatValue);
    861.                 aWriter.Write(AsFloat);
    862.                 return;
    863.             }
    864.             tmp.AsDouble = AsDouble;
    865.             if (tmp.m_Data == this.m_Data)
    866.             {
    867.                 aWriter.Write((byte)JSONBinaryTag.DoubleValue);
    868.                 aWriter.Write(AsDouble);
    869.                 return;
    870.             }
    871.        
    872.             tmp.AsBool = AsBool;
    873.             if (tmp.m_Data == this.m_Data)
    874.             {
    875.                 aWriter.Write((byte)JSONBinaryTag.BoolValue);
    876.                 aWriter.Write(AsBool);
    877.                 return;
    878.             }
    879.             aWriter.Write((byte)JSONBinaryTag.Value);
    880.             aWriter.Write(m_Data);
    881.         }
    882.     } // End of JSONData
    883.  
    884.     internal class JSONLazyCreator : JSONNode
    885.     {
    886.         private JSONNode m_Node = null;
    887.         private string m_Key = null;
    888.    
    889.         public JSONLazyCreator(JSONNode aNode)
    890.         {
    891.             m_Node = aNode;
    892.             m_Key  = null;
    893.         }
    894.         public JSONLazyCreator(JSONNode aNode, string aKey)
    895.         {
    896.             m_Node = aNode;
    897.             m_Key = aKey;
    898.         }
    899.    
    900.         private void Set(JSONNode aVal)
    901.         {
    902.             if (m_Key == null)
    903.             {
    904.                 m_Node.Add(aVal);
    905.             }
    906.             else
    907.             {
    908.                 m_Node.Add(m_Key, aVal);
    909.             }
    910.             m_Node = null; // Be GC friendly.
    911.         }
    912.    
    913.         public override JSONNode this[int aIndex]
    914.         {
    915.             get
    916.             {
    917.                 return new JSONLazyCreator(this);
    918.             }
    919.             set
    920.             {
    921.                 var tmp = new JSONArray();
    922.                 tmp.Add(value);
    923.                 Set(tmp);
    924.             }
    925.         }
    926.    
    927.         public override JSONNode this[string aKey]
    928.         {
    929.             get
    930.             {
    931.                 return new JSONLazyCreator(this, aKey);
    932.             }
    933.             set
    934.             {
    935.                 var tmp = new JSONClass();
    936.                 tmp.Add(aKey, value);
    937.                 Set(tmp);
    938.             }
    939.         }
    940.         public override void Add (JSONNode aItem)
    941.         {
    942.             var tmp = new JSONArray();
    943.             tmp.Add(aItem);
    944.             Set(tmp);
    945.         }
    946.         public override void Add (string aKey, JSONNode aItem)
    947.         {
    948.             var tmp = new JSONClass();
    949.             tmp.Add(aKey, aItem);
    950.             Set(tmp);
    951.         }
    952.         public static bool operator ==(JSONLazyCreator a, object b)
    953.         {
    954.             if (b == null)
    955.                 return true;
    956.             return System.Object.ReferenceEquals(a,b);
    957.         }
    958.    
    959.         public static bool operator !=(JSONLazyCreator a, object b)
    960.         {
    961.             return !(a == b);
    962.         }
    963.         public override bool Equals (object obj)
    964.         {
    965.             if (obj == null)
    966.                 return true;
    967.             return System.Object.ReferenceEquals(this, obj);
    968.         }
    969.         public override int GetHashCode ()
    970.         {
    971.             return base.GetHashCode();
    972.         }
    973.    
    974.         public override string ToString()
    975.         {
    976.             return "";
    977.         }
    978.         public override string ToString(string aPrefix)
    979.         {
    980.             return "";
    981.         }
    982.    
    983.         public override int AsInt
    984.         {
    985.             get
    986.             {
    987.                 JSONData tmp = new JSONData(0);
    988.                 Set(tmp);
    989.                 return 0;
    990.             }
    991.             set
    992.             {
    993.                 JSONData tmp = new JSONData(value);
    994.                 Set(tmp);
    995.             }
    996.         }
    997.         public override float AsFloat
    998.         {
    999.             get
    1000.             {
    1001.                 JSONData tmp = new JSONData(0.0f);
    1002.                 Set(tmp);
    1003.                 return 0.0f;
    1004.             }
    1005.             set
    1006.             {
    1007.                 JSONData tmp = new JSONData(value);
    1008.                 Set(tmp);
    1009.             }
    1010.         }
    1011.         public override double AsDouble
    1012.         {
    1013.             get
    1014.             {
    1015.                 JSONData tmp = new JSONData(0.0);
    1016.                 Set(tmp);
    1017.                 return 0.0;
    1018.             }
    1019.             set
    1020.             {
    1021.                 JSONData tmp = new JSONData(value);
    1022.                 Set(tmp);
    1023.             }
    1024.         }
    1025.         public override bool AsBool
    1026.         {
    1027.             get
    1028.             {
    1029.                 JSONData tmp = new JSONData(false);
    1030.                 Set(tmp);
    1031.                 return false;
    1032.             }
    1033.             set
    1034.             {
    1035.                 JSONData tmp = new JSONData(value);
    1036.                 Set(tmp);
    1037.             }
    1038.         }
    1039.         public override JSONArray AsArray
    1040.         {
    1041.             get
    1042.             {
    1043.                 JSONArray tmp = new JSONArray();
    1044.                 Set(tmp);
    1045.                 return tmp;
    1046.             }
    1047.         }
    1048.         public override JSONClass AsObject
    1049.         {
    1050.             get
    1051.             {
    1052.                 JSONClass tmp = new JSONClass();
    1053.                 Set(tmp);
    1054.                 return tmp;
    1055.             }
    1056.         }
    1057.     } // End of JSONLazyCreator
    1058.  
    1059.     public static class JSON
    1060.     {
    1061.         public static JSONNode Parse(string aJSON)
    1062.         {
    1063.             return JSONNode.Parse(aJSON);
    1064.         }
    1065.     }
    1066.  
    1067.     public static class test
    1068.     {
    1069.         public static JSONClass TestClass() {
    1070.             JSONClass container = new JSONClass();
    1071.             JSONClass subContainer = new JSONClass();
    1072.             JSONArray subArray     = new JSONArray();
    1073.        
    1074.             subContainer["key1"         ]          = "value1";
    1075.        
    1076.             subArray    [0              ].AsInt    = 0;
    1077.             subArray    [1              ].AsInt    = 1;
    1078.             subArray    [2              ]          = "2";
    1079.             subArray    [3              ]          = "3";
    1080.        
    1081.             container   ["boolean true" ].AsBool   = true;
    1082.             container   ["boolean false"].AsBool   = false;
    1083.             container   ["int 0"        ].AsInt    = 0;
    1084.             container   ["int 1"        ].AsInt    = 1;
    1085.             container   ["float 0"      ].AsFloat  = 0.0f;
    1086.             container   ["float 1"      ].AsFloat  = 1.0f;
    1087.             container   ["double 0"     ].AsDouble = 0.0;
    1088.             container   ["double 1"     ].AsDouble = 1.0;
    1089.             container   ["string hello" ]          = "hello";
    1090.             container   ["string 0"     ]          = "0";
    1091.             container   ["class"        ]          = subContainer;
    1092.             container   ["array"        ]          = subArray;
    1093.        
    1094.             return container;
    1095.         }
    1096.    
    1097.         public static string TestString() {
    1098.             return TestClass().ToString();
    1099.         }
    1100.    
    1101.         public static bool HasExpectedOutput() {
    1102.             string actualOutput   = TestString();
    1103.             string expectedOutput = "{\"boolean true\":true, \"boolean false\":false, \"int 0\":0, \"int 1\":1, \"float 0\":0, \"float 1\":1, \"double 0\":0, \"double 1\":1, \"string hello\":\"hello\", \"string 0\":\"0\", \"class\":{\"key1\":\"value1\"}, \"array\":[ 0, 1, \"2\", \"3\" ]}";
    1104.             return actualOutput == expectedOutput;
    1105.         }
    1106.     }
    1107. }
    accounts.php

    Code (CSharp):
    1. <?
    2. /////////////////////////
    3. //if you are having promblems please make sure that the table and column names in your database match the ones being used in the sql below
    4. /////////////////////////
    5. // Connection INFO ----------------------------------------------------------
    6. //FILL THIS OUT
    7. $host = "localhost"; //host location (use localhost if your mysql database is hosted on the same machine/account as your site)
    8. $user = ""; //username
    9. $password = ""; //password here
    10. $dbname = ""; //your database
    11. $connection = mysqli_connect($host,$user,$password,$dbname) or die("Error " . mysqli_error($connection));
    12. //--------------------------------------------------------------------------------------------------------------
    13. // Here we protect ourselves from SQL Injection and convert the string to MD5 if we want
    14. function anti_injection_login($sql, $formUse, $encrypt){
    15.     $sql = preg_replace("/(from|select|insert|delete|where|drop table|show tables|,|'|#|\*|--|\\\\)/i","",$sql);
    16.     $sql = trim($sql);
    17.     $sql = strip_tags($sql);
    18.     if(!$formUse || !get_magic_quotes_gpc())
    19.         $sql = addslashes($sql);
    20.         if($encrypt){
    21.             $sql = md5(trim($sql));
    22.         }
    23.     return $sql;
    24. }
    25. //--------------------------------------------------------------------------------------------------------------
    26. $unityHashPass = anti_injection_login($_POST["hash"],true,false);
    27. $phpHashPass = "theHashCode"; // must be the same code you set in unity
    28. $email = anti_injection_login($_POST["email"],true,false);
    29. $pass = anti_injection_login($_POST["pass"],true,true);
    30. $pass2 = anti_injection_login($_POST["pass2"],true,true);
    31. $secQ = anti_injection_login($_POST["securityQuestion"],true,false);
    32. $secA = anti_injection_login($_POST["securityAnswer"],true,false);
    33. $creatingAccount = $_POST["creatingAccount"];
    34. //check if our hashpass's are the same and if an email and password where sent.
    35. if ($unityHashPass != $phpHashPass || !$email || !$pass){
    36.     echo "Username or password can not be empty.";
    37. } else {//if they are the same
    38.     if($creatingAccount == "true"){//if we are creating an account. Variable is sent from the WWWSubmit function in Login.cs in Unity
    39.         $SQL = "SELECT email FROM Accounts WHERE email = '" . $email . "'";
    40.         $result_id = mysqli_query($connection, $SQL) or die("Error in Selecting " . mysqli_error($connection));
    41.         $results = mysqli_num_rows($result_id);
    42.         if($results > 0) {
    43.             echo "That account already exists.";
    44.         }else{
    45.             if(!$secQ || !$secA || !$pass2){
    46.                 echo "Please fill out all fields.";
    47.             }else{
    48.                 if($pass == $pass2){
    49.                     $SQL = "INSERT INTO Accounts (`email`, `password`, `secretQuestion`, `answer`)
    50.                            VALUES ('". $email ."', '". $pass ."', '". $secQ ."','". $secA ."')";
    51.                     $result = mysqli_query($connection, $SQL) or die("DATABASE ERROR!");
    52.                         echo "Account created.";
    53.                 }else{
    54.                     echo "Passwords must match";
    55.                 }
    56.             }
    57.         }
    58.     }else{
    59.         $SQL = "SELECT * FROM Accounts WHERE email = '" . $email . "'";
    60.         $result = mysqli_query($connection, $SQL) or die("Error in Selecting " . mysqli_error($connection));
    61.         $results = mysqli_num_rows($result);
    62.         $temparray[] = array();
    63.         while($row = mysqli_fetch_assoc($result)){
    64.             $temparray[] = $row;
    65.             $comPass = $row['password'];
    66.         }
    67.         if($results) {
    68.             if(!strcmp($pass,$comPass)) {
    69.                 echo json_encode($temparray);
    70.             } else {
    71.                 echo "Login or password incorrect.";
    72.             }
    73.         } else {
    74.             echo "Email doesnt exist.";
    75.         }
    76.     }
    77. }
    78. mysql_close();
    79. ?>
    Thank You!
     

    Attached Files:

    Last edited: Apr 11, 2017
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,748
    Your PHP data seems to be missing an "ID" field. So it tries to get that field, comes up with null, and passes that into int.Parse, which causes the error.
    This may be an issue with your server. Try outputting the raw text of the login response, and make sure it contains the ID field you expect to be there.
     
    michalides likes this.
  3. michalides

    michalides

    Joined:
    Jan 9, 2017
    Posts:
    15
    Yes of course :) i got it, THANKS !!
     
  4. iHammadArshad

    iHammadArshad

    Joined:
    Mar 26, 2017
    Posts:
    2
    Thanks bro for the tip. Solved one of my errors with this tip as well.