Пример #1
0
        public virtual Task Trigger(string eventName, EventArgs args)
        {
            InvokeEventSubscriptions(eventName, args);
            IJsonable jsonable = args as IJsonable;

            return(Trigger(eventName, jsonable == null ? string.Empty: jsonable.ToJson()));
        }
Пример #2
0
        public async Task <HttpRequestResponse> Delete(Resource resource, IJsonable body, params String[] urlSegments)
        {
            IHttpSetter hs = Setter(resource, urlSegments);

            hs.SetMethod(HttpMethod.Delete)
            .SetBody(FormatJson(body?.ToJson()));
            return(await RunRequestFromSetter(hs));
        }
Пример #3
0
            public void Add(string key, IJsonable v)
            {
                var n = v?.ToJSON()?.Impl;

                if (n != null)
                {
                    c_?.Add(key, n);
                }
            }
Пример #4
0
        }         // CreatePostRequest

        private RestRequest CreateRequest(string sResource = "", IJsonable oData = null)
        {
            Method nMethod   = oData == null ? Method.GET : Method.POST;
            object oJsonData = null;

            var oHeaders = new Dictionary <string, string>();

            oHeaders["Accept"] = "application/xml";

            var oRequest = new RestRequest(sResource, nMethod);

            if (null != oData)
            {
                oHeaders["Content-Type"] = "application/json";
                oHeaders["x-li-format"]  = "json";

                oRequest.RequestFormat = DataFormat.Json;

                oJsonData = oData.ToJson();
                oRequest.AddBody(oJsonData);
            }             // if

            var aryHeaders = new List <string>();

            foreach (KeyValuePair <string, string> h in oHeaders)
            {
                oRequest.AddHeader(h.Key, h.Value);
                aryHeaders.Add(string.Format("{0}: {1}", h.Key, h.Value));
            }             // for each

            Debug(@"
*******************************************
*
* Request details - begin
*
*******************************************

Method: {0}

Resourse: {1}

Headers: {2}

Data: {3}

*******************************************
*
* Request details - end
*
*******************************************
", nMethod.ToString(), sResource, string.Join("\n         ", aryHeaders), oJsonData == null ? "-- no data --" : JsonConvert.SerializeObject(oJsonData));

            return(oRequest);
        }         // CreateRequest
Пример #5
0
        }         // ExecutePostRequest

        private XmlDocument ExecuteRequest(string sResource = "", IJsonable oData = null)
        {
            sResource = (sResource ?? string.Empty).Trim();

            if (sResource == string.Empty)
            {
                return(ExecuteRequest(CreateRequest(sResource)));
            }

            return(ExecuteRequest(CreateRequest(sResource, oData)));
        }         // ExecuteRequest
Пример #6
0
 public void Add(IJsonable v)
 {
     if (v != null)
     {
         var n = v.ToJSON();
         if (n != null)
         {
             a_?.Add(n.Impl);
         }
     }
 }
Пример #7
0
        /// <summary>
        /// Send to remote host with user id
        /// </summary>
        /// <param name="query"> A copied <code>QueryObject</code> </param>
        private static async Task <ReceiveObject> SendWithUser(IJsonable query)
        {
            if (Storage.Test)
            {
                return(new ReceiveObject());
            }

            if (!Instance.SocketConnected)
            {
                await Instance.Reconnect();
            }
            query.UserId = Storage.UserId;
            var send = Encoding.UTF8.GetBytes(query.ToJson());

            byte[] receive;
            try
            {
                int sendLen = await Instance.Send(send);

                Debug.WriteLine("Send of \"{0}\" finish, total {1} bytes.", query.Type, sendLen);

                receive = new byte[1 << 14];
                int recvLen = await Instance.Receive(receive);

                Debug.WriteLine("Receive finish, total {0} bytes.", recvLen);

                Instance.Close();
            }
            catch (Exception)
            {
                await Instance.Reconnect();

                return(await SendWithUser(query));                // recurrence
            }
            var json       = Encoding.UTF8.GetString(receive);
            var receiveObj = ReceiveObject.FromJson(json);

            if (receiveObj == null)
            {
                await Instance.Reconnect();

                return(await SendWithUser(query));                // recurrence
            }
            return(receiveObj);
        }
Пример #8
0
        public string ToJson()
        {
            IJsonable args = EventArgs as IJsonable;

            if (args != null)
            {
                return(args.ToJson());
            }
            else
            {
                return(new
                {
                    Name = Name,
                    UserName = UserName,
                    Json = Json
                }.ToJson());
            }
        }
Пример #9
0
        /// <summary>
        /// Send to remote host with user id of admin
        /// </summary>
        /// <param name="query"> A copied <code>QueryObject</code> </param>
        private static async Task <string> SendAdminWithUser(IJsonable query)
        {
            if (Storage.Test)
            {
                return("");
            }

            if (!InstanceAdmin.SocketConnected)
            {
                await InstanceAdmin.Reconnect();
            }
            query.UserId = Storage.UserId;
            var send = Encoding.UTF8.GetBytes(query.ToJson());

            byte[] receive;
            try
            {
                int sendLen = await InstanceAdmin.Send(send);

                Debug.WriteLine("Send of \"{0}\" finish, total {1} bytes.", query.Type, sendLen);

                receive = new byte[1 << 14];
                int recvLen = await InstanceAdmin.Receive(receive);

                Debug.WriteLine("Receive finish, total {0} bytes.", recvLen);

                InstanceAdmin.Close();
            }
            catch (Exception)
            {
                await InstanceAdmin.Reconnect();

                return(await SendAdminWithUser(query));                // recurrence
            }
            var str = Encoding.UTF8.GetString(receive);

            if (str == null || str.Trim().Length == 0)
            {
                await InstanceAdmin.Reconnect();

                return(await SendAdminWithUser(query));                // recurrence
            }
            return(str);
        }
Пример #10
0
        /// <summary>
        /// Serializes using custom methods (JsonAdaptor, IJsonable, Type serializer).
        /// </summary>
        private void SerializeCustomData(object data)
        {
            Type       dataType       = data.GetType();
            JsonObject serializedData = null;

            // Serialize objects registered to adaptor.
            serializedData = JsonAdaptor.Serialize(dataType, data);
            if (serializedData != null)
            {
                SerializeObject(serializedData);
                return;
            }

            // Serialize jsonable objects
            IJsonable jsonableObject = data as IJsonable;

            if (jsonableObject != null)
            {
                serializedData = jsonableObject.ToJsonObject();
                if (serializedData != null)
                {
                    SerializeObject(jsonableObject.ToJsonObject());
                    return;
                }
            }

            // Use reflection.
            serializedData = JsonTypeSerializer.Serialize(dataType, data);
            if (serializedData != null)
            {
                SerializeObject(serializedData);
                return;
            }

            //This is when all the above methods fail.
            //Just return the stringified data.
            sb.Append('"');
            AppendEscapedString(data.ToString());
            sb.Append('"');
        }
Пример #11
0
        /// <summary>
        /// Deserializes the specified JsonData for a specific type.
        /// Highly recommended to use Json.Parse with Type parameter instead.
        /// </summary>
        public static object Deserialize(Type t, object instance, JsonObject data)
        {
            object adaptorResult = JsonAdaptor.Deserialize(t, data);

            if (adaptorResult != null)
            {
                return(adaptorResult);
            }

            //IJsonable method requires an instance to be present.
            if (instance == null)
            {
                instance = DynamicService.CreateObject(t);
                if (instance == null)
                {
                    RenLog.Log(LogLevel.Error, string.Format(
                                   "JsonDeserializer.Deserialize - Failed to instantiate a dynamic object of type ({0}). If possible, try adding a parameterless constructor.",
                                   t.Name
                                   ));
                    return(null);
                }
            }

            IJsonable jsonable = instance as IJsonable;

            if (jsonable != null)
            {
                jsonable.FromJsonObject(data);
                return(instance);
            }

            //No deserializer is available.
            RenLog.Log(LogLevel.Warning, string.Format(
                           "JsonDeserializer.Deserialize - There is no deserializer available for type ({0}). Returning null."
                           ));
            return(null);
        }
 /// <summary>
 /// Serialize the object into a Json type.
 /// </summary>
 /// <param name="item">The item.</param>
 /// <returns></returns>
 public static string ToSerialize(this IJsonable item) => JsonConvert.SerializeObject(item);
Пример #13
0
 IRequestBuilder IMessageBuilder <IRequestBuilder> .WithBody(IJsonable body)
 {
     RequestBody = body;
     return(this);
 }
Пример #14
0
 IResponseBuilder IMessageBuilder <IResponseBuilder> .WithBody(object body)
 {
     ResponseBody = new JsonBody(body);
     return(this);
 }
Пример #15
0
 public WebSocketMessage(MessageOptions options, IJsonable package = null)
 {
     this.package = package;
     this.options = options;
 }
 /// <summary>
 /// Deserialize a Json, convert and load the T item.
 /// </summary>
 /// <typeparam name="T">The item Type you want to load.</typeparam>
 /// <param name="item">The item.</param>
 /// <param name="itemToLoad">The item you want to load.</param>
 /// <param name="json">The json with the item you want to load.</param>
 public static void ToDeserializeAndLoad <T>(this IJsonable item, ref T itemToLoad, string json)
     where T : IJsonable =>
 itemToLoad = JsonConvert.DeserializeObject <T>(json);
 /// <summary>
 /// Deserialize the object into a T type.
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="item">The item.</param>
 /// <param name="json">The json you want to Deserialize into a T object.</param>
 /// <returns></returns>
 public static T ToDeserialize <T>(this IJsonable item, string json) where T : IJsonable =>
 JsonConvert.DeserializeObject <T>(json);
Пример #18
0
 public async Task <HttpRequestResponse> Put(Resource resource, IJsonable body, params String[] urlSegments)
 {
     return(await Post(resource, body, urlSegments));
 }