Exemplo n.º 1
0
 public string Serialize()
 {
     LitJson.JsonWriter writer = new LitJson.JsonWriter();
     writer.PrettyPrint = true;
     LitJson.JsonMapper.ToJson(this, writer);
     return(writer.TextWriter.ToString());
 }
Exemplo n.º 2
0
    static int ToJson(IntPtr L)
    {
        try
        {
            int count = LuaDLL.lua_gettop(L);

            if (count == 1 && TypeChecker.CheckTypes(L, typeof(LitJson.JsonData)))
            {
                LitJson.JsonData obj = (LitJson.JsonData)ToLua.ToObject(L, 1);
                string           o   = obj.ToJson();
                LuaDLL.lua_pushstring(L, o);
                return(1);
            }
            else if (count == 2 && TypeChecker.CheckTypes(L, typeof(LitJson.JsonData), typeof(LitJson.JsonWriter)))
            {
                LitJson.JsonData   obj  = (LitJson.JsonData)ToLua.ToObject(L, 1);
                LitJson.JsonWriter arg0 = (LitJson.JsonWriter)ToLua.ToObject(L, 2);
                obj.ToJson(arg0);
                return(0);
            }
            else
            {
                return(LuaDLL.luaL_throw(L, "invalid arguments to method: LitJson.JsonData.ToJson"));
            }
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e));
        }
    }
Exemplo n.º 3
0
    /// <summary>
    /// 将一场战斗序列化到路径...
    /// </summary>
    /// <param name="outputPath"></param>
    private void SerializeBattleFieldToPath(string outputPath)
    {
        string folderPath = Path.GetDirectoryName(outputPath);

        if (!Directory.Exists(folderPath))
        {
            Directory.CreateDirectory(folderPath);
        }

        using (TextWriter tw = new StreamWriter(outputPath))
        {
            LitJson.JsonWriter jsonWriter = new LitJson.JsonWriter(tw);
#if UNITY_EDITOR
            //弄得好看一点
            jsonWriter.PrettyPrint = true;
#endif
            jsonWriter.WriteObjectStart();
            {
                //序列化战斗
                jsonWriter.WriteObject("battleField", battleField);
            }
            jsonWriter.WriteObjectEnd();
            Debug.LogFormat("序列化战场完毕 => {0}", outputPath);

            System.Diagnostics.Process.Start("explorer.exe", folderPath);
        }
    }
Exemplo n.º 4
0
    public static JsonData DataTableToJson(DataTable dt)
    {
        JsonData jsdata = new JsonData();

        try
        {
            StringBuilder      sb = new StringBuilder();
            LitJson.JsonWriter jw = new LitJson.JsonWriter(sb);
            jw.WriteArrayStart();
            foreach (DataRow dr in dt.Rows)
            {
                jw.WriteObjectStart();
                foreach (DataColumn dc in dt.Columns)
                {
                    jw.WritePropertyName(dc.ColumnName);
                    jw.Write(dr[dc.ColumnName].ToString());
                }
                jw.WriteObjectEnd();
            }
            jw.WriteArrayEnd();
            jsdata = JsonMapper.ToObject(sb.ToString());
        }
        catch (System.Exception ex)
        {
        }

        return(jsdata);
    }
Exemplo n.º 5
0
        public string Encode(object obj)
        {
            JsonWriter writer = new JsonWriter();
            JsonMapper.ToJson(obj, writer);

            return writer.ToString();
        }
Exemplo n.º 6
0
        //[MenuItem("Editors/LiumkTest/123123")]
        static void ShowEditor()
        {
            //EditorUtility.DisplayDialog("MyTool", "Do It in C# !", "OK", "");
            if (s_instance == null)
            {
                //Type[] types = new Type[2] { typeof(BlackWood.NodeCanvas.Editor.SkinContainer), typeof(BlackWood.NodeCanvas.Editor.BBPContainer) };
                //s_instance = GetWindow<ZEditor>("Unit Browser", true, types);
                s_instance = GetWindow <ZEditor>(false, "ZEditor");
            }
            //s_instance.Show();
            s_instance.Show();

            var testObject = new ObjectTest();
            var writer     = new LitJson.JsonWriter {
                PrettyPrint = true
            };

            LitJson.JsonMapper.ToJson(testObject, writer);

            string path = "./Assets/test.json";

            if (File.Exists(path))
            {
                File.Delete(path);
            }
            File.WriteAllText(path, writer.ToString(), Encoding.UTF8);
        }
Exemplo n.º 7
0
 public static void WriteObj2UnicodeJson(string path, object obj, bool isPretty = true)
 {
     LitJson.JsonWriter writer = new LitJson.JsonWriter();
     writer.PrettyPrint = isPretty;
     LitJson.JsonMapper.ToJson(obj, writer);
     Utils.WriteFileUTF8(path, ConvUnicode(Obj2Json(obj, isPretty)));
 }
Exemplo n.º 8
0
 public static string beautyJson(object obj, bool isPretty = true)
 {
     LitJson.JsonWriter writer = new LitJson.JsonWriter();
     writer.PrettyPrint = isPretty;
     LitJson.JsonMapper.ToJson(obj, writer);
     return(writer.TextWriter.ToString());
 }
Exemplo n.º 9
0
 static void Write(JsonWriter writer, string failedMessage)
 {
     WriteObject(writer, () =>
         {
             WriteProperty(writer, "message", failedMessage);
         });
 }
Exemplo n.º 10
0
        public static void createResource()
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            DirectoryInfo di = new DirectoryInfo(Global.PATH + "/res");
            var jd = new LitJson.JsonData();
            FileInfo[] fs = di.GetFiles("*", SearchOption.TopDirectoryOnly);

            foreach (FileInfo fi in fs)
            {
                if (fi.Name.Contains(".manifest"))
                {
                    continue;
                }

                string pPath = "res/" + fi.Name;
                jd[pPath.Replace("/", "@").Replace("\\", "@")] = pPath;
            }


            getJsonData(jd,"");
            JsonWriter writer = new JsonWriter(sb);
            writer.PrettyPrint = true;
            writer.IndentValue = 4;
            jd.ToJson(writer);
             
            

 
            string result = CoccosHelper.Properties.Resources.tpl.Replace("#1#", sb.ToString());
            File.WriteAllText(Global.PATH + "/src/resource.js", result);

        }
Exemplo n.º 11
0
        private void SerializeTable(SerializeTable table, LitJson.JsonWriter writer)
        {
            if (0 == table.KeyValueMap.Count && 0 == table.Children.Count)
            {
                return;
            }

            writer.WritePropertyName(table.Name);
            writer.WriteObjectStart();
            using (Dictionary <string, SerializeTable.Value> .Enumerator next = table.KeyValueMap.GetEnumerator())
            {
                while (next.MoveNext())
                {
                    writer.WritePropertyName(next.Current.Key);
                    //writer.Write(next.Current.Value.obj);
                    WriteValue(next.Current.Value.obj, writer, 0);
                }
            }

            foreach (SerializeTable node in table.Children)
            {
                SerializeTable(node, writer);
            }

            writer.WriteObjectEnd();
        }
Exemplo n.º 12
0
    public void ToJson(LitJson.JsonWriter jsonWriter)
    {
        switch (_type)
        {
        case enType.Float:
            jsonWriter.Write(Float);
            break;

        case enType.Int:
            jsonWriter.Write(Int);
            break;

        case enType.Long:
            jsonWriter.Write(Long);
            break;

        case enType.String:
            jsonWriter.Write(String);
            break;

        default:
            jsonWriter.Write(null);
            break;
        }
    }
Exemplo n.º 13
0
 public static string JsonPrettyFormat(this string json)
 {
     LitJson.JsonWriter writer1 = new LitJson.JsonWriter();
     writer1.PrettyPrint = true;
     writer1.IndentValue = 4;
     LitJson.JsonMapper.ToJson(MiniJSON.Json.Deserialize(json), writer1);
     return(writer1.ToString());
 }
Exemplo n.º 14
0
 public override void ExportJson(JsonWriter writer)
 {
     using (var scope = new JsonScopeObjectWriter(writer)) {
         scope.WriteKeyValue("url", "./" + Name);
         scope.WriteKeyValue("uuid", Uuid);
         scope.WriteKeyValue("name", Name);
     }
 }
Exemplo n.º 15
0
 public override void ExportJson(JsonWriter writer)
 {
     using (var scope = new JsonScopeObjectWriter(writer)) {
         WriteCommonObjectNode(writer, scope);
         scope.WriteKeyValue("geometry", Geometry.Uuid);
         scope.WriteKeyValue("material", Material.Uuid);
     }
 }
Exemplo n.º 16
0
 static void Write(JsonWriter writer, IEnumerable<StepDefinition> stepDefinitions)
 {
     WriteArray(writer, () =>
         {
             foreach (var stepDefinition in stepDefinitions)
                 Write(writer, stepDefinition);
         });
 }
 public override void ExportJson(JsonWriter writer)
 {
     using (var scope = new JsonScopeObjectWriter(writer)) {
         WriteCommonObjectNode(writer, scope);
         scope.WriteKeyValue("color", Color);
         scope.WriteKeyValue("intensity", Intensity);
     }
 }
Exemplo n.º 18
0
        public void ErrorArrayClosingTest()
        {
            JsonWriter writer = new JsonWriter ();

            writer.WriteArrayStart ();
            writer.Write (true);
            writer.WriteObjectEnd ();
        }
Exemplo n.º 19
0
        public void ErrorPropertyExpectedTest ()
        {
            JsonWriter writer = new JsonWriter ();

            writer.WriteObjectStart ();
            writer.Write (10);
            writer.WriteObjectEnd ();
        }
Exemplo n.º 20
0
 static void Write(JsonWriter writer, StepDefinition stepDefinition)
 {
     WriteObject(writer, () =>
         {
             WriteProperty(writer, "id", stepDefinition.Id);
             WriteProperty(writer, "regexp", stepDefinition.Pattern);
         });
 }
Exemplo n.º 21
0
        private static void exportRewardAsRewardJsonWritter(Reward value, LitJson.JsonWriter writer)
        {
            StringBuilder stringBuilder = new StringBuilder();

            LitJson.JsonWriter writer2 = new LitJson.JsonWriter(stringBuilder);
            JsonMapper.ToJson(RewardJsonWritter.FromReward(value), writer2);
            writer.WriteRaw(stringBuilder.ToString());
        }
Exemplo n.º 22
0
        public static void LitJsonWriterObjects ()
        {
            for (int j = 0; j < Common.Iterations; j++) {
                StringBuilder output = new StringBuilder ();
                JsonWriter writer = new JsonWriter (new StringWriter (output));

                int n = Common.SampleObject.Length;
                for (int i = 0; i < n; i += 2) {
                    switch ((char) Common.SampleObject[i]) {
                    case '{':
                        writer.WriteObjectStart ();
                        break;

                    case '}':
                        writer.WriteObjectEnd ();
                        break;

                    case '[':
                        writer.WriteArrayStart ();
                        break;

                    case ']':
                        writer.WriteArrayEnd ();
                        break;

                    case 'P':
                        writer.WritePropertyName (
                            (string) Common.SampleObject[i + 1]);
                        break;

                    case 'I':
                        writer.Write (
                            (int) Common.SampleObject[i + 1]);
                        break;

                    case 'D':
                        writer.Write (
                            (double) Common.SampleObject[i + 1]);
                        break;

                    case 'S':
                        writer.Write (
                            (string) Common.SampleObject[i + 1]);
                        break;

                    case 'B':
                        writer.Write (
                            (bool) Common.SampleObject[i + 1]);
                        break;

                    case 'N':
                        writer.Write (null);
                        break;
                    }
                }

            }
        }
Exemplo n.º 23
0
		public void SaveTasks(TaskList.SerializedForm serializedForm) {
			JsonWriter writer = new JsonWriter();
			writer.PrettyPrint = true;
			JsonMapper.ToJson(serializedForm, writer);
			string json = writer.ToString();
			StreamWriter sr = new StreamWriter(this.taskFile);
			sr.Write(json);
			sr.Close();
		}
Exemplo n.º 24
0
		public void SaveSettings(Settings.SerializedForm serializedForm) {
			JsonWriter writer = new JsonWriter();
			writer.PrettyPrint = true;
			JsonMapper.ToJson(serializedForm, writer);
			string json = writer.ToString();
			StreamWriter sr = new StreamWriter(this.configFile);
			sr.Write(json);
			sr.Close();
		}
Exemplo n.º 25
0
 public static void WriteIntField(this LitJson.JsonWriter writer, string propertyName, Vector2 value)
 {
     propertyName = propertyName.Replace(".", "#");
     writer.WritePropertyName(propertyName);
     writer.WriteObjectStart();
     writer.WriteField("x", (int)value.x);
     writer.WriteField("y", (int)value.y);
     writer.WriteObjectEnd();
 }
Exemplo n.º 26
0
        public void ErrorObjectClosingTest()
        {
            JsonWriter writer = new JsonWriter ();

            writer.WriteObjectStart ();
            writer.WritePropertyName ("foo");
            writer.Write ("bar");
            writer.WriteArrayEnd ();
        }
Exemplo n.º 27
0
        public void ErrorExcessDataTest()
        {
            JsonWriter writer = new JsonWriter ();

            writer.WriteArrayStart ();
            writer.Write (true);
            writer.WriteArrayEnd ();
            writer.Write (false);
        }
Exemplo n.º 28
0
        public override void OnSerializeTable(SerializeTable rootTable)
        {
            writer             = new JsonWriter(stream);
            writer.PrettyPrint = PrettyPrint;

            writer.WriteObjectStart();
            SerializeTable(rootTable, writer);
            writer.WriteObjectEnd();
        }
Exemplo n.º 29
0
 static void Write(JsonWriter writer, Exception exception)
 {
     WriteObject(writer, () =>
         {
             WriteProperty(writer, "exception", exception.GetType().ToString());
             WriteProperty(writer, "message", exception.Message);
             WriteProperty(writer, "backtrace", exception.StackTrace);
         });
 }
Exemplo n.º 30
0
    public static string ToString(object obj, bool prettyPrint)
    {
        var writer = new LitJson.JsonWriter {
            PrettyPrint = prettyPrint
        };

        LitJson.JsonMapper.ToJson(obj, writer);
        return(writer.ToString());
    }
Exemplo n.º 31
0
    public static string JsonBeauty(string str)
    {
        object obj = LitJson.JsonMapper.ToObject <object>(str);

        LitJson.JsonWriter writer = new LitJson.JsonWriter();
        writer.PrettyPrint = true;
        LitJson.JsonMapper.ToJson(obj, writer);
        return(writer.TextWriter.ToString());
    }
Exemplo n.º 32
0
        private void saveCellMapSetting()
        {
            var writer = new LitJson.JsonWriter {
                PrettyPrint = true
            };

            LitJson.JsonMapper.ToJson(m_curMapConfig, writer);
            File.WriteAllText(mt_curFilePath, writer.ToString());
            Repaint();
        }
Exemplo n.º 33
0
 public static void WriteField(this LitJson.JsonWriter writer, string propertyName, Quaternion value)
 {
     propertyName = propertyName.Replace(".", "#");
     writer.WritePropertyName(propertyName);
     writer.WriteObjectStart();
     writer.WriteField("x", value.eulerAngles.x);
     writer.WriteField("y", value.eulerAngles.y);
     writer.WriteField("z", value.eulerAngles.z);
     writer.WriteObjectEnd();
 }
Exemplo n.º 34
0
    public static string ToJSON(object o)
    {
        LitJson.JsonWriter writer = new LitJson.JsonWriter(Console.Out);
        writer.PrettyPrint = true;
        writer.IndentValue = 2;

        string json = LitJson.JsonMapper.ToJson(o);

        return(json);
    }
Exemplo n.º 35
0
    public static string ToLitJson(this object obj)
    {
        var w = new LitJson.JsonWriter
        {
            PrettyPrint = false
        };

        LitJson.JsonMapper.ToJson(obj, w);
        w.TextWriter.Flush();
        return(w.TextWriter.ToString());
    }
Exemplo n.º 36
0
        public void BooleansTest()
        {
            JsonWriter writer = new JsonWriter ();

            writer.WriteArrayStart ();
            writer.Write (true);
            writer.Write (false);
            writer.Write (false);
            writer.Write (true);
            writer.WriteArrayEnd ();
        }
        public static void ToNetMsg(Dictionary<long, F3_NetServerInfo> servers, ref NetOutgoingMessage netMsg)
        {
            netMsg.Write((byte)NetDataType.eDATA_REQUEST_SERVER_LIST);

            StringBuilder sb = new StringBuilder();
            JsonWriter writer = new JsonWriter(sb);

            writer.WriteObjectStart();
            writer.WritePropertyName("servers");
            writer.WriteArrayStart();

            for (int i = 0; i < servers.Count; i++)
            {
                F3_NetServerInfo info = servers.ElementAt(i).Value;
                writer.WriteObjectStart();

                writer.WritePropertyName("UUID");
                writer.Write(servers.ElementAt(i).Key);

                writer.WritePropertyName("serverName");
                writer.Write(info.m_serverName);

                writer.WritePropertyName("type");
                writer.Write((int)info.m_serverType);

                writer.WritePropertyName("internal_ip");
                writer.Write(info.m_serverInternalAdress.Address.ToString());

                writer.WritePropertyName("internal_port");
                writer.Write(info.m_serverInternalAdress.Port);

                writer.WritePropertyName("external_ip");
                writer.Write(info.m_serverExternalAdress.Address.ToString());

                writer.WritePropertyName("external_port");
                writer.Write(info.m_serverExternalAdress.Port);

                writer.WritePropertyName("maxPlayers");
                writer.Write(info.m_maxPlayers);

                writer.WritePropertyName("currentPlayers");
                writer.Write(info.m_currentNbPlayers);

                writer.WritePropertyName("token");
                writer.Write(info.m_NATtoken);

                writer.WriteObjectEnd();
            }

            writer.WriteArrayEnd();
            writer.WriteObjectEnd();

            netMsg.Write(sb.ToString());
        }
Exemplo n.º 38
0
 public static void WriteField(this LitJson.JsonWriter writer, string propertyName, string[] value)
 {
     propertyName = propertyName.Replace(".", "#");
     writer.WritePropertyName(propertyName);
     writer.WriteArrayStart();
     for (int i = 0; i < value.Length; i++)
     {
         writer.Write(value[i]);
     }
     writer.WriteArrayEnd();
 }
Exemplo n.º 39
0
    public void Destroy()
    {
        if (destroyed)
        {
            return;
        }
        destroyed = true;

        m_thread.Abort();
        m_thread = null;

        m_wpos   = 0;
        m_rpos   = 0;
        m_buffer = null;
        m_socket = null;

        #region NetStat statistic

        #if NETSTAT
        m_net   = null;
        m_parse = null;
        networkDelay.Clear();
        parseDelay.Clear();
        #endif

        #endregion

        lock (m_guard_packet)
        {
            #if DEVELOPMENT_BUILD || UNITY_EDITOR
            m_jsonWriter.Reset();
            m_jsonWriter = null;

            m_sb.Clear();
            m_sb = null;
            #endif

            m_packet.Destroy();
            m_packet = null;
        }

        lock (m_guard_write)
        {
            m_front.Clear(true);
            //m_back.Clear();  // Back queue will clear by Session

            m_front = null;
            m_back  = null;
        }

        m_guard_write  = null;
        m_guard_packet = null;
    }
Exemplo n.º 40
0
 public static string generateReadParamJson()
 {
     System.Text.StringBuilder sb = new System.Text.StringBuilder();
     JsonWriter writer = new JsonWriter(sb);
     writer.WriteObjectStart();
     writer.WritePropertyName("action");
     writer.Write("get");
     writer.WritePropertyName("id");
     writer.Write("SC9008637");
     writer.WritePropertyName("page");
     writer.Write("channel_param");
     writer.WriteObjectEnd();
     return sb.ToString();
 }
Exemplo n.º 41
0
    public static Boolean AddJsonProperty(string name, ref JsonData targetjsondata)
    {
        Boolean bRet = false;

        if (targetjsondata != null)
        {
            StringBuilder      sb = new StringBuilder(targetjsondata.ToJson());
            LitJson.JsonWriter jw = new LitJson.JsonWriter(sb);
            jw.WriteObjectStart();
            jw.WritePropertyName(name);
            jw.Write("");
            jw.WriteObjectEnd();
            targetjsondata = JsonMapper.ToObject(sb.ToString());
            bRet           = true;
        }
        return(bRet);
    }
Exemplo n.º 42
0
    public static Boolean AddJsonArray(string name, ref JsonData targetjsondata)
    {
        Boolean bRet = false;

        if (targetjsondata != null)
        {
            StringBuilder      sb = new StringBuilder(targetjsondata.ToJson());
            LitJson.JsonWriter jw = new LitJson.JsonWriter(sb);
            jw.WriteArrayStart();
            //jw.Write("{}");
            jw.WriteArrayEnd();
            targetjsondata[name] = JsonMapper.ToObject(sb.ToString());
            targetjsondata[name].SetJsonType(JsonType.Array);
            bRet = true;
        }
        return(bRet);
    }
Exemplo n.º 43
0
        public static void LitJsonWriterNumbers ()
        {
            for (int i = 0; i < Common.Iterations; i++) {
                StringBuilder output = new StringBuilder ();
                JsonWriter writer = new JsonWriter (new StringWriter (output));

                writer.WriteArrayStart ();

                foreach (int n in Common.SampleInts)
                    writer.Write (n);

                foreach (double n in Common.SampleDoubles)
                    writer.Write (n);

                writer.WriteArrayEnd ();
            }
        }
 public string ListStepDefinitionsAsJson()
 {
     StringBuilder sb = new StringBuilder();
     JsonWriter writer = new JsonWriter(sb);
     writer.WriteArrayStart();
     foreach (StepDefinition sd in _stepDefinitions)
     {
         writer.WriteObjectStart();
         writer.WritePropertyName("id");
         writer.Write(sd.Id);
         writer.WritePropertyName("regexp");
         writer.Write(sd.Pattern);
         writer.WriteObjectEnd();
     }
     writer.WriteArrayEnd();
     return sb.ToString();
 }
Exemplo n.º 45
0
    /// <summary>
    /// 将对象序列化为Json并保存为文件
    /// </summary>
    /// <param name="value"></param>
    /// <param name="filePath"></param>
    /// <param name="fileName"></param>
    public static void WriteLitJson(object value, string filePath, string fileName)
    {
        if (!Directory.Exists(filePath))
        {
            Directory.CreateDirectory(filePath);
        }

        var stringBuilder = new StringBuilder();
        var jsonWriter    = new LitJson.JsonWriter(stringBuilder)
        {
            PrettyPrint = true
        };                                                                           // 缩进格式输出。缩进间隔:IndentValue = 2;

        JsonMapper.ToJson(value, jsonWriter);
        var jsonData = Regex.Unescape(stringBuilder.ToString()); // 保存中文字符

        File.WriteAllText(Path.Combine(filePath, fileName), jsonData);
    }
Exemplo n.º 46
0
        private JsonData JngsSgyParser(JsonData jsobj)
        {
            JsonData jret = null;
            JsonBase jbr  = null;

            if (jsobj != null)
            {
                #region 统一代码
                try
                {
                    if (jsobj != null)
                    {
                        string optaction = "mobile_BLL.Interface." + jsobj["optstring"].ToString() + ",mobile_BLL";
                        Type   type      = Type.GetType(optaction);
                        jbr = (JsonBase)Activator.CreateInstance(type, jsobj["optdata"]);
                    }
                    if (jbr != null)
                    {
                        jbr.strBaseUrl  = HttpContext.Current.Request.Url.AbsoluteUri;
                        jbr.strBaseUrl  = jbr.strBaseUrl.Replace(HttpContext.Current.Request.Url.AbsolutePath, "");
                        jbr.strBaseUrl += HttpContext.Current.Request.ApplicationPath;
                        StringBuilder      sb = new StringBuilder();
                        LitJson.JsonWriter jw = new LitJson.JsonWriter(sb);
                        jw.WriteObjectStart();
                        jw.WritePropertyName("result");
                        jw.Write("");
                        jw.WriteObjectEnd();
                        jret           = JsonMapper.ToObject(sb.ToString());
                        jret["result"] = (JsonData)jbr.GetData();
                    }
                }
                catch (Exception ex)
                {
                    BaseDal.RecordError("json数据返回出错_get_data.ashx", ex.ToString());
                }
                #endregion
            }

            return(jret);
        }
Exemplo n.º 47
0
 private static void DBNull2Null(DBNull dbNull, LitJson.JsonWriter jw)
 {
     jw.Write(null);
 }
    public static string GetSchedule(IDbConnection db)
    {
        TimeSpan t = DateTime.UtcNow - new DateTime(1970, 1, 1);
        long today = (long)t.TotalSeconds;
        StringBuilder sb = new StringBuilder();
        LitJson.JsonWriter writer = new LitJson.JsonWriter(sb);
        writer.WriteObjectStart();
        writer.WritePropertyName("bookings");
        writer.WriteArrayStart();
        using (IDbCommand command = db.CreateCommand())
        {
            command.CommandText = "select id, day, [from], till,  _user, _meetingroom, users_notified, users_to_be_notified, users_checkedin from booking where day>= @Day order by day, [from]";
            IDbDataParameter p = command.CreateParameter();
            p.ParameterName = "@Day";
            p.Value = today;
            command.Parameters.Add(p);
            using (IDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    new MeetingRoomBooking(reader).Write(writer);
                }
            }
        }
        writer.WriteArrayEnd();

        writer.WritePropertyName("rooms");
        writer.WriteObjectStart();
        List<MeetingRoom> MeetingRooms = new List<MeetingRoom>();
        MeetingRooms = MeetingRoom.List(db);
        foreach (MeetingRoom meetingRoom in MeetingRooms)
        {
            writer.WritePropertyName(meetingRoom.Id.ToString());
            meetingRoom.Write(writer);
        }
        writer.WriteObjectEnd();
        writer.WritePropertyName("users");
        writer.WriteObjectStart();
        List<User> Users = new List<User>();
        Users = User.list(db);
        foreach (User user in Users)
        {
            writer.WritePropertyName(user.Email);
            user.Write(writer);
        }
        writer.WriteObjectEnd();
        writer.WriteObjectEnd();
        return sb.ToString();
    }
 void WriteUserdata(JsonWriter writer)
 {
     using (var s1 = new JsonScopeObjectWriter(writer)) {
         foreach (var kv in varGroupDict) {
             writer.WritePropertyName(kv.Key);
             WriteScriptVariableGroup(writer, kv.Value);
         }
     }
 }
 void WriteScriptVariableGroup(JsonWriter writer, List<ScriptVariable> vars)
 {
     using (var s2 = new JsonScopeObjectWriter(writer)) {
         foreach (var val in vars) {
             writer.WritePropertyName(val.key);
             WriterScriptNodeVariable(writer, val);
         }
     }
 }
 void WriterScriptNodeVariable(JsonWriter writer, ScriptVariable val)
 {
     using (var s1 = new JsonScopeObjectWriter(writer)) {
         s1.WriteKeyValue("key", val.key);
         s1.WriteKeyValue("type", val.ShortFieldType);
         WriteObjectVariable(s1, val.value);
     }
 }
        public void WriteCommonObjectNode(JsonWriter writer, JsonScopeObjectWriter scope)
        {
            scope.WriteKeyValue("uuid", Uuid);
            scope.WriteKeyValue("type", Type);
            scope.WriteKeyValue("name", Name);
            scope.WriteKeyValue("matrix", Matrix);
            scope.WriteKeyValue("visible", Visible);

            if((userdata.Count + varGroupDict.Count) > 0) {
                writer.WritePropertyName("userdata");
                WriteUserdata(writer);
            }

            if (ChildCount > 0) {
                writer.WritePropertyName("children");
                using (var s = new JsonScopeArrayWriter(writer)) {
                    foreach (var child in Children) {
                        child.ExportJson(writer);
                    }
                }
            }
        }
 public void WriteResponse(string id, Response resp, Exception error, StreamWriter sw)
 {
     JsonWriter writer = new JsonWriter(sw);
     writer.WriteObjectStart();
     writer.WritePropertyName("id");
     writer.Write(id);
     if (error == null)
     {
         writer.WritePropertyName("error");
         writer.Write(null);
         writer.WritePropertyName("result");
         if (resp == null)
             writer.Write(null);
         else
             resp.Write(writer, false);
     }
     else
     {
         writer.WritePropertyName("result");
         writer.Write(null);
         writer.WritePropertyName("error");
         writer.Write(string.Format("{0}\n{1}", error.Message, error.StackTrace.ToString()));
     }
     writer.WriteObjectEnd();
 }
Exemplo n.º 54
0
 // Use this for initialization
 void Start()
 {
     m_PrettyWriter             = new LitJson.JsonWriter();
     m_PrettyWriter.PrettyPrint = true;
 }
Exemplo n.º 55
0
    private void ProcessData()
    {
        var received = m_wpos - m_rpos;

        while (received >= Packet.headerSize)
        {
            if (destroyed || !m_socket.Connected)
            {
                return;                                            // if the session is disconnected or receiver destroyed, stop processing data immdiately
            }
            var mask   = ByteConverter.ToUInt32(m_buffer, m_rpos); // low 24 bit = length, hight 8 bit = bitmask
            var length = (int)((mask & 0xFFFFFF) + 4);             // server side packet length does not contain mask length
            //var bimask = mask >> 24;

            if (length < Packet.headerSize) // got invalid packet data, stop processing data immdiately and disconnect from server
            {
                Logger.LogException("PacketReceiver got invalid packet data header, header length is {0} but required {1}", length, Packet.headerSize);

                Close();
                return;
            }

            if (received >= length)
            {
                var id     = ByteConverter.ToUInt16(m_buffer, m_rpos + 4);
                var header = id | (long)length << 16;

                var bytes = new byte[length];
                Array.Copy(m_buffer, m_rpos, bytes, 0, length);
                m_rpos   += length;
                received -= length;

                PacketObject o;

                lock (m_guard_packet)
                {
                    m_packet.Set(header, bytes);
                    o = PacketObject.Create(m_packet);

                    #if DEVELOPMENT_BUILD || UNITY_EDITOR
                    if (o != null)
                    {
                        var f = ConfigManager.Get <ProtocolLoggerFilter>(o._ID);
                        if (!f || !f.disabled)
                        {
                            if (!f || !f.noDetail)
                            {
                                m_jsonWriter.Reset();
                                try
                                {
                                    LitJson.JsonMapper.ToJson(o, m_jsonWriter, 5);
                                    Logger.Log(LogType.RECV, "Recv: [{0}:{1}-{2},{3}] {4}", m_packet.ID, m_packet.dataSize, Level.realTime, o._name, m_jsonWriter);
                                }
                                catch (Exception ee)
                                {
                                    m_jsonWriter = new LitJson.JsonWriter()
                                    {
                                        CsFormat = true, PrettyPrint = true
                                    };
                                    Logger.Log(LogType.RECV, "Recv: [{0}:{1}-{2},{3}]", m_packet.ID, m_packet.dataSize, Level.realTime, o._name);
                                    Logger.LogException(ee);
                                }
                            }
                            else
                            {
                                Logger.Log(LogType.RECV, "Recv: [{0}:{1}-{2},{3}]", m_packet.ID, m_packet.dataSize, Level.realTime, o._name);
                            }

                            if (f && f.cpp)
                            {
                                o.LogCppString(m_sb);
                            }
                        }
                    }
                    else
                    {
                        Logger.LogError("Receive unknow packet: [{0}:{1}-{2}], packet not registered.", m_packet.ID, m_packet.dataSize, Level.realTime);
                    }
                    #endif

                    m_packet.Reset();
                }

                if (o != null)
                {
                    lock (m_guard_write)
                    {
                        m_front.Add(o);
                    }
                }
            }
            else
            {
                break;
            }
        }
    }
Exemplo n.º 56
0
    public static bool SaveProject(bool add, ProjectBuildData data)
    {
        DataRow   drProject = null;
        DataTable dt        = LoadAndCreateProjects(PROJECTS_CONFIG_FILE);

        foreach (DataRow dr in dt.Rows)
        {
            string name = dr["ProjectName"].ToString();
            if (name == data.Name)
            {
                drProject = dr;
                break;
            }
        }

        if (add && drProject != null)
        {
            Debug.LogError("exist same project name already " + data.Name);
            return(false);
        }
        else if (!add && drProject == null)
        {
            Debug.LogError("project not exist " + data.Name);
            return(false);
        }
        else if (add)
        {
            drProject = dt.NewRow();
            dt.Rows.Add(drProject);
        }

        drProject["ProjectName"] = data.Name;
        drProject["Version"]     = data.Version;

        List <string> sceneList = new List <string>();

        foreach (EditorBuildSettingsScene scene in EditorBuildSettings.scenes)
        {
            if (!scene.enabled)
            {
                continue;
            }
            sceneList.Add(scene.path);
        }
        string scenes = string.Join(";", sceneList.ToArray());

        drProject["Scenes"] = scenes;

        drProject["Target"]       = EditorUserBuildSettings.activeBuildTarget;
        drProject["SymbolDefine"] = PlayerSettings.GetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup);
        drProject["DebugBuild"]   = EditorUserBuildSettings.development.ToString();

        FieldInfo[] optionFields = typeof(GameOptions).GetFields();
        foreach (var field in optionFields)
        {
            if (!field.IsPublic || field.IsStatic)
            {
                continue;
            }

            if (!dt.Columns.Contains(field.Name))
            {
                dt.Columns.Add(field.Name);
            }

            var obj = field.GetValue(data.Options);
            if (obj != null)
            {
                if (field.FieldType == typeof(string) ||
                    field.FieldType == typeof(bool) ||
                    field.FieldType == typeof(int) ||
                    field.FieldType.IsEnum)
                {
                    drProject[field.Name] = obj.ToString();
                }
                else if (field.FieldType.IsGenericType)
                {
                    drProject[field.Name] = LitJson.JsonMapper.ToJson(obj);
                }
            }
        }

        PropertyInfo[] fields = typeof(PlayerSettings).GetProperties(BindingFlags.Public | BindingFlags.Static);
        foreach (var field in fields)
        {
            if (!field.CanWrite)
            {
                continue;
            }

            var obj = field.GetValue(null, null);
            if (obj != null)
            {
                drProject[field.Name] = obj.ToString();
                if (field.PropertyType == typeof(Texture2D))
                {
                    var texture = obj as Texture2D;
                    drProject[field.Name] = texture.name;
                }
            }
        }

        var types = typeof(PlayerSettings).GetNestedTypes();

        foreach (var type in types)
        {
            var sb     = new StringBuilder();
            var writer = new LitJson.JsonWriter(sb);

            writer.WriteObjectStart();

            var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Static);
            foreach (var property in properties)
            {
                if (!property.CanWrite)
                {
                    continue;
                }

                writer.WritePropertyName(property.Name);
                var obj = property.GetValue(null, null);
                writer.Write(obj != null ? obj.ToString() : "");
            }

            writer.WriteObjectEnd();

            if (!drProject.Table.Columns.Contains(type.Name))
            {
                drProject.Table.Columns.Add(type.Name);
            }
            drProject[type.Name] = sb.ToString();
        }

        var iconList = new List <string>();
        var group    = GetBuildGroupByTarget(data.Target);
        var icons    = PlayerSettings.GetIconsForTargetGroup(group);

        foreach (var texture2D in icons)
        {
            if (texture2D != null)
            {
                var path = AssetDatabase.GetAssetPath(texture2D.GetInstanceID());
                iconList.Add(path);
            }
        }

        var iconsStr = string.Join(",", iconList.ToArray());

        drProject["Icons"] = iconsStr;

        if (data.Games != null)
        {
            var str = LitJson.JsonMapper.ToJson(data.Games);
            drProject["Games"] = str;
        }

        SaveToDB(dt, PROJECTS_CONFIG_FILE);

        //SaveConfig(data);

        return(true);
    }
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest request = context.Request;
            HttpResponse response = context.Response;

            // Validate incoming request
            if (request.HttpMethod != "POST")
            {
                response.StatusCode = 405;
                response.StatusDescription = "Method not allowed";
                response.End();
                return;
            }
            if (request.Headers["X-Nuntiuz-Service-Key"] != sikey)
            {
                response.StatusCode = 401;
                response.StatusDescription = "Not authorized";
                response.End();
                return;
            }
            if (!request.ContentType.StartsWith("application/json-rpc"))
            {
                response.StatusCode = 400;
                response.StatusDescription = "Bad request";
                response.End();
                return;
            }

            string id = null;
            string method = null;
            IDictionary<string, object> parameters = null;

            // parse request with culter en-US for safe JSON parsing
            CultureInfo serverCulture = Thread.CurrentThread.CurrentCulture;
            CultureInfo usCulture = new CultureInfo("en-US");
            Thread.CurrentThread.CurrentCulture = usCulture;
            try
            {
                try
                {
                    IDictionary<String, object> jsonRpcData = ReadJsonRpcData(request.InputStream);
                    id = (string)jsonRpcData["id"];
                    method = (string)jsonRpcData["method"];
                    parameters = (IDictionary<string, object>)jsonRpcData["parameters"];
                }
                catch (Exception e)
                {
                    using (StreamWriter sw = new StreamWriter(response.OutputStream))
                    {
                        JsonWriter writer = new JsonWriter(sw);
                        writer.WriteObjectStart();
                        writer.WritePropertyName("id");
                        writer.Write(id);
                        writer.WritePropertyName("result");
                        writer.Write(null);
                        writer.WritePropertyName("error");
                        writer.Write(string.Format("{0}\n{1}", e.Message, e.StackTrace.ToString()));
                        writer.WriteObjectEnd();
                    }
                    response.ContentType = "application/json-rpc";
                    response.StatusCode = 200;
                    response.End();
                    return;
                }
            }
            finally
            {
                Thread.CurrentThread.CurrentCulture = serverCulture;
            }

            Exception error = null;
            Response resp = null;
            try
            {
                resp = ExecuteMethod(method, parameters);
            }
            catch (Exception exception)
            {
                error = exception;
            }

            Thread.CurrentThread.CurrentCulture = usCulture;
            try
            {
                using (StreamWriter sw = new StreamWriter(response.OutputStream))
                {
                    WriteResponse(id, resp, error, sw);
                }
            }
            finally
            {
                Thread.CurrentThread.CurrentCulture = serverCulture;
            }

            response.ContentType = "application/json-rpc";
            response.StatusCode = 200;
            response.End();
        }
Exemplo n.º 58
0
 private static void Float2double(float value, LitJson.JsonWriter jw)
 {
     jw.Write(value);
 }
        private static void serializeCallbackResult(JsonWriter writer, CallbackResult result)
        {
            if (result == null)
            {
                writer.Write(null);
            }
            else
            {
                writer.WriteObjectStart();
                writer.WritePropertyName("type");

                if (result is FlowCallbackResult)
                    writer.Write("flow");
                else if (result is MessageCallbackResult)
                        writer.Write("message");
                    else if (result is FormCallbackResult)
                            writer.Write("form");
                writer.WritePropertyName("value");
                result.Write(writer, false);
                writer.WriteObjectEnd();
            }
        }
        public void LoadWidgets(bool exclude_unless_post)
        {
            Debug.Assert(m_setup_complete, "You must call SetupComplete() before LoadWidgets()");
            if (m_widgets_loaded) return; // already loaded - presumably by SetupComplete()
            m_widgets_loaded = true;

            // make request to backend to get widget HTML
            JsonWriter w = new JsonWriter();

            w.WriteObjectStart();

            w.WritePropertyName("modules");
            w.WriteArrayStart();
            foreach (RemoteWidget wi in m_widgets.Values)
            {
                if (exclude_unless_post && wi.Method == "get") continue;
                wi.DumpJson(w);
            }
            w.WriteArrayEnd(); // modules

            w.WritePropertyName("global");
            w.WriteObjectStart();
            w.WritePropertyName("user");
            w.WriteObjectStart();
            w.WritePropertyName("namespace");
            w.Write(m_user_namespace);
            w.WritePropertyName("user_id");
            w.Write(m_user_id); // placeholder for now until we get shadow accounts working
            w.WritePropertyName("email");
            w.Write(m_user_email);
            w.WritePropertyName("first_name");
            w.Write(m_user_first_name);
            w.WritePropertyName("last_name");
            w.Write(m_user_last_name);
            w.WriteObjectEnd(); // user
            w.WriteObjectEnd(); // global

            w.WriteObjectEnd(); // outer

            string json_request = w.ToString();

            // now post the request to the backend server
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(m_remote_url);
            req.Method = "POST";
            req.ContentType = "application/x-javascript";
            byte[] post_data = Encoding.UTF8.GetBytes(json_request);
            req.ContentLength = post_data.Length;
            Stream post_stream = req.GetRequestStream();
            post_stream.Write(post_data, 0, post_data.Length);
            post_stream.Close();

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            StreamReader resp_stream = new StreamReader(resp.GetResponseStream());
            /*
            while (true)
            {
                string line = resp_stream.ReadLine();
                if (line == null) break;
                Debug.Print("line from response: " + line);
            }
            */
            string raw_data = resp_stream.ReadToEnd();
            resp.Close();
            string error = null;
            try
            {
                JsonData data = JsonMapper.ToObject(raw_data);

                // http request done - now handle the json response
                if (((IDictionary)data).Contains("error"))
                {
                    error = (string)data["error"];
                }
                else
                {
                    JsonData modules = data["modules"];
                    if (!modules.IsArray) error = "JSON server returned non-array for modules.";
                    else foreach (JsonData module in modules)
                    {
                        string module_id = module["id"].ToString();
                        RemoteWidget wi = (RemoteWidget)m_widgets[module_id];
                        wi.LoadFromJson(module);
                    }
                }
            }
            catch (JsonException)
            {
                error = "BAD JSON RESPONSE FROM WIDGET SERVER: " + raw_data;
            }
            if (error != null)
            {
                foreach (RemoteWidget wi in m_widgets.Values)
                {
                    wi.HTML = m_page.Server.HtmlEncode(error);
                }
            }
        }