// if the document has more than 1 rev, we should create a new child '_revisions' containing an array of all the revs history. private void HandleRevs(JObject document) { string id = document["_id"].ToString(); bool exists = documents.ContainsKey(id); if (!exists) { return; } JObject current = GetCurrentDocument(id); string _rev = document["_rev"].ToString(); if (current["_revisions"] == null) { JArray ja = new JArray(GetRevId(current["_rev"].ToString())); document["_revisions"] = new JObject( new JProperty("start", 1), new JProperty("ids", ja)); } else { document["_revisions"] = current["_revisions"]; } JArray j = (JArray)document["_revisions"]["ids"]; j.AddFirst(GetRevId(_rev)); document["_revisions"]["start"] = j.Count; }
public void IndexOf() { JValue v1 = new JValue(1); JValue v2 = new JValue(1); JValue v3 = new JValue(1); JArray j = new JArray(); j.Add(v1); Assert.AreEqual(0, j.IndexOf(v1)); j.Add(v2); Assert.AreEqual(0, j.IndexOf(v1)); Assert.AreEqual(1, j.IndexOf(v2)); j.AddFirst(v3); Assert.AreEqual(1, j.IndexOf(v1)); Assert.AreEqual(2, j.IndexOf(v2)); Assert.AreEqual(0, j.IndexOf(v3)); v3.Remove(); Assert.AreEqual(0, j.IndexOf(v1)); Assert.AreEqual(1, j.IndexOf(v2)); Assert.AreEqual(-1, j.IndexOf(v3)); }
private void InitDataDir(string hostname, int port, string password) { Directory.CreateDirectory(ResolvePath($"{ServerDir}/Mods")); string multiplayerServerString = $"{name},{hostname}:{port},{password}"; dynamic clientSettings; string serverClientSettingsFilePath = $"{ServerDir}/clientsettings.json"; if (!File.Exists(ResolvePath(serverClientSettingsFilePath))) { string defaultClientSettingsFilePath = $"{DataDir}/clientsettings.json"; Log($"Creating dataPath at {ServerDir}..."); if (!File.Exists(ResolvePath(defaultClientSettingsFilePath))) { throw new Exception($"Please run Vintagestory with its standard launcher first, to generate the {defaultClientSettingsFilePath} file"); } File.Copy(ResolvePath(defaultClientSettingsFilePath), ResolvePath(serverClientSettingsFilePath)); clientSettings = JsonConvert.DeserializeObject(File.ReadAllText(ResolvePath(serverClientSettingsFilePath))); string serverModDir = ResolvePath($"{ServerDir}/Mods"); if (Environment.OSVersion.Platform != PlatformID.Unix) { serverModDir = serverModDir.Replace('/', '\\'); } clientSettings["stringListSettings"].Replace(new JObject { { "multiplayerservers", new JArray(new[] { multiplayerServerString } ) }, { "modPaths", new JArray(new[] { serverModDir } ) } }); File.WriteAllText(ResolvePath(serverClientSettingsFilePath), JsonConvert.SerializeObject(clientSettings, Formatting.Indented)); // Note: this could probably be avoided by adding the install directory to a modPath var coreModFileNames = new[] { "VSCreativeMod.dll", "VSEssentials.dll", "VSSurvivalMod.dll" }; foreach (var coreModFileName in coreModFileNames) { File.Copy(ResolvePath($"{InstallDir}/Mods/{coreModFileName}"), ResolvePath($"{ServerDir}/Mods/{coreModFileName}")); } } else { // Log($"dataPath already exists at {ServerDir}"); // update server details, if they've changed! clientSettings = JsonConvert.DeserializeObject(File.ReadAllText(ResolvePath(serverClientSettingsFilePath))); var multiplayerServers = new JArray(clientSettings["stringListSettings"]["multiplayerservers"]); multiplayerServers.Where(x => x.Type == JTokenType.String && ((string)x).StartsWith($"{name},")).ToList().ForEach(x => x.Remove()); multiplayerServers.AddFirst(multiplayerServerString); clientSettings["stringListSettings"]["multiplayerservers"].Replace(multiplayerServers); File.WriteAllText(ResolvePath(serverClientSettingsFilePath), JsonConvert.SerializeObject(clientSettings)); } cacheData = File.Exists(ResolvePath(CacheDataFilePath)) ? JsonConvert.DeserializeObject <CacheData>(File.ReadAllText(ResolvePath(CacheDataFilePath))) : new CacheData(); }
private void PrepareLists(IEntityQuad list, IEnumerable <IEntityQuad> quads, bool useNativeTypes) { var localSubject = list.Subject; int anotherPropertyInList = quads.Count(q => q.Subject.Equals(localSubject) && !q.Predicate.Equals(RdfType)); var firstValues = quads.Where(q => (q.Subject.Equals(localSubject) && q.Predicate.Equals(RdfFirst))).Select(q => q.Object); var firstValue = firstValues.First(); var restValue = list.Object; _listInGraph.AddFirst(ReturnListProperties(firstValue, useNativeTypes)); _nodesInList.Add(localSubject); IEnumerable <IEntityQuad> quad = quads.Where(q => (q.Subject.IsBlank && q.Predicate.Equals(RdfRest) && q.Object.Equals(localSubject))); if (anotherPropertyInList > 2 || firstValues.Count() > 1) { if (_listInGraph.Count() > 1) { _listInGraph.First.Remove(); _nodesInList = _nodesInList.Where(n => !n.Equals(localSubject)).ToList(); } _listInGraph.AddFirst(restValue.ToString()); } else if (quad.Count() == 1) { PrepareLists(quad.First(), quads, useNativeTypes); } else { IEnumerable <IEntityQuad> firstQuad = quads.Where(q => (q.Subject.IsBlank && q.Predicate.Equals(RdfFirst) && q.Object.Equals(localSubject))); if (firstQuad.Count() == 1) { _listInGraph.First.Remove(); _nodesInList = _nodesInList.Where(n => !n.Equals(localSubject)).ToList(); _listInGraph.AddFirst((restValue.IsBlank && firstValue.IsBlank) ? localSubject.ToString() : restValue.ToString()); } else { _listInGraph.AddFirst(localSubject.ToString()); } } }
public async Task <SendTransactionOperationResult> SendTransaction(Keys keys, string from, string to, BigFloat amount, BigFloat fee, BigFloat gasLimit = null, BigFloat storageLimit = null) { gasLimit = gasLimit ?? 200; storageLimit = storageLimit ?? 0; JObject head = await GetHeader(); JObject account = await GetAccountForBlock(head["hash"].ToString(), from); int counter = int.Parse(account["counter"].ToString()); JArray operations = new JArray(); JToken managerKey = await GetManagerKey(from); string gas = gasLimit.ToString(); string storage = storageLimit.ToString(); if (keys != null && managerKey["key"] == null) { JObject revealOp = new JObject(); operations.AddFirst(revealOp); revealOp["kind"] = "reveal"; revealOp["fee"] = "0"; revealOp["public_key"] = keys.DecryptPublicKey(); revealOp["source"] = from; revealOp["storage_limit"] = storage; revealOp["gas_limit"] = gas; revealOp["counter"] = (++counter).ToString(); } JObject transaction = new JObject(); operations.Add(transaction); transaction["destination"] = to; transaction["amount"] = new BigFloat(amount.ToMicroTez().ToString(6)).Round().ToString(); // Convert to microtez, truncate at 6 digits, round up transaction["storage_limit"] = storage; transaction["gas_limit"] = gas; transaction["counter"] = (++counter).ToString(); transaction["fee"] = fee.ToString(); transaction["source"] = from; transaction["kind"] = Operations.Transaction; JObject parameters = new JObject(); transaction["parameters"] = parameters; parameters["prim"] = "Unit"; parameters["args"] = new JArray(); // No args for this contract. List <OperationResult> sendResults = await SendOperations(operations, keys, head); return(sendResults.LastOrDefault() as SendTransactionOperationResult); }
// POST api/data //public HttpResponseMessage Post([FromBody]string value) public HttpResponseMessage Post(postData value) { bool updated = false; if (value == null) { return(Request.CreateResponse(HttpStatusCode.BadRequest)); } if (value.password != password) { return(Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid Password")); } try { var fullPath = System.Web.Hosting.HostingEnvironment.MapPath(filePath); string fileDataString = System.IO.File.ReadAllText(fullPath + fileName); dynamic fileData = JsonConvert.DeserializeObject(fileDataString); JArray games = fileData.Games; // override last saved game if submitted twice dynamic lastGame = games.First(); if (lastGame.GameDate == value.gameData.GameDate) { games.Remove(lastGame); updated = true; } // backup string newFileName = fileName + ".backup_" + DateTime.Now.ToString("dd-MM-yyyy_hhmm"); System.IO.File.WriteAllText(fullPath + newFileName, JsonConvert.SerializeObject(fileData)); // save new game games.AddFirst(value.gameData); System.IO.File.WriteAllText(fullPath + fileName, JsonConvert.SerializeObject(fileData)); } catch (Exception e) { return(Request.CreateResponse(HttpStatusCode.InternalServerError, e.ToString())); } string text; if (updated) { text = "Game updated successfully"; } else { text = "Game saved successfully"; } return(Request.CreateResponse(HttpStatusCode.OK, text)); }
/// <summary> /// Adds an item to the products to order given an Item Code and Quantity /// </summary> /// <param name="itemCode">The ItemCode to order </param> /// <param name="quantity">The quantity of the Item we're ordering</param> public void addItem(string itemCode, int quantity) { JToken item = menu.variants[itemCode]; item["ID"] = 1; item["isNew"] = true; item["qty"] = quantity; item["AutoRemove"] = false; JArray products = JArray.Parse(data.GetValue("Products").ToString()); products.AddFirst(item); data["Products"] = products; }
public void AddFirstAddedTokenShouldBeFirst() { JValue v1 = new JValue(1); JValue v2 = new JValue(2); JValue v3 = new JValue(3); JArray j = new JArray(); Assert.AreEqual(null, j.First); Assert.AreEqual(null, j.Last); j.AddFirst(v1); Assert.AreEqual(v1, j.First); Assert.AreEqual(v1, j.Last); j.AddFirst(v2); Assert.AreEqual(v2, j.First); Assert.AreEqual(v1, j.Last); j.AddFirst(v3); Assert.AreEqual(v3, j.First); Assert.AreEqual(v1, j.Last); }
// check for replication conflicts and add them to the document under '_conflicts'. private void HandleConflicts(JObject document, JObject conflict, out bool hasConflicts) { string id = document["_id"].ToString(); bool exists = documents.ContainsKey(id) && GetCurrentDocument(id) != null; hasConflicts = true; JObject current = GetCurrentDocument(id); if (!exists) { return; } int new_revNum = GetRevNum(document["_rev"].ToString()); int current_revNum = GetRevNum(conflict["_rev"].ToString()); foreach (JObject result in results) { int seq = GetRevNum(result["seq"].ToString()); if (seq > last_seq && result["id"].ToString() == document["_id"].ToString()) { if (current["_conflicts"] == null) { document["_conflicts"] = new JArray(); } else { document["_conflicts"] = current["_conflicts"]; } JArray j = (JArray)document["_conflicts"]; string rev = conflict["_rev"].ToString(); if (j.Count > 0 && CompareRevs(rev, j[0].ToString()) > 0) { j.AddFirst(rev); } else { j.Add(rev); } documents[id][rev] = conflict.ToString(); hasConflicts = true; return; } } hasConflicts = false; }
/// <summary> /// Adds a coupon to the current order /// </summary> /// <param name="coupon">The coupon to add</param> public void addCoupon(Coupon coupon) { JToken token = menu.coupons[coupon.code]; token["ID"] = 1; token["isNew"] = true; token["qty"] = coupon.quantity; token["AutoRemove"] = false; JArray coupons = JArray.Parse(data.GetValue("Coupons").ToString()); coupons.AddFirst(token); data["Coupons"] = coupons; }
/// <summary> /// Adds a List of Coupons onto the order /// </summary> /// <param name="coupons">The list of coupons to add</param> public void addCoupons(Coupon[] coupons) { JArray originalCoupons = JArray.Parse(data.GetValue("Coupons").ToString()); for (int i = 0; i < coupons.Length; i++) { JToken coupon = menu.coupons[coupons[i].code]; coupon["ID"] = 1; coupon["isNew"] = true; coupon["qty"] = coupons[i].quantity; coupon["AutoRemove"] = false; originalCoupons.AddFirst(coupon); } data["Coupons"] = originalCoupons; }
/// <summary> /// Does the same function as addItem() but takes arrays /// The 'quantity' property can be null if you want to avoid having a lengthy array of integers, the default value will be one. /// </summary> /// <param name="itemCodes">An array of the item codes we're adding</param> /// <param name="quantity">An array of the quantity of the items we're ordering</param> public void addItems(string[] itemCodes, int[] quantity) { JArray products = JArray.Parse(data.GetValue("Products").ToString()); for (int i = 0; i < itemCodes.Length; i++) { JToken item = menu.variants[itemCodes[i]]; item["ID"] = 1; item["isNew"] = true; item["qty"] = quantity[i]; item["AutoRemove"] = false; products.AddFirst(item); } data["Products"] = products; }
/// <summary> /// 获取combox下拉模板列表 /// </summary> /// <returns></returns> public ActionResult comboxData() { var query = from m in mangae.db.TG_Templet orderby m.ID descending select new { m.ID, m.sTempletName }; JArray array = JArray.Parse(JsonHelper.toJson(query)); JObject job = new JObject(); job.Add(new JProperty("ID", 0)); job.Add(new JProperty("sTempletName", "请选择模板")); array.AddFirst(job); return(Content(JsonHelper.toJson(array))); }
public string BestSellersByTotalSalesMoney(int numOfSellers) { if (!(Session["User"] is Seller)) { return("Access Denied"); } if (numOfSellers < 0) { numOfSellers = 3; } JObject jobj = new JObject(); JArray jsonArrSellerNames = new JArray(); JArray jsonArrSellerTotalSalesMoney = new JArray(); int i = 0; foreach (var element in from prod in db.Products where prod.Sold == true join seller in db.Sellers on prod.SellerID equals seller.UserID group new { prod, seller } by seller.UserID into g orderby g.Key select new { sellerID = g.Select(e => e.seller.UserID).FirstOrDefault(), sellerName = g.Select(e => e.seller.Username).Distinct(), sum = g.Sum(e => e.prod.Price) }) { if (i < numOfSellers && element.sellerID != (Session["User"] as User).UserID) { jsonArrSellerNames.Add(element.sellerName); jsonArrSellerTotalSalesMoney.Add(element.sum); i++; } if (element.sellerID == (Session["User"] as User).UserID) { jsonArrSellerNames.AddFirst(element.sellerName.FirstOrDefault() + " (you)"); jsonArrSellerTotalSalesMoney.AddFirst(element.sum); } } jobj.Add("labels", jsonArrSellerNames); jobj.Add("data", jsonArrSellerTotalSalesMoney); return(jobj.ToString()); }
/// <summary> /// Merges new config values with the existing ones (overriding). /// </summary> /// <param name="config">The config object.</param> public void Merge(JObject config) { if (config.ContainsKey("config") && config["config"].Type == JTokenType.Object) { foreach (var item in (JObject)config["config"]) { settings[item.Key] = item.Value; } } if (config.ContainsKey("repositories") && config["repositories"].Type == JTokenType.Array) { // Push in and out to ensure consistent order. var stack = new Stack <JObject>(); foreach (var item in (JArray)config["repositories"]) { stack.Push((JObject)item); } while (stack.Count > 0) { var repository = stack.Pop(); if (repository.ContainsKey("type")) { repositories.AddFirst(repository); continue; } foreach (var disabledItem in repository) { if (disabledItem.Value.Type == JTokenType.Boolean && !disabledItem.Value.Value <bool>()) { disabledRepositories.Add(disabledItem.Key); } } } repositoriesCache = null; } }
public JArray Find(string substring) { string commandText = "select * from products where product_name ~* '.*" + substring + "*.';"; NpgsqlCommand command = new NpgsqlCommand(commandText, _conn); NpgsqlDataReader reader = command.ExecuteReader(); JArray jsonArray = new JArray(); var count = 0; foreach (DbDataRecord item in reader) { JObject jsonItem = new JObject(); jsonItem.Add("product_name", item["product_name"].ToString()); jsonItem.Add("category_name", item["category_name"].ToString()); jsonItem.Add("cost", item["cost"].ToString()); jsonArray.Add(jsonItem); count++; } JObject jItem = new JObject(); jItem.Add("count", count); jsonArray.AddFirst(jItem); return(reader.HasRows ? jsonArray : null); }
public async Task <bool> AutoFillAsync( IKeyStorage keyStorage, WalletAddress address, bool useDefaultFee) { var xtz = (Atomex.Tezos)Currency; if (address.KeyIndex == null) { Log.Error("Can't find private key for address {@address}", address); return(false); } using var securePrivateKey = keyStorage .GetPrivateKey(Currency, address.KeyIndex); if (securePrivateKey == null) { Log.Error("Can't find private key for address {@address}", address); return(false); } using var privateKey = securePrivateKey.ToUnsecuredBytes(); using var securePublicKey = keyStorage .GetPublicKey(Currency, address.KeyIndex); using var publicKey = securePublicKey.ToUnsecuredBytes(); var rpc = new Rpc(xtz.RpcNodeUri); Head = await rpc .GetHeader() .ConfigureAwait(false); var managerKey = await rpc .GetManagerKey(From) .ConfigureAwait(false); Operations = new JArray(); var gas = GasLimit.ToString(CultureInfo.InvariantCulture); var storage = StorageLimit.ToString(CultureInfo.InvariantCulture); var counter = await TezosCounter.Instance .GetCounter(xtz, From, Head, ignoreCache : true) .ConfigureAwait(false); if (managerKey.Value <string>() == null) { //var revealOpCounter = await TezosCounter.Instance // .GetCounter(xtz, From, Head, ignoreCache: true) // .ConfigureAwait(false); var revealOp = new JObject { ["kind"] = OperationType.Reveal, ["fee"] = "0", ["public_key"] = Base58Check.Encode(publicKey, Prefix.Edpk), ["source"] = From, ["storage_limit"] = storage, ["gas_limit"] = gas, ["counter"] = counter.ToString()//revealOpCounter.ToString() }; Operations.AddFirst(revealOp); counter++; } //var counter = await TezosCounter.Instance // .GetCounter(xtz, From, Head) // .ConfigureAwait(false); var transaction = new JObject { ["kind"] = OperationType.Delegation, ["source"] = From, ["fee"] = ((int)Fee).ToString(CultureInfo.InvariantCulture), ["counter"] = counter.ToString(), ["gas_limit"] = gas, ["storage_limit"] = storage, ["delegate"] = To }; Operations.Add(transaction); if (Params != null) { transaction["parameters"] = Params; } var fill = await rpc .AutoFillOperations(xtz, Head, Operations, useDefaultFee) .ConfigureAwait(false); if (!fill) { Log.Error("Delegation autofilling error"); return(false); } // Fee = Operations[0]["fee"].Value<decimal>() / 1_000_000; Fee = Operations.Last["fee"].Value <decimal>() / 1_000_000; return(true); }
// add the new document to the changes list. public void addResult(JObject doc) { seq_num++; seq_id = Guid.NewGuid().ToString(); session_id = Guid.NewGuid().ToString(); string id = doc["_id"].ToString(); string rev = doc["_rev"].ToString(); bool exists = false; for (int i = 0; i < results.Count; i++) { if (results[i]["id"].ToString() == id) { exists = true; JArray c = (JArray)results[i]["changes"]; for (int j = 0; j < c.Count; j++) { string r = c[j]["rev"].ToString(); if (HasRev(doc, r)) { c.RemoveAt(j); } } c.AddFirst(new JObject(new JProperty("rev", rev))); if (GetCurrentDocument(id) == null) { results[i]["deleted"] = true; } else if (results[i]["deleted"] != null) { results[i]["deleted"].Remove(); } results[i]["seq"] = seq_num + "-" + session_id; break; } } if (!exists) { JArray changes = new JArray(); changes.Add(new JObject(new JProperty("rev", rev))); JObject result = new JObject( new JProperty("id", id), new JProperty("seq", seq_num + "-" + session_id), new JProperty("changes", changes)); if (GetCurrentDocument(id) == null) { result.Add("deleted", true); } results.Add(result); } }
public void AddFirst() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); a.AddFirst("First"); Assert.AreEqual("First", (string)a[0]); Assert.AreEqual(a, a[0].Parent); Assert.AreEqual(a[1], a[0].Next); Assert.AreEqual(5, a.Count()); a.AddFirst("NewFirst"); Assert.AreEqual("NewFirst", (string)a[0]); Assert.AreEqual(a, a[0].Parent); Assert.AreEqual(a[1], a[0].Next); Assert.AreEqual(6, a.Count()); Assert.AreEqual(a[0], a[0].Next.Previous); }
public void HandleMessage(Message message, RouterSocket serverSocket, PublisherSocket ioPub) { this.logger.Debug(string.Format("Message Content {0}", message.Content)); ExecuteRequest executeRequest = message.Content.ToObject <ExecuteRequest>(); this.logger.Info(string.Format("Execute Request received with code \n{0}", executeRequest.Code)); // 1: Send Busy status on IOPub this.messageSender.SendStatus(message, ioPub, StatusValues.Busy); // 2: Send execute input on IOPub if (!executeRequest.Silent) { this.executionCount += 1; this.SendExecuteInputMessageToIOPub(message, ioPub, executeRequest.Code); } // 3: Evaluate the C# code IOPubConsole ioPubConsole = new IOPubConsole(message, ioPub, this.messageSender, this.executionCount, this.logger); ioPubConsole.RedirectConsole(); string code = executeRequest.Code; ExecutionResult results = this.replEngine.Execute(code); ioPubConsole.CancelRedirect(); if (!results.IsError) { // 4: Send execute result message to IOPub if (results.OutputResultWithColorInformation.Any()) { string codeOutput = this.GetCodeOutput(results); string codeHtmlOutput = this.GetCodeHtmlOutput(results); JObject data = new JObject() { { "text/plain", codeOutput }, { "text/html", codeHtmlOutput } }; DisplayData displayData = new DisplayData() { Data = data, }; this.SendDisplayDataMessageToIOPub(message, ioPub, displayData); } // 5: Send execute reply to shell socket this.SendExecuteReplyOkMessage(message, serverSocket); } else { var ex = results.CompileError != null ? results.CompileError : results.ExecuteError; dynamic errorContent = new JObject(); errorContent.execution_count = this.executionCount; errorContent.ename = ex.GetType().ToString(); errorContent.evalue = ex.Message; var trace = new JArray(ex.StackTrace.Split('\n')); trace.AddFirst(ex.Message); errorContent.traceback = trace; // 6: Send error message to IOPub this.SendErrorMessageToIOPub(message, ioPub, errorContent); // 7: Send execute reply message to shell socket this.SendExecuteReplyErrorMessage(message, serverSocket, errorContent); } // 8: Send IDLE status message to IOPub this.messageSender.SendStatus(message, ioPub, StatusValues.Idle); }
public async Task <bool> SignAsync( IKeyStorage keyStorage, WalletAddress address, CancellationToken cancellationToken = default(CancellationToken)) { var xtz = (Atomix.Tezos)Currency; if (address.KeyIndex == null) { Log.Error("Can't find private key for address {@address}", address); return(false); } var privateKey = keyStorage .GetPrivateKey(Currency, address.KeyIndex); if (privateKey == null) { Log.Error("Can't find private key for address {@address}", address); return(false); } var publicKey = keyStorage .GetPublicKey(Currency, address.KeyIndex); var rpc = new Rpc(xtz.RpcProvider); Head = await rpc .GetHeader() .ConfigureAwait(false); var managerKey = await rpc .GetManagerKey(From) .ConfigureAwait(false); Operations = new JArray(); var gas = GasLimit.ToString(CultureInfo.InvariantCulture); var storage = StorageLimit.ToString(CultureInfo.InvariantCulture); if (managerKey["key"] == null) { var revealOpCounter = await TezosCounter.Instance .GetCounter(xtz, From, Head) .ConfigureAwait(false); var revealOp = new JObject { ["kind"] = OperationType.Reveal, ["fee"] = "0", ["public_key"] = Base58Check.Encode(publicKey, Prefix.Edpk), ["source"] = From, ["storage_limit"] = storage, ["gas_limit"] = gas, ["counter"] = revealOpCounter.ToString() }; Operations.AddFirst(revealOp); } var counter = await TezosCounter.Instance .GetCounter(xtz, From, Head) .ConfigureAwait(false); var transaction = new JObject { ["kind"] = OperationType.Transaction, ["source"] = From, ["fee"] = Fee.ToString(CultureInfo.InvariantCulture), ["counter"] = counter.ToString(), ["gas_limit"] = gas, ["storage_limit"] = storage, ["amount"] = Math.Round(Amount, 0).ToString(CultureInfo.InvariantCulture), ["destination"] = To }; Operations.Add(transaction); if (Params != null) { transaction["parameters"] = Params; } else { var parameters = new JObject { ["prim"] = "Unit", ["args"] = new JArray() }; transaction["parameters"] = parameters; } var forgedOpGroup = await rpc .ForgeOperations(Head, Operations) .ConfigureAwait(false); SignedMessage = TezosSigner.SignHash( data: Hex.FromString(forgedOpGroup.ToString()), privateKey: privateKey, watermark: Watermark.Generic, isExtendedKey: privateKey.Length == 64); return(true); }
public async Task <(bool result, bool isRunSuccess, bool hasReveal)> FillOperationsAsync( SecureBytes securePublicKey, TezosConfig tezosConfig, int headOffset = 0, bool isAlreadyRevealed = false, CancellationToken cancellationToken = default) { using var publicKey = securePublicKey.ToUnsecuredBytes(); var rpc = new Rpc(tezosConfig.RpcNodeUri); var managerKey = await rpc .GetManagerKey(From) .ConfigureAwait(false); var actualHead = await rpc .GetHeader() .ConfigureAwait(false); if (Head == null) { Head = await rpc .GetHeader(headOffset) .ConfigureAwait(false); } Operations = new JArray(); var gas = GasLimit.ToString(CultureInfo.InvariantCulture); var storage = StorageLimit.ToString(CultureInfo.InvariantCulture); var revealed = managerKey.Value <string>() != null || isAlreadyRevealed; UsedCounters = revealed ? 1 : 2; var counter = UseOfflineCounter ? await TezosCounter.Instance .GetOfflineCounterAsync( address : From, head : actualHead["hash"].ToString(), rpcNodeUri : tezosConfig.RpcNodeUri, numberOfCounters : UsedCounters) .ConfigureAwait(false) : await TezosCounter.Instance .GetCounterAsync( address : From, head : actualHead["hash"].ToString(), rpcNodeUri : tezosConfig.RpcNodeUri) .ConfigureAwait(false); if (!revealed) { var revealOp = new JObject { ["kind"] = Internal.OperationType.Reveal, ["fee"] = "0", ["public_key"] = Base58Check.Encode(publicKey, Prefix.Edpk), ["source"] = From, ["storage_limit"] = "0", ["gas_limit"] = tezosConfig.RevealGasLimit.ToString(), ["counter"] = counter.ToString() }; Operations.AddFirst(revealOp); counter++; } var operation = new JObject { ["kind"] = OperationType, ["source"] = From, ["fee"] = ((int)Fee).ToString(CultureInfo.InvariantCulture), ["counter"] = counter.ToString(), ["gas_limit"] = gas, ["storage_limit"] = storage, }; if (OperationType == Internal.OperationType.Transaction) { operation["amount"] = Math.Round(Amount, 0).ToString(CultureInfo.InvariantCulture); operation["destination"] = To; } else if (OperationType == Internal.OperationType.Delegation) { operation["delegate"] = To; } else { throw new NotSupportedException($"Operation type {OperationType} not supporeted yet."); } Operations.Add(operation); if (Params != null) { operation["parameters"] = Params; } var isRunSuccess = false; if (UseRun) { var fill = await rpc .AutoFillOperations(tezosConfig, Head, Operations, UseSafeStorageLimit) .ConfigureAwait(false); if (!fill) { Log.Warning("Operation autofilling error"); } else { Fee = Operations.Last["fee"].Value <decimal>().ToTez(); isRunSuccess = true; } } return( result : true, isRunSuccess : isRunSuccess, hasReveal : !revealed ); }
public async Task <SendTransactionOperationResult> SendTransaction( Keys keys, string from, string to, decimal amount, decimal fee, decimal gasLimit, decimal storageLimit, JObject param = null) { gasLimit = gasLimit != 0 ? gasLimit : 200; var head = await GetHeader() .ConfigureAwait(false); var account = await GetAccountForBlock(head["hash"].ToString(), from) .ConfigureAwait(false); var counter = int.Parse(account["counter"].ToString()); var operations = new JArray(); var managerKey = await GetManagerKey(from) .ConfigureAwait(false); var gas = gasLimit.ToString(CultureInfo.InvariantCulture); var storage = storageLimit.ToString(CultureInfo.InvariantCulture); if (keys != null && managerKey["key"] == null) { var revealOp = new JObject { ["kind"] = OperationType.Reveal, ["fee"] = "0", ["public_key"] = keys.DecryptPublicKey(), ["source"] = from, ["storage_limit"] = storage, ["gas_limit"] = gas, ["counter"] = (++counter).ToString() }; operations.AddFirst(revealOp); } var transaction = new JObject { ["kind"] = OperationType.Transaction, ["source"] = from, ["fee"] = fee.ToString(CultureInfo.InvariantCulture), ["counter"] = (++counter).ToString(), ["gas_limit"] = gas, ["storage_limit"] = storage, ["amount"] = Math.Round(amount.ToMicroTez(), 0).ToString(CultureInfo.InvariantCulture), ["destination"] = to }; operations.Add(transaction); if (param != null) { transaction["parameters"] = param; } else { var parameters = new JObject { ["prim"] = "Unit", ["args"] = new JArray() // No args for this contract. }; transaction["parameters"] = parameters; } var sendResults = await SendOperations(operations, keys, head) .ConfigureAwait(false); return(sendResults.LastOrDefault() as SendTransactionOperationResult); }
public void AddFirstAddedTokenShouldBeFirst() { JValue v1 = new JValue(1); JValue v2 = new JValue(2); JValue v3 = new JValue(3); JArray j = new JArray(); Assert.AreEqual(null, j.First); Assert.AreEqual(null, j.Last); j.AddFirst(v1); Assert.AreEqual(v1, j.First); Assert.AreEqual(v1, j.Last); j.AddFirst(v2); Assert.AreEqual(v2, j.First); Assert.AreEqual(v1, j.Last); j.AddFirst(v3); Assert.AreEqual(v3, j.First); Assert.AreEqual(v1, j.Last); }
public void IndexOf() { JValue v1 = new JValue(1); JValue v2 = new JValue(1); JValue v3 = new JValue(1); JArray j = new JArray(); j.Add(v1); Assert.AreEqual(0, j.IndexOf(v1)); j.Add(v2); Assert.AreEqual(0, j.IndexOf(v1)); Assert.AreEqual(1, j.IndexOf(v2)); j.AddFirst(v3); Assert.AreEqual(1, j.IndexOf(v1)); Assert.AreEqual(2, j.IndexOf(v2)); Assert.AreEqual(0, j.IndexOf(v3)); v3.Remove(); Assert.AreEqual(0, j.IndexOf(v1)); Assert.AreEqual(1, j.IndexOf(v2)); Assert.AreEqual(-1, j.IndexOf(v3)); }
public override void ToJSON( JObject ParentObject ) { CswNbtNode RelatedNode = null; if( CswTools.IsPrimaryKey( RelatedNodeId ) ) { //ParentObject[_NodeIDSubField.ToXmlNodeName( true ).ToLower()] = RelatedNodeId.ToString(); RelatedNode = _CswNbtResources.Nodes[RelatedNodeId]; } if( IsEditModeEditable ) { JArray JOptions = (JArray) ( ParentObject["options"] = new JArray() ); bool AllowEdit = _CswNbtResources.Permit.isPropWritable( CswEnumNbtNodeTypePermission.Create, NodeTypeProp, null ); Int32 OptionCount = 0; if( AllowEdit ) { CswPrimaryKey pk = null; if( null != RelatedNode ) { pk = RelatedNode.NodeId; } //Dictionary<CswPrimaryKey, string> Options = _OptionsOverride ?? _getOptions( _CswNbtResources, _CswNbtMetaDataNodeTypeProp.IsRequired, _CswNbtMetaDataNodeTypeProp.FKValue, pk, View ); Dictionary<CswPrimaryKey, string> Options = _OptionsOverride ?? _getOptions( _CswNbtResources, CswConvert.ToBoolean( _CswNbtNodePropData[CswNbtFieldTypeRuleRelationship.AttributeName.Required] ), CswConvert.ToInt32( _CswNbtNodePropData[CswNbtFieldTypeRuleRelationship.AttributeName.Target, CswNbtFieldTypeRuleMetaDataList.SubFieldName.Id] ), pk, View ); if( Options.Count > _SearchThreshold ) { ParentObject["usesearch"] = true; } else { ParentObject["usesearch"] = false; CswPrimaryKey FirstPk = null; foreach( CswPrimaryKey NodePk in Options.Keys ) { if( CswTools.IsPrimaryKey( NodePk ) ) { OptionCount += 1; JObject JOption = new JObject(); FirstPk = FirstPk ?? NodePk; JOption["id"] = NodePk.ToString(); JOption["value"] = Options[NodePk]; JOption["link"] = CswNbtNode.getNodeLink( NodePk, Options[NodePk] ); JOptions.Add( JOption ); } } //If Required, show empty when no value is selected and if there is more than one option to select from bool ShowEmptyOption = Required && false == CswTools.IsPrimaryKey( RelatedNodeId ) && 1 < OptionCount; //If not Required, always show the empty value ShowEmptyOption = ShowEmptyOption || false == Required; if( ShowEmptyOption ) { JObject JOption = new JObject(); JOption["id"] = ""; JOption["value"] = ""; JOptions.AddFirst( JOption ); } else { //Case 30030 if( null == RelatedNode && Required && Options.Count == 1 && CswTools.IsPrimaryKey( FirstPk ) ) { RelatedNode = _CswNbtResources.Nodes[FirstPk]; } } } } ParentObject["nodetypeid"] = 0; ParentObject["objectclassid"] = 0; ParentObject["propertysetid"] = 0; bool AllowAdd = false; bool AllowView = true; if( null != RelatedNodeId ) { CswNbtMetaDataNodeType TargetNodeType = _CswNbtResources.MetaData.getNodeTypeFromNodeId( RelatedNodeId ); AllowAdd = ( null != TargetNodeType && _CswNbtResources.Permit.canNodeType( CswEnumNbtNodeTypePermission.Create, TargetNodeType ) ); AllowView = ( null != TargetNodeType && _CswNbtResources.Permit.canNodeType( CswEnumNbtNodeTypePermission.View, TargetNodeType ) ); } else if( TargetType == CswEnumNbtViewRelatedIdType.NodeTypeId ) { ParentObject["nodetypeid"] = TargetId; CswNbtMetaDataNodeType TargetNodeType = _CswNbtResources.MetaData.getNodeType( TargetId ); AllowAdd = ( null != TargetNodeType && _CswNbtResources.Permit.canNodeType( CswEnumNbtNodeTypePermission.Create, TargetNodeType ) ); AllowView = ( null != TargetNodeType && _CswNbtResources.Permit.canNodeType( CswEnumNbtNodeTypePermission.View, TargetNodeType ) ); } else if( TargetType == CswEnumNbtViewRelatedIdType.ObjectClassId ) { ParentObject["objectclassid"] = TargetId; CswNbtMetaDataObjectClass TargetObjectClass = _CswNbtResources.MetaData.getObjectClass( TargetId ); AllowAdd = ( null != TargetObjectClass && TargetObjectClass.CanAdd && TargetObjectClass.getNodeTypes().Any( nt => _CswNbtResources.Permit.canNodeType( CswEnumNbtNodeTypePermission.Create, nt ) ) ); if( false == AllowAdd ) { AllowView = ( null != TargetObjectClass && TargetObjectClass.getNodeTypes().Any( nt => _CswNbtResources.Permit.canNodeType( CswEnumNbtNodeTypePermission.View, nt ) ) ); } } else if( TargetType == CswEnumNbtViewRelatedIdType.PropertySetId ) { ParentObject["propertysetid"] = TargetId; CswNbtMetaDataPropertySet TargetPropSet = _CswNbtResources.MetaData.getPropertySet( TargetId ); AllowAdd = TargetPropSet.getObjectClasses().Any( oc => null != oc && oc.CanAdd && oc.getNodeTypes().Any( nt => _CswNbtResources.Permit.canNodeType( CswEnumNbtNodeTypePermission.Create, nt ) ) ); if( false == AllowAdd ) { AllowView = TargetPropSet.getObjectClasses().Any( oc => null != oc && oc.getNodeTypes().Any( nt => _CswNbtResources.Permit.canNodeType( CswEnumNbtNodeTypePermission.View, nt ) ) ); } } ParentObject["allowadd"] = AllowAdd; ParentObject["allowview"] = AllowView; if( null != View ) { ParentObject["viewid"] = View.ViewId.ToString(); if( AllowEdit && OptionCount == 0 ) { ParentObject["doGetNodes"] = true; } } } // if( ForEdit ) ParentObject[_NodeIDSubField.ToXmlNodeName( true ).ToLower()] = string.Empty; ParentObject[_NameSubField.ToXmlNodeName( true ).ToLower()] = CachedNodeName; ParentObject["relatednodeid"] = string.Empty; ParentObject["relatednodelink"] = string.Empty; if( null != RelatedNode ) { ParentObject[_NodeIDSubField.ToXmlNodeName( true ).ToLower()] = RelatedNode.NodeId.ToString(); ParentObject[_NameSubField.ToXmlNodeName( true ).ToLower()] = RelatedNode.NodeName; ParentObject["relatednodeid"] = RelatedNode.NodeId.ToString(); ParentObject["relatednodelink"] = RelatedNode.NodeLink; } } // ToJSON()
public IEnumerator PopulateCategory(JArray inJData, bool updateInBg = false) { yield return(new WaitForEndOfFrame()); if (ShowLoader) { UILoader.Instance.StartLoader(); } yield return(new WaitForSeconds(0.3f)); Debug.Log("populating: " + gameObject.name); if (inJData.Any()) { var rootCategories = inJData.TryAndFindList <Category>(cat => cat.HasValues); var rootItems = inJData.TryAndFindList <Item>(item => item["Data"] != null); var allCatData = rootCategories.SelectMany(category => category.CategoryData).ToList(); //trying to find all category types after the root level in hierarchy AllCategories = allCatData.TryAndFindList <Category>(i => i.HasValues); //adding the root categories into the _all categories list AllCategories = rootCategories.Concat(AllCategories).ToList(); //getting all the items AllItems = AllCategories.SelectMany(category => category.CategoryData).TryAndFindList <Item>(item => item["Data"] != null).Concat(rootItems).ToList(); yield return(new WaitForEndOfFrame()); AllItems = AllItems.OrderByDescending(item => item.UploadDate.FromUnixTime()).ToList(); AllFreeItems.AddRange(from item in AllItems.Where(item => item.IsFree.Equals(true)) orderby item.UploadDate.FromUnixTime() descending select item); AllPremiumItems.AddRange(from item in AllItems.Where(item => item.IsFree.Equals(false)) orderby item.UploadDate.FromUnixTime() descending select item); yield return(new WaitForEndOfFrame()); Debug.Log("Data is set"); InitFavoriteItems(); CallBackOnInitialize.Invoke(); //if we want to show the favorite as category and if there is favorite items available if (HasFavoriteCategory && FavoriteItems.Any()) { var favCat = new Category("Favorites", FavIconLink, null); //todo:later change the icon image from the mainJson var favToken = JToken.FromObject(favCat); inJData.AddFirst(favToken); } yield return(StartCoroutine(PopulateContents(inJData, false, createNewPanel: false, updateInBg: updateInBg))); } yield return(new WaitForEndOfFrame()); if (ShowLoader) { UILoader.Instance.StopLoader(true); } }
/// <summary> /// Create a new table in the current working database. /// </summary> /// <param name="name">The name of the table</param> /// <param name="prototype">The prtotype of the table</param> /// <returns>The current Database instance</returns> public Database CreateTable(string name, JObject prototype) { Benchmark.Mark("Database_(createTable)_start"); if (string.IsNullOrWhiteSpace(name)) { Benchmark.Mark("Database_(createTable)_end"); throw new Exception("Database Error: Can\'t create table, without a name."); } if (!IsWorkingDatabase()) { Benchmark.Mark("Database_(createTable)_end"); throw new Exception("Database Error: Trying to create a table without using a database."); } var path = Util.MakePath(_serverName, _databaseName, name + ".jdbt"); if (Util.Exists(path)) { Benchmark.Mark("Database_(createTable)_end"); throw new Exception("Database Error: Can't create the table \"" + name + "\" in the database \"" + _databaseName + "\". The table already exist."); } var fields = new JArray(); var properties = new JObject { ["last_insert_id"] = 0, ["last_valid_row_id"] = 0, ["last_link_id"] = 0, ["primary_keys"] = new JArray(), ["unique_keys"] = new JArray() }; var aiExist = false; foreach (var item in prototype) { var field = item.Key; var prop = (JObject)item.Value; var hasAi = prop["auto_increment"] != null; var hasPk = prop["primary_key"] != null; var hasUk = prop["unique_key"] != null; var hasTp = prop["type"] != null; if (aiExist && hasAi) { Benchmark.Mark("Database_(createTable)_end"); throw new Exception("Database Error: Can't use the \"auto_increment\" property on more than one field."); } if (!aiExist && hasAi) { aiExist = true; prototype[field]["unique_key"] = true; prototype[field]["not_null"] = true; prototype[field]["type"] = "int"; hasTp = true; hasUk = true; } if (hasPk) { prototype[field]["not_null"] = true; ((JArray)properties["primary_keys"]).Add(field); } if (hasUk) { prototype[field]["not_null"] = true; ((JArray)properties["unique_keys"]).Add(field); } if (hasTp) { var jToken = prop["type"]; if (jToken != null) { if (Regex.IsMatch(jToken.ToString(), "link\\(.+\\)")) { var link = Regex.Replace(jToken.ToString(), "link\\((.+)\\)", "$1"); var linkInfo = link.Split('.'); var linkTablePath = Util.MakePath(_serverName, _databaseName, linkInfo[0] + ".jdbt"); if (!Util.Exists(linkTablePath)) { throw new Exception("Database Error: Can't create the table \"" + name + "\". An error occur when linking the column \"" + field + "\" with the column \"" + linkInfo[1] + "\", the table \"" + linkInfo[0] + "\" doesn't exist in the database \"" + _databaseName + "\"."); } var linkTableData = GetTableData(linkTablePath); if (Array.IndexOf(linkTableData["prototype"].ToArray(), linkInfo[1]) == -1) { throw new Exception("Database Error: Can't create the table \"" + name + "\". An error occur when linking the column \"" + field + "\" with the column \"" + linkInfo[1] + "\", the column \"" + linkInfo[1] + "\" doesn't exist in the table \"" + linkInfo[0] + "\" ."); } if ((linkTableData["properties"]["primary_keys"] != null && Array.IndexOf(linkTableData["properties"]["primary_keys"].ToArray(), linkInfo[1]) == -1) || (linkTableData["properties"]["unique_keys"] != null && Array.IndexOf(linkTableData["properties"]["unique_keys"].ToArray(), linkInfo[1]) == -1)) { throw new Exception("Database Error: Can't create the table \"" + name + "\". An error occur when linking the column \"" + field + "\" with the column \"" + linkInfo[1] + "\", the column \"" + linkInfo[1] + "\" is not a PRIMARY KEY or an UNIQUE KEY in the table \"" + linkInfo[0] + "\" ."); } ((JObject)prototype[field]).Remove("default"); ((JObject)prototype[field]).Remove("max_length"); } else { switch (jToken.ToString()) { case "bool": case "boolean": if (prototype[field]["default"] != null) { bool res; if (bool.TryParse(prototype[field]["default"].ToString(), out res)) { prototype[field]["default"] = res; } else { prototype[field]["default"] = false; } } ((JObject)prototype[field]).Remove("max_length"); break; case "int": case "integer": case "number": if (prototype[field]["default"] != null) { int res; if (int.TryParse(prototype[field]["default"].ToString(), out res)) { prototype[field]["default"] = res; } else { prototype[field]["default"] = 0; } } ((JObject)prototype[field]).Remove("max_length"); break; case "float": case "decimal": if (prototype[field]["default"] != null) { float res; if (float.TryParse(prototype[field]["default"].ToString(), out res)) { prototype[field]["default"] = res; } else { prototype[field]["default"] = 0f; } } if (prototype[field]["max_length"] != null) { int res; if (int.TryParse(prototype[field]["max_length"].ToString(), out res)) { prototype[field]["max_length"] = res; } else { prototype[field]["max_length"] = 0; } } break; case "string": if (prototype[field]["default"] != null) { prototype[field]["default"] = prototype[field]["default"].ToString(); } if (prototype[field]["max_length"] != null) { int res; if (int.TryParse(prototype[field]["max_length"].ToString(), out res)) { prototype[field]["max_length"] = res; } else { prototype[field]["max_length"] = 0; } } break; default: throw new NotSupportedException("Database Error: The type \"" + jToken + "\" isn't supported by JSONDB."); } } } } else { prototype[field]["type"] = "string"; } fields.Add(field); } properties.Merge(prototype); fields.AddFirst("#rowid"); var data = new JObject { ["prototype"] = fields, ["properties"] = properties, ["data"] = new JObject() }; Util.WriteTextFile(path, data.ToString()); Benchmark.Mark("Database_(createTable)_end"); return(this); }
public async Task FillOperationsAsync( JObject head, SecureBytes securePublicKey, bool incrementCounter = true, CancellationToken cancellationToken = default) { using var publicKey = securePublicKey.ToUnsecuredBytes(); var xtz = (Atomex.Tezos)Currency; var rpc = new Rpc(xtz.RpcNodeUri); var managerKey = await rpc .GetManagerKey(From) .ConfigureAwait(false); Operations = new JArray(); var gas = GasLimit.ToString(CultureInfo.InvariantCulture); var storage = StorageLimit.ToString(CultureInfo.InvariantCulture); var counter = await TezosCounter.Instance .GetCounter(xtz, From, head, ignoreCache : !incrementCounter) .ConfigureAwait(false); // if (managerKey["key"] == null) if (managerKey.Value <string>() == null) { //var revealOpCounter = ; var revealOp = new JObject { ["kind"] = OperationType.Reveal, ["fee"] = "0", ["public_key"] = Base58Check.Encode(publicKey, Prefix.Edpk), ["source"] = From, ["storage_limit"] = "0", ["gas_limit"] = xtz.RevealGasLimit.ToString(), ["counter"] = counter.ToString() }; Operations.AddFirst(revealOp); counter++; } var transaction = new JObject { ["kind"] = OperationType.Transaction, ["source"] = From, ["fee"] = ((int)Fee).ToString(CultureInfo.InvariantCulture), ["counter"] = counter.ToString(), ["gas_limit"] = gas, ["storage_limit"] = storage, ["amount"] = Math.Round(Amount, 0).ToString(CultureInfo.InvariantCulture), ["destination"] = To }; Operations.Add(transaction); if (Params != null) { transaction["parameters"] = Params; } }