public Config_Module(Newtonsoft.Json.Linq.JObject json) { HttpListenEndPoint = json["HttpListenEndPoint"].AsIPEndPoint(); if (json.ContainsKey("HttpsListenEndPoint")) { HttpsListenEndPoint = json["HttpsListenEndPoint"].AsIPEndPoint(); } else { HttpsListenEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0); } if (json.ContainsKey("HttpsPFXFilePath")) { HttpsPFXFilePath = json["HttpsPFXFilePath"].AsString(); } else { HttpsPFXFilePath = ""; } if (json.ContainsKey("HttpsPFXFilePassword")) { HttpsPFXFilePassword = json["HttpsPFXFilePassword"].AsString(); } else { HttpsPFXFilePassword = ""; } }
public Module_Node(AllPet.Common.ILogger logger, Newtonsoft.Json.Linq.JObject configJson) : base(true) { this.guid = Helper_NEO.CalcHash256(Guid.NewGuid().ToByteArray()); this.logger = logger; this.config = new Config_Module(configJson); this.chainHash = Helper_NEO.CalcHash256(this.config.ChainInfo.ToInitScript()); //this.config = new Config_ChainInit(configJson); this.linkNodes = new System.Collections.Concurrent.ConcurrentDictionary <ulong, LinkObj>(); this.provedNodes = new System.Collections.Concurrent.ConcurrentDictionary <ulong, LinkObj>(); this.linkIDs = new System.Collections.Concurrent.ConcurrentDictionary <string, ulong>(); this.listCanlink = new Struct.ThreadSafeQueueWithKey <CanLinkObj>(); try { if (configJson.ContainsKey("Key_Nep2") && configJson.ContainsKey("Key_Password")) { var nep2 = configJson["Key_Nep2"].AsString(); var password = configJson["Key_Password"].AsString(); this.prikey = Helper_NEO.GetPrivateKeyFromNEP2(nep2, password); this.pubkey = Helper_NEO.GetPublicKey_FromPrivateKey(prikey); //区分记账人 var address = Helper_NEO.GetAddress_FromPublicKey(pubkey); //证明人的地址 //如果证明人的地址和初始记账人的地址相同即为记账人 if (this.config.ChainInfo.InitOwner.Contains(address)) { this.isProved = true; this.pLevel = 0;//记账节点 } } //return; blockChain = new BlockChain(); blockChain.InitChain(this.config.SimpleDbPath, this.config.ChainInfo); this.blockIndex = blockChain.GetBlockCount(); //记账节点才需要出块 if (this.isProved) { this.blockTimer = new System.Timers.Timer(); this.blockTimer.Interval = blockTime * 1000; //毫秒 this.blockTimer.Enabled = true; this.blockTimer.AutoReset = true; //一直执行true this.blockTimer.Elapsed += new System.Timers.ElapsedEventHandler(MakeBlock); this.blockTimer.Start(); } } catch (Exception err) { logger.Error("Error in Get Prikey:" + err.ToString()); throw new Exception("error in get prikey.", err); } this.txpool = new Node.TXPool(); ResetCanlinkList(); }
public void connect(string url, string[] protocols, JObject options, int id) { var webSocket = new MessageWebSocket(); webSocket.Control.MessageType = SocketMessageType.Utf8; if (protocols != null) { foreach (var protocol in protocols) { webSocket.Control.SupportedProtocols.Add(protocol); } } if (options != null && options.ContainsKey("origin")) { throw new NotImplementedException(/* TODO: (#253) */); } webSocket.MessageReceived += (sender, args) => { OnMessageReceived(id, sender, args); }; webSocket.Closed += (sender, args) => { OnClosed(id, sender, args); }; InitializeInBackground(id, url, webSocket); }
public static NEP6Account FromJson(Newtonsoft.Json.Linq.JObject json, NEP6Wallet wallet) { var strAdd = (json["address"] as Newtonsoft.Json.Linq.JValue).Value as string; var pubkeyhash = Helper_NEO.GetScriptHash_FromAddress(strAdd); string key = null; if (json.ContainsKey("key") && json["key"] != null) { key = json["key"].Value <string>(); } var acc = new NEP6Account(pubkeyhash, key); if (json.ContainsKey("contract") && json["contract"] != null) { acc.Contract = NEP6Contract.FromJson(json["contract"] as JObject); } return(acc); }
public void showAlert( JObject config, ICallback errorCallback, ICallback actionCallback) { var message = config.Value<string>("message") ?? ""; var title = config.Value<string>("title") ?? ""; bool containsTitle = config.ContainsKey("title"); bool containsPositive = config.ContainsKey(DialogModuleHelper.KeyButtonPositive); bool containsNegative = config.ContainsKey(DialogModuleHelper.KeyButtonNegative); if (containsPositive && containsNegative) { var result = MessageBox.Show(message, title, MessageBoxButton.OKCancel); if (result == MessageBoxResult.OK) { actionCallback.Invoke(DialogModuleHelper.ActionButtonClicked, DialogModuleHelper.KeyButtonPositiveValue); } else { actionCallback.Invoke(DialogModuleHelper.ActionButtonClicked, DialogModuleHelper.KeyButtonNegativeValue); } } else if (containsPositive) { var result = MessageBox.Show(message, title, MessageBoxButton.OK); if (result == MessageBoxResult.OK) { actionCallback.Invoke(DialogModuleHelper.ActionButtonClicked, DialogModuleHelper.KeyButtonPositiveValue); } } else if (containsTitle) { MessageBox.Show(message, title); } else { MessageBox.Show(message); } }
public void showAlert( JObject config, ICallback errorCallback, ICallback actionCallback) { var message = config.Value<string>("message") ?? ""; var messageDialog = new MessageDialog(message) { Title = config.Value<string>("title"), }; if (config.ContainsKey(DialogModuleHelper.KeyButtonPositive)) { messageDialog.Commands.Add(new UICommand { Label = config.Value<string>(DialogModuleHelper.KeyButtonPositive), Id = DialogModuleHelper.KeyButtonPositiveValue, Invoked = target => OnInvoked(target, actionCallback), }); } if (config.ContainsKey(DialogModuleHelper.KeyButtonNegative)) { messageDialog.Commands.Add(new UICommand { Label = config.Value<string>(DialogModuleHelper.KeyButtonNegative), Id = DialogModuleHelper.KeyButtonNegativeValue, Invoked = target => OnInvoked(target, actionCallback), }); } RunOnDispatcher(async () => { if (_isInForeground) { await messageDialog.ShowAsync().AsTask().ConfigureAwait(false); } else { _pendingDialog = messageDialog; } }); }
/// <summary> /// Expansion Algorithm /// http://json-ld.org/spec/latest/json-ld-api/#expansion-algorithm /// </summary> /// <param name="activeCtx"></param> /// <param name="activeProperty"></param> /// <param name="element"></param> /// <returns></returns> /// <exception cref="JsonLdError">JsonLdError</exception> /// <exception cref="JsonLD.Core.JsonLdError"></exception> public virtual JToken Expand(Context activeCtx, string activeProperty, JToken element ) { // 1) if (element.IsNull()) { return null; } // 3) if (element is JArray) { // 3.1) JArray result = new JArray(); // 3.2) foreach (JToken item in (JArray)element) { // 3.2.1) JToken v = Expand(activeCtx, activeProperty, item); // 3.2.2) if (("@list".Equals(activeProperty) || "@list".Equals(activeCtx.GetContainer(activeProperty ))) && (v is JArray || (v is JObject && ((IDictionary<string, JToken>)v).ContainsKey ("@list")))) { throw new JsonLdError(JsonLdError.Error.ListOfLists, "lists of lists are not permitted." ); } else { // 3.2.3) if (!v.IsNull()) { if (v is JArray) { JsonLD.Collections.AddAll(result, (JArray)v); } else { result.Add(v); } } } } // 3.3) return result; } else { // 4) if (element is JObject) { // access helper IDictionary<string, JToken> elem = (JObject)element; // 5) if (elem.ContainsKey("@context")) { activeCtx = activeCtx.Parse(elem["@context"]); } // 6) JObject result = new JObject(); // 7) JArray keys = new JArray(element.GetKeys()); keys.SortInPlace(); foreach (string key in keys) { JToken value = elem[key]; // 7.1) if (key.Equals("@context")) { continue; } // 7.2) string expandedProperty = activeCtx.ExpandIri(key, false, true, null, null); JToken expandedValue = null; // 7.3) if (expandedProperty == null || (!expandedProperty.Contains(":") && !JsonLdUtils.IsKeyword (expandedProperty))) { continue; } // 7.4) if (JsonLdUtils.IsKeyword(expandedProperty)) { // 7.4.1) if ("@reverse".Equals(activeProperty)) { throw new JsonLdError(JsonLdError.Error.InvalidReversePropertyMap, "a keyword cannot be used as a @reverse propery" ); } // 7.4.2) if (result.ContainsKey(expandedProperty)) { throw new JsonLdError(JsonLdError.Error.CollidingKeywords, expandedProperty + " already exists in result" ); } // 7.4.3) if ("@id".Equals(expandedProperty)) { if (!(value.Type == JTokenType.String)) { throw new JsonLdError(JsonLdError.Error.InvalidIdValue, "value of @id must be a string" ); } expandedValue = activeCtx.ExpandIri((string)value, true, false, null, null); } else { // 7.4.4) if ("@type".Equals(expandedProperty)) { if (value is JArray) { expandedValue = new JArray(); foreach (JToken v in (JArray)value) { if (v.Type != JTokenType.String) { throw new JsonLdError(JsonLdError.Error.InvalidTypeValue, "@type value must be a string or array of strings" ); } ((JArray)expandedValue).Add(activeCtx.ExpandIri((string)v, true, true, null , null)); } } else { if (value.Type == JTokenType.String) { expandedValue = activeCtx.ExpandIri((string)value, true, true, null, null); } else { // TODO: SPEC: no mention of empty map check if (value is JObject) { if (((JObject)value).Count != 0) { throw new JsonLdError(JsonLdError.Error.InvalidTypeValue, "@type value must be a an empty object for framing" ); } expandedValue = value; } else { throw new JsonLdError(JsonLdError.Error.InvalidTypeValue, "@type value must be a string or array of strings" ); } } } } else { // 7.4.5) if ("@graph".Equals(expandedProperty)) { expandedValue = Expand(activeCtx, "@graph", value); } else { // 7.4.6) if ("@value".Equals(expandedProperty)) { if (!value.IsNull() && (value is JObject || value is JArray)) { throw new JsonLdError(JsonLdError.Error.InvalidValueObjectValue, "value of " + expandedProperty + " must be a scalar or null"); } expandedValue = value; if (expandedValue.IsNull()) { result["@value"] = null; continue; } } else { // 7.4.7) if ("@language".Equals(expandedProperty)) { if (!(value.Type == JTokenType.String)) { throw new JsonLdError(JsonLdError.Error.InvalidLanguageTaggedString, "Value of " + expandedProperty + " must be a string"); } expandedValue = ((string)value).ToLower(); } else { // 7.4.8) if ("@index".Equals(expandedProperty)) { if (!(value.Type == JTokenType.String)) { throw new JsonLdError(JsonLdError.Error.InvalidIndexValue, "Value of " + expandedProperty + " must be a string"); } expandedValue = value; } else { // 7.4.9) if ("@list".Equals(expandedProperty)) { // 7.4.9.1) if (activeProperty == null || "@graph".Equals(activeProperty)) { continue; } // 7.4.9.2) expandedValue = Expand(activeCtx, activeProperty, value); // NOTE: step not in the spec yet if (!(expandedValue is JArray)) { JArray tmp = new JArray(); tmp.Add(expandedValue); expandedValue = tmp; } // 7.4.9.3) foreach (JToken o in (JArray)expandedValue) { if (o is JObject && ((JObject)o).ContainsKey("@list")) { throw new JsonLdError(JsonLdError.Error.ListOfLists, "A list may not contain another list" ); } } } else { // 7.4.10) if ("@set".Equals(expandedProperty)) { expandedValue = Expand(activeCtx, activeProperty, value); } else { // 7.4.11) if ("@reverse".Equals(expandedProperty)) { if (!(value is JObject)) { throw new JsonLdError(JsonLdError.Error.InvalidReverseValue, "@reverse value must be an object" ); } // 7.4.11.1) expandedValue = Expand(activeCtx, "@reverse", value); // NOTE: algorithm assumes the result is a map // 7.4.11.2) if (((IDictionary<string, JToken>)expandedValue).ContainsKey("@reverse")) { JObject reverse = (JObject)((JObject)expandedValue)["@reverse"]; foreach (string property in reverse.GetKeys()) { JToken item = reverse[property]; // 7.4.11.2.1) if (!result.ContainsKey(property)) { result[property] = new JArray(); } // 7.4.11.2.2) if (item is JArray) { JsonLD.Collections.AddAll(((JArray)result[property]), (JArray)item); } else { ((JArray)result[property]).Add(item); } } } // 7.4.11.3) if (((JObject)expandedValue).Count > (((JObject)expandedValue).ContainsKey("@reverse") ? 1 : 0)) { // 7.4.11.3.1) if (!result.ContainsKey("@reverse")) { result["@reverse"] = new JObject(); } // 7.4.11.3.2) JObject reverseMap = (JObject)result["@reverse"]; // 7.4.11.3.3) foreach (string property in expandedValue.GetKeys()) { if ("@reverse".Equals(property)) { continue; } // 7.4.11.3.3.1) JArray items = (JArray)((JObject)expandedValue)[property]; foreach (JToken item in items) { // 7.4.11.3.3.1.1) if (item is JObject && (((JObject)item).ContainsKey("@value") || ((JObject)item).ContainsKey("@list"))) { throw new JsonLdError(JsonLdError.Error.InvalidReversePropertyValue); } // 7.4.11.3.3.1.2) if (!reverseMap.ContainsKey(property)) { reverseMap[property] = new JArray(); } // 7.4.11.3.3.1.3) ((JArray)reverseMap[property]).Add(item); } } } // 7.4.11.4) continue; } else { // TODO: SPEC no mention of @explicit etc in spec if ("@explicit".Equals(expandedProperty) || "@default".Equals(expandedProperty) || "@embed".Equals(expandedProperty) || "@embedChildren".Equals(expandedProperty) || "@omitDefault".Equals(expandedProperty)) { expandedValue = Expand(activeCtx, expandedProperty, value); } } } } } } } } } } // 7.4.12) if (!expandedValue.IsNull()) { result[expandedProperty] = expandedValue; } // 7.4.13) continue; } else { // 7.5 if ("@language".Equals(activeCtx.GetContainer(key)) && value is JObject) { // 7.5.1) expandedValue = new JArray(); // 7.5.2) foreach (string language in value.GetKeys()) { JToken languageValue = ((IDictionary<string, JToken>)value)[language]; // 7.5.2.1) if (!(languageValue is JArray)) { JToken tmp = languageValue; languageValue = new JArray(); ((JArray)languageValue).Add(tmp); } // 7.5.2.2) foreach (JToken item in (JArray)languageValue) { // 7.5.2.2.1) if (!(item.Type == JTokenType.String)) { throw new JsonLdError(JsonLdError.Error.InvalidLanguageMapValue, "Expected " + item .ToString() + " to be a string"); } // 7.5.2.2.2) JObject tmp = new JObject(); tmp["@value"] = item; tmp["@language"] = language.ToLower(); ((JArray)expandedValue).Add(tmp); } } } else { // 7.6) if ("@index".Equals(activeCtx.GetContainer(key)) && value is JObject) { // 7.6.1) expandedValue = new JArray(); // 7.6.2) JArray indexKeys = new JArray(value.GetKeys()); indexKeys.SortInPlace(); foreach (string index in indexKeys) { JToken indexValue = ((JObject)value)[index]; // 7.6.2.1) if (!(indexValue is JArray)) { JToken tmp = indexValue; indexValue = new JArray(); ((JArray)indexValue).Add(tmp); } // 7.6.2.2) indexValue = Expand(activeCtx, key, indexValue); // 7.6.2.3) foreach (JObject item in (JArray)indexValue) { // 7.6.2.3.1) if (!item.ContainsKey("@index")) { item["@index"] = index; } // 7.6.2.3.2) ((JArray)expandedValue).Add(item); } } } else { // 7.7) expandedValue = Expand(activeCtx, key, value); } } } // 7.8) if (expandedValue.IsNull()) { continue; } // 7.9) if ("@list".Equals(activeCtx.GetContainer(key))) { if (!(expandedValue is JObject) || !((JObject)expandedValue).ContainsKey("@list")) { JToken tmp = expandedValue; if (!(tmp is JArray)) { tmp = new JArray(); ((JArray)tmp).Add(expandedValue); } expandedValue = new JObject(); ((JObject)expandedValue)["@list"] = tmp; } } // 7.10) if (activeCtx.IsReverseProperty(key)) { // 7.10.1) if (!result.ContainsKey("@reverse")) { result["@reverse"] = new JObject(); } // 7.10.2) JObject reverseMap = (JObject)result["@reverse"]; // 7.10.3) if (!(expandedValue is JArray)) { JToken tmp = expandedValue; expandedValue = new JArray(); ((JArray)expandedValue).Add(tmp); } // 7.10.4) foreach (JToken item in (JArray)expandedValue) { // 7.10.4.1) if (item is JObject && (((JObject)item).ContainsKey("@value") || ((JObject)item).ContainsKey("@list"))) { throw new JsonLdError(JsonLdError.Error.InvalidReversePropertyValue); } // 7.10.4.2) if (!reverseMap.ContainsKey(expandedProperty)) { reverseMap[expandedProperty] = new JArray(); } // 7.10.4.3) if (item is JArray) { JsonLD.Collections.AddAll(((JArray)reverseMap[expandedProperty]), (JArray)item); } else { ((JArray)reverseMap[expandedProperty]).Add(item); } } } else { // 7.11) // 7.11.1) if (!result.ContainsKey(expandedProperty)) { result[expandedProperty] = new JArray(); } // 7.11.2) if (expandedValue is JArray) { JsonLD.Collections.AddAll(((JArray)result[expandedProperty]), (JArray)expandedValue); } else { ((JArray)result[expandedProperty]).Add(expandedValue); } } } // 8) if (result.ContainsKey("@value")) { // 8.1) // TODO: is this method faster than just using containsKey for // each? ICollection<string> keySet = new HashSet<string>(result.GetKeys()); keySet.Remove("@value"); keySet.Remove("@index"); bool langremoved = keySet.Remove("@language"); bool typeremoved = keySet.Remove("@type"); if ((langremoved && typeremoved) || !keySet.IsEmpty()) { throw new JsonLdError(JsonLdError.Error.InvalidValueObject, "value object has unknown keys" ); } // 8.2) JToken rval = result["@value"]; if (rval.IsNull()) { // nothing else is possible with result if we set it to // null, so simply return it return null; } // 8.3) if (!(rval.Type == JTokenType.String) && result.ContainsKey("@language")) { throw new JsonLdError(JsonLdError.Error.InvalidLanguageTaggedValue, "when @language is used, @value must be a string" ); } else { // 8.4) if (result.ContainsKey("@type")) { // TODO: is this enough for "is an IRI" if (!(result["@type"].Type == JTokenType.String) || ((string)result["@type"]).StartsWith("_:") || !((string)result["@type"]).Contains(":")) { throw new JsonLdError(JsonLdError.Error.InvalidTypedValue, "value of @type must be an IRI" ); } } } } else { // 9) if (result.ContainsKey("@type")) { JToken rtype = result["@type"]; if (!(rtype is JArray)) { JArray tmp = new JArray(); tmp.Add(rtype); result["@type"] = tmp; } } else { // 10) if (result.ContainsKey("@set") || result.ContainsKey("@list")) { // 10.1) if (result.Count > (result.ContainsKey("@index") ? 2 : 1)) { throw new JsonLdError(JsonLdError.Error.InvalidSetOrListObject, "@set or @list may only contain @index" ); } // 10.2) if (result.ContainsKey("@set")) { // result becomes an array here, thus the remaining checks // will never be true from here on // so simply return the value rather than have to make // result an object and cast it with every // other use in the function. return result["@set"]; } } } } // 11) if (result.ContainsKey("@language") && result.Count == 1) { result = null; } // 12) if (activeProperty == null || "@graph".Equals(activeProperty)) { // 12.1) if (result != null && (result.Count == 0 || result.ContainsKey("@value") || result .ContainsKey("@list"))) { result = null; } else { // 12.2) if (result != null && result.ContainsKey("@id") && result.Count == 1) { result = null; } } } // 13) return result; } else { // 2) If element is a scalar // 2.1) if (activeProperty == null || "@graph".Equals(activeProperty)) { return null; } return activeCtx.ExpandValue(activeProperty, element); } } }
/// <summary>Converts RDF statements into JSON-LD.</summary> /// <remarks>Converts RDF statements into JSON-LD.</remarks> /// <param name="statements">the RDF statements.</param> /// <param name="options">the RDF conversion options.</param> /// <param name="callback">(err, output) called once the operation completes.</param> /// <exception cref="JSONLDProcessingError">JSONLDProcessingError</exception> /// <exception cref="JsonLD.Core.JsonLdError"></exception> public virtual JArray FromRDF(RDFDataset dataset) { // 1) JObject defaultGraph = new JObject(); // 2) JObject graphMap = new JObject(); graphMap["@default"] = defaultGraph; // 3/3.1) foreach (string name in dataset.GraphNames()) { IList<RDFDataset.Quad> graph = dataset.GetQuads(name); // 3.2+3.4) JObject nodeMap; if (!graphMap.ContainsKey(name)) { nodeMap = new JObject(); graphMap[name] = nodeMap; } else { nodeMap = (JObject)graphMap[name]; } // 3.3) if (!"@default".Equals(name) && !Obj.Contains(defaultGraph, name)) { defaultGraph[name] = new JsonLdApi.NodeMapNode(this, name); } // 3.5) foreach (RDFDataset.Quad triple in graph) { string subject = triple.GetSubject().GetValue(); string predicate = triple.GetPredicate().GetValue(); RDFDataset.Node @object = triple.GetObject(); // 3.5.1+3.5.2) JsonLdApi.NodeMapNode node; if (!nodeMap.ContainsKey(subject)) { node = new JsonLdApi.NodeMapNode(this, subject); nodeMap[subject] = node; } else { node = (NodeMapNode)nodeMap[subject]; } // 3.5.3) if ((@object.IsIRI() || @object.IsBlankNode()) && !nodeMap.ContainsKey(@object.GetValue ())) { nodeMap[@object.GetValue()] = new JsonLdApi.NodeMapNode(this, @object.GetValue()); } // 3.5.4) if (JSONLDConsts.RdfType.Equals(predicate) && (@object.IsIRI() || @object.IsBlankNode ()) && !opts.GetUseRdfType()) { JsonLdUtils.MergeValue(node, "@type", @object.GetValue()); continue; } // 3.5.5) JObject value = @object.ToObject(opts.GetUseNativeTypes()); // 3.5.6+7) JsonLdUtils.MergeValue(node, predicate, value); // 3.5.8) if (@object.IsBlankNode() || @object.IsIRI()) { // 3.5.8.1-3) ((NodeMapNode)nodeMap[@object.GetValue()]).usages.Add(new JsonLdApi.UsagesNode(this, node, predicate , value)); } } } // 4) foreach (string name_1 in graphMap.GetKeys()) { JObject graph = (JObject)graphMap[name_1]; // 4.1) if (!graph.ContainsKey(JSONLDConsts.RdfNil)) { continue; } // 4.2) JsonLdApi.NodeMapNode nil = (NodeMapNode)graph[JSONLDConsts.RdfNil]; // 4.3) foreach (JsonLdApi.UsagesNode usage in nil.usages) { // 4.3.1) JsonLdApi.NodeMapNode node = usage.node; string property = usage.property; JObject head = usage.value; // 4.3.2) JArray list = new JArray(); JArray listNodes = new JArray(); // 4.3.3) while (JSONLDConsts.RdfRest.Equals(property) && node.IsWellFormedListNode()) { // 4.3.3.1) list.Add(((JArray)node[JSONLDConsts.RdfFirst])[0]); // 4.3.3.2) listNodes.Add((string)node["@id"]); // 4.3.3.3) JsonLdApi.UsagesNode nodeUsage = node.usages[0]; // 4.3.3.4) node = nodeUsage.node; property = nodeUsage.property; head = nodeUsage.value; // 4.3.3.5) if (!JsonLdUtils.IsBlankNode(node)) { break; } } // 4.3.4) if (JSONLDConsts.RdfFirst.Equals(property)) { // 4.3.4.1) if (JSONLDConsts.RdfNil.Equals(node["@id"])) { continue; } // 4.3.4.3) string headId = (string)head["@id"]; // 4.3.4.4-5) head = (JObject)((JArray)graph[headId][JSONLDConsts.RdfRest ])[0]; // 4.3.4.6) list.RemoveAt(list.Count - 1); listNodes.RemoveAt(listNodes.Count - 1); } // 4.3.5) JsonLD.Collections.Remove(head, "@id"); // 4.3.6) JsonLD.Collections.Reverse(list); // 4.3.7) head["@list"] = list; // 4.3.8) foreach (string nodeId in listNodes) { JsonLD.Collections.Remove(graph, nodeId); } } } // 5) JArray result = new JArray(); // 6) JArray ids = new JArray(defaultGraph.GetKeys()); ids.SortInPlace(); foreach (string subject_1 in ids) { JsonLdApi.NodeMapNode node = (NodeMapNode)defaultGraph[subject_1]; // 6.1) if (graphMap.ContainsKey(subject_1)) { // 6.1.1) node["@graph"] = new JArray(); // 6.1.2) JArray keys = new JArray(graphMap[subject_1].GetKeys()); keys.SortInPlace(); foreach (string s in keys) { JsonLdApi.NodeMapNode n = (NodeMapNode)graphMap[subject_1][s]; if (n.Count == 1 && n.ContainsKey("@id")) { continue; } ((JArray)node["@graph"]).Add(n.Serialize()); } } // 6.2) if (node.Count == 1 && node.ContainsKey("@id")) { continue; } result.Add(node.Serialize()); } return result; }
/// <exception cref="JsonLD.Core.JsonLdError"></exception> private bool FilterNode(JsonLdApi.FramingContext state, JObject node, JObject frame) { JToken types = frame["@type"]; if (!types.IsNull()) { if (!(types is JArray)) { throw new JsonLdError(JsonLdError.Error.SyntaxError, "frame @type must be an array" ); } JToken nodeTypes = node["@type"]; if (nodeTypes.IsNull()) { nodeTypes = new JArray(); } else { if (!(nodeTypes is JArray)) { throw new JsonLdError(JsonLdError.Error.SyntaxError, "node @type must be an array" ); } } if (((JArray)types).Count == 1 && ((JArray)types)[0] is JObject && ((JObject)((JArray)types)[0]).Count == 0) { return !((JArray)nodeTypes).IsEmpty(); } else { foreach (JToken i in (JArray)nodeTypes) { foreach (JToken j in (JArray)types) { if (JsonLdUtils.DeepCompare(i, j)) { return true; } } } return false; } } else { foreach (string key in frame.GetKeys()) { if ("@id".Equals(key) || !JsonLdUtils.IsKeyword(key) && !(node.ContainsKey(key))) { return false; } } return true; } }
/// <summary>Frames subjects according to the given frame.</summary> /// <remarks>Frames subjects according to the given frame.</remarks> /// <param name="state">the current framing state.</param> /// <param name="subjects">the subjects to filter.</param> /// <param name="frame">the frame.</param> /// <param name="parent">the parent subject or top-level array.</param> /// <param name="property">the parent property, initialized to null.</param> /// <exception cref="JSONLDProcessingError">JSONLDProcessingError</exception> /// <exception cref="JsonLD.Core.JsonLdError"></exception> private void Frame(JsonLdApi.FramingContext state, JObject nodes , JObject frame, JToken parent, string property) { // filter out subjects that match the frame JObject matches = FilterNodes(state, nodes, frame); // get flags for current frame bool embedOn = GetFrameFlag(frame, "@embed", state.embed); bool explicitOn = GetFrameFlag(frame, "@explicit", state.@explicit); // add matches to output JArray ids = new JArray(matches.GetKeys()); ids.SortInPlace(); foreach (string id in ids) { if (property == null) { state.embeds = new Dictionary<string, JsonLdApi.EmbedNode>(); } // start output JObject output = new JObject(); output["@id"] = id; // prepare embed meta info JsonLdApi.EmbedNode embeddedNode = new JsonLdApi.EmbedNode(this); embeddedNode.parent = parent; embeddedNode.property = property; // if embed is on and there is an existing embed if (embedOn && state.embeds.ContainsKey(id)) { JsonLdApi.EmbedNode existing = state.embeds[id]; embedOn = false; if (existing.parent is JArray) { foreach (JToken p in (JArray)(existing.parent)) { if (JsonLdUtils.CompareValues(output, p)) { embedOn = true; break; } } } else { // existing embed's parent is an object if (((JObject)existing.parent).ContainsKey(existing.property)) { foreach (JToken v in (JArray)((JObject)existing.parent)[existing.property]) { if (v is JObject && ((JObject)v)["@id"].SafeCompare(id)) { embedOn = true; break; } } } } // existing embed has already been added, so allow an overwrite if (embedOn) { RemoveEmbed(state, id); } } // not embedding, add output without any other properties if (!embedOn) { AddFrameOutput(state, parent, property, output); } else { // add embed meta info state.embeds[id] = embeddedNode; // iterate over subject properties JObject element = (JObject)matches[id]; JArray props = new JArray(element.GetKeys()); props.SortInPlace(); foreach (string prop in props) { // copy keywords to output if (JsonLdUtils.IsKeyword(prop)) { output[prop] = JsonLdUtils.Clone(element[prop]); continue; } // if property isn't in the frame if (!frame.ContainsKey(prop)) { // if explicit is off, embed values if (!explicitOn) { EmbedValues(state, element, prop, output); } continue; } // add objects JArray value = (JArray)element[prop]; foreach (JToken item in value) { // recurse into list if ((item is JObject) && ((JObject)item).ContainsKey("@list")) { // add empty list JObject list = new JObject(); list["@list"] = new JArray(); AddFrameOutput(state, output, prop, list); // add list objects foreach (JToken listitem in (JArray)((JObject)item)["@list" ]) { // recurse into subject reference if (JsonLdUtils.IsNodeReference(listitem)) { JObject tmp = new JObject(); string itemid = (string)((IDictionary<string, JToken>)listitem)["@id"]; // TODO: nodes may need to be node_map, // which is global tmp[itemid] = this.nodeMap[itemid]; Frame(state, tmp, (JObject)((JArray)frame[prop])[0], list , "@list"); } else { // include other values automatcially (TODO: // may need JsonLdUtils.clone(n)) AddFrameOutput(state, list, "@list", listitem); } } } else { // recurse into subject reference if (JsonLdUtils.IsNodeReference(item)) { JObject tmp = new JObject(); string itemid = (string)((JObject)item)["@id"]; // TODO: nodes may need to be node_map, which is // global tmp[itemid] = this.nodeMap[itemid]; Frame(state, tmp, (JObject)((JArray)frame[prop])[0], output , prop); } else { // include other values automatically (TODO: may // need JsonLdUtils.clone(o)) AddFrameOutput(state, output, prop, item); } } } } // handle defaults props = new JArray(frame.GetKeys()); props.SortInPlace(); foreach (string prop_1 in props) { // skip keywords if (JsonLdUtils.IsKeyword(prop_1)) { continue; } JArray pf = (JArray)frame[prop_1]; JObject propertyFrame = pf.Count > 0 ? (JObject)pf[0] : null; if (propertyFrame == null) { propertyFrame = new JObject(); } bool omitDefaultOn = GetFrameFlag(propertyFrame, "@omitDefault", state.omitDefault ); if (!omitDefaultOn && !output.ContainsKey(prop_1)) { JToken def = "@null"; if (propertyFrame.ContainsKey("@default")) { def = JsonLdUtils.Clone(propertyFrame["@default"]); } if (!(def is JArray)) { JArray tmp = new JArray(); tmp.Add(def); def = tmp; } JObject tmp1 = new JObject(); tmp1["@preserve"] = def; JArray tmp2 = new JArray(); tmp2.Add(tmp1); output[prop_1] = tmp2; } } // add output to parent AddFrameOutput(state, parent, property, output); } } }
private void HandleTradeResult(TradeResult result, JObject order) { if (result.IsSuccessful) { if (result.Position != null) { var p = result.Position; JObject o = new JObject( new JProperty("cmd", "position_created_result"), new JProperty("_callbackId", order.ContainsKey("_callbackId") ? (string)order["_callbackId"] : null), new JProperty("payload", new JObject( new JProperty("label", p.Label), new JProperty("_id", p.Id), new JProperty("id", p.Label.Split('|')[0]), new JProperty("symbol", p.SymbolCode.ToLower()), new JProperty("openprice", p.EntryPrice), new JProperty("etime", p.EntryTime.ToUnixTime()), new JProperty("sl", p.StopLoss), new JProperty("tp", p.TakeProfit) ))); _publishMessage(o); } else if (result.PendingOrder != null) { JObject o = new JObject( new JProperty("cmd", "order_created_result"), new JProperty("_callbackId", order.ContainsKey("_callbackId") ? (string)order["_callbackId"] : null), new JProperty("payload", new JObject( new JProperty("label", result.PendingOrder.Label), new JProperty("_id", result.PendingOrder.Id), new JProperty("id", result.PendingOrder.Label.Split('|')[0]) ) )); _publishMessage(o); } } else { JObject o = new JObject( new JProperty("cmd", "order_create_failed_result"), new JProperty("_callbackId", order.ContainsKey("_callbackId") ? (string)order["_callbackId"] : null), new JProperty("payload", new JObject( new JProperty("label", (string)order["label"]) ) )); _publishMessage(o); } }
// //////////////////////////////////////////////////// OLD CODE BELOW /// <summary>Adds a value to a subject.</summary> /// <remarks> /// Adds a value to a subject. If the value is an array, all values in the /// array will be added. /// Note: If the value is a subject that already exists as a property of the /// given subject, this method makes no attempt to deeply merge properties. /// Instead, the value will not be added. /// </remarks> /// <param name="subject">the subject to add the value to.</param> /// <param name="property">the property that relates the value to the subject.</param> /// <param name="value">the value to add.</param> /// <?></?> /// <?></?> internal static void AddValue(JObject subject, string property , JToken value, bool propertyIsArray, bool allowDuplicate) { if (IsArray(value)) { if (((JArray)value).Count == 0 && propertyIsArray && !subject.ContainsKey(property )) { subject[property] = new JArray(); } foreach (JToken val in (JArray)value) { AddValue(subject, property, val, propertyIsArray, allowDuplicate); } } else { if (subject.ContainsKey(property)) { // check if subject already has the value if duplicates not allowed bool hasValue = !allowDuplicate && HasValue(subject, property, value); // make property an array if value not present or always an array if (!IsArray(subject[property]) && (!hasValue || propertyIsArray)) { JArray tmp = new JArray(); tmp.Add(subject[property]); subject[property] = tmp; } // add new value if (!hasValue) { ((JArray)subject[property]).Add(value); } } else { // add new value as a set or single value JToken tmp; if (propertyIsArray) { tmp = new JArray(); ((JArray)tmp).Add(value); } else { tmp = value; } subject[property] = tmp; } } }
private void HandleGetOrders(JObject msg) { var orders = this.PendingOrders.AsQueryable(); if (msg.ContainsKey("magic")) { orders = orders.Where(p => p.Label.Contains((string)msg["magic"])); } if (msg.ContainsKey("symbol")) { orders = orders.Where(p => p.SymbolCode == ((string)msg["symbol"]).ToUpper()); } var jarray = new JArray(); foreach (var p in orders) { jarray.Add( new JObject( new JProperty("_id", p.Id), new JProperty("id", p.Label.Split('|')[0]), new JProperty("symbol", p.SymbolCode.ToLower()), new JProperty("price", p.TargetPrice), new JProperty("lot", p.Quantity), new JProperty("tp", p.TakeProfitPips), new JProperty("sl", p.StopLossPips), new JProperty("label", p.Label), new JProperty("note", p.Comment), new JProperty("type", p.TradeType.ToString().ToLower() + "_" + p.OrderType.ToString().ToLower()) )); } JObject o = new JObject( new JProperty("cmd", "get_orders_result"), new JProperty("_callbackId", msg.ContainsKey("_callbackId") ? (string)msg["_callbackId"] : null), new JProperty("payload", jarray)); _publishMessage(o); }
private void HandleClosePosition(JObject message) { var id = (string)message["id"]; foreach (var p in this.Positions) { if (p.Id.ToString() == id) { alreadyHandledActions.Add(_getPositionString(p, "close_position"), null); TradeResult result = this.ClosePosition(p); if (result.IsSuccessful) { JObject o = new JObject( new JProperty("cmd", "position_closed_result"), new JProperty("_callbackId", message.ContainsKey("_callbackId") ? (string)message["_callbackId"] : null), new JProperty("payload", new JObject( new JProperty("label", p.Label), new JProperty("_id", p.Id), new JProperty("id", p.Label.Split('|')[0]), new JProperty("symbol", p.SymbolCode.ToLower()), new JProperty("pips", p.Pips), new JProperty("net_profit", p.NetProfit), new JProperty("gross_profit", p.GrossProfit), new JProperty("ctime", DateTime.UtcNow.ToUnixTime()) ) )); _publishMessage(o); } else { JObject o = new JObject( new JProperty("cmd", "position_closed_failed_result"), new JProperty("_callbackId", message.ContainsKey("_callbackId") ? (string)message["_callbackId"] : null), new JProperty("payload", new JObject( new JProperty("label", p.Label), new JProperty("_id", p.Id), new JProperty("id", p.Label.Split('|')[0]), new JProperty("symbol", p.SymbolCode.ToLower()) ))); _publishMessage(o); } } } }
private void HandleCloseOrder(JObject msg) { var id = (string)msg["id"]; foreach (var p in this.PendingOrders) { if (p.Id.ToString() == id) { var result = this.CancelPendingOrder(p); JObject o = new JObject( new JProperty("cmd", "order_closed_result"), new JProperty("_callbackId", msg.ContainsKey("_callbackId") ? (string)msg["_callbackId"] : null), new JProperty("payload", new JObject( new JProperty("cancelled", result.IsSuccessful), new JProperty("label", p.Label), new JProperty("_id", p.Id), new JProperty("id", p.Label.Split('|')[0]), new JProperty("symbol", p.SymbolCode.ToLower())) )); _publishMessage(o); } } }
private void HandleCloseAllOrders(JObject msg) { var jarray = new JArray(); var magic = (string)msg["magic"]; foreach (var p in this.PendingOrders) { // Only cancel these orders if (p.Label.Contains(magic)) { var result = this.CancelPendingOrder(p); jarray.Add( new JObject( new JProperty("cancelled", result.IsSuccessful), new JProperty("label", p.Label), new JProperty("_id", p.Id), new JProperty("id", p.Label.Split('|')[0]), new JProperty("symbol", p.SymbolCode.ToLower()) )); } } JObject o = new JObject( new JProperty("cmd", "cancel_orders_all_result"), new JProperty("_callbackId", msg.ContainsKey("_callbackId") ? (string)msg["_callbackId"] : null), new JProperty("payload", (JArray)jarray)); _publishMessage(o); }
private TradeResult CreateOrder(JObject order) { var symbol = this.MarketData.GetSymbol(((string)order["symbol"]).ToUpper()); TradeResult result = null; var expiration = Server.Time.AddMinutes(order_expiration); if (order.ContainsKey("exp")) { expiration = Server.Time.AddMinutes((int)order["exp"]); } try { switch ((string)order["type"]) { case "buy_limit": result = PlaceLimitOrder( TradeType.Buy, symbol, (long)order["vol"], (double)order["price"], (string)order["label"], (double)order["sl"], (double)order["tp"], expiration, order.ContainsKey("comment") ? (string)order["comment"] : "" ); break; case "sell_limit": result = PlaceLimitOrder( TradeType.Sell, symbol, (long)order["vol"], (double)order["price"], (string)order["label"], (double)order["sl"], (double)order["tp"], expiration, order.ContainsKey("comment") ? (string)order["comment"] : "" ); break; case "buy_stop": result = PlaceStopOrder( TradeType.Buy, symbol, (long)order["vol"], (double)order["price"], (string)order["label"], (double)order["sl"], (double)order["tp"], expiration, order.ContainsKey("comment") ? (string)order["comment"] : "" ); break; case "sell_stop": result = PlaceStopOrder( TradeType.Sell, symbol, (long)order["vol"], (double)order["price"], (string)order["label"], (double)order["sl"], (double)order["tp"], expiration, order.ContainsKey("comment") ? (string)order["comment"] : "" ); break; case "sell_market": result = ExecuteMarketOrder( TradeType.Sell, symbol, (long)order["vol"], (string)order["label"], (double)order["sl"], (double)order["tp"], order.ContainsKey("range") ? (double?)order["range"] : null, order.ContainsKey("comment") ? (string)order["comment"] : "" ); try { alreadyHandledActions.Add( _getPositionString("market_order", symbol.Code, (string)order["label"], (long)order["vol"], TradeType.Sell.ToString()), null); } catch (Exception ex) { this.Print("labels should have unique ids to prevent this: {0}", ex.Message); } break; case "buy_market": result = ExecuteMarketOrder( TradeType.Buy, symbol, (long)order["vol"], (string)order["label"], (double)order["sl"], (double)order["tp"], order.ContainsKey("range") ? (double?)order["range"] : null, order.ContainsKey("comment") ? (string)order["comment"] : "" ); try { alreadyHandledActions.Add( _getPositionString("market_order", symbol.Code, (string)order["label"], (long)order["vol"], TradeType.Sell.ToString()), null); } catch (Exception ex) { this.Print("labels should have unique ids to prevent this: {0}", ex.Message); } break; default: break; } } catch (Exception ex) { this.Print("Error creating order"); var exMessage = new JObject( new JProperty("cmd", "invalid_message_response"), new JProperty("_callbackId", order.ContainsKey("_callbackId") ? (string)order["_callbackId"] : null), new JProperty("payload", new JObject( new JProperty("error", ex.Message), new JProperty("source", ex.Source), new JProperty("advice", "check order parameters") ) )); _publishMessage(exMessage); return null; } return result; }
/// <summary> /// Compaction Algorithm /// http://json-ld.org/spec/latest/json-ld-api/#compaction-algorithm /// </summary> /// <param name="activeCtx"></param> /// <param name="activeProperty"></param> /// <param name="element"></param> /// <param name="compactArrays"></param> /// <returns></returns> /// <exception cref="JsonLD.Core.JsonLdError"></exception> public virtual JToken Compact(Context activeCtx, string activeProperty, JToken element , bool compactArrays) { // 2) if (element is JArray) { // 2.1) JArray result = new JArray(); // 2.2) foreach (JToken item in element) { // 2.2.1) JToken compactedItem = Compact(activeCtx, activeProperty, item, compactArrays); // 2.2.2) if (!compactedItem.IsNull()) { result.Add(compactedItem); } } // 2.3) if (compactArrays && result.Count == 1 && activeCtx.GetContainer(activeProperty) == null) { return result[0]; } // 2.4) return result; } // 3) if (element is JObject) { // access helper IDictionary<string, JToken> elem = (IDictionary<string, JToken>)element; // 4 if (elem.ContainsKey("@value") || elem.ContainsKey("@id")) { JToken compactedValue = activeCtx.CompactValue(activeProperty, (JObject)element); if (!(compactedValue is JObject || compactedValue is JArray)) { return compactedValue; } } // 5) bool insideReverse = ("@reverse".Equals(activeProperty)); // 6) JObject result = new JObject(); // 7) JArray keys = new JArray(element.GetKeys()); keys.SortInPlace(); foreach (string expandedProperty in keys) { JToken expandedValue = elem[expandedProperty]; // 7.1) if ("@id".Equals(expandedProperty) || "@type".Equals(expandedProperty)) { JToken compactedValue; // 7.1.1) if (expandedValue.Type == JTokenType.String) { compactedValue = activeCtx.CompactIri((string)expandedValue, "@type".Equals(expandedProperty )); } else { // 7.1.2) JArray types = new JArray(); // 7.1.2.2) foreach (string expandedType in (JArray)expandedValue) { types.Add(activeCtx.CompactIri(expandedType, true)); } // 7.1.2.3) if (types.Count == 1) { compactedValue = types[0]; } else { compactedValue = types; } } // 7.1.3) string alias = activeCtx.CompactIri(expandedProperty, true); // 7.1.4) result[alias] = compactedValue; continue; } // TODO: old add value code, see if it's still relevant? // addValue(rval, alias, compactedValue, // isArray(compactedValue) // && ((List<Object>) expandedValue).size() == 0); // 7.2) if ("@reverse".Equals(expandedProperty)) { // 7.2.1) JObject compactedValue = (JObject)Compact(activeCtx, "@reverse", expandedValue, compactArrays); // 7.2.2) List<string> properties = new List<string>(compactedValue.GetKeys()); foreach (string property in properties) { JToken value = compactedValue[property]; // 7.2.2.1) if (activeCtx.IsReverseProperty(property)) { // 7.2.2.1.1) if (("@set".Equals(activeCtx.GetContainer(property)) || !compactArrays) && !(value is JArray)) { JArray tmp = new JArray(); tmp.Add(value); result[property] = tmp; } // 7.2.2.1.2) if (!result.ContainsKey(property)) { result[property] = value; } else { // 7.2.2.1.3) if (!(result[property] is JArray)) { JArray tmp = new JArray(); tmp.Add(result[property]); result[property] = tmp; } if (value is JArray) { JsonLD.Collections.AddAll(((JArray)result[property]), (JArray)value ); } else { ((JArray)result[property]).Add(value); } } // 7.2.2.1.4) TODO: this doesn't seem safe (i.e. // modifying the map being used to drive the loop)! JsonLD.Collections.Remove(compactedValue, property); } } // 7.2.3) if (compactedValue.Count != 0) { // 7.2.3.1) string alias = activeCtx.CompactIri("@reverse", true); // 7.2.3.2) result[alias] = compactedValue; } // 7.2.4) continue; } // 7.3) if ("@index".Equals(expandedProperty) && "@index".Equals(activeCtx.GetContainer(activeProperty ))) { continue; } else { // 7.4) if ("@index".Equals(expandedProperty) || "@value".Equals(expandedProperty) || "@language" .Equals(expandedProperty)) { // 7.4.1) string alias = activeCtx.CompactIri(expandedProperty, true); // 7.4.2) result[alias] = expandedValue; continue; } } // NOTE: expanded value must be an array due to expansion // algorithm. // 7.5) if (((JArray)expandedValue).Count == 0) { // 7.5.1) string itemActiveProperty = activeCtx.CompactIri(expandedProperty, expandedValue, true, insideReverse); // 7.5.2) if (!result.ContainsKey(itemActiveProperty)) { result[itemActiveProperty] = new JArray(); } else { JToken value = result[itemActiveProperty]; if (!(value is JArray)) { JArray tmp = new JArray(); tmp.Add(value); result[itemActiveProperty] = tmp; } } } // 7.6) foreach (JToken expandedItem in (JArray)expandedValue) { // 7.6.1) string itemActiveProperty = activeCtx.CompactIri(expandedProperty, expandedItem, true, insideReverse); // 7.6.2) string container = activeCtx.GetContainer(itemActiveProperty); // get @list value if appropriate bool isList = (expandedItem is JObject && ((IDictionary<string, JToken>)expandedItem ).ContainsKey("@list")); JToken list = null; if (isList) { list = ((IDictionary<string, JToken>)expandedItem)["@list"]; } // 7.6.3) JToken compactedItem = Compact(activeCtx, itemActiveProperty, isList ? list : expandedItem , compactArrays); // 7.6.4) if (isList) { // 7.6.4.1) if (!(compactedItem is JArray)) { JArray tmp = new JArray(); tmp.Add(compactedItem); compactedItem = tmp; } // 7.6.4.2) if (!"@list".Equals(container)) { // 7.6.4.2.1) JObject wrapper = new JObject(); // TODO: SPEC: no mention of vocab = true wrapper[activeCtx.CompactIri("@list", true)] = compactedItem; compactedItem = wrapper; // 7.6.4.2.2) if (((IDictionary<string, JToken>)expandedItem).ContainsKey("@index")) { ((IDictionary<string, JToken>)compactedItem)[activeCtx.CompactIri("@index", true) ] = ((IDictionary<string, JToken>)expandedItem)["@index"]; } } else { // TODO: SPEC: no mention of vocab = // true // 7.6.4.3) if (result.ContainsKey(itemActiveProperty)) { throw new JsonLdError(JsonLdError.Error.CompactionToListOfLists, "There cannot be two list objects associated with an active property that has a container mapping" ); } } } // 7.6.5) if ("@language".Equals(container) || "@index".Equals(container)) { // 7.6.5.1) JObject mapObject; if (result.ContainsKey(itemActiveProperty)) { mapObject = (JObject)result[itemActiveProperty]; } else { mapObject = new JObject(); result[itemActiveProperty] = mapObject; } // 7.6.5.2) if ("@language".Equals(container) && (compactedItem is JObject && ((IDictionary <string, JToken>)compactedItem).ContainsKey("@value"))) { compactedItem = compactedItem["@value"]; } // 7.6.5.3) string mapKey = (string)expandedItem[container]; // 7.6.5.4) if (!mapObject.ContainsKey(mapKey)) { mapObject[mapKey] = compactedItem; } else { JArray tmp; if (!(mapObject[mapKey] is JArray)) { tmp = new JArray(); tmp.Add(mapObject[mapKey]); mapObject[mapKey] = tmp; } else { tmp = (JArray)mapObject[mapKey]; } tmp.Add(compactedItem); } } else { // 7.6.6) // 7.6.6.1) bool check = (!compactArrays || "@set".Equals(container) || "@list".Equals(container ) || "@list".Equals(expandedProperty) || "@graph".Equals(expandedProperty)) && ( !(compactedItem is JArray)); if (check) { JArray tmp = new JArray(); tmp.Add(compactedItem); compactedItem = tmp; } // 7.6.6.2) if (!result.ContainsKey(itemActiveProperty)) { result[itemActiveProperty] = compactedItem; } else { if (!(result[itemActiveProperty] is JArray)) { JArray tmp = new JArray(); tmp.Add(result[itemActiveProperty]); result[itemActiveProperty] = tmp; } if (compactedItem is JArray) { JsonLD.Collections.AddAll(((JArray)result[itemActiveProperty]), (JArray)compactedItem); } else { ((JArray)result[itemActiveProperty]).Add(compactedItem); } } } } } // 8) return result; } // 2) return element; }
private void HandleGetPositions(JObject msg) { var positions = this.Positions.ToArray(); if (msg.ContainsKey("label")) { if (msg.ContainsKey("symbol")) { positions = this.Positions.FindAll((string)msg["label"], this.MarketData.GetSymbol(((string)msg["symbol"]).ToUpper())); } else { positions = this.Positions.FindAll((string)msg["label"]); } } var jarray = new JArray(); foreach (var p in positions) { jarray.Add( new JObject( new JProperty("label", p.Label), new JProperty("_id", p.Id), new JProperty("id", p.Label.Split('|')[0]), new JProperty("symbol", p.SymbolCode.ToLower()), new JProperty("entry_price", p.EntryPrice), new JProperty("entry_time", p.EntryTime.ToUnixTime()), new JProperty("pips", p.Pips) )); } JObject o = new JObject( new JProperty("cmd", "getpositions_result"), new JProperty("_callbackId", msg.ContainsKey("_callbackId") ? (string)msg["_callbackId"] : null), new JProperty("payload", jarray)); _publishMessage(o); }
/// <exception cref="JsonLD.Core.JsonLdError"></exception> private static void Resolve(JToken input, JObject cycles) { Pattern regex = Pattern.Compile("(http|https)://(\\w+:{0,1}\\w*@)?(\\S+)(:[0-9]+)?(/|/([\\w#!:.?+=&%@!\\-/]))?" ); if (cycles.Count > MaxContextUrls) { throw new JsonLdError(JsonLdError.Error.UnknownError); } // for tracking the URLs to resolve JObject urls = new JObject(); // find all URLs in the given input if (!FindContextUrls(input, urls, false)) { // finished FindContextUrls(input, urls, true); } // queue all unresolved URLs JArray queue = new JArray(); foreach (string url in urls.GetKeys()) { if (urls[url].SafeCompare(false)) { // validate URL if (!regex.Matcher(url).Matches()) { throw new JsonLdError(JsonLdError.Error.UnknownError); } queue.Add(url); } } // resolve URLs in queue int count = queue.Count; foreach (string url_1 in queue) { // check for context URL cycle if (cycles.ContainsKey(url_1)) { throw new JsonLdError(JsonLdError.Error.UnknownError); } JObject _cycles = (JObject)Clone(cycles); _cycles[url_1] = true; try { JObject ctx = (JObject)new DocumentLoader().LoadDocument(url_1).Document; if (!ctx.ContainsKey("@context")) { ctx = new JObject(); ctx["@context"] = new JObject(); } Resolve(ctx, _cycles); urls[url_1] = ctx["@context"]; count -= 1; if (count == 0) { FindContextUrls(input, urls, true); } } //catch (JsonParseException) //{ // throw new JsonLdError(JsonLdError.Error.UnknownError); //} //catch (MalformedURLException) //{ // throw new JsonLdError(JsonLdError.Error.UnknownError); //} catch (IOException) { throw new JsonLdError(JsonLdError.Error.UnknownError); } } }
private static bool HasProperty(JObject subject, string property ) { bool rval = false; if (subject.ContainsKey(property)) { JToken value = subject[property]; rval = (!(value is JArray) || ((JArray)value).Count > 0); } return rval; }
private void HandleGetTime(JObject message) { JObject o = new JObject( new JProperty("cmd", "get_time_result"), new JProperty("_callbackId", message.ContainsKey("_callbackId") ? (string)message["_callbackId"] : null), new JProperty("payload", new JObject( new JProperty("time", this.Server.Time.ToUnixTime()) ))); _publishMessage(o); }
/// <summary>Finds all @context URLs in the given JSON-LD input.</summary> /// <remarks>Finds all @context URLs in the given JSON-LD input.</remarks> /// <param name="input">the JSON-LD input.</param> /// <param name="urls">a map of URLs (url => false/@contexts).</param> /// <param name="replace">true to replace the URLs in the given input with the</param> /// <contexts>from the urls map, false not to.</contexts> /// <returns>true if new URLs to resolve were found, false if not.</returns> private static bool FindContextUrls(JToken input, JObject urls , bool replace) { int count = urls.Count; if (input is JArray) { foreach (JToken i in (JArray)input) { FindContextUrls(i, urls, replace); } return count < urls.Count; } else { if (input is JObject) { foreach (string key in input.GetKeys()) { if (!"@context".Equals(key)) { FindContextUrls(((JObject)input)[key], urls, replace); continue; } // get @context JToken ctx = ((JObject)input)[key]; // array @context if (ctx is JArray) { int length = ((JArray)ctx).Count; for (int i = 0; i < length; i++) { JToken _ctx = ((JArray)ctx)[i]; if (_ctx.Type == JTokenType.String) { // replace w/@context if requested if (replace) { _ctx = urls[(string)_ctx]; if (_ctx is JArray) { // add flattened context ((JArray)ctx).RemoveAt(i); JsonLD.Collections.AddAllObj(((JArray)ctx), (ICollection)_ctx); i += ((JArray)_ctx).Count; length += ((JArray)_ctx).Count; } else { ((JArray)ctx)[i] = _ctx; } } else { // @context URL found if (!urls.ContainsKey((string)_ctx)) { urls[(string)_ctx] = false; } } } } } else { // string @context if (ctx.Type == JTokenType.String) { // replace w/@context if requested if (replace) { ((JObject)input)[key] = urls[(string)ctx]; } else { // @context URL found if (!urls.ContainsKey((string)ctx)) { urls[(string)ctx] = false; } } } } } return (count < urls.Count); } } return false; }
private void HandleModifyPosition(JObject message) { var id = (string)message["id"]; foreach (var p in this.Positions) { if (p.Id.ToString() == id) { var tp = message.ContainsKey("tp") ? (double?)message["tp"] : null; var sl = message.ContainsKey("sl") ? (double?)message["sl"] : null; if (p.TakeProfit == tp && p.StopLoss == sl) { JObject o = new JObject( new JProperty("cmd", "modify_position_failed_result"), new JProperty("_callbackId", message.ContainsKey("_callbackId") ? (string)message["_callbackId"] : null), new JProperty("payload", new JObject( new JProperty("error", "SL and TP are the same"), new JProperty("_id", p.Id), new JProperty("id", p.Label.Split('|')[0]), new JProperty("symbol", p.SymbolCode.ToLower()), new JProperty("sl", p.StopLoss), new JProperty("tp", p.TakeProfit) ) )); _publishMessage(o); return; } TradeResult result = ModifyPosition(p, sl, tp); if (result.IsSuccessful) { JObject o = new JObject( new JProperty("cmd", "modify_position_result"), new JProperty("_callbackId", message.ContainsKey("_callbackId") ? (string)message["_callbackId"] : null), new JProperty("payload", new JObject( new JProperty("label", p.Label), new JProperty("_id", p.Id), new JProperty("id", p.Label.Split('|')[0]), new JProperty("symbol", p.SymbolCode.ToLower()), new JProperty("sl", result.Position.StopLoss), new JProperty("tp", result.Position.TakeProfit) ) )); _publishMessage(o); } else { JObject o = new JObject( new JProperty("cmd", "modify_position_failed_result"), new JProperty("_callbackId", message.ContainsKey("_callbackId") ? (string)message["_callbackId"] : null), new JProperty("payload", new JObject( new JProperty("label", p.Label), new JProperty("_id", p.Id), new JProperty("id", p.Label.Split('|')[0]), new JProperty("symbol", p.SymbolCode.ToLower()) ) )); _publishMessage(o); } } } }