Example #1
0
        public static void Deserialize(string _Input, out AdvertiseRequest Out)
        {
            StringReader _Reader = new StringReader (_Input);
            JSONReader JSONReader = new JSONReader (_Reader);

            JSONReader.StartObject ();
            string token = JSONReader.ReadToken ();
            Out = null;

            switch (token) {

                case "AdvertiseRequest" : {
                    AdvertiseRequest Result = new AdvertiseRequest ();
                    Result.Deserialize (JSONReader);
                    Out = Result;
                    break;
                    }

                default : {
                    throw new Exception ("Not supported");
                    }
                }
            JSONReader.EndObject ();

            // should we check for EOF here?
        }
Example #2
0
        public static void Deserialize(string _Input, out BindRequest Out)
        {
            StringReader _Reader = new StringReader (_Input);
            JSONReader JSONReader = new JSONReader (_Reader);

            JSONReader.StartObject ();
            string token = JSONReader.ReadToken ();
            Out = null;

            switch (token) {

                case "BindRequest" : {
                    Out = null;
                    throw new Exception ("Can't create abstract type");
                    }

                case "OpenRequest" : {
                    OpenRequest Result = new OpenRequest ();
                    Result.Deserialize (JSONReader);
                    Out = Result;
                    break;
                    }

                default : {
                    throw new Exception ("Not supported");
                    }
                }
            JSONReader.EndObject ();

            // should we check for EOF here?
        }
		/// <summary>
        /// Construct an instance from the specified tagged JSONReader stream.
        /// </summary>
        /// <param name="JSONReader">Input stream</param>
        /// <param name="Out">The created object</param>
        public static void Deserialize(JSONReader JSONReader, out JSONObject Out) {
	
			JSONReader.StartObject ();
            if (JSONReader.EOR) {
                Out = null;
                return;
                }

			string token = JSONReader.ReadToken ();
			Out = null;

			switch (token) {

				case "MailProfile" : {
					var Result = new MailProfile ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}


				case "MailProfilePrivate" : {
					var Result = new MailProfilePrivate ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}

				default : {
					throw new Exception ("Not supported");
					}
				}	
			JSONReader.EndObject ();
            }
		/// <summary>
        /// Construct an instance from the specified tagged JSONReader stream.
        /// </summary>
        public static void Deserialize(JSONReader JSONReader, out JSONObject Out) {
	
			JSONReader.StartObject ();
            if (JSONReader.EOR) {
                Out = null;
                return;
                }

			string token = JSONReader.ReadToken ();
			Out = null;

			switch (token) {

				case "PortalEntry" : {
					Out = null;
					throw new Exception ("Can't create abstract type");
					}


				case "Account" : {
					var Result = new Account ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}


				case "AccountProfile" : {
					var Result = new AccountProfile ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}


				case "ConnectionsPending" : {
					var Result = new ConnectionsPending ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}

				default : {
					throw new Exception ("Not supported");
					}
				}	
			JSONReader.EndObject ();
            }
        private bool InitInvoke()
        {
            var key = paramsList.Text;
            var f   = _abi.functions[key];

            DebugParameters = new DebugParameters();

            //Get the private key used
            DebugParameters.PrivateKey = privateKeyInput.Text;

            //Get the witness mode
            CheckWitnessMode witnessMode;
            var ws = witnessComboBox.SelectedItem.ToString().Replace(" ", "");

            if (!Enum.TryParse <CheckWitnessMode>(ws, out witnessMode))
            {
                return(false);
            }
            DebugParameters.WitnessMode = witnessMode;

            //Get the trigger type
            TriggerType type;
            var         ts = triggerComboBox.SelectedItem.ToString().Replace(" ", "");

            if (!Enum.TryParse <TriggerType>(ts, out type))
            {
                return(false);
            }
            DebugParameters.TriggerType = type;

            var HasRawScript = RawScriptText.Text.Length != 0;

            //Get the arguments list
            if (!HasRawScript)
            {
                var argList = "";
                if (f.inputs != null)
                {
                    int index = 0;
                    foreach (var p in f.inputs)
                    {
                        var temp = ($"{key}_{f.name}").ToLower();
                        var name = inputGrid.Rows[index].Cells[0].Value;

                        object val;

                        // detect placeholder
                        if (inputGrid.Rows[index].Cells[1].Style.ForeColor == Color.Gray)
                        {
                            val = "";
                        }
                        else
                        {
                            val = ReadCellVal(index, 1);
                        }

                        if (val == null)
                        {
                            val = ""; // temporary hack, necessary to avoid VM crash
                        }

                        if (val != null && !val.Equals(""))
                        {
                            var param_key = (currentContractName + "_" + f.name + "_" + p.name).ToLower();
                            //Add our default running parameters for next time
                            DebugParameters.DefaultParams[param_key] = val.ToString();
                        }

                        if (index > 0)
                        {
                            argList += ",";
                        }

                        if (p.type == Emulator.Type.Array || p.type == Emulator.Type.ByteArray)
                        {
                            var s = val.ToString();

                            if (s.StartsWith("[") && s.EndsWith("]"))
                            {
                                val = s;
                            }
                            else
                            if (s.StartsWith("\"") && s.EndsWith("\""))
                            {
                                s   = s.Substring(1, s.Length - 2);
                                val = ConvertArray(s);

                                if (val == null && p.type == Emulator.Type.ByteArray)
                                {
                                    val = DebuggerUtils.BytesToString(LuxUtils.ReverseHex(LuxUtils.ByteToHex(System.Text.Encoding.UTF8.GetBytes(s))).HexToBytes());
                                }
                                else
                                {
                                    if (val == null)
                                    {
                                        ShowArgumentError(f, index, val);
                                        return(false);
                                    }
                                }
                            }
                            else
                            {
                                ShowArgumentError(f, index, val);
                                return(false);
                            }

                            var items = JSONReader.ReadFromString(val.ToString());

                            val = "";
                            int itemIndex = 0;
                            foreach (var item in items)
                            {
                                if (itemIndex > 0)
                                {
                                    val += ",";
                                }

                                if (item.Kind == LunarParser.NodeKind.String)
                                {
                                    var vv = ConvertArray(item.Value);
                                    if (vv != null)
                                    {
                                        val += vv;
                                    }
                                    else
                                    {
                                        val += "\"" + item.Value + "\"";
                                    }
                                }
                                else
                                {
                                    val += item.Value;
                                }

                                itemIndex++;
                            }

                            val = $"[{val}]";
                        }
                        else
                        {
                            switch (p.type)
                            {
                            case Emulator.Type.String:
                            {
                                var s = val.ToString();
                                if (!s.StartsWith("\"") || !s.EndsWith("\""))
                                {
                                    ShowArgumentError(f, index, val);
                                    return(false);
                                }

                                break;
                            }

                            case Emulator.Type.Integer:
                            {
                                BigInteger n;
                                var        s = val.ToString();
                                if (string.IsNullOrEmpty(s) || !BigInteger.TryParse(s, out n))
                                {
                                    ShowArgumentError(f, index, val);
                                    ResetTabs();
                                    return(false);
                                }
                                break;
                            }

                            case Emulator.Type.Boolean:
                            {
                                switch (val.ToString().ToLower())
                                {
                                case "true": val = true; break;

                                case "false": val = false; break;

                                default:
                                {
                                    ShowArgumentError(f, index, val);
                                    ResetTabs();
                                    return(false);
                                }
                                }
                                break;
                            }
                            }
                        }

                        argList += val;
                        index++;
                    }
                }
                if (key != _abi.entryPoint.name)
                {
                    if (f.inputs == null || f.inputs.Count == 0)
                    {
                        argList = "[]";
                    }
                    var operation = Char.ToLowerInvariant(key[0]) + key.Substring(1);
                    argList = $"\"{operation}\", [{argList}]";
                }

                //Set the arguments list
                try
                {
                    DebugParameters.ArgList = DebuggerUtils.GetArgsListAsNode(argList);
                }
                catch
                {
                    MessageBox.Show("Error parsing input!");
                    ResetTabs();
                    return(false);
                }
            }

            if (assetComboBox.SelectedIndex > 0)
            {
                foreach (var entry in Asset.Entries)
                {
                    if (entry.name == assetComboBox.SelectedItem.ToString())
                    {
                        BigInteger amount;
                        BigInteger.TryParse(assetAmount.Text, out amount);
                        if (amount > 0)
                        {
                            lastSentSymbol = entry.name;
                            lastSentAmount = assetAmount.Text;

                            amount *= Asset.Decimals; // fix decimals

                            //Add the transaction info
                            DebugParameters.Transaction.Add(entry.id, amount);
                        }
                        else
                        {
                            MessageBox.Show(entry.name + " amount must be greater than zero");
                            return(false);
                        }

                        break;
                    }
                }
            }

            uint timestamp;

            if (!uint.TryParse(timestampBox.Text, out timestamp))
            {
                MessageBox.Show("Invalid timestamp");
                return(false);
            }
            else
            {
                DebugParameters.Timestamp = timestamp;
            }

            DebugParameters.RawScript = HasRawScript ? RawScriptText.Text.HexToBytes() : null;

            return(true);
        }
        /// <summary>
		/// Create a new instance from untagged string input.
		/// i.e. {... data ... }
        /// </summary>	
        /// <param name="_Input">The input data.</param>
        /// <returns>The created object.</returns>				
		public static new RecryptResponse From (string _Input) {
			StringReader _Reader = new StringReader (_Input);
            JSONReader JSONReader = new JSONReader (_Reader);
			return new RecryptResponse (JSONReader);
			}
        /// <summary>
        /// Deserialize a tagged stream
        /// </summary>
        /// <param name="JSONReader"></param>
        public static new RecryptResponse  FromTagged (JSONReader JSONReader) {
			RecryptResponse Out = null;

			JSONReader.StartObject ();
            if (JSONReader.EOR) {
                return null;
                }

			string token = JSONReader.ReadToken ();

			switch (token) {

				case "RecryptResponse" : {
					var Result = new RecryptResponse ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}

				case "HelloResponse" : {
					var Result = new HelloResponse ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}

				case "SetResponse" : {
					var Result = new SetResponse ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}

				case "GetResponse" : {
					var Result = new GetResponse ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}

				case "DeleteResponse" : {
					var Result = new DeleteResponse ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}

				case "SearchResponse" : {
					var Result = new SearchResponse ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}

				case "JoinResponse" : {
					var Result = new JoinResponse ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}

				case "LeaveResponse" : {
					var Result = new LeaveResponse ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}

				default : {
					//Ignore the unknown data
                    //throw new Exception ("Not supported");
                    break;
					}
				}
			JSONReader.EndObject ();

			return Out;
			}
Example #8
0
        public override IEnumerable <PendingSwap> Update()
        {
            logger.Message($"Update NeoInterop.");
            var result = new List <PendingSwap>();

            int maxPages = 1;

            {
                var json = neoscanAPI.ExecuteRequest($"get_address_abstracts/{LocalAddress}/1");
                if (json == null)
                {
                    logger.Message($"maxPages {maxPages}, null result through request {LocalAddress}");
                    return(result); // it will try again later
                }

                var root = JSONReader.ReadFromString(json);
                maxPages = root.GetInt32("total_pages");
            }

            logger.Message($"maxPages {maxPages}, got result through request {LocalAddress}");

            for (int page = maxPages; page >= 1; page--)
            {
                logger.Message($"fetching page {page} now");

                var json = neoscanAPI.ExecuteRequest($"get_address_abstracts/{LocalAddress}/{page}");
                if (json == null)
                {
                    logger.Warning("failed to fetch address page");
                    break;
                }

                var root = JSONReader.ReadFromString(json);

                var entries = root.GetNode("entries");

                logger.Message($"entries: {entries.ChildCount}");
                for (int i = entries.ChildCount - 1; i >= 0; i--)
                {
                    var entry = entries.GetNodeByIndex(i);

                    var temp   = entry.GetString("block_height");
                    var height = BigInteger.Parse(temp);
                    logger.Message($"block_height: {_blockHeight.ToString()} height: {height}");

                    if (height >= _blockHeight)
                    {
                        try
                        {
                            ProcessTransaction(entry, result);
                            _blockHeight = height;
                        }
                        catch (Exception e)
                        {
                            logger.Error("error: " + e.ToString());
                        }
                    }
                }
            }

            return(result);
        }
		/// <summary>
        /// Construct an instance from the specified tagged JSONReader stream.
        /// </summary>
        public static void Deserialize(JSONReader JSONReader, out JSONObject Out) {
	
			JSONReader.StartObject ();
            if (JSONReader.EOR) {
                Out = null;
                return;
                }

			string token = JSONReader.ReadToken ();
			Out = null;

			switch (token) {

				case "RecryptRequest" : {
					var Result = new RecryptRequest ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}


				case "RecryptResponse" : {
					var Result = new RecryptResponse ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}


				case "Version" : {
					var Result = new Version ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}


				case "Encoding" : {
					var Result = new Encoding ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}


				case "Resource" : {
					var Result = new Resource ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}


				case "Static" : {
					var Result = new Static ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}


				case "Dynamic" : {
					var Result = new Dynamic ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}


				case "ResourceSet" : {
					var Result = new ResourceSet ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}


				case "User" : {
					var Result = new User ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}


				case "Label" : {
					var Result = new Label ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}


				case "KeySet" : {
					var Result = new KeySet ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}


				case "HelloRequest" : {
					var Result = new HelloRequest ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}


				case "HelloResponse" : {
					var Result = new HelloResponse ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}


				case "SetRequest" : {
					var Result = new SetRequest ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}


				case "SetResponse" : {
					var Result = new SetResponse ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}


				case "GetRequest" : {
					var Result = new GetRequest ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}


				case "GetResponse" : {
					var Result = new GetResponse ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}


				case "DeleteRequest" : {
					var Result = new DeleteRequest ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}


				case "DeleteResponse" : {
					var Result = new DeleteResponse ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}


				case "SearchRequest" : {
					var Result = new SearchRequest ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}


				case "SearchResponse" : {
					var Result = new SearchResponse ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}


				case "JoinRequest" : {
					var Result = new JoinRequest ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}


				case "JoinResponse" : {
					var Result = new JoinResponse ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}


				case "LeaveRequest" : {
					var Result = new LeaveRequest ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}


				case "LeaveResponse" : {
					var Result = new LeaveResponse ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}

				default : {
					throw new Exception ("Not supported");
					}
				}	
			JSONReader.EndObject ();
            }
Example #10
0
        public void DoNotRecordRequestsAttribute()
        {
            var endpoint = JSONReader.ReadEndpoint("{'name': 'foo', 'pathregex': 'bar', 'responses': [], 'record': false}", "p:\\ath\\to\\endpoint\\directory", globalDefaults: null);

            Assert.False(endpoint.RecordRequests);
        }
        /// <summary>
		/// Initialize class from JSONReader stream.
        /// </summary>		
        /// <param name="JSONReader">Input stream</param>	
		public HostEntry (JSONReader JSONReader) {
			Deserialize (JSONReader);
			}
        /// <summary>
        /// Search for the specified profile on the local machine.
        /// </summary>
        /// <param name="UDF">Fingerprint of the profile to find.</param>
        /// <param name="FileName">The name of the file</param>
        /// <returns>The signed profile if found or null otherwise.</returns>
        public static SignedPersonalProfile FromFile(string UDF, string FileName) {

            using (var FileReader = FileName.OpenFileReadShared()) {
                using (var TextReader = FileReader.OpenTextReader()) {
                    var Reader = new JSONReader(TextReader);
                    var Result = SignedPersonalProfile.FromTagged(Reader);

                    var Test = Result.Signed.UDF;
                    Goedel.Cryptography.UDF.Validate(UDF, Test);

                    return Result;
                    }
                }
            }
        /// <summary>
        /// Having read a tag, process the corresponding value data.
        /// </summary>
        /// <param name="JSONReader">The input stream</param>
        /// <param name="Tag">The tag</param>
		public override void DeserializeToken (JSONReader JSONReader, string Tag) {
			
			switch (Tag) {
				default : {
					base.DeserializeToken(JSONReader, Tag);
					break;
					}
				}
			// check up that all the required elements are present
			}
Example #14
0
        public void Record_MapJSToCLRTypes()
        {
            var json =
                @"{
  'fields': 
   [
     {
       'def': {
         'Name': 'STR',
         'Type': 'string'
       },
       'val': 'ABBA'
     },
     {
       'def': {
         'Name': 'INT',
         'Type': 'int'
       },
       'val': -23
     },
     {
       'def': {
         'Name': 'NUM',
         'Type': 'real'
       },
       'val': -123.456
     },
     {
       'def': {
         'Name': 'BOOL',
         'Type': 'bool'
       },
       'val': true
     },
     {
       'def': {
         'Name': 'DATE',
         'Type': 'datetime'
       },
       'val': '2016-03-23 12:23:59'
     },
     {
       'def': {
         'Name': 'OBJ',
         'Type': 'object'
       },
       'val': { 'n': 'name', 'age': 23 }
     },
     {
       'def': {
         'Name': 'DFT'
       },
       'val': 'Default type is string'
     }
   ]
}";

            var rec    = new Record(json);
            var errors = rec.ServerErrors.ToList();

            Aver.AreEqual(0, errors.Count);

            Aver.AreEqual(7, rec.Schema.FieldCount);

            var fdef = rec.Schema["STR"];

            Aver.IsNotNull(fdef);
            Aver.AreObjectsEqual("STR", fdef.Name);
            Aver.AreObjectsEqual(typeof(string), fdef.Type);
            Aver.AreObjectsEqual("ABBA", rec["STR"]);

            fdef = rec.Schema["INT"];
            Aver.IsNotNull(fdef);
            Aver.AreObjectsEqual("INT", fdef.Name);
            Aver.AreObjectsEqual(typeof(long), fdef.Type);
            Aver.AreObjectsEqual((long)-23, rec["INT"]);

            fdef = rec.Schema["NUM"];
            Aver.IsNotNull(fdef);
            Aver.AreObjectsEqual("NUM", fdef.Name);
            Aver.AreObjectsEqual(typeof(double), fdef.Type);
            Aver.AreObjectsEqual(-123.456, rec["NUM"]);

            fdef = rec.Schema["BOOL"];
            Aver.IsNotNull(fdef);
            Aver.AreObjectsEqual("BOOL", fdef.Name);
            Aver.AreObjectsEqual(typeof(bool), fdef.Type);
            Aver.AreObjectsEqual(true, rec["BOOL"]);

            fdef = rec.Schema["DATE"];
            Aver.IsNotNull(fdef);
            Aver.AreObjectsEqual("DATE", fdef.Name);
            Aver.AreObjectsEqual(typeof(DateTime), fdef.Type);
            Aver.AreObjectsEqual("2016-03-23 12:23:59".AsDateTime(), rec["DATE"]);

            fdef = rec.Schema["OBJ"];
            Aver.IsNotNull(fdef);
            Aver.AreObjectsEqual("OBJ", fdef.Name);
            Aver.AreObjectsEqual(typeof(object), fdef.Type);
            var value = JSONReader.DeserializeDataObject("{ 'n': 'name', 'age': 23 }") as JSONDataMap;

            var got = rec["OBJ"] as JSONDataMap;

            Aver.IsNotNull(got);
            Aver.IsTrue(value.SequenceEqual(got));

            fdef = rec.Schema["DFT"];
            Aver.IsNotNull(fdef);
            Aver.AreObjectsEqual("DFT", fdef.Name);
            Aver.AreObjectsEqual(typeof(string), fdef.Type);
            Aver.AreObjectsEqual("Default type is string", rec["DFT"]);
        }
Example #15
0
        public void Record_ValidInitJSON()
        {
            var json =
                @"{
  'OK': true,
  'ID': '39a833dd-b48f-46c1-83a6-96603cc962a6',
  'ISOLang': 'eng',
  '__FormMode': 'Edit',
  '__CSRFToken': '1kk_qzXPLyScAa2A5y5GLTo9IlCqjuP',
  '__Roundtrip': '{\'GDID\':\'0:1:5\'}',
  'fields': [
      {
        'def': {
          'Name': 'Mnemonic',
          'Type': 'string',
          'Description': 'Mnemonic',
          'Required': true,
          'MinSize': 1,
          'Size': 25,
          'Placeholder': 'Mnemonic',
          'Stored': false
        },
        'val': 'Dns'
      },
      {
        'def': {
          'Name': 'Vertical_ID',
          'Type': 'string',
          'Description': 'Vertical',
          'Required': false,
          'Visible': false,
          'Size': 15,
          'DefaultValue': 'HAB',
          'Key': true,
          'Case': 'Upper',
          'LookupDict': {
            'HAB': 'HAB.rs Health and Beauty',
            'READRS': 'READ.rs Book Business',
            'SLRS': 'SL.RS General Business'
          }
        },
        'val': 'HAB'
      },
      {
        'def': {
          'Name': 'Table_ID',
          'Type': 'int',
          'Key': true,
          'Description': 'Table',
          'Required': true,
          'Visible': false,
          'MinValue': 1,
          'MaxValue': 123,
          'DefaultValue': 15,
          'Kind': 'Number',
          'Stored': true
        },
        'val': 2
      }
    ]
}";

            var init = JSONReader.DeserializeDataObject(json) as JSONDataMap;
            var rec  = new Record(init);

            Aver.AreEqual(0, rec.ServerErrors.Count());

            Aver.AreEqual(true, rec.OK);
            Aver.AreObjectsEqual("eng", rec.ISOLang);
            Aver.AreEqual(new Guid("39a833dd-b48f-46c1-83a6-96603cc962a6"), rec.ID);
            Aver.AreObjectsEqual("Edit", rec.FormMode);
            Aver.AreObjectsEqual("1kk_qzXPLyScAa2A5y5GLTo9IlCqjuP", rec.CSRFToken);

            var roundtrip = rec.Roundtrip;

            Aver.IsNotNull(roundtrip);
            Aver.AreEqual(roundtrip.Count, 1);
            Aver.AreObjectsEqual("0:1:5", roundtrip["GDID"]);

            Aver.AreEqual(3, rec.Schema.FieldCount);

            var fdef = rec.Schema["Mnemonic"];

            Aver.IsNotNull(fdef);
            Aver.AreObjectsEqual("Mnemonic", fdef.Name);
            Aver.AreObjectsEqual(typeof(string), fdef.Type);
            Aver.AreEqual(false, fdef.AnyTargetKey);
            Aver.IsNotNull(fdef.Attrs);
            Aver.AreEqual(1, fdef.Attrs.Count());
            var attr = fdef.Attrs.First();

            Aver.AreObjectsEqual("Mnemonic", attr.Description);
            Aver.AreEqual(true, attr.Required);
            Aver.AreEqual(true, attr.Visible);
            Aver.IsNull(attr.Min);
            Aver.IsNull(attr.Max);
            Aver.AreEqual(1, attr.MinLength);
            Aver.AreEqual(25, attr.MaxLength);
            Aver.IsNull(attr.Default);
            Aver.AreEqual(0, attr.ParseValueList().Count);
            Aver.IsTrue(StoreFlag.OnlyLoad == attr.StoreFlag);
            Aver.AreEqual(@"''{Name=Mnemonic Type=string Description=Mnemonic Required=True MinSize=1 Size=25 Placeholder=Mnemonic Stored=False}", attr.MetadataContent);
            Aver.AreObjectsEqual("Dns", rec["Mnemonic"]);

            fdef = rec.Schema["Vertical_ID"];
            Aver.IsNotNull(fdef);
            Aver.AreObjectsEqual("Vertical_ID", fdef.Name);
            Aver.AreObjectsEqual(typeof(string), fdef.Type);
            Aver.AreEqual(true, fdef.AnyTargetKey);
            Aver.IsNotNull(fdef.Attrs);
            Aver.AreEqual(1, fdef.Attrs.Count());
            attr = fdef.Attrs.First();
            Aver.AreObjectsEqual("Vertical", attr.Description);
            Aver.AreEqual(false, attr.Required);
            Aver.AreEqual(false, attr.Visible);
            Aver.IsNull(attr.Min);
            Aver.IsNull(attr.Max);
            Aver.AreEqual(0, attr.MinLength);
            Aver.AreEqual(15, attr.MaxLength);
            Aver.IsTrue(CharCase.Upper == attr.CharCase);
            Aver.AreObjectsEqual("HAB", attr.Default);

            var map1 = FieldAttribute.ParseValueListString("HAB:HAB.rs Health and Beauty,READRS:READ.rs Book Business,SLRS:SL.RS General Business", true);
            var map2 = attr.ParseValueList(true);

            Aver.IsTrue(map1.SequenceEqual(map2));

            Aver.AreObjectsEqual("''{Name=Vertical_ID Type=string Description=Vertical Required=False Visible=False Size=15 DefaultValue=HAB Key=True Case=Upper LookupDict=\"{\\\"HAB\\\":\\\"HAB.rs Health and Beauty\\\",\\\"READRS\\\":\\\"READ.rs Book Business\\\",\\\"SLRS\\\":\\\"SL.RS General Business\\\"}\"}", attr.MetadataContent);
            Aver.AreObjectsEqual("HAB", rec["Vertical_ID"]);

            fdef = rec.Schema["Table_ID"];
            Aver.IsNotNull(fdef);
            Aver.AreObjectsEqual("Table_ID", fdef.Name);
            Aver.AreObjectsEqual(typeof(long), fdef.Type);
            Aver.AreEqual(true, fdef.AnyTargetKey);
            Aver.IsNotNull(fdef.Attrs);
            Aver.AreEqual(1, fdef.Attrs.Count());
            attr = fdef.Attrs.First();
            Aver.AreObjectsEqual("Table", attr.Description);
            Aver.AreEqual(true, attr.Required);
            Aver.AreEqual(false, attr.Visible);
            Aver.AreObjectsEqual(1, attr.Min);
            Aver.AreObjectsEqual(123, attr.Max);
            Aver.AreObjectsEqual(15, attr.Default);
            Aver.IsTrue(DataKind.Number == attr.Kind);
            Aver.IsTrue(StoreFlag.LoadAndStore == attr.StoreFlag);
            Aver.AreEqual(0, attr.ParseValueList(true).Count);
            Aver.AreObjectsEqual("''{Name=Table_ID Type=int Key=True Description=Table Required=True Visible=False MinValue=1 MaxValue=123 DefaultValue=15 Kind=Number Stored=True}", attr.MetadataContent);
            Aver.AreObjectsEqual((long)2, rec["Table_ID"]);
        }
        public override void Execute(string[] args, Action <ShellMessageType, string> output)
        {
            if (Shell.Debugger.IsSteppingOrOnBreakpoint)
            {
                output(ShellMessageType.Error, $"Please finish debugging the current invoke: {Shell.Debugger.Emulator.currentMethod}");
                return;
            }

            DataNode inputs;

            try
            {
                inputs = JSONReader.ReadFromString(args[1]);
            }
            catch
            {
                output(ShellMessageType.Error, "Invalid arguments format. Must be valid JSON.");
                return;
            }

            if (args.Length >= 3)
            {
                bool valid = false;

                if (args[2].ToLower() == "with")
                {
                    if (args.Length >= 5)
                    {
                        var assetAmount = BigInteger.Parse(args[3]);
                        var assetName   = args[4];

                        foreach (var entry in Asset.Entries)
                        {
                            if (entry.name == assetName)
                            {
                                output(ShellMessageType.Default, $"Attaching {assetAmount} {assetName} to transaction");
                                Shell.Debugger.Emulator.SetTransaction(entry.id, assetAmount);
                                break;
                            }
                        }

                        valid = true;
                    }
                }

                if (!valid)
                {
                    output(ShellMessageType.Error, "Invalid sintax.");
                    return;
                }
            }

            output(ShellMessageType.Default, "Executing transaction...");

            var loaderScript = Shell.Debugger.Emulator.GenerateLoaderScriptFromInputs(inputs);
            var methodName   = inputs.ChildCount > 0 ? inputs[0].Value : null;

            Shell.Debugger.Emulator.Reset(loaderScript, Shell.Debugger.ABI, methodName);

            Runtime.OnLogMessage = (x => output(ShellMessageType.Default, x));

            Shell.Debugger.Run();
            ShellRunner.UpdateState(Shell, output);
        }
 public List <NECResultDataModel> Process(DateTime date)
 {
     return(JSONReader <NECResultDataModel> .Read(Directory.GetFiles($"../SmICSWebApp/Resources/nec/json", date.ToString("yyyy-MM-dd") + ".json")[0]));
 }
Example #18
0
 public static Schema FromJSON(string json, bool readOnly = false)
 {
     return(FromJSON(JSONReader.DeserializeDataObject(json) as JSONDataMap, readOnly));
 }
Example #19
0
        private void readFromFile()
        {
            var data = JSONReader.DeserializeDataObjectFromFile(m_FileName, caseSensitiveMaps: false) as JSONDataMap;

            read(data);
        }
        /// <summary>
        /// Having read a tag, process the corresponding value data.
        /// </summary>
        /// <param name="JSONReader">The input stream</param>
        /// <param name="Tag">The tag</param>
		public override void DeserializeToken (JSONReader JSONReader, string Tag) {
			
			switch (Tag) {
				case "Account" : {
					Account = JSONReader.ReadString ();
					break;
					}
				case "DeviceEntries" : {
					// Have a sequence of values
					bool _Going = JSONReader.StartArray ();
					DeviceEntries = new List <DeviceEntry> ();
					while (_Going) {
						// an untagged structure.
						var _Item = new DeviceEntry (JSONReader);
						DeviceEntries.Add (_Item);
						_Going = JSONReader.NextArray ();
						}
					break;
					}
				case "HostEntries" : {
					// Have a sequence of values
					bool _Going = JSONReader.StartArray ();
					HostEntries = new List <HostEntry> ();
					while (_Going) {
						// an untagged structure.
						var _Item = new HostEntry (JSONReader);
						HostEntries.Add (_Item);
						_Going = JSONReader.NextArray ();
						}
					break;
					}
				default : {
					base.DeserializeToken(JSONReader, Tag);
					break;
					}
				}
			// check up that all the required elements are present
			}
Example #21
0
        /// <summary>
        /// Fills method invocation param array with args doing some interpretation for widely used types like JSONDataMaps, Rows etc..
        /// </summary>
        protected virtual void BindParameters(Controller controller, string action, ActionAttribute attrAction, MethodInfo method, WorkContext work, out object[] args)
        {
            var mpars = method.GetParameters();

            args = new object[mpars.Length];

            if (mpars.Length == 0)
            {
                return;
            }

            var requested = GetRequestAsJSONDataMap(work);

            var strictParamBinding = attrAction.StrictParamBinding;

            //check for complex type
            for (var i = 0; i < mpars.Length; i++)
            {
                var ctp = mpars[i].ParameterType;
                if (ctp == typeof(object) || ctp == typeof(JSONDataMap) || ctp == typeof(Dictionary <string, object>))
                {
                    args[i] = requested;
                    continue;
                }
                if (typeof(TypedRow).IsAssignableFrom(ctp))
                {
                    args[i] = JSONReader.ToRow(ctp, requested);
                    continue;
                }
            }

            for (var i = 0; i < args.Length; i++)
            {
                var mp = mpars[i];

                var got = requested[mp.Name];

                if (got == null)
                {
                    if (mp.HasDefaultValue)
                    {
                        args[i] = mp.DefaultValue;
                    }
                    continue;
                }

                var strVal = got.AsString();
                try
                {
                    args[i] = strVal.AsType(mp.ParameterType, strictParamBinding);
                }
                catch
                {
                    const int MAX_LEN = 30;
                    if (strVal.Length > MAX_LEN)
                    {
                        strVal = strVal.Substring(0, MAX_LEN) + "...";
                    }
                    throw new HTTPStatusException(SysConsts.STATUS_400,
                                                  SysConsts.STATUS_400_DESCRIPTION,
                                                  StringConsts.MVCCONTROLLER_ACTION_PARAM_BINDER_ERROR
                                                  .Args(
                                                      controller.GetType().DisplayNameWithExpandedGenericArgs(),
                                                      strictParamBinding ? "strict" : "relaxed",
                                                      action,
                                                      mp.Name,
                                                      mp.ParameterType.DisplayNameWithExpandedGenericArgs(), strVal));
                }
            }
        }
Example #22
0
        public static decimal GetCoinRate(string ticker, string currrency)
        {
            string json;
            string baseticker;

            switch (ticker)
            {
            case "SOUL":
                baseticker = "phantasma";
                break;

            case "KCAL":
                baseticker = "phantasma-energy";
                break;

            case "NEO":
                baseticker = "neo";
                break;

            case "GAS":
                baseticker = "gas";
                break;

            case "USDT":
                baseticker = "tether";
                break;

            case "ETH":
                baseticker = "ethereum";
                break;

            case "DAI":
                baseticker = "dai";
                break;

            case "DYT":
                baseticker = "dynamite";
                break;

            case "DANK":
                baseticker = "mu-dank";
                break;

            case "GOATI":
                baseticker = "GOATI";
                break;

            case "USDC":
                baseticker = "usd-coin";
                break;

            case "BNB":
                baseticker = "binancecoin";
                break;

            case "BUSD":
                baseticker = "binance-usd";
                break;

            default:
                baseticker = "";
                break;
            }

            if (String.IsNullOrEmpty(baseticker))
            {
                return(0);
            }

            var url = $"https://api.coingecko.com/api/v3/simple/price?ids={baseticker}&vs_currencies={currrency}";

            try
            {
                using (var httpClient = new HttpClient())
                {
                    json = httpClient.GetStringAsync(new Uri(url)).Result;
                }

                var root = JSONReader.ReadFromString(json);

                // hack for goati price .10
                if (ticker == "GOATI")
                {
                    var price = 0.10m;
                    return(price);
                }
                else
                {
                    root = root[baseticker];
                    var price = root.GetDecimal(currrency.ToLower());
                    return(price);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception occurred: {ex}");
                return(0);
            }
        }
Example #23
0
 /// <summary>
 /// Reads either Table or Rowset from JSON created by WriteAsJSON. Metadata must be present
 /// </summary>
 public static RowsetBase FromJSON(string json, bool schemaOnly = false, bool readOnlySchema = false)
 {
     return(FromJSON(JSONReader.DeserializeDataObject(json) as JSONDataMap, schemaOnly, readOnlySchema));
 }
Example #24
0
        public override void Execute(string[] args)
        {
            if (Shell.debugger == null)
            {
                Shell.Write("Smart contract not loaded yet.");
                return;
            }


            DataNode inputs;

            try
            {
                inputs = JSONReader.ReadFromString(args[1]);
            }
            catch
            {
                Shell.Write("Invalid arguments format. Must be valid JSON.");
                return;
            }

            if (args.Length >= 3)
            {
                bool valid = false;

                if (args[2].ToLower() == "with")
                {
                    if (args.Length >= 5)
                    {
                        BigInteger assetAmount = BigInteger.Parse(args[3]);
                        var        assetName   = args[4];

                        foreach (var entry in Asset.Entries)
                        {
                            if (entry.name == assetName)
                            {
                                Shell.Write($"Attaching {assetAmount} {assetName} to transaction");
                                Shell.debugger.SetTransaction(entry.id, assetAmount);
                                break;
                            }
                        }

                        valid = true;
                    }
                }

                if (!valid)
                {
                    Shell.Write("Invalid sintax.");
                    return;
                }

                Shell.Write("Executing transaction...");

                Shell.debugger.Reset(inputs);
                Shell.debugger.Run();

                var val = Shell.debugger.GetOutput();

                Shell.blockchain.Save(Shell.blockchainPath);

                Shell.Write("Result: " + FormattingUtils.StackItemAsString(val));
                Shell.Write("GAS used: " + Shell.debugger.GetUsedGas());
            }
        }
        /// <summary>
		/// Create a new instance from untagged string input.
		/// i.e. {... data ... }
        /// </summary>	
        /// <param name="_Input">The input data.</param>
        /// <returns>The created object.</returns>				
		public static new SSHProfilePrivate From (string _Input) {
			StringReader _Reader = new StringReader (_Input);
            JSONReader JSONReader = new JSONReader (_Reader);
			return new SSHProfilePrivate (JSONReader);
			}
Example #26
0
        private void RunForm_Shown(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.None;

            assetAmmount.Enabled = assetListBox.SelectedIndex > 0;

            if (Runtime.invokerKeys == null && File.Exists("last.key"))
            {
                var privKey = File.ReadAllBytes("last.key");
                if (privKey.Length == 32)
                {
                    Runtime.invokerKeys = new NeoLux.KeyPair(privKey);
                }
            }

            if (Runtime.invokerKeys != null)
            {
                addressLabel.Text = Runtime.invokerKeys.address;
            }
            else
            {
                addressLabel.Text = "(No key loaded)";
            }

            if (!string.IsNullOrEmpty(MainForm.targetAVMPath))
            {
                var fileName = MainForm.targetAVMPath.Replace(".avm", ".json");
                if (File.Exists(fileName))
                {
                    try
                    {
                        _paramMap = new Dictionary <string, DataNode>();

                        var contents = File.ReadAllText(fileName);

                        var contractInfo = JSONReader.ReadFromString(contents);

                        var contractNode = contractInfo["contract"];
                        var inputs       = contractNode["inputs"];

                        paramsList.Items.Clear();
                        foreach (var node in inputs.Children)
                        {
                            var name = node.GetString("name");
                            var data = node.GetNode("params");
                            _paramMap[name] = data;
                        }
                    }
                    finally
                    {
                    }
                }
            }

            button1.Enabled = _paramMap != null && _paramMap.Count > 0;
            paramsList.Items.Clear();

            if (_paramMap != null)
            {
                foreach (var entry in _paramMap)
                {
                    paramsList.Items.Add(entry.Key);

                    if (lastParams != null && entry.Key.Equals(lastParams))
                    {
                        paramsList.SelectedIndex = paramsList.Items.Count - 1;
                    }
                }

                if (paramsList.SelectedIndex < 0 && paramsList.Items.Count > 0)
                {
                    paramsList.SelectedIndex = 0;
                }
            }
        }
        /// <summary>
		/// Initialize class from JSONReader stream.
        /// </summary>		
        /// <param name="JSONReader">Input stream</param>	
		public DeviceEntry (JSONReader JSONReader) {
			Deserialize (JSONReader);
			}
Example #28
0
        private bool InitInvoke()
        {
            var json = contractInputField.Text;

            if (string.IsNullOrEmpty(json))
            {
                MessageBox.Show("Invalid input!");
                return(false);
            }

            DataNode node;

            try
            {
                node = JSONReader.ReadFromString(json);
            }
            catch
            {
                MessageBox.Show("Error parsing input!");
                return(false);
            }

            var items = node.GetNode("params");

            debugger.ContractArgs.Clear();
            foreach (var item in items.Children)
            {
                // TODO - auto convert value to proper types, currently everything is assumed to be strings!

                var obj = ConvertArgument(item);
                debugger.ContractArgs.Add(obj);
            }

            debugger.ClearTransactions();
            if (assetListBox.SelectedIndex > 0)
            {
                foreach (var entry in Asset.Entries)
                {
                    if (entry.name == assetListBox.SelectedItem.ToString())
                    {
                        BigInteger ammount;

                        BigInteger.TryParse(assetAmmount.Text, out ammount);

                        if (ammount > 0)
                        {
                            debugger.AddTransaction(entry.id, ammount);
                        }
                        else
                        {
                            MessageBox.Show(entry.name + " ammount must be greater than zero");
                            return(false);
                        }

                        break;
                    }
                }
            }

            return(true);
        }
        /// <summary>
        /// Create a new instance from tagged string input.
		/// i.e. { "HostEntry" : {... data ... } }
        /// </summary>
        /// <param name="_Input">The input data.</param>
        /// <returns>The created object.</returns>		
		public static new HostEntry FromTagged (string _Input) {
			//HostEntry _Result;
			//Deserialize (_Input, out _Result);
			StringReader _Reader = new StringReader (_Input);
            JSONReader JSONReader = new JSONReader (_Reader);
			return FromTagged (JSONReader) ;
			}
Example #30
0
 public override object Deserialize(string serialized)
 {
     return(JSONReader.DeserializeDataObject(serialized).ConvertTo <object>());
 }
        /// <summary>
        /// Construct an instance from a JSON encoded stream.
        /// </summary>
		public RecryptProtocol (JSONReader JSONReader) {
			Deserialize (JSONReader);
			_Initialize () ;
			}
Example #32
0
 public override object Deserialize(Stream inputStream)
 {
     inputStream.Seek(0, SeekOrigin.Begin);
     return(JSONReader.DeserializeDataObject(inputStream).ConvertTo <object>());
 }
        /// <summary>
		/// Initialize class from JSONReader stream.
        /// </summary>		
		public RecryptResponse (JSONReader JSONReader) {
			Deserialize (JSONReader);
			}
Example #34
0
        public void Start()
        {
            // Start listening for client requests.
            server.Start();

            // Buffer for reading data
            Byte[] bytes = new Byte[256];

            // Enter the listening loop.
            while (true)
            {
                try
                {
                    Console.Write("Waiting for a connection... ");

                    // Perform a blocking call to accept requests.
                    // You could also user server.AcceptSocket() here.
                    TcpClient client = server.AcceptTcpClient();
                    Console.WriteLine("Connected!");

                    // Get a stream object for reading and writing
                    NetworkStream stream = client.GetStream();

                    int i;

                    // Loop to receive all the data sent by the client.
                    var sb = new StringBuilder();
                    while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        var str = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                        sb.Append(str);
                    }

                    var json = sb.ToString();
                    var root = JSONReader.ReadFromString(json);

                    var method = root.GetString("method");

                    string result = null;

                    switch (method)
                    {
                    case "getaccountstate":
                    {
                        break;
                    }

                    case "getstorage":
                    {
                        break;
                    }

                    case "sendrawtransaction":
                    {
                        break;
                    }

                    case "invokescript":
                    {
                        break;
                    }

                    case "getrawtransaction":
                    {
                        break;
                    }

                    case "getblockcount":
                    {
                        break;
                    }

                    case "getblock":
                    {
                        break;
                    }
                    }

                    var output = Encoding.ASCII.GetBytes(result);
                    stream.Write(output, 0, output.Length);

                    client.Close();
                }
                catch (SocketException e)
                {
                    Console.WriteLine("SocketException: {0}", e);
                }
            }
            // Stop listening for new clients.
            server.Stop();
        }
        /// <summary>
        /// Create a new instance from tagged string input.
		/// i.e. { "RecryptResponse" : {... data ... } }
        /// </summary>
        /// <param name="_Input">The input data.</param>
        /// <returns>The created object.</returns>		
		public static new RecryptResponse FromTagged (string _Input) {
			//RecryptResponse _Result;
			//Deserialize (_Input, out _Result);
			StringReader _Reader = new StringReader (_Input);
            JSONReader JSONReader = new JSONReader (_Reader);
			return FromTagged (JSONReader) ;
			}
Example #36
0
        public static IEnumerator SendRequest(string url, string method, Action<EPHANTASMA_SDK_ERROR_TYPE, string> errorHandlingCallback, 
                                            Action<DataNode> callback, params object[] parameters)
        {
            string contents;

            var paramData = DataNode.CreateArray("params");
            
            if (parameters!=null && parameters.Length > 0)
            {
                foreach (var obj in parameters)
                {
                    paramData.AddField(null, obj);
                }
            }

            var jsonRpcData = DataNode.CreateObject(null);
            jsonRpcData.AddField("jsonrpc", "2.0");
            jsonRpcData.AddField("method", method);
            jsonRpcData.AddField("id", "1");
            jsonRpcData.AddNode(paramData);
            
            UnityWebRequest www;
            string json;

            try
            {
				json = JSONWriter.WriteToString(jsonRpcData);
            }
            catch (Exception e)
            {
                throw e;
            }
            
            Debug.Log("www request json: " + json);

            www = UnityWebRequest.Post(url, json);
            yield return www.SendWebRequest();
            
            if (www.isNetworkError || www.isHttpError)
            {
                Debug.Log(www.error);
				if (errorHandlingCallback != null) errorHandlingCallback(EPHANTASMA_SDK_ERROR_TYPE.WEB_REQUEST_ERROR, www.error);			
            }
            else
            {
                Debug.Log(www.downloadHandler.text);
				var root = JSONReader.ReadFromString(www.downloadHandler.text);
				
				if (root == null)
				{
					if (errorHandlingCallback != null) errorHandlingCallback(EPHANTASMA_SDK_ERROR_TYPE.FAILED_PARSING_JSON, "failed to parse JSON");
				}
				else 
				if (root.HasNode("error")) {
					var errorDesc = root["error"].GetString("message");
					if (errorHandlingCallback != null) errorHandlingCallback(EPHANTASMA_SDK_ERROR_TYPE.API_ERROR, errorDesc);
				}
				else
				if (root.HasNode("result"))
				{
					var result = root["result"];
					callback(result);
				}
				else {					
					if (errorHandlingCallback != null) errorHandlingCallback(EPHANTASMA_SDK_ERROR_TYPE.MALFORMED_RESPONSE, "malformed response");
				}				
            }

			yield break;
        }		
Example #37
0
        internal void SendRequest(string url, string method, Action <EPHANTASMA_SDK_ERROR_TYPE, string> errorHandlingCallback,
                                  Action <DataNode> callback, params object[] parameters)
        {
            var paramData = DataNode.CreateArray("params");

            if (parameters != null && parameters.Length > 0)
            {
                foreach (var obj in parameters)
                {
                    paramData.AddField(null, obj);
                }
            }

            var jsonRpcData = DataNode.CreateObject(null);

            jsonRpcData.AddField("jsonrpc", "2.0");
            jsonRpcData.AddField("method", method);
            jsonRpcData.AddField("id", "1");
            jsonRpcData.AddNode(paramData);

            string json;

            try
            {
                json = JSONWriter.WriteToString(jsonRpcData);
            }
            catch (Exception e)
            {
                throw e;
            }

            string contents;

            try {
                using (var wc = new WebClient())
                {
                    wc.Headers[HttpRequestHeader.ContentType] = "application/json";
                    contents = wc.UploadString(url, json);
                }
            }
            catch (Exception e)
            {
                if (errorHandlingCallback != null)
                {
                    errorHandlingCallback(EPHANTASMA_SDK_ERROR_TYPE.WEB_REQUEST_ERROR, e.Message);
                }
                return;
            }

            var root = JSONReader.ReadFromString(contents);

            if (root == null)
            {
                if (errorHandlingCallback != null)
                {
                    errorHandlingCallback(EPHANTASMA_SDK_ERROR_TYPE.FAILED_PARSING_JSON, "failed to parse JSON");
                }
            }
            else
            if (root.HasNode("error"))
            {
                var errorDesc = root["error"].GetString("message");
                if (errorHandlingCallback != null)
                {
                    errorHandlingCallback(EPHANTASMA_SDK_ERROR_TYPE.API_ERROR, errorDesc);
                }
            }
            else
            if (root.HasNode("result"))
            {
                var result = root["result"];
                callback(result);
            }
            else
            {
                if (errorHandlingCallback != null)
                {
                    errorHandlingCallback(EPHANTASMA_SDK_ERROR_TYPE.MALFORMED_RESPONSE, "malformed response");
                }
            }
        }
Example #38
0
        public InteropTransaction ReadTransaction(Hash hash)
        {
            var hashText = hash.ToString();

            var apiCall = $"get_transaction/{hashText}";
            var json    = ExecuteRequest(apiCall);

            if (json == null)
            {
                throw new OracleException("Network read failure: " + apiCall);
            }

            string inputSource = null;

            try
            {
                var root = JSONReader.ReadFromString(json);

                var scripts = root.GetNode("scripts");
                Throw.IfNull(scripts, nameof(scripts));

                if (scripts.ChildCount != 1)
                {
                    throw new OracleException("Transactions with multiple sources not supported yet");
                }

                Address interopAddress = Address.Null;
                foreach (var scriptEntry in scripts.Children)
                {
                    var vs = scriptEntry.GetNode("verification");
                    if (vs == null)
                    {
                        continue;
                    }

                    var verificationScript = Base16.Decode(vs.Value);
                    var pubKey             = new byte[33];
                    Core.Utils.ByteArrayUtils.CopyBytes(verificationScript, 1, pubKey, 0, 33);

                    var signatureScript = NeoKeys.CreateSignatureScript(pubKey);
                    var signatureHash   = Neo.Utils.CryptoUtils.ToScriptHash(signatureScript);
                    inputSource = Neo.Utils.CryptoUtils.ToAddress(signatureHash);

                    pubKey         = Core.Utils.ByteArrayUtils.ConcatBytes((byte)AddressKind.User, pubKey);
                    interopAddress = Address.FromBytes(pubKey);
                    break;
                }

                if (interopAddress.IsNull)
                {
                    throw new OracleException("Could not fetch public key from transaction");
                }

                if (string.IsNullOrEmpty(inputSource))
                {
                    throw new OracleException("Could not fetch source address from transaction");
                }

                var attrNodes = root.GetNode("attributes");
                if (attrNodes != null)
                {
                    foreach (var entry in attrNodes.Children)
                    {
                        var kind = entry.GetString("usage");
                        if (kind == "Description")
                        {
                            var data  = entry.GetString("data");
                            var bytes = Base16.Decode(data);

                            var text = Encoding.UTF8.GetString(bytes);
                            if (Address.IsValidAddress(text))
                            {
                                interopAddress = Address.FromText(text);
                            }
                        }
                    }
                }

                return(FillTransaction(hashText, inputSource, interopAddress));
            }
            catch (Exception e)
            {
                throw new OracleException(e.Message);
            }
        }
        public static DataNode GetArgsListAsNode(string argList)
        {
            var node = JSONReader.ReadFromString("{\"params\": [" + argList + "]}");

            return(node.GetNode("params"));
        }
Example #40
0
        public void LoadFromFile(string path)
        {
            if (!File.Exists(path))
            {
                throw new FileNotFoundException();
            }

            var json = File.ReadAllText(path);
            var root = JSONReader.ReadFromString(json);

            var avmInfo = root["avm"];

            if (avmInfo != null)
            {
                /*var curHash = bytes.MD5().ToLowerInvariant();
                 * var oldHash = avmInfo.GetString("hash").ToLowerInvariant();
                 *
                 * if (curHash != oldHash)
                 * {
                 *  throw new Exception("Hash mismatch, please recompile the code to get line number info");
                 * }*/

                this.contractName = avmInfo.GetString("name");
            }
            else
            {
                this.contractName = Path.GetFileNameWithoutExtension(path);
            }

            _fileNames.Clear();

            var files    = new Dictionary <int, string>();
            var fileNode = root["files"];

            foreach (var temp in fileNode.Children)
            {
                files[temp.GetInt32("id")] = temp.GetString("url");
            }

            _entries = new List <DebugMapEntry>();
            var mapNode = root["map"];

            foreach (var temp in mapNode.Children)
            {
                int fileID = temp.GetInt32("file");

                if (!files.ContainsKey(fileID))
                {
                    throw new Exception("Error loading map file, invalid file entry");
                }

                var entry = new DebugMapEntry();
                entry.startOfs = temp.GetInt32("start");
                entry.endOfs   = temp.GetInt32("end");
                entry.line     = temp.GetInt32("line");
                entry.url      = files[fileID];
                _entries.Add(entry);

                if (!string.IsNullOrEmpty(entry.url))
                {
                    _fileNames.Add(entry.url);
                }
            }
        }
Example #41
0
        private void readFromString(string content)
        {
            var data = JSONReader.DeserializeDataObject(content, caseSensitiveMaps: false) as JSONDataMap;

            read(data);
        }
Example #42
0
        private bool InitInvoke()
        {
            var key = paramsList.Text;
            var f   = abi.functions[key];

            var argList = "\"" + key + "\"";

            if (f.inputs != null)
            {
                argList += ", [";

                int index = 0;
                foreach (var p in f.inputs)
                {
                    var temp = (key + "_" + f.name).ToLower();
                    var val  = inputGrid.Rows[index].Cells[1].Value;

                    if (index > 0)
                    {
                        argList += ",";
                    }

                    switch (p.type.ToLower())
                    {
                    case "string": val = "\"" + val + "\""; break;
                    }

                    argList += val;
                    index++;
                }

                argList += "]";
            }
            else
            {
                argList += ", [null]";
            }

            string json = "{\"params\": [" + argList + "]}";

            if (string.IsNullOrEmpty(json))
            {
                MessageBox.Show("Invalid input!");
                return(false);
            }

            DataNode node;

            try
            {
                node = JSONReader.ReadFromString(json);
            }
            catch
            {
                MessageBox.Show("Error parsing input!");
                return(false);
            }

            var items = node.GetNode("params");

            if (assetListBox.SelectedIndex > 0)
            {
                foreach (var entry in Asset.Entries)
                {
                    if (entry.name == assetListBox.SelectedItem.ToString())
                    {
                        BigInteger ammount;

                        BigInteger.TryParse(assetAmmount.Text, out ammount);

                        if (ammount > 0)
                        {
                            emulator.SetTransaction(entry.id, ammount);
                        }
                        else
                        {
                            MessageBox.Show(entry.name + " ammount must be greater than zero");
                            return(false);
                        }

                        break;
                    }
                }
            }

            emulator.Reset(items);

            return(true);
        }
        /// <summary>
        /// Search for the specified profile on the local machine.
        /// </summary>
        /// <param name="UDF">Fingerprint of the profile to find.</param>
        /// <param name="FileName">The name of the file</param>
        /// <returns>The signed profile if found or null otherwise.</returns>
        public static SignedApplicationProfile FromFile(string UDF, string FileName) {

            using (var FileReader = FileName.OpenFileReadShared()) {
                using (var TextReader = FileReader.OpenTextReader()) {
                    var Reader = new JSONReader(TextReader);
                    var Result = SignedApplicationProfile.FromTagged(Reader);

                    return Result;
                    }
                }
            }
Example #44
0
        public static decimal GetCoinRate(string ticker, string currrency)
        {
            string json;
            string baseticker;

            switch (ticker)
            {
            case "SOUL":
                baseticker = "phantasma";
                break;

            case "KCAL":
                baseticker = "phantasma";
                break;

            case "NEO":
                baseticker = "neo";
                break;

            case "GAS":
                baseticker = "gas";
                break;

            default:
                baseticker = "phantasma";
                break;
            }

            var url = $"https://api.coingecko.com/api/v3/simple/price?ids={baseticker}&vs_currencies={currrency}";

            try
            {
                using (var httpClient = new HttpClient())
                {
                    json = httpClient.GetStringAsync(new Uri(url)).Result;
                }
                var root = JSONReader.ReadFromString(json);

                // hack for kcal price 1/5 soul & goati .10
                if (ticker == "KCAL")
                {
                    root = root["phantasma"];
                    var price = root.GetDecimal(currrency.ToLower()) / 5;
                    return(price);
                }
                else if (ticker == "GOATI")
                {
                    var price = 0.10m;
                    return(price);
                }
                else
                {
                    root = root[baseticker];
                    var price = root.GetDecimal(currrency.ToLower());
                    return(price);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception occurred: {ex}");
                return(0);
            }
        }
Example #45
0
        private void btnReadJson_Click(object sender, EventArgs e)
        {
            List <Invoice> invoices = new List <Invoice>();

            JsonSerializer jsonSerializer = new JsonSerializer();

            using (StreamReader r = new StreamReader(@"D:\DotNet\Forms\JsonReader\JsonReader\Json\Data.json"))
            {
                var json = r.ReadToEnd();

                var        items      = JsonConvert.DeserializeObject <JSONReader>(json);
                JSONReader jSONReader = new JSONReader()
                {
                    b2b   = items.b2b,
                    gstin = items.gstin,
                    fp    = items.fp
                };
                Itm itmm = new Itm();
                using (RootDataContext dbContext = new RootDataContext())
                {
                    var b2bList = jSONReader.b2b; //b2b
                    foreach (var data in b2bList)
                    {
                        B2b b2 = new B2b()
                        {
                            cfs   = data.cfs,
                            cname = data.cname,
                            ctin  = data.ctin,
                            inv   = data.inv//
                        };

                        var invList = data.inv;
                        foreach (var invItem in invList)// inv
                        {
                            var        invItems = invItem.itms;
                            List <Inv> InvList  = new List <Inv>();
                            // Itm Done Here
                            foreach (var Items in invItems)
                            {
                                var Itm_DetItem = Items.itm_det;
                                var ItemDetObj  = new Itm_Det()
                                {
                                    camt  = Itm_DetItem.camt,
                                    csamt = Itm_DetItem.csamt,
                                    rt    = Itm_DetItem.rt,
                                    samt  = Itm_DetItem.samt,
                                    txval = Itm_DetItem.txval
                                };

                                var itm = new Itm()
                                {
                                    num     = Items.num,
                                    itm_det = ItemDetObj
                                };

                                List <Itm> ItemList = new List <Itm>()  // inv List Done Here
                                {
                                    new Itm()
                                    {
                                        num     = itm.num,
                                        itm_det = itm.itm_det
                                    }
                                };
                                Inv inv = new Inv()
                                {
                                    chksum  = invItem.chksum,
                                    idt     = invItem.idt,
                                    inum    = invItem.inum,
                                    inv_typ = invItem.inv_typ,
                                    pos     = invItem.pos,
                                    rchrg   = invItem.rchrg,
                                    val     = invItem.val,
                                    itms    = ItemList,
                                };


                                InvList.Add(inv);
                            }
                        }
                    }
                }
            }
        }
Example #46
0
 public override DataNode ReadStore(string content)
 {
     return(JSONReader.ReadFromString(content));
 }
Example #47
0
        public static IEnumerator RPCRequest(string url, string method, int timeout, Action <EPHANTASMA_SDK_ERROR_TYPE, string> errorHandlingCallback,
                                             Action <DataNode> callback, params object[] parameters)
        {
            var paramData = DataNode.CreateArray("params");

            if (parameters != null && parameters.Length > 0)
            {
                foreach (var obj in parameters)
                {
                    paramData.AddField(null, obj);
                }
            }

            var jsonRpcData = DataNode.CreateObject(null);

            jsonRpcData.AddField("jsonrpc", "2.0");
            jsonRpcData.AddField("method", method);
            jsonRpcData.AddField("id", "1");
            jsonRpcData.AddNode(paramData);

            UnityWebRequest request;
            string          json;

            try
            {
                json = JSONWriter.WriteToString(jsonRpcData);
            }
            catch (Exception e)
            {
                throw e;
            }

            var requestNumber = GetNextRequestNumber();

            Log.Write($"RPC request [{requestNumber}]\nurl: {url}\njson: {json}", Log.Level.Networking);

            request = new UnityWebRequest(url, "POST");
            byte[] bodyRaw = Encoding.UTF8.GetBytes(json);
            request.uploadHandler   = (UploadHandler) new UploadHandlerRaw(bodyRaw);
            request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
            request.SetRequestHeader("Content-Type", "application/json");

            DateTime startTime = DateTime.Now;

            if (timeout > 0)
            {
                request.timeout = timeout;
            }

            yield return(request.SendWebRequest());

            TimeSpan responseTime = DateTime.Now - startTime;

            if (request.isNetworkError || request.isHttpError)
            {
                Log.Write($"RPC error [{requestNumber}]\nurl: {url}\nResponse time: {responseTime.Seconds}.{responseTime.Milliseconds} sec\n{request.error}\nisNetworkError: {request.isNetworkError}\nisHttpError: {request.isHttpError}\nresponseCode: {request.responseCode}", Log.Level.Networking);
                if (errorHandlingCallback != null)
                {
                    errorHandlingCallback(EPHANTASMA_SDK_ERROR_TYPE.WEB_REQUEST_ERROR, request.error + $"\nURL: {url}\nIs network error: {request.isNetworkError}\nIs HTTP error: {request.isHttpError}\nResponse code: {request.responseCode}");
                }
            }
            else
            {
                Log.Write($"RPC response [{requestNumber}]\nurl: {url}\nResponse time: {responseTime.Seconds}.{responseTime.Milliseconds} sec\n{request.downloadHandler.text}", Log.Level.Networking);
                DataNode root = null;

                try
                {
                    root = JSONReader.ReadFromString(request.downloadHandler.text);
                }
                catch (Exception e)
                {
                    Log.Write($"RPC response [{requestNumber}]\nurl: {url}\nFailed to parse JSON: " + e.Message, Log.Level.Networking);
                    if (errorHandlingCallback != null)
                    {
                        errorHandlingCallback(EPHANTASMA_SDK_ERROR_TYPE.FAILED_PARSING_JSON, "Failed to parse JSON: " + e.Message);
                    }
                    yield break;
                }

                if (root == null)
                {
                    Log.Write($"RPC response [{requestNumber}]\nurl: {url}\nFailed to parse JSON", Log.Level.Networking);
                    if (errorHandlingCallback != null)
                    {
                        errorHandlingCallback(EPHANTASMA_SDK_ERROR_TYPE.FAILED_PARSING_JSON, "failed to parse JSON");
                    }
                }
                else
                if (root.HasNode("error"))
                {
                    var errorDesc = root["error"].GetString("message");
                    Log.Write($"RPC response [{requestNumber}]\nurl: {url}\nError node found: {errorDesc}", Log.Level.Networking);
                    if (errorHandlingCallback != null)
                    {
                        errorHandlingCallback(EPHANTASMA_SDK_ERROR_TYPE.API_ERROR, errorDesc);
                    }
                }
                else
                if (root.HasNode("result"))
                {
                    var result = root["result"];

                    if (result.HasNode("error"))
                    {
                        // This is incorrect way of RPC error reporting,
                        // but it happens sometimes and should be handeled at least for now.
                        var errorDesc = result.GetString("error");
                        Log.Write($"RPC response [{requestNumber}]\nurl: {url}\nError node found (2): {errorDesc}", Log.Level.Networking);
                        if (errorHandlingCallback != null)
                        {
                            errorHandlingCallback(EPHANTASMA_SDK_ERROR_TYPE.API_ERROR, errorDesc);
                        }
                    }
                    else
                    {
                        callback(result);
                    }
                }
                else
                {
                    if (errorHandlingCallback != null)
                    {
                        errorHandlingCallback(EPHANTASMA_SDK_ERROR_TYPE.MALFORMED_RESPONSE, "malformed response");
                    }
                }
            }

            yield break;
        }
        /// <summary>
		/// Initialize class from JSONReader stream.
        /// </summary>		
		public JoinResponse (JSONReader JSONReader) {
			Deserialize (JSONReader);
			}
        /// <summary>
		/// Initialize class from JSONReader stream.
        /// </summary>		
        /// <param name="JSONReader">Input stream</param>	
		public SSHProfilePrivate (JSONReader JSONReader) {
			Deserialize (JSONReader);
			}
        /// <summary>
		/// Initialize class from JSONReader stream.
        /// </summary>		
		public LeaveRequest (JSONReader JSONReader) {
			Deserialize (JSONReader);
			}
        /// <summary>
        /// Create a new instance from tagged string input.
		/// i.e. { "SSHProfilePrivate" : {... data ... } }
        /// </summary>
        /// <param name="_Input">The input data.</param>
        /// <returns>The created object.</returns>		
		public static new SSHProfilePrivate FromTagged (string _Input) {
			//SSHProfilePrivate _Result;
			//Deserialize (_Input, out _Result);
			StringReader _Reader = new StringReader (_Input);
            JSONReader JSONReader = new JSONReader (_Reader);
			return FromTagged (JSONReader) ;
			}
        /// <summary>
		/// Create a new instance from untagged string input.
		/// i.e. {... data ... }
        /// </summary>	
        /// <param name="_Input">The input data.</param>
        /// <returns>The created object.</returns>				
		public static new LeaveRequest From (string _Input) {
			StringReader _Reader = new StringReader (_Input);
            JSONReader JSONReader = new JSONReader (_Reader);
			return new LeaveRequest (JSONReader);
			}
        /// <summary>
        /// Construct an instance from a JSON encoded stream.
        /// </summary>
        /// <param name="JSONReader">Input stream</param>
		public MeshSSH (JSONReader JSONReader) {
			Deserialize (JSONReader);
			_Initialize () ;
			}
        /// <summary>
        /// Create a new instance from tagged string input.
		/// i.e. { "LeaveRequest" : {... data ... } }
        /// </summary>
        /// <param name="_Input">The input data.</param>
        /// <returns>The created object.</returns>		
		public static new LeaveRequest FromTagged (string _Input) {
			//LeaveRequest _Result;
			//Deserialize (_Input, out _Result);
			StringReader _Reader = new StringReader (_Input);
            JSONReader JSONReader = new JSONReader (_Reader);
			return FromTagged (JSONReader) ;
			}
        /// <summary>
        /// Having read a tag, process the corresponding value data.
        /// </summary>
        /// <param name="JSONReader">The input stream</param>
        /// <param name="Tag">The tag</param>
		public override void DeserializeToken (JSONReader JSONReader, string Tag) {
			
			switch (Tag) {
				case "UDF" : {
					UDF = JSONReader.ReadString ();
					break;
					}
				case "UserKeys" : {
					// Have a sequence of values
					bool _Going = JSONReader.StartArray ();
					UserKeys = new List <PublicKey> ();
					while (_Going) {
						// an untagged structure.
						var _Item = new PublicKey (JSONReader);
						UserKeys.Add (_Item);
						_Going = JSONReader.NextArray ();
						}
					break;
					}
				default : {
					base.DeserializeToken(JSONReader, Tag);
					break;
					}
				}
			// check up that all the required elements are present
			}
        /// <summary>
		/// Initialize class from JSONReader stream.
        /// </summary>		
		public LeaveResponse (JSONReader JSONReader) {
			Deserialize (JSONReader);
			}
        /// <summary>
		/// Create a new instance from untagged string input.
		/// i.e. {... data ... }
        /// </summary>	
        /// <param name="_Input">The input data.</param>
        /// <returns>The created object.</returns>				
		public static new HostEntry From (string _Input) {
			StringReader _Reader = new StringReader (_Input);
            JSONReader JSONReader = new JSONReader (_Reader);
			return new HostEntry (JSONReader);
			}
        /// <summary>
		/// Initialize class from JSONReader stream.
        /// </summary>		
		public RecryptRequest (JSONReader JSONReader) {
			Deserialize (JSONReader);
			}
        /// <summary>
        /// Deserialize a tagged stream
        /// </summary>
        /// <param name="JSONReader">The input stream</param>
        /// <returns>The created object.</returns>		
        public static new HostEntry  FromTagged (JSONReader JSONReader) {
			HostEntry Out = null;

			JSONReader.StartObject ();
            if (JSONReader.EOR) {
                return null;
                }

			string token = JSONReader.ReadToken ();

			switch (token) {

				case "HostEntry" : {
					var Result = new HostEntry ();
					Result.Deserialize (JSONReader);
					Out = Result;
					break;
					}

				default : {
					//Ignore the unknown data
                    //throw new Exception ("Not supported");
                    break;
					}
				}
			JSONReader.EndObject ();

			return Out;
			}
Example #60
0
        private List <Script> GetAllScripts(string projectJson, int projectId)
        {
            JObject       projectObject = JObject.Parse(projectJson);
            List <Script> toReturn      = new List <Script>();

            projectObject.TryGetValue("scripts", out JToken stageScriptToken);
            using (ApplicationDatabase ctxt = new ApplicationDatabase())
            {
                if (stageScriptToken != null)
                {
                    foreach (var obj in stageScriptToken.Children())
                    {
                        string scriptCoordinates = $"{obj[0].Value<Int32>()}-{obj[1].Value<Int32>()}"; //Get X and Y coordinates
                        Script currentScript     = new Script()
                        {
                            Coordinates = scriptCoordinates, ProjectId = projectId, SpriteTypeId = 2, SpriteName = "stage"
                        };

                        currentScript = ctxt.Scripts.Add(currentScript);
                        ctxt.SaveChanges();

                        List <Block> blocksInScript = GetAllBlockFromScript((JArray)obj, currentScript.ScriptId);
                        currentScript.TotalBlocks = blocksInScript.Count();

                        foreach (Block b in blocksInScript)
                        {
                            b.ScriptId = currentScript.ScriptId;
                            JSONReader.SaveBlockWithParameters(b, b.parameters);
                        }
                        ctxt.SaveChanges();
                    }
                }

                projectObject.TryGetValue("children", out JToken childrenToken);
                if (childrenToken != null)
                {
                    foreach (JObject sprite in childrenToken.Children())
                    {
                        string spriteName = sprite.Value <string>("objName");
                        sprite.TryGetValue("scripts", out JToken spriteScriptsToken);
                        if (spriteScriptsToken != null)
                        {
                            foreach (var obj in spriteScriptsToken.Children())
                            {
                                string scriptCoordinates = $"{obj[0].Value<Int32>()}-{obj[1].Value<Int32>()}"; //Get X and Y coordinates
                                Script currentScript     = new Script()
                                {
                                    Coordinates = scriptCoordinates, ProjectId = projectId, SpriteTypeId = 1, SpriteName = spriteName
                                };
                                currentScript = ctxt.Scripts.Add(currentScript);
                                ctxt.SaveChanges();

                                List <Block> blocksInScript = GetAllBlockFromScript((JArray)obj, currentScript.ScriptId);
                                currentScript.TotalBlocks = blocksInScript.Count();

                                foreach (Block b in blocksInScript)
                                {
                                    b.ScriptId = currentScript.ScriptId;
                                    JSONReader.SaveBlockWithParameters(b, b.parameters);
                                }
                                if (blocksInScript.Any(o => o.IsPartOfProcDef)) //Just check if we found any block that was procDef , which can only occur if the entire script is a procDef
                                {
                                    currentScript.SpriteTypeId = 3;
                                }
                                ctxt.SaveChanges();
                            }
                        }
                    }
                }
            }
            return(toReturn);
        }