Esempio n. 1
0
        public object[] Decode(IJsonEncoder encoder)
        {
            if (IsDecoded || encoder == null)
            {
                return(DecodedArgs);
            }
            IsDecoded = true;
            if (string.IsNullOrEmpty(Payload))
            {
                return(DecodedArgs);
            }
            List <object> list = encoder.Decode(Payload);

            if (list != null && list.Count > 0)
            {
                if (SocketIOEvent == SocketIOEventTypes.Ack || SocketIOEvent == SocketIOEventTypes.BinaryAck)
                {
                    DecodedArgs = list.ToArray();
                }
                else
                {
                    list.RemoveAt(0);
                    DecodedArgs = list.ToArray();
                }
            }
            return(DecodedArgs);
        }
Esempio n. 2
0
        /// <summary>
        /// Adds class implementing IJsonEncoder
        /// </summary>
        /// <param name="propertyName"></param>
        /// <param name="val"></param>
        /// <returns></returns>
        public JsonEncoder Add(string propertyName, IJsonEncoder val)
        {
            if (!String.IsNullOrEmpty(propertyName))
            {
                if (val == null)
                {
                    return(this);
                }
                else
                {
                    AddProp(propertyName);
                }
            }
            else if (val == null)
            {
                AddNull();
                return(this);
            }


            sb.Append("{");
            lastchar = '{';
            val.BiserJsonEncode(this);
            sb.Append("}");
            lastchar = '}';

            return(this);
        }
 public WebClientTransport(
     IHttpClient httpClient,
     ICrypto crypto,
     ICache publicKeyCache,
     string baseUrl,
     EntityIdentifier issuer,
     IJwtService jwtService,
     IJweService jweService,
     int offsetTTL,
     int currentPublicKeyTTL,
     EntityKeyMap keyMap,
     IJsonEncoder jsonDecoder)
 {
     _httpClient          = httpClient;
     _crypto              = crypto;
     _publicKeyCache      = publicKeyCache;
     _baseUrl             = baseUrl;
     _issuer              = issuer;
     _jwtService          = jwtService;
     _jweService          = jweService;
     _offsetTtl           = offsetTTL;
     _currentPublicKeyTtl = currentPublicKeyTTL;
     _keyMap              = keyMap;
     _jsonDecoder         = jsonDecoder;
 }
Esempio n. 4
0
        public static IServerMessage Parse(IJsonEncoder encoder, string json)
        {
            if (string.IsNullOrEmpty(json))
            {
                HTTPManager.Logger.Error("MessageFactory", "Parse - called with empty or null string!");
                return(null);
            }
            if (json.Length == 2 && json == "{}")
            {
                return(new KeepAliveMessage());
            }
            IDictionary <string, object> dictionary = null;

            try
            {
                dictionary = encoder.DecodeMessage(json);
            }
            catch (Exception ex)
            {
                HTTPManager.Logger.Exception("MessageFactory", "Parse - encoder.DecodeMessage", ex);
                return(null);

                IL_006f :;
            }
            if (dictionary == null)
            {
                HTTPManager.Logger.Error("MessageFactory", "Parse - Json Decode failed for json string: \"" + json + "\"");
                return(null);
            }
            IServerMessage serverMessage = null;

            serverMessage = (IServerMessage)(dictionary.ContainsKey("C") ? new MultiMessage() : (dictionary.ContainsKey("E") ? ((object)new FailureMessage()) : ((object)new ResultMessage())));
            serverMessage.Parse(dictionary);
            return(serverMessage);
        }
Esempio n. 5
0
        /// <summary>
        /// Updates multiple items
        /// </summary>
        /// <typeparam name="T">The type of the item to be updated</typeparam>
        /// <param name="items">A dictionary of id => item where item can be encoded
        /// with encoder</param>
        /// <param name="encoder">The encoder that can handle T</param>
        /// <param name="parms">Additional params for the platform</param>
        /// <returns>A dictionary of id => item</returns>
        public async Task <Dictionary <string, T> > UpdateMany <T>(Dictionary <string, T> items,
                                                                   IJsonEncoder <T> encoder, Dictionary <string, string> parms = null)
        {
            if (!this.canUpdate)
            {
                throw new FlowThingsNotImplementedException();
            }

            JObject jo = new JObject();

            foreach (KeyValuePair <string, T> kvp in items)
            {
                jo.Add(new JProperty(kvp.Key, encoder.Encode(kvp.Value)));
            }

            JToken jt = await this.RequestAsync("MPUT", "", jo, parms);

            Dictionary <string, T> d = new Dictionary <string, T>();

            foreach (KeyValuePair <string, JToken> kvp in (JObject)jt["body"])
            {
                string id   = kvp.Key;
                T      item = encoder.Decode(kvp.Value);

                d.Add(id, item);
            }

            return(d);
        }
Esempio n. 6
0
        /// <summary>
        /// Find one or multiple drops that match filter
        /// </summary>
        /// <typeparam name="T">The type of the object to find</typeparam>
        /// <param name="filter">The filter string</param>
        /// <param name="encoder">An encode that handles T</param>
        /// <param name="parms">Additional parameters to be passed to the platform</param>
        /// <returns>A list of objects of type T that satisfy filter</returns>
        public async Task <List <T> > Find <T>(string filter, IJsonEncoder <T> encoder,
                                               Dictionary <string, string> parms = null)
        {
            if (!this.canRead)
            {
                throw new FlowThingsNotImplementedException();
            }

            if (parms == null)
            {
                parms = new Dictionary <string, string>();
            }
            parms.Add("filter", filter);

            string url = this.MakeURL("", parms);
            JToken jt  = await this.RequestAsync("GET", null, url);

            List <T> l = new List <T>();

            foreach (JToken t in (JArray)jt["body"])
            {
                l.Add(encoder.Decode(t));
            }

            return(l);
        }
Esempio n. 7
0
 public JsonEncoder(IJsonEncoder obj, JsonSettings settings = null)
     : this(settings)
 {
     if (obj != null)
     {
         obj.BiserJsonEncode(this);
     }
 }
Esempio n. 8
0
        /// <summary>
        /// When the json string is successfully parsed will return with an IServerMessage implementation.
        /// </summary>
        public static IServerMessage Parse(IJsonEncoder encoder, string json)
        {
            // Nothing to parse?
            if (string.IsNullOrEmpty(json))
            {
                HTTPManager.Logger.Error("MessageFactory", "Parse - called with empty or null string!");
                return(null);
            }

            // We don't have to do further decoding, if it's an empty json object, then it's a KeepAlive message from the server
            if (json.Length == 2 && json == "{}")
            {
                return(new KeepAliveMessage());
            }

            IDictionary <string, object> msg = null;

            try
            {
                // try to decode the json message with the encoder
                msg = encoder.DecodeMessage(json);
            }
            catch (Exception ex)
            {
                HTTPManager.Logger.Exception("MessageFactory", "Parse - encoder.DecodeMessage", ex);
                return(null);
            }

            if (msg == null)
            {
                HTTPManager.Logger.Error("MessageFactory", "Parse - Json Decode failed for json string: \"" + json + "\"");
                return(null);
            }

            // "C" is for message id
            IServerMessage result = null;

            if (!msg.ContainsKey("C"))
            {
                // If there are no ErrorMessage in the object, then it was a success
                if (!msg.ContainsKey("E"))
                {
                    result = new ResultMessage();
                }
                else
                {
                    result = new FailureMessage();
                }
            }
            else
            {
                result = new MultiMessage();
            }

            result.Parse(msg);

            return(result);
        }
Esempio n. 9
0
        public ListEncoder(Column column)
        {
            _getFunc = column.GetFunction;

            Debug.Assert(column.Children.Count == 1);

            var child = column.Children.First();

            _childEncoder = EncoderHelper.GetEncoder(child);
        }
Esempio n. 10
0
        /// <summary>
        /// Updates the item with the passed ID on the platform.
        /// </summary>
        /// <typeparam name="T">The type of the item to be updated</typeparam>
        /// <param name="id">The ID of the item to be updated</param>
        /// <param name="item">The contents of the item -- all fields produced by Encode(item) will
        /// be updated on the platform; to update only certain fields use Update with dynamics
        /// below</param>
        /// <param name="encoder">The encoder that can encode/decode T to a JToken</param>
        /// <param name="parms">Additional parameters passed to the platform</param>
        /// <returns>The updated item as an object of type T</returns>
        public async Task <T> Update <T>(string id, T item, IJsonEncoder <T> encoder,
                                         Dictionary <string, string> parms = null)
        {
            if (!this.canUpdate)
            {
                throw new FlowThingsNotImplementedException();
            }

            JToken jt = await this.RequestAsync("PUT", "/" + id, encoder.Encode(item), parms);

            return(encoder.Decode(jt["body"]));
        }
Esempio n. 11
0
        /// <summary>
        /// Reads an item from the server by ID and decodes it with the encoder.
        /// </summary>
        /// <typeparam name="T">The type of the item expected as return</typeparam>
        /// <param name="id">The id of the item</param>
        /// <param name="encoder">An encoder that can parse T from a JToken</param>
        /// <param name="parms">The parameters to pass to the platform</param>
        /// <returns>An item of type T from the platform</returns>
        public async Task <T> Read <T>(string id, IJsonEncoder <T> encoder,
                                       Dictionary <string, string> parms = null)
        {
            if (!this.canRead)
            {
                throw new FlowThingsNotImplementedException();
            }

            JToken jt = await this.RequestAsync("GET", "/" + id, null, parms);

            return(encoder.Decode(jt["body"]));
        }
Esempio n. 12
0
        public JsonEncoder Add(IJsonEncoder val)
        {
            if (val == null)
            {
                AddNull();
                return(this);
            }


            sb.Append("{");
            lastchar = '{';
            val.BiserJsonEncode(this);
            sb.Append("}");
            lastchar = '}';

            return(this);

            //return Add(null,val);
        }
Esempio n. 13
0
        public object[] Decode(IJsonEncoder encoder)
        {
            if (this.IsDecoded || encoder == null)
            {
                return(this.DecodedArgs);
            }
            this.IsDecoded = true;
            if (string.IsNullOrEmpty(this.Payload))
            {
                return(this.DecodedArgs);
            }
            List <object> list = encoder.Decode(this.Payload);

            if (list != null && list.Count > 0)
            {
                list.RemoveAt(0);
                this.DecodedArgs = list.ToArray();
            }
            return(this.DecodedArgs);
        }
Esempio n. 14
0
 public override void WriteJson(IJsonEncoder encoder, object value)
 {
     throw new NotSupportedException("JsonObjectFactory should only be used while decoding unless you overwrite WriteJson");
 }
 public override void WriteJson(IJsonEncoder encoder, Doodle value)
 {
     encoder.EncodeKeyValuePair("key-that-isnt-on-object", true);
     encoder.EncodeKeyValuePair("another_key", "with a value");
 }
 public override void WriteJson(IJsonEncoder encoder, Doodle value)
 {
     encoder.EncodeKeyValuePair("key-that-isnt-on-object", true);
     encoder.EncodeKeyValuePair("another_key", "with a value");
     encoder.EncodeKeyValuePair("string_array", new string[] { "first", "second" });
 }
Esempio n. 17
0
        /// <summary>
        /// Returns multiple items based on the IDs passed
        /// </summary>
        /// <typeparam name="T">The type of the item expected as return</typeparam>
        /// <param name="targets">An array of the form accepted by the platform</param>
        /// <param name="encoder">An encoder that can parse T from a JToken</param>
        /// <param name="parms">The parameters to pass to the platform</param>
        /// <returns>An item of type T from the platform</returns>
        public async Task <Dictionary <string, List <T> > > FindMany <T>(dynamic targets, IJsonEncoder <T> encoder)
        {
            if (!this.canRead)
            {
                throw new FlowThingsNotImplementedException();
            }

            string url = (this.secure ? "https:" : "http:") + "//" + this.host + "/v" + this.version + "/" +
                         this.creds.account + "/drop";

            JToken jt = await this.RequestAsync("MGET", JObject.FromObject(targets), url);

            Dictionary <string, List <T> > items = new Dictionary <string, List <T> >();

            foreach (KeyValuePair <string, JToken> kvp in (JObject)jt["body"])
            {
                string flowId   = kvp.Key;
                JArray dropList = (JArray)kvp.Value;

                List <T> l = new List <T>();
                foreach (JToken t in dropList)
                {
                    T obj = encoder.Decode(t);
                    l.Add(obj);
                }

                items.Add(flowId, l);
            }

            return(items);
        }
        /// <summary>
        /// When the json string is successfully parsed will return with an IServerMessage implementation.
        /// </summary>
        public static IServerMessage Parse(IJsonEncoder encoder, string json)
        {
            // Nothing to parse?
            if (string.IsNullOrEmpty(json))
            {
                HTTPManager.Logger.Error("MessageFactory", "Parse - called with empty or null string!");
                return null;
            }

            // We don't have to do further decoding, if it's an empty json object, then it's a KeepAlive message from the server
            if (json.Length == 2 && json == "{}")
                return new KeepAliveMessage();

            IDictionary<string, object> msg = null;

            try
            {
                // try to decode the json message with the encoder
                msg = encoder.DecodeMessage(json);
            }
            catch(Exception ex)
            {
                HTTPManager.Logger.Exception("MessageFactory", "Parse - encoder.DecodeMessage", ex);
                return null;
            }

            if (msg == null)
            {
                HTTPManager.Logger.Error("MessageFactory", "Parse - Json Decode failed for json string: \"" + json + "\"");
                return null;
            }

            // "C" is for message id
            IServerMessage result = null;
            if (!msg.ContainsKey("C"))
            {
                // If there are no ErrorMessage in the object, then it was a success
                if (!msg.ContainsKey("E"))
                    result = new ResultMessage();
                else
                    result = new FailureMessage();
            }
            else
              result = new MultiMessage();

            result.Parse(msg);

            return result;
        }
Esempio n. 19
0
 public abstract void WriteJson(IJsonEncoder encoder, object value);
Esempio n. 20
0
        private static async Task Execute(string sql, HttpContext context)
        {
            context.Response.Headers.Add("Content-Type", "application/json");

            var koraliumService = context.RequestServices.GetService <IKoraliumTransportService>();
            var logger          = context.RequestServices.GetService <ILogger <IKoraliumTransportService> >();


            QueryResult result = null;

            try
            {
                result = await koraliumService.Execute(sql, new Shared.SqlParameters(), context);
            }
            catch (SqlErrorException error)
            {
                logger.LogWarning(error.Message);
                await WriteError(context, 400, error.Message);

                return;
            }
            catch (AuthorizationFailedException authFailed)
            {
                logger.LogWarning(authFailed.Message, authFailed);
                await WriteError(context, 401, authFailed.Message);

                return;
            }
            catch (Exception e)
            {
                logger.LogError(e, "Unexpected exception thrown");
                await WriteError(context, 500, "Internal error");

                return;
            }

            var responseStream = new System.Text.Json.Utf8JsonWriter(context.Response.Body);

            IJsonEncoder[]    encoders = new IJsonEncoder[result.Columns.Count];
            JsonEncodedText[] names    = new JsonEncodedText[result.Columns.Count];

            for (int i = 0; i < encoders.Length; i++)
            {
                encoders[i] = EncoderHelper.GetEncoder(result.Columns[i]);
                names[i]    = JsonEncodedText.Encode(result.Columns[i].Name);
            }

            System.Diagnostics.Stopwatch encodingWatch = new System.Diagnostics.Stopwatch();
            encodingWatch.Start();
            responseStream.WriteStartObject();

            responseStream.WriteStartArray(_valuesText);
            foreach (var row in result.Result)
            {
                responseStream.WriteStartObject();
                for (int i = 0; i < encoders.Length; i++)
                {
                    responseStream.WritePropertyName(names[i]);
                    encoders[i].Encode(in responseStream, in row);
                }
                responseStream.WriteEndObject();
            }
            responseStream.WriteEndArray();
            responseStream.WriteEndObject();

            encodingWatch.Stop();

            await responseStream.FlushAsync();
        }