Serialize() public static method

public static Serialize ( object jsonAble ) : JSONObject,
jsonAble object
return JSONObject,
 //...
 private static void SavePrefs()
 {
     data.filterFavorites = filterFavorites;
     if (currentKeyType != null)
     {
         data.allFavorites[currentKeyType.Name] = favorites;
     }
     EditorPrefs.SetString(PREFERENCES_KEY, JSONSerializer.Serialize(typeof(SerializationData), data));
 }
Exemplo n.º 2
0
        public void DeserializeJSONDummiesTest()
        {
            DummyClassA a = new DummyClassA
            {
                Id = 1
            };

            DummyClassB b = new DummyClassB
            {
                Id = 2
            };

            DummyClassC c = new DummyClassC
            {
                Id = 3
            };

            a.Other = b;
            b.Other = c;
            c.Other = a;



            b.Text = "HELLO";
            c.Time = new DateTime(2020, 1, 1);



            DummyClassA a2;
            DummyClassB b2;

            JSONSerializer serializer = new JSONSerializer();

            serializer.Serialize("test.json", a);
            a2 = serializer.Deserialize <DummyClassA>("test.json");

            Assert.AreEqual(1, a2.Id);
            Assert.AreEqual(2, a2.Other.Id);
            Assert.AreEqual(3, a2.Other.Other.Id);
            Assert.AreEqual(1, a2.Other.Other.Other.Id);

            Assert.AreEqual(typeof(DummyClassA), a2.GetType());
            Assert.AreEqual(typeof(DummyClassB), a2.Other.GetType());
            Assert.AreEqual(typeof(DummyClassC), a2.Other.Other.GetType());
            Assert.AreEqual(typeof(DummyClassA), a2.Other.Other.Other.GetType());

            Assert.AreEqual("HELLO", a2.Other.Text);
            Assert.AreEqual(2020, a2.Other.Other.Time.Year);
            Assert.AreEqual(1, a2.Other.Other.Time.Month);
            Assert.AreEqual(1, a2.Other.Other.Time.Day);

            b2 = a2.Other;
            Assert.ReferenceEquals(a2.Other, b2);
            b2.Id = 10f;
            Assert.AreEqual(10f, a2.Other.Id);
        }
Exemplo n.º 3
0
        ///<summary>Will try save to file found in DefaultEditorResources</summary>
        static void TrySaveSyncFile(List <Type> types)
        {
            var absPath = SyncFilePath();

            if (!string.IsNullOrEmpty(absPath))
            {
                var json = JSONSerializer.Serialize(typeof(List <Type>), types, null, true);
                System.IO.File.WriteAllText(absPath, json);
            }
        }
 public void Test_ConditionalNST_Serialization()
 {
     using (var stream = new MemoryStream())
     {
         var formater = new JSONSerializer();
         formater.Serialize(stream, _testCase);
         stream.Seek(0, SeekOrigin.Begin);
         Console.WriteLine(new StreamReader(stream).ReadToEnd());
     }
 }
 public void Test_ConditionalNST_Serialization()
 {
     using (var stream = new MemoryStream())
     {
         var formater = new JSONSerializer();
         formater.Serialize(stream, _testCase);
         stream.Seek(0, SeekOrigin.Begin);
         Console.WriteLine(new StreamReader(stream).ReadToEnd());
     }
 }
Exemplo n.º 6
0
                internal Dictionary <string, string> Save()
                {
                    Dictionary <string, string> _json = new Dictionary <string, string>();

                    foreach (string _key in _containerKeys)
                    {
                        _json[_key] = JSONSerializer.Serialize(_charaAccData[_key].GetType(), _charaAccData[_key]);
                    }
                    return(_json);
                }
Exemplo n.º 7
0
        public void Deserialization_AllCorrect_Object()
        {
            Person p = new Person()
            {
                Name = "John", Age = 26
            };
            string serialized = JSONSerializer.Serialize <Person>(p);

            Assert.IsTrue(p == JSONSerializer.Deserialize <Person>(serialized));
        }
Exemplo n.º 8
0
        public static object JsonClone(this object _self)
        {
            if (_self == null)
            {
                return(null);
            }
            string _json = JSONSerializer.Serialize(_self.GetType(), _self);

            return(JSONSerializer.Deserialize(_self.GetType(), _json));
        }
Exemplo n.º 9
0
        void DoSavePreset()
        {
            var path = EditorUtility.SaveFilePanelInProject("Save Preset", "", "actionList", "");

            if (!string.IsNullOrEmpty(path))
            {
                System.IO.File.WriteAllText(path, JSONSerializer.Serialize(typeof(ActionList), this, true));   //true for pretyJson
                AssetDatabase.Refresh();
            }
        }
Exemplo n.º 10
0
 public void OnBeforeSerialize()
 {
     VariableJSON = new DerivedComponentJsonDataRow();
     if (Variable != null)
     {
         VariableJSON.SerializedObjects     = new List <UnityEngine.Object>();
         VariableJSON.AssemblyQualifiedName = Variable.GetType().AssemblyQualifiedName;
         VariableJSON.JsonText = JSONSerializer.Serialize(Variable.GetType(), Variable, false, VariableJSON.SerializedObjects);
     }
 }
Exemplo n.º 11
0
        internal static void PrintRendererInfo(ChaControl chaCtrl, GameObject go, bool chara = false)
        {
            if (go == null)
            {
                return;
            }

            MaterialRouterController pluginCtrl = GetController(chaCtrl);

            Renderer[]       rends = go.GetComponentsInChildren <Renderer>(true);
            List <RouteRule> rules = new List <RouteRule>();
            int skipped            = 0;

            foreach (Renderer rend in rends)
            {
                foreach (Material mat in rend.materials)
                {
                    string ObjPath = GetGameObjectPath(rend.transform).Replace(chaCtrl.gameObject.name + "/", "");
                    string MatName = mat.NameFormatted();

                    RouteRule rule = new RouteRule
                    {
                        GameObjectPath = ObjPath,
                        Action         = Action.Clone,
                        OldName        = MatName,
                        NewName        = MatName + "_cloned"
                    };

                    RouteRule exist = null;
                    if (chara)
                    {
                        exist = pluginCtrl.BodyTrigger.Where(x => x.GameObjectPath == ObjPath && x.NewName == MatName).FirstOrDefault();
                    }
                    else
                    {
                        exist = pluginCtrl.CurOutfitTrigger.Where(x => x.GameObjectPath == ObjPath && x.NewName == MatName).FirstOrDefault();
                    }

                    if (exist != null)
                    {
                        if (CfgSkipCloned.Value)
                        {
                            skipped++;
                            continue;
                        }
                        else
                        {
                            rule.Action = exist.Action;
                        }
                    }
                    rules.Add(rule);
                }
            }
            Logger.LogWarning($"cloned/renamed skipped: {skipped}\n" + JSONSerializer.Serialize(rules.GetType(), rules, true));
        }
Exemplo n.º 12
0
        void ISerializationCallbackReceiver.OnBeforeSerialize()
        {
#if UNITY_EDITOR
            if (JSONSerializer.applicationPlaying)
            {
                return;
            }
            _objectReferences = new List <UnityEngine.Object>();
            _serializedList   = JSONSerializer.Serialize(typeof(ActionList), _actionList, false, _objectReferences);
#endif
        }
Exemplo n.º 13
0
        /// <summary>
        /// Met à jour la configuration de l'application
        /// </summary>
        /// <param name="config"></param>
        public void ApplyNewConfiguration(ApplicationConfiguration config)
        {
            AppClient.EndPoint.Address = IPAddress.Parse(config.Hostname);
            AppClient.EndPoint.Port    = config.Port;
            Target = config.Target;
            AppServer.EndPoint.Port = config.Port;

            string json = JSONSerializer.Serialize <ApplicationConfiguration>(config);

            FileManager.Write(AppDomain.CurrentDomain.BaseDirectory + FILE_NAME, json, FileManager.WriteOptions.CreateDirectory);
        }
Exemplo n.º 14
0
        public void Serialize_AllCorrect_SerializeValue()
        {
            string actual = JSONSerializer.Serialize <Person>(new Person()
            {
                Name = "John",
                Age  = 26
            });

            string excepted = "{\"age\":26,\"name\":\"John\"}";

            Assert.AreEqual(excepted, actual);
        }
        public void BasicSerializationTest()
        {
            var asset = new SerializationTestClass();            //Name.Parse("A(B,C(D,E,f(H)))"); //new SerializationTestClass();

            using (var stream = new MemoryStream())
            {
                var formater = new JSONSerializer();
                formater.Serialize(stream, asset);
                stream.Seek(0, SeekOrigin.Begin);
                Trace.Write(new StreamReader(stream).ReadToEnd());
            }
        }
Exemplo n.º 16
0
    public override JSONObject toJSONObject()
    {
        JSONObject[] array = new JSONObject[l.Count];
        int          i     = 0;

        foreach (var o in this.l.getSerializable())
        {
            array[i] = JSONSerializer.Serialize(o);
            i++;
        }
        return(new JSONObject(array));
    }
Exemplo n.º 17
0
    private void Json(Type type)
    {
        object obj = Activator.CreateInstance(type);

        Log($"JsonPack:     {obj.GetType().FullName}\nValue:    {obj.ToString()}\nHashCode: {obj.GetHashCode()}\n");
        string text = JSONSerializer.Serialize(obj, type);

        Log($"JsonPacked:     {obj.GetType().FullName}\nValue:    {obj.ToString()}\nHashCode: {obj.GetHashCode()}\nStream: {text}");
        Coop_Model_Base coop_Model_Base = JSONSerializer.Deserialize <Coop_Model_Base>(text, type);

        Log($"JsonUnpack:     {coop_Model_Base.GetType().FullName}\nValue:    {coop_Model_Base.ToString()}\nHashCode: {coop_Model_Base.GetHashCode()}\n");
    }
Exemplo n.º 18
0
 public string Serialize(bool pretyJson, List <UnityEngine.Object> objectReferences)
 {
     if (objectReferences == null)
     {
         objectReferences = this.m_objectReference = new List <UnityEngine.Object>();
     }
     else
     {
         objectReferences.Clear();
     }
     return(JSONSerializer.Serialize(typeof(DataSerializerUIManagare), new DataSerializerUIManagare(this), pretyJson, objectReferences));
 }
Exemplo n.º 19
0
        public void IAT_Serialization_Test()
        {
            var asset = Build_IAT_Asset();

            using (var stream = new MemoryStream())
            {
                var formater = new JSONSerializer();
                formater.Serialize(stream, asset);
                stream.Seek(0, SeekOrigin.Begin);
                Console.WriteLine(new StreamReader(stream).ReadToEnd());
            }
        }
Exemplo n.º 20
0
        public void SerializeDeserialize()
        {
            var Temp = new JSONSerializer(Canister.Builder.Bootstrapper);

            Assert.Equal(new Temp()
            {
                A = 10
            }.A, ((Temp)Temp.Deserialize(typeof(Temp), Temp.Serialize(typeof(Temp), new Temp()
            {
                A = 10
            }))).A);
        }
        public void EmotionalAppraisal_Serialization_Test()
        {
            var asset = BuildTestAsset();

            using (var stream = new MemoryStream())
            {
                var formater = new JSONSerializer();
                formater.Serialize(stream, asset);
                stream.Seek(0, SeekOrigin.Begin);
                Console.WriteLine(new StreamReader(stream).ReadToEnd());
            }
        }
Exemplo n.º 22
0
        public async Task InitializeResourceBarrierAsync(string clientsPath,
                                                         string resourcesPath,
                                                         string epochPath)
        {
            this.clientsPath   = clientsPath;
            this.resourcesPath = resourcesPath;
            this.epochPath     = epochPath;

            await EnsurePathAsync(this.clientsPath);
            await EnsurePathAsync(this.epochPath);
            await EnsurePathAsync(this.resourcesPath, Encoding.UTF8.GetBytes(JSONSerializer <ResourcesZnodeData> .Serialize(new ResourcesZnodeData())));
        }
Exemplo n.º 23
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            WebApiConfiguration config = new WebApiConfiguration()
            {
                ClientId          = " ",
                ClientSecret      = " ",
                CRMApiEndpointUri = "https://orgname.api.crm8.dynamics.com/api/data/v9.1/",
                RedirectUrl       = "https://orgname.crm8.dynamics.com/",
                TenantId          = ""
            };

            CrmApiInstance.CreateCrmApiInstance(config);

            ContactRequest contactRequest = new ContactRequest()
            {
                firstname = "IwthRemove",
                lastname  = "lastnameKumar" + DateTime.Now.ToLongTimeString()
            };

            var contactId = CrmApiInstance.Instance.CreateRecord("contacts", JSONSerializer <ContactRequest> .Serialize(contactRequest)).Result;

            contactRequest = new ContactRequest()
            {
                emailaddress1 = $"sanjayemail{DateTime.Now.ToLongTimeString()}@email.com"
            };

            string json = JsonConvert.SerializeObject(contactRequest, Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings
            {
                NullValueHandling    = NullValueHandling.Ignore,
                DefaultValueHandling = DefaultValueHandling.Ignore,
            });

            bool   updated      = CrmApiInstance.Instance.UpdateRecord("contacts", contactId, json).Result;
            string queryOptions = "?$select=fullname,firstname,lastname,emailaddress1,createdon,description&$orderby=createdon desc";
            string result       = CrmApiInstance.Instance.RetrieveRecord("contacts", contactId, queryOptions).Result;
            string result2      = CrmApiInstance.Instance.RetrieveRecords("contacts", queryOptions, maxpagesize: 5000).Result;

            EntityCollection collection = JsonConvert.DeserializeObject <EntityCollection>(result2);
            IList <string>   results    = new List <string>
            {
                result2
            };

            while (!string.IsNullOrEmpty(collection?.OdataNextLink))
            {
                var result3 = CrmApiInstance.Instance.RetrieveRecordsByNextLink(collection.OdataNextLink, maxpagesize: 10).Result;
                results.Add(result3);
                collection = JsonConvert.DeserializeObject <EntityCollection>(result3);
            }
        }
        /// <summary>
        /// 获取全部图书馆的使用情况
        /// </summary>
        /// <returns></returns>
        public string GetLibraryNowState()
        {
            AJM_HandleResult result = new AJM_HandleResult();

            try
            {
                //获取阅览室座位使用状态
                List <ReadingRoomInfo> readingRoomInfos = SeatManageDateService.GetReadingRoomInfo(null);
                Dictionary <string, ReadingRoomSeatUsedState> roomSeatUsedStates = SeatManageDateService.GetRoomSeatUsedStateV5(readingRoomInfos.Select(u => u.No).ToList());
                List <AJM_LibraryStatus> ajmLibraryStates = new List <AJM_LibraryStatus>();

                foreach (ReadingRoomInfo room in readingRoomInfos)
                {
                    if (ajmLibraryStates.Count < 1 || !ajmLibraryStates.Exists(u => u.LibraryNo == room.Libaray.No))
                    {
                        AJM_LibraryStatus status = new AJM_LibraryStatus();
                        status.LibraryNo   = room.Libaray.No;
                        status.LibraryName = room.Libaray.Name;
                        ajmLibraryStates.Add(status);
                    }
                    AJM_ReadingRoomState ajmReadingRoomState = new AJM_ReadingRoomState();
                    ajmReadingRoomState.RoomName           = room.Name;
                    ajmReadingRoomState.RoomNo             = room.No;
                    ajmReadingRoomState.OpenCloseState     = room.Setting.ReadingRoomOpenState(DateTime.Now).ToString();
                    ajmReadingRoomState.IsCanBookNowSeat   = room.Setting.SeatBespeak.Used && room.Setting.SeatBespeak.NowDayBespeak;
                    ajmReadingRoomState.SeatAmount_All     = room.SeatList.Seats.Count(u => u.Value.IsSuspended != true);
                    ajmReadingRoomState.SeatAmount_Used    = roomSeatUsedStates[room.No].SeatAmountUsed;
                    ajmReadingRoomState.SeatAmount_Bespeak = roomSeatUsedStates[room.No].SeatBookingCount;
                    ajmReadingRoomState.SeatAmount_Last    = ajmReadingRoomState.SeatAmount_All - ajmReadingRoomState.SeatAmount_Used - ajmReadingRoomState.SeatAmount_Bespeak + roomSeatUsedStates[room.No].SeatTemUseCount;
                    ajmLibraryStates.Find(u => u.LibraryNo == room.Libaray.No).RoomStatus.Add(ajmReadingRoomState);
                }
                foreach (AJM_LibraryStatus status in ajmLibraryStates)
                {
                    status.AllSeats       = status.RoomStatus.Sum(u => u.SeatAmount_All);
                    status.AllBooked      = status.RoomStatus.Sum(u => u.SeatAmount_Bespeak);
                    status.AllUsed        = status.RoomStatus.Sum(u => u.SeatAmount_Used);
                    status.UsedPercentage = (int)((double)status.AllUsed / (double)status.AllSeats * 100);
                }


                result.Result = true;
                result.Msg    = JSONSerializer.Serialize(ajmLibraryStates);
                return(JSONSerializer.Serialize(result));
            }
            catch (Exception ex)
            {
                WriteLog.Write(string.Format("获取阅览室使用状态遇到异常:{0}", ex.Message));
                result.Result = false;
                result.Msg    = "获取阅览室使用状态执行遇到异常!";
                return(JSONSerializer.Serialize(result));
            }
        }
Exemplo n.º 25
0
        public override bool Handle(HttpListenerContext context)
        {
            context.Response.ContentType = "application/json";
            var list      = new JSONArray();
            var endpoints = from s in BackEndServer.Services
                            let j = s as JSONService
                                    where j != null
                                    from e in j.Endpoints
                                    select e;

            foreach (var endpoint in endpoints)
            {
                var json = new JSONObject {
                    ["path"] = endpoint.Key.Substring("/kappa".Length),
                };
                var args = new JSONArray();

                if (endpoint.Value.Method != null)
                {
                    foreach (var att in endpoint.Value.Method.DeclaringType.GetCustomAttributes <DocsAttribute>())
                    {
                        json[att.Field] = JSONSerializer.Serialize(att.Value);
                    }
                    foreach (var att in endpoint.Value.Method.GetCustomAttributes <DocsAttribute>())
                    {
                        json[att.Field] = JSONSerializer.Serialize(att.Value);
                    }
                    var parms = endpoint.Value.Method.GetParameters();
                    foreach (var parm in parms)
                    {
                        args.Add(new JSONObject {
                            ["name"]      = parm.Name,
                            ["type"]      = parm.ParameterType.Name,
                            ["stringify"] = ShouldStringify(parm.ParameterType)
                        });
                    }
                }

                json["args"] = args;
                list.Add(json);
            }
            var docs = new JSONObject {
                ["name"]      = "Kappa Backend",
                ["host"]      = BackEndServer.HostName,
                ["base"]      = "/kappa",
                ["endpoints"] = list,
            };
            var bytes = docs.ToJSON().GetBytes();

            context.Response.OutputStream.Write(bytes, 0, bytes.Length);
            return(true);
        }
        private HttpResponseMessage regVentaToApi(int venta, int suc, int cliente)
        {
            try
            {
                using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
                {
                    SqlCommand cmd1 = new SqlCommand("SELECT idProducto AS ean, Cantidad AS cantidad FROM DETALLEPEDIDO WHERE idPedido=@id");
                    cmd1.Parameters.AddWithValue("@id", venta);
                    cmd1.Connection = conn;
                    conn.Open();
                    using (var reader = cmd1.ExecuteReader())
                    {
                        var    r = serial.Serialize(reader);
                        string JSONresult;
                        JSONresult = JsonConvert.SerializeObject(r);
                        string  jsonText         = JSONresult.Replace("\"", "");
                        string  sqlFormattedDate = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.fff");
                        JObject ven = new JObject();
                        ven.Add("idCliente", cliente);
                        ven.Add("idEmpleado", 0);
                        ven.Add("idSucursal", suc);
                        ven.Add("productos", JArray.Parse(JSONresult));
                        ven.Add("tipoPago", 1);
                        ven.Add("fecha", sqlFormattedDate);
                        ven.Add("starts", "00:00:00");
                        ven.Add("ends", "00:00:00");
                        ven.Add("idcaja", 0);
                        var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://gsprest.azurewebsites.net/api/Ventas/");
                        httpWebRequest.ContentType = "application/json";
                        httpWebRequest.Method      = "POST";

                        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                        {
                            streamWriter.Write(ven);
                            streamWriter.Flush();
                            streamWriter.Close();
                        }

                        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                        {
                            var result = streamReader.ReadToEnd();
                            return(Request.CreateResponse(HttpStatusCode.OK, result.Replace("\"", "")));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex));
            }
        }
Exemplo n.º 27
0
        /// <summary>
        /// 获取进出记录
        /// </summary>
        /// <param name="studentNo">用户学号</param>
        /// <param name="pageIndex">页编码</param>
        /// <param name="pageSize">每页数目</param>
        /// <returns></returns>
        public string GetEnterOutLog(string studentNo, int pageIndex, int pageSize)
        {
            AJM_HandleResult result = new AJM_HandleResult();

            try
            {
                if (string.IsNullOrEmpty(studentNo))
                {
                    result.Result = false;
                    result.Msg    = "学号不能为空!";
                    return(JSONSerializer.Serialize(result));
                }
                if (pageIndex < 0 || pageSize < 0)
                {
                    result.Result = false;
                    result.Msg    = "页数和每页显示数目必须大于等于0";
                    return(JSONSerializer.Serialize(result));
                }
                List <EnterOutLogInfo> enterOutLogInfos = SeatManageDateService.GetEnterOutLogsByPage(studentNo, pageIndex, pageSize);
                List <AJM_EnterOutLog> ajmEnterOutLogs  = new List <AJM_EnterOutLog>();
                for (int i = 0; i < enterOutLogInfos.Count; i++)
                {
                    AJM_EnterOutLog ajmEnterOutLog = new AJM_EnterOutLog();
                    ajmEnterOutLog = new AJM_EnterOutLog();
                    ajmEnterOutLog.EnterOutState = enterOutLogInfos[i].EnterOutState.ToString();
                    ajmEnterOutLog.EnterOutTime  = enterOutLogInfos[i].EnterOutTime.ToString("yyyy-MM-d HH:mm:ss");
                    ajmEnterOutLog.Id            = enterOutLogInfos[i].EnterOutLogID;
                    ajmEnterOutLog.Remark        = enterOutLogInfos[i].Remark;
                    ajmEnterOutLog.RoomName      = enterOutLogInfos[i].ReadingRoomName;
                    ajmEnterOutLog.RoomNo        = enterOutLogInfos[i].ReadingRoomNo;
                    ajmEnterOutLog.SeatNo        = enterOutLogInfos[i].SeatNo;
                    ajmEnterOutLog.SeatShortNo   = enterOutLogInfos[i].ShortSeatNo;
                    ajmEnterOutLogs.Add(ajmEnterOutLog);
                }
                if (ajmEnterOutLogs.Count < 1)
                {
                    result.Result = false;
                    result.Msg    = "暂时没有进出记录!";
                    return(JSONSerializer.Serialize(result));
                }
                result.Result = true;
                result.Msg    = JSONSerializer.Serialize(ajmEnterOutLogs);
                return(JSONSerializer.Serialize(result));
            }
            catch (Exception ex)
            {
                WriteLog.Write(string.Format("获取进出记录遇到异常:{0}", ex.Message));
                result.Result = false;
                result.Msg    = "获取进出记录执行异常!";
                return(JSONSerializer.Serialize(result));
            }
        }
Exemplo n.º 28
0
 public void DoSavePreset()
 {
                 #if !UNITY_WEBPLAYER
     var path = EditorUtility.SaveFilePanelInProject("Save Preset", "", "conditionList", "");
     if (!string.IsNullOrEmpty(path))
     {
         System.IO.File.WriteAllText(path, JSONSerializer.Serialize(typeof(ConditionList), this, true));   //true for pretyJson
         AssetDatabase.Refresh();
     }
     #else
     Debug.LogWarning("Preset saving is not possible with WebPlayer as active platform");
     #endif
 }
Exemplo n.º 29
0
    public IEnumerator RequestCoroutine <T1, T2>(string path, T1 postData, Action <T2> call_back, string get_param = "", string token = "") where T2 : BaseModel, new()
    {
        WWWForm form = new WWWForm();
        string  data = JSONSerializer.Serialize <T1>(postData);

        AccountManager.Account account = MonoBehaviourSingleton <AccountManager> .I.account;
        string key          = (!string.IsNullOrEmpty(account.userHash)) ? account.userHash : "ELqdT/y.pM#8+J##x7|3/tLb7jZhmqJ,";
        string encrypt_data = Cipher.EncryptRJ128(key, "yCNBH$$rCNGvC+#f", data);
        string data_to_send = string.IsNullOrEmpty(encrypt_data) ? string.Empty : encrypt_data;

        form.AddField("data", data_to_send);
        yield return((object)this.StartCoroutine(this.RequestFormCoroutine <T2>(path, form, call_back, get_param, token)));
    }
Exemplo n.º 30
0
                internal Dictionary <string, string> Save()
                {
                    if (!_installed)
                    {
                        return(null);
                    }
                    Dictionary <string, string> _json = new Dictionary <string, string>();

                    _json["TriggerPropertyList"] = JSONSerializer.Serialize(_charaAccData["TriggerPropertyList"].GetType(), _charaAccData["TriggerPropertyList"]);
                    _json["TriggerGroupList"]    = JSONSerializer.Serialize(_charaAccData["TriggerGroupList"].GetType(), _charaAccData["TriggerGroupList"]);

                    return(_json);
                }
Exemplo n.º 31
0
        public void JSONSerializer_SelfReferencing()
        {
            var serializer = new JSONSerializer();

            try
            {
                throw new Exception("asdf");
            }
            catch (Exception ex)
            {
                serializer.Serialize(ex);
            }
        }
Exemplo n.º 32
0
        private static void SerializeResponseMessage(IServerResponseChannelSinkStack sinkStack
                                                     , IMessage responseMsg
                                                     , ref ITransportHeaders responseHeaders
                                                     , ref Stream responseStream)
        {
            if (sinkStack == null)
            {
                throw new ArgumentNullException("sinkStack");
            }
            if (responseMsg == null)
            {
                throw new ArgumentNullException("responseMsg");
            }

            var methodReturnMessage = responseMsg as IMethodReturnMessage;

            if (methodReturnMessage == null)
            {
                throw new ArgumentException(string.Format(
                                                "Invalid response message type: '{0}'.", responseMsg.GetType()), "responseMsg");
            }

            if (responseHeaders == null)
            {
                responseHeaders = new TransportHeaders();
            }

            bool shouldRewindStream = false;

            if (responseStream == null)
            {
                responseStream = sinkStack.GetResponseStream(responseMsg, responseHeaders);

                if (responseStream == null)
                {
                    responseStream     = new MemoryStream();
                    shouldRewindStream = true;
                }
            }

            var m = new JsonMessage();

            m.Return    = methodReturnMessage.ReturnValue;
            m.Exception = methodReturnMessage.Exception;
            JSONSerializer.Serialize(responseStream, m, typeof(JsonMessage));

            if (shouldRewindStream)
            {
                responseStream.Position = 0;
            }
        }
Exemplo n.º 33
0
 private void SendMessage()
 {
     ISerializeJSON jsonSerializer = new JSONSerializer();
     applicationGlobalState.IsEditingCode = false;
     var messagesToSend = messageTextBox.GetTextEditorMessages();
     chatRoomControlService.SendMessages(messagesToSend, roomId);
     foreach(var message in messagesToSend)
         chatRoomControlService.AddReceivedMessage(GetChatUIElements(), messageScroll, jsonSerializer.Serialize(new ChatMessageModel { body = jsonSerializer.Serialize(message), chatMessageBody = message, user_id = userProvider.GetUser().id.ToString(), username = userProvider.GetUser().first_name, date = DateTime.Now.ToString()}));
     messageTextBox.Clear();
     messageTextBox.Resources.Clear();
 }
Exemplo n.º 34
0
		static void Main(string[] args)
		{
			if (args.Length < 2)
			{
				Console.WriteLine("USAGE: NBTExtractor <region dir> <output json>");
				Console.WriteLine("USAGE: NBTExtractor <backup tar.gz> <world json> <nether json> <end json>");
				return;
			}
			//args = new string[] { @"A:\Games\MC18DJ\saves\Civcraft\region", @"A:\Games\MC18DJ\saves\Civcraft\tiles.json" };
			

			if (File.GetAttributes(args[0]).HasFlag(FileAttributes.Directory))
			{
				var allTileEntities = new List<object>();
				var files = Directory.GetFiles(args[0], "*.mca");
				for (int i = 0; i < files.Length; i++)
				{
					var file = files[i];
					Console.WriteLine("[{0,4}/{1,4}] {2}", i + 1, files.Length, file);
					using (var fs = new FileStream(file, FileMode.Open))
					{
						foreach (var lst1 in ExtractRegion(fs))
						{
							var lst = (List<KeyValuePair<string, object>>)lst1.Where(x => x.Key == "Level").Single().Value;
							
							foreach (var tileEntities in lst.Where(x => x.Key == "TileEntities" && x.Value is List<KeyValuePair<string, object>>).Select(x => (List<KeyValuePair<string, object>>)x.Value))
							{
								allTileEntities.AddRange(tileEntities.Select(x => x.Value));
							}
							foreach (var tileEntities in lst.Where(x => x.Key == "TileEntities" && x.Value is object[]).Select(x => (object[])x.Value))
							{
								allTileEntities.AddRange(tileEntities);
							}

						}
					}
				}

				Console.WriteLine("{0} TileEntities gathered", allTileEntities.Count);
				Console.WriteLine("Converting to JSON...");
				var js = new JSONSerializer();
				using (var sw = new StreamWriter(args[1]))
					js.Serialize(ConvertObject(allTileEntities), sw);
				Console.WriteLine("Successfully exported to {0}", args[1]);
			}
			else
			{
				if (args.Length < 4)
				{
					Console.WriteLine("USAGE: NBTExtractor <backup tar.gz> <world json> <nether json> <end json>");
					return;
				}

				var allTileEntities = new SortedDictionary<string, List<Object>>();
				var outputStreams = new SortedDictionary<string, TextWriter>();
				var firsts = new SortedDictionary<string, bool>();
				
				string[] worlds = { "world", "world_nether", "world_the_end" };

				foreach (var world in worlds)
				{
					allTileEntities[world] = new List<object>();
					firsts[world] = true;
				}

				for (int i = 0; i < worlds.Length; i++)
				{
					var sw = new StreamWriter(args[i + 1]);
					outputStreams[worlds[i]] = sw;
					sw.WriteLine("[");
				}

				using (var fs = new FileStream(args[0], FileMode.Open))
				using (var gis = new GZipInputStream(fs))
				using(var tis = new TarInputStream(gis))
				{
					//Console.WriteLine("Start");

					TarEntry tarEntry;
					
					while((tarEntry = tis.GetNextEntry()) != null)
					{
						//Console.WriteLine(tarEntry.Name);
						if (tarEntry.IsDirectory)
							continue;

						foreach(var world in worlds)
						{
							FlushStreams(worlds, firsts, outputStreams, allTileEntities, 4096);
							if (tarEntry.Name.Contains("/" + world + "/") && tarEntry.Name.EndsWith(".mca"))
							{
								Console.WriteLine("[/] {0}", tarEntry.Name);
								var currentList = allTileEntities[world];


								using (var fss = new MemoryStream())
								{
									int numRead;
									byte[] buffer = new byte[4096];
									numRead = tis.Read(buffer, 0, buffer.Length);

									while(numRead > 0)
									{
										fss.Write(buffer, 0, numRead);
										numRead = tis.Read(buffer, 0, buffer.Length);
									}
									fss.Seek(0, SeekOrigin.Begin);

									foreach (var lst1 in ExtractRegion(fss))
									{
										var lst = (List<KeyValuePair<string, object>>)lst1.Where(x => x.Key == "Level").Single().Value;

										foreach (var tileEntities in lst.Where(x => x.Key == "TileEntities" && x.Value is List<KeyValuePair<string, object>>).Select(x => (List<KeyValuePair<string, object>>)x.Value))
										{
											currentList.AddRange(tileEntities.Select(x => x.Value));
										}
										foreach (var tileEntities in lst.Where(x => x.Key == "TileEntities" && x.Value is object[]).Select(x => (object[])x.Value))
										{
											currentList.AddRange(tileEntities);
										}

									}
								}

								break;
							}
						}
					}

					Console.WriteLine("Done");
					FlushStreams(worlds, firsts, outputStreams, allTileEntities, 0);
					foreach(var kvp in outputStreams)
					{
						kvp.Value.WriteLine("]");
						kvp.Value.Close();
					}
				}
			}

			
		}
Exemplo n.º 35
0
		static void Main(string[] args)
		{
			if (args.Length < 2)
			{
				Console.WriteLine("USAGE: BookExtractor <json output> <json inputs...>");
				return;
			}

			var json = new JSONSerializer();

			var booksOutput = new ConfigList();

			var sb = new StringBuilder();
			
			for (int i = 1; i < args.Length; i++)
			{
				long fsz = new FileInfo(args[i]).Length;
				using (var sr = new StreamReader(args[i]))
				{
					Console.WriteLine("Reading {0}", args[i]);
					string line;
					int lastPercent = 0;
					bool skip = true;

					while ((line = sr.ReadLine()) != null)
					{
						int newPercent = (int)((sr.BaseStream.Position * 100L) / fsz);

						if (newPercent != lastPercent)
						{
							lastPercent = newPercent;
							Console.WriteLine("{0}: {1,3}%", args[i], lastPercent);
						}

						if (line.StartsWith("\t{"))
						{
							sb.Clear();
							sb.AppendLine("{");
							skip = true;
						}
						else if (line.StartsWith("\t}"))
						{
							if (skip)
								continue;

							sb.AppendLine("}");
							var lst = json.Deserialize(sb.ToString());

							if (lst.ContainsKey("Items"))
							{
								var lstt = lst["Items"] as ConfigList;
								if (lstt != null)
								{
									foreach (ConfigPair pair in lstt)
									{
										ConfigList pairData = (ConfigList)pair.Value;

										string pdi = pairData["id"] as string;
										if (pdi == null)
											continue;
										if (pdi == "minecraft:written_book")
											booksOutput.Add(null, pairData["tag"]);
									}
								}
							}
						}
						else
						{
							if (line.StartsWith("\t\t\"Items\":"))
								skip = false;
							sb.AppendLine(line);
						}
					}
				}
			}

			using (var sw = new StreamWriter(args[0]))
				json.Serialize(booksOutput, sw);
		}
        /// <summary>
        /// Creates an global JavaScript object object that holds all non-control 
        /// local string resources as property values.
        /// 
        /// All resources are returned in normalized fashion from most specifc
        /// to more generic (de-ch,de,invariant depending on availability)
        /// </summary>
        /// <param name="javaScriptVarName">Name of the JS object variable to createBackupTable</param>
        /// <param name="ResourceSet">ResourceSet name. Pass NULL for locale Resources</param>
        /// <param name="LocaleId"></param>
        public string GetResourcesAsJavascriptObject(string javaScriptVarName, string ResourceSet, string LocaleId)
        {
            if (LocaleId == null)
                LocaleId = CultureInfo.CurrentUICulture.IetfLanguageTag;
            if (ResourceSet == null)
                ResourceSet = WebUtils.GetAppRelativePath();

            IDictionary resources = GetResourceSetNormalizedForLocaleId(
                LocaleId, ResourceSet);

            // Filter the list to non-control resources 
            Dictionary<string, string> localRes = new Dictionary<string, string>();
            foreach (string key in resources.Keys)
            {
                // We're only interested in non control local resources 
                if (!key.Contains(".") && resources[key] is string)
                    localRes.Add(key, resources[key] as string);
            }

            JSONSerializer ser = new JSONSerializer();
            ser.FormatJsonOutput = HttpContext.Current.IsDebuggingEnabled;
            string json = ser.Serialize(localRes);

            return "var " + javaScriptVarName + " = " + json + ";\r\n";
        }
Exemplo n.º 37
0
        public void Test_Tell_Pass_Add_With_Perspective(string nativePerspective, string tellPerdicate, string tellPerspective, string queryPerdicate, string queryPerspective)
        {
            var kb = new KB(Name.BuildName(nativePerspective));
            kb.Tell(Name.BuildName(tellPerdicate), Name.BuildName(true), Name.BuildName(tellPerspective));

            using (var stream = new MemoryStream())
            {
                var formater = new JSONSerializer();
                formater.Serialize(stream, kb);
                stream.Seek(0, SeekOrigin.Begin);
                Console.WriteLine(new StreamReader(stream).ReadToEnd());
            }

            var r = kb.AskProperty(Name.BuildName(queryPerdicate), Name.BuildName(queryPerspective));
            bool b;
            if (!r.TryConvertToValue(out b))
                Assert.Fail();

            Assert.IsTrue(b);
        }
        /// <summary>
        /// Generic method that handles processing a Callback request by routing to
        /// a method in a provided target object.
        /// 
        /// </summary>
        /// <param name="target">The target object that is to be called. If null this is used</param>
        public void ProcessCallbackMethodCall(object target, string methodToCall)
        {
            if (target == null)
                target = this;

            HttpRequest Request = HttpContext.Current.Request;
            HttpResponse Response = HttpContext.Current.Response;
            Response.Charset = null;

            // check for Route Data method name
            if (target is CallbackHandler)
            {
                var routeData = ((CallbackHandler)target).RouteData;                
                if (routeData != null)
                    methodToCall = ((CallbackHandlerRouteHandler)routeData.RouteHandler).MethodName;
            }

            CallbackMethodProcessorHelper helper = new CallbackMethodProcessorHelper(this);
            
            List<string> parameterList = null;
            
            string contentType = Request.ContentType.ToLower();

            // Allow for a single JSON object to be POSTed rather than POST variables
            if (contentType.StartsWith(WebResources.STR_JavaScriptContentType) ||
                contentType.StartsWith(WebResources.STR_JsonContentType))
            {
                if (string.IsNullOrEmpty(methodToCall))
                    methodToCall = Request.Params["Method"];

                if (string.IsNullOrEmpty(methodToCall))
                {
                    WriteErrorResponse("No method to call specified.",null);
                    return;
                }

                // Pass a Parameter List with our JSON encoded parameters
                parameterList = new List<string>();

                if (Request.ContentLength > 0L)
                {
                    // Pick up single unencoded JSON parameter
                    string singleParm;
                    using (StreamReader sr = new StreamReader(Request.InputStream))
                    {
                        singleParm = sr.ReadToEnd();
                    }

                    if (!string.IsNullOrEmpty(singleParm))
                        parameterList.Add(singleParm);
                }
            }
            // Post AjaxMethodCallback style interface            
            else if (contentType.StartsWith(WebResources.STR_UrlEncodedContentType) && Request.Params["CallbackMethod"] != null)
                // Only pick up the method name - Parameters are parsed out of POST buffer during method calling
                methodToCall = Request.Params["CallbackMethod"];                
            else
            {
                JsonPMethod = Request.QueryString["jsonp"] ?? Request.QueryString["callback"];

                // Check for querystring method parameterList
                if (string.IsNullOrEmpty(methodToCall)) 
                    methodToCall = Request.QueryString["Method"];               

                // No method - no can do
                if (string.IsNullOrEmpty(methodToCall))
                {
                    WriteErrorResponse("No method to call specified.",null);
                    return;
                }
            }

            // Explicitly set the content type here - set here so the method 
            // can override it if it so desires
            Response.ContentType = WebResources.STR_JsonContentType;
            
            object result = null;
            string stringResult = null;
            CallbackMethodAttribute attr = new CallbackMethodAttribute();
            try
            {
                if (parameterList != null)
                    // use the supplied parameter list
                    result = helper.ExecuteMethod(methodToCall, target, parameterList.ToArray(),
                        CallbackMethodParameterType.Json, ref attr);
                else
                // grab the info out of QueryString Values or POST buffer during parameter parsing 
                // for optimization
                    result = helper.ExecuteMethod(methodToCall, target, null,
                        CallbackMethodParameterType.Json, ref attr);
            }
            catch (CallbackException ex)
            {
                WriteErrorResponse(ex.Message,
                                  (HttpContext.Current.IsDebuggingEnabled ? ex.StackTrace : null),
                                  ex.StatusCode);
            }
            catch (Exception ex)
            {                
                WriteErrorResponse(ex.GetBaseException().Message,
                                  ( HttpContext.Current.IsDebuggingEnabled ? ex.StackTrace : null ) );
                return;
            }

            // Special return type handling: Stream, Bitmap, byte[] and raw string results
            // are converted and returned directly
            HandleSpecialReturnTypes(result, attr, Request, Response);
            
            // Standard json formatting            
            try
            {
                JSONSerializer Serializer = new JSONSerializer();
                Serializer.DateSerializationMode = JsonDateEncoding;               

                // In debug mode show nicely formatted JSON 
                // In release normal packed JSON is used
                if (HttpContext.Current.IsDebuggingEnabled)
                    Serializer.FormatJsonOutput = true;

                if (result == null)
                    stringResult = "null";
                else
                    stringResult = Serializer.Serialize(result);
            }            
            catch (Exception ex)
            {
                WriteErrorResponse(ex.Message, HttpContext.Current.IsDebuggingEnabled ? ex.StackTrace : null);
                return;
            }
            
           
            if (!string.IsNullOrEmpty(JsonPMethod))            
                stringResult = JsonPMethod + "( " + stringResult + " );";
            
            Response.Write(stringResult);
            Response.End();
        }
        /// <summary>
        /// Returns an error response to the client from a callback. Code
        /// should exit after this call.
        /// </summary>
        /// <param name="ErrorMessage"></param>
        public void WriteErrorResponse(string errorMessage, string stackTrace, int statusCode = 500)
        {
            CallbackErrorResponseMessage Error = new CallbackErrorResponseMessage(errorMessage);
            Error.detail = stackTrace;
            Error.statusCode = statusCode;

            JSONSerializer Serializer = new JSONSerializer( SupportedJsonParserTypes.JavaScriptSerializer);            
            string result = Serializer.Serialize(Error);

            if (!string.IsNullOrEmpty(JsonPMethod))
                result = JsonPMethod + "( " + result + " );";

            HttpResponse Response = HttpContext.Current.Response;
            Response.ContentType = WebResources.STR_JsonContentType;

            Response.TrySkipIisCustomErrors = true;
            
            // override status code but only if it wasn't set already
            if (Response.StatusCode == 200)
                Response.StatusCode = statusCode;
            
            Response.Write(result);            
            Response.End();
        }