public void Test_ConditionalNST_Deserialization()
        {
            using (var stream = new MemoryStream())
            {
                var writer = new StreamWriter(stream);
                writer.Write(DESERIALIZATION_TEST_CASE);
                writer.Flush();
                stream.Seek(0, SeekOrigin.Begin);

                var formater = new JSONSerializer();
                var obj = formater.Deserialize(stream);
                Assert.AreEqual(obj, _testCase);
            }
        }
        public void EmotionalAppraisal_Deserialization_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());
                stream.Seek(0, SeekOrigin.Begin);
                var obj = formater.Deserialize(stream);
            }
        }
예제 #3
0
        private void Awake()
        {
            Log.SetLogSource(Logger);
            Harmony.CreateAndPatchAll(typeof(Hooks));

            if (File.Exists(savePath))
            {
                try
                {
                    var json = File.ReadAllText(savePath);
                    data = JSONSerializer.Deserialize <ParamData>(json);
                }
                catch (Exception ex)
                {
                    Log.Error($"Failed to load settings from {savePath} with error: " + ex);
                    data = new ParamData();
                }
            }

            CharacterParam.Init(data.charaParamData);
            SceneParam.Init(data.sceneParamData);
        }
예제 #4
0
        ///Duplicate node alone assigned to the provided graph
        public Node Duplicate(Graph targetGraph)
        {
            if (targetGraph == null)
            {
                Debug.LogError("Can't duplicate a Node without providing a Target Graph");
                return(null);
            }

            //deep clone
            var newNode = JSONSerializer.Deserialize <Node>(JSONSerializer.Serialize(typeof(Node), this));

                        #if UNITY_EDITOR
            if (!Application.isPlaying)
            {
                UnityEditor.Undo.RecordObject(targetGraph, "Duplicate");
            }
                        #endif

            targetGraph.allNodes.Add(newNode);
            newNode.inConnections.Clear();
            newNode.outConnections.Clear();

            if (targetGraph == this.graph)
            {
                newNode.nodePosition += new Vector2(50, 50);
            }

            newNode.graph = targetGraph;
            BBParameter.SetBBFields(newNode, targetGraph.blackboard);

            var assignable = this as ITaskAssignable;
            if (assignable != null && assignable.task != null)
            {
                (newNode as ITaskAssignable).task = assignable.task.Duplicate(targetGraph);
            }

            newNode.OnValidate(targetGraph);
            return(newNode);
        }
예제 #5
0
        private void Awake()
        {
            Logger = base.Logger;
            HarmonyWrapper.PatchAll();

            if (File.Exists(savePath))
            {
                try
                {
                    var json = File.ReadAllText(savePath);
                    data = JSONSerializer.Deserialize <ParamData>(json);
                }
                catch (Exception ex)
                {
                    Logger.Log(LogLevel.Error, $"[DefaultParamEditor] Failed to load settings from {savePath} with error: " + ex);
                    data = new ParamData();
                }
            }

            CharacterParam.Init(data.charaParamData);
            SceneParam.Init(data.sceneParamData);
        }
예제 #6
0
        //...
        private static void LoadPrefs()
        {
            if (data == null)
            {
                var json = EditorPrefs.GetString("ParadoxNotion.ContextBrowserPreferences");
                if (!string.IsNullOrEmpty(json))
                {
                    data = JSONSerializer.Deserialize <SerializationData>(json);
                }
                if (data == null)
                {
                    data = new SerializationData();
                }

                searchMode      = data.searchMode;
                filterFavorites = data.filterFavorites;
                if (!data.allFavorites.TryGetValue(currentKeyType.Name, out favorites))
                {
                    favorites = new List <string>();
                }
            }
        }
예제 #7
0
        private void readTurns(int startAtTurn)
        {
            lock (LOCK) {
                if (startAtTurn < fileTurn)
                {
                    // reset Stream
                    this.stream = File.OpenText(FILE);
                    fileTurn    = 0;
                }
                while (fileTurn + 1 < startAtTurn)
                {
                    // skip lines until read line with turns
                    stream.ReadLine();
                    fileTurn++;
                }
                JSONSerializer serializer = new JSONSerializer();

                int i = 0;
                for (i = 0; i < turns.Length; i++)
                {
                    string line = stream.ReadLine();
                    if (line != null)
                    {
                        Turn turn = serializer.Deserialize(line);
                        turns[i] = turn;
                        fileTurn++;
                    }
                    else
                    {
                        break;
                    }
                }
                for (; i < turns.Length; i++)
                {
                    turns[i] = null;
                }
            }
        }
예제 #8
0
파일: DB.cs 프로젝트: AlexErohin/test_back
        string EditData(string table, Dictionary <string, object> data)
        {
            string code = data["code"] + "";

            string str = GetData(table);

            List <JObject> json = JSONSerializer.Deserialize <List <JObject> >(str);

            int index = json.FindIndex(delegate(JObject b) { return(((JValue)b["code"]).Value + "" == code); });

            if (index == -1)
            {
                return(AddData(table, data));
            }

            json[index] = JObject.FromObject(data);

            string result = JArray.FromObject(json).ToString();

            File.WriteAllText("UserData/" + table + ".json", result);

            return(code);
        }
    public static GoogleAccountInfo getGoogleAccounts()
    {
        //IL_0015: Unknown result type (might be due to invalid IL or missing references)
        //IL_001a: Expected O, but got Unknown
        GoogleAccountInfo result = new GoogleAccountInfo();

        try
        {
            AndroidJavaClass val            = new AndroidJavaClass(Property.BundleIdentifier + ".NetworkHelper");
            string           uniqueDeviceId = getUniqueDeviceId();
            string           message        = val.CallStatic <string>("getGoogleAccounts", new object[1]
            {
                uniqueDeviceId
            });
            result = JSONSerializer.Deserialize <GoogleAccountInfo>(message);
            return(result);
        }
        catch (Exception ex)
        {
            Debug.LogError((object)ex);
            return(result);
        }
    }
예제 #10
0
    public void DoLoadPreset()
    {
#if !UNITY_WEBPLAYER
        var path = EditorUtility.OpenFilePanel("Load Preset", "Assets", "ConditionnedAction");
        if (!string.IsNullOrEmpty(path))
        {
            var json = System.IO.File.ReadAllText(path);
            var list = JSONSerializer.Deserialize <MultipleCondition>(json);

            this.conditionTasks = list.conditionTasks;

            this.conditionTasks.SetOwnerSystem(this.ownerSystem);


            foreach (var c in this.conditionTasks.conditions)
            {
                c.SetOwnerSystem(this.ownerSystem);
            }
        }
#else
        Debug.LogWarning("Preset loading is not possible with WebPlayer as active platform");
#endif
    }
 /// <summary>
 /// 获取可预约阅览室的座位
 /// </summary>
 /// <param name="date"></param>
 /// <param name="schoolNo"></param>
 /// <returns></returns>
 public List <AJM_ReadingRoom> GetBesapeakRoomList(string date, string schoolNo)
 {
     try
     {
         IMobileAppDataObtianProxy appService = new MobileAppDataObtainProxy(schoolNo);
         string           result    = appService.GetCanBespeakRoomInfo(date);
         AJM_HandleResult ajmResult = JSONSerializer.Deserialize <AJM_HandleResult>(result);
         if (ajmResult == null)
         {
             throw new Exception("获取可预约的阅览室列表失败!");
         }
         if (!ajmResult.Result)
         {
             throw new Exception(ajmResult.Msg);
         }
         List <AJM_ReadingRoom> ajmReadingRooms = JSONSerializer.Deserialize <List <AJM_ReadingRoom> >(ajmResult.Msg);
         return(ajmReadingRooms);
     }
     catch (Exception ex)
     {
         WriteLog.Write(string.Format("获取可预约的阅览室列表失败:{0}", ex.Message));
         return(null);
     }
 }
 /// <summary>
 /// 获取阅览室可预约的座位
 /// </summary>
 /// <param name="roomNo">阅览室编号</param>
 /// <param name="bespeakTime"></param>
 /// <returns></returns>
 public List <AJM_BespeakSeat> GetRoomBesapeakSeat(string roomNo, string bespeakTime, string schoolNo)
 {
     try
     {
         IMobileAppDataObtianProxy appService = new MobileAppDataObtainProxy(schoolNo);
         string           result    = appService.GetRoomBesapeakState(roomNo, bespeakTime);
         AJM_HandleResult ajmResult = JSONSerializer.Deserialize <AJM_HandleResult>(result);
         if (ajmResult == null)
         {
             throw new Exception("获取阅览室的可预约座位失败!");
         }
         if (!ajmResult.Result)
         {
             throw new Exception(ajmResult.Msg);
         }
         List <AJM_BespeakSeat> ajmBespeakSeats = JSONSerializer.Deserialize <List <AJM_BespeakSeat> >(ajmResult.Msg);
         return(ajmBespeakSeats);
     }
     catch (Exception ex)
     {
         WriteLog.Write(string.Format("获取阅览室的可预约座位失败:{0}", ex.Message));
         throw ex;
     }
 }
 /// <summary>
 /// 获取阅览室布局图
 /// </summary>
 /// <param name="roomNo">阅览室编号</param>
 /// <param name="schoolNo"></param>
 /// <returns></returns>
 public AJM_SeatLayout GetRoomSeatLayout(string roomNo, string schoolNo)
 {
     try
     {
         IMobileAppDataObtianProxy appService = new MobileAppDataObtainProxy(schoolNo);
         string           result    = appService.GetRoomSeatLayout(roomNo);
         AJM_HandleResult ajmResult = JSONSerializer.Deserialize <AJM_HandleResult>(result);
         if (ajmResult == null)
         {
             throw new Exception("获取全部阅览室的当前的使用状态失败!");
         }
         if (!ajmResult.Result)
         {
             throw new Exception(ajmResult.Msg);
         }
         AJM_SeatLayout ajmSeatLayout = JSONSerializer.Deserialize <AJM_SeatLayout>(ajmResult.Msg);
         return(ajmSeatLayout);
     }
     catch (Exception ex)
     {
         WriteLog.Write(string.Format("获取全部阅览室的当前的使用状态失败:{0}", ex.Message));
         return(null);
     }
 }
 // <summary>
 /// 扫描座位二维码
 /// </summary>
 /// <param name="codeStr">扫描后的二维码</param>
 /// <returns></returns>
 public AJM_SeatStatus QRcodeSeatInfo(string codeStr, string schoolNo)
 {
     try
     {
         IMobileAppDataObtianProxy appService = new MobileAppDataObtainProxy(schoolNo);
         string           result    = appService.QRcodeSeatInfo(codeStr);
         AJM_HandleResult ajmResult = JSONSerializer.Deserialize <AJM_HandleResult>(result);
         if (ajmResult == null)
         {
             throw new Exception("扫描座位二维码失败!");
         }
         if (!ajmResult.Result)
         {
             throw new Exception(ajmResult.Msg);
         }
         AJM_SeatStatus ajmSeatStatus = JSONSerializer.Deserialize <AJM_SeatStatus>(ajmResult.Msg);
         return(ajmSeatStatus);
     }
     catch (Exception ex)
     {
         WriteLog.Write(string.Format("扫描座位二维码失败:{0}", ex.Message));
         return(null);
     }
 }
 /// <summary>
 /// 获取座位预约的信息
 /// </summary>
 /// <param name="seatNo"></param>
 /// <param name="roomNo"></param>
 /// <param name="bespeakTime"></param>
 /// <param name="schoolNo"></param>
 /// <returns></returns>
 public AJM_SeatBespeakInfo GetSeatBespeakInfo(string seatNo, string roomNo, string bespeakTime, string schoolNo)
 {
     try
     {
         IMobileAppDataObtianProxy appService = new MobileAppDataObtainProxy(schoolNo);
         string           result    = appService.GetRandomSeat(roomNo);
         AJM_HandleResult ajmResult = JSONSerializer.Deserialize <AJM_HandleResult>(result);
         if (ajmResult == null)
         {
             throw new Exception("获取预约座位信息失败!");
         }
         if (!ajmResult.Result)
         {
             throw new Exception(ajmResult.Msg);
         }
         AJM_SeatBespeakInfo ajmSeat = JSONSerializer.Deserialize <AJM_SeatBespeakInfo>(ajmResult.Msg);
         return(ajmSeat);
     }
     catch (Exception ex)
     {
         WriteLog.Write(string.Format("获取预约座位信息失败:{0}", ex.Message));
         return(null);
     }
 }
 /// <summary>
 /// 获取常用座位
 /// </summary>
 /// <param name="studentNo">学号</param>
 /// <param name="seatCount">获取的座位数目</param>
 /// <param name="dayCount">统计的天数</param>
 /// <returns></returns>
 public List <AJM_Seat> GetOftenSeat(string studentNo, int seatCount, int dayCount, string schoolNo)
 {
     try
     {
         IMobileAppDataObtianProxy appService = new MobileAppDataObtainProxy(schoolNo);
         string           result    = appService.GetOftenSeat(studentNo, seatCount, dayCount);
         AJM_HandleResult ajmResult = JSONSerializer.Deserialize <AJM_HandleResult>(result);
         if (ajmResult == null)
         {
             throw new Exception("获取常坐座位失败!");
         }
         if (!ajmResult.Result)
         {
             throw new Exception(ajmResult.Msg);
         }
         List <AJM_Seat> ajmSeats = JSONSerializer.Deserialize <List <AJM_Seat> >(ajmResult.Msg);
         return(ajmSeats);
     }
     catch (Exception ex)
     {
         WriteLog.Write(string.Format("获取常坐座位失败:{0}", ex.Message));
         return(null);
     }
 }
 /// <summary>
 /// 获取单个阅览室开闭状态
 /// </summary>
 /// <param name="roomNo"></param>
 /// <param name="datetime"></param>
 /// <param name="schoolNo"></param>
 /// <returns></returns>
 public AJM_ReadingRoomState GetSingleRoomOpenState(string roomNo, string datetime, string schoolNo)
 {
     try
     {
         IMobileAppDataObtianProxy appService = new MobileAppDataObtainProxy(schoolNo);
         string           result    = appService.GetAllRoomNowState();
         AJM_HandleResult ajmResult = JSONSerializer.Deserialize <AJM_HandleResult>(result);
         if (ajmResult == null)
         {
             throw new Exception("获取单个阅览室的当前的开闭状态失败!");
         }
         if (!ajmResult.Result)
         {
             throw new Exception(ajmResult.Msg);
         }
         AJM_ReadingRoomState ajmReadingRoomState = JSONSerializer.Deserialize <AJM_ReadingRoomState>(ajmResult.Msg);
         return(ajmReadingRoomState);
     }
     catch (Exception ex)
     {
         WriteLog.Write(string.Format("获取单个阅览室的当前的开闭状态失败:{0}", ex.Message));
         return(null);
     }
 }
 /// <summary>
 /// 获取全部阅览室的当前的使用状态(在座人数,是否开馆等)
 /// </summary>
 /// <returns></returns>
 public List <AJM_ReadingRoomState> GetAllRoomNowState(string schoolNo)
 {
     try
     {
         IMobileAppDataObtianProxy appService = new MobileAppDataObtainProxy(schoolNo);
         string           result    = appService.GetAllRoomNowState();
         AJM_HandleResult ajmResult = JSONSerializer.Deserialize <AJM_HandleResult>(result);
         if (ajmResult == null)
         {
             throw new Exception("获取全部阅览室的当前的使用状态失败!");
         }
         if (!ajmResult.Result)
         {
             throw new Exception(ajmResult.Msg);
         }
         List <AJM_ReadingRoomState> ajmReadingRoomStates = JSONSerializer.Deserialize <List <AJM_ReadingRoomState> >(ajmResult.Msg);
         return(ajmReadingRoomStates);
     }
     catch (Exception ex)
     {
         WriteLog.Write(string.Format("获取全部阅览室的当前的使用状态失败:{0}", ex.Message));
         return(null);
     }
 }
예제 #19
0
        public static void LoadData()
        {
            var dataPath = Path.Combine(Paths.ConfigPath, dataFileName);

            if (File.Exists(dataPath))
            {
                try
                {
                    var json = File.ReadAllText(dataPath);
                    data = JSONSerializer.Deserialize <TargetData>(json);
                    Log.Info("Loading custom target data.");
                }
                catch (Exception ex)
                {
                    Log.Info($"Failed to deserialize custom target data. Loading default target data.\n{ex}");
                    LoadResourceData();
                }
            }
            else
            {
                Log.Debug("Loading default target data.");
                LoadResourceData();
            }
        }
 /// <summary>
 /// 获取读者信息
 /// </summary>
 /// <param name="cardNo"></param>
 /// <param name="schoolNo"></param>
 /// <returns></returns>
 public AJM_Reader GetReaderInfo(string cardNo, string schoolNo)
 {
     try
     {
         IMobileAppDataObtianProxy appService = new MobileAppDataObtainProxy(schoolNo);
         string           result    = appService.GetUserInfo(cardNo);
         AJM_HandleResult ajmResult = JSONSerializer.Deserialize <AJM_HandleResult>(result);
         if (ajmResult == null)
         {
             throw new Exception("获取读者信息失败!");
         }
         if (!ajmResult.Result)
         {
             throw new Exception(ajmResult.Msg);
         }
         AJM_Reader ajm_reader = JSONSerializer.Deserialize <AJM_Reader>(ajmResult.Msg);
         return(ajm_reader);
     }
     catch (Exception ex)
     {
         WriteLog.Write("获取读者信息失败:" + ex.Message);
         return(null);
     }
 }
예제 #21
0
        public bool Deserialize(string json, List <UnityEngine.Object> storedObjectReferences, bool removeMissing = true)
        {
            var bb = JSONSerializer.Deserialize <BlackboardSource>(json, storedObjectReferences);

            if (bb == null)
            {
                return(false);
            }

            foreach (var pair in bb.variables)
            {
                if (_blackboard.variables.ContainsKey(pair.Key))
                {
                    _blackboard.SetValue(pair.Key, pair.Value.value);
                }
                else
                {
                    _blackboard.variables[pair.Key] = pair.Value;
                }
            }

            if (removeMissing)
            {
                var keys = new List <string>(_blackboard.variables.Keys);
                foreach (string key in keys)
                {
                    if (!bb.variables.ContainsKey(key))
                    {
                        _blackboard.variables.Remove(key);
                    }
                }
            }

            _blackboard.InitializePropertiesBinding(propertiesBindTarget, true);
            return(true);
        }
 /// <summary>
 /// 获取读者信息
 /// </summary>
 /// <param name="loginId"></param>
 /// <param name="password"></param>
 /// <param name="schoolNo"></param>
 /// <returns></returns>
 public AJM_Reader CheckReader(string loginId, string password, string schoolNo)
 {
     try
     {
         IMobileAppDataObtianProxy appService = new MobileAppDataObtainProxy(schoolNo);
         string           result    = appService.CheckUser(loginId, password);
         AJM_HandleResult ajmResult = JSONSerializer.Deserialize <AJM_HandleResult>(result);
         if (ajmResult == null)
         {
             throw new Exception("验证读者信息失败!");
         }
         if (!ajmResult.Result)
         {
             ajmResult = null;
             throw new Exception(ajmResult.Msg);
         }
         result    = appService.GetUserInfo(loginId);
         ajmResult = JSONSerializer.Deserialize <AJM_HandleResult>(result);
         if (ajmResult == null)
         {
             throw new Exception("验证读者信息失败!");
         }
         if (!ajmResult.Result)
         {
             ajmResult = null;
             throw new Exception(ajmResult.Msg);
         }
         AJM_Reader ajmReader = JSONSerializer.Deserialize <AJM_Reader>(ajmResult.Msg);
         return(ajmReader);
     }
     catch (Exception ex)
     {
         WriteLog.Write("验证读者信息失败:" + ex.Message);
         return(null);
     }
 }
예제 #23
0
 /// <summary>
 /// 获取黑名单记录
 /// </summary>
 /// <param name="studentNo">用户学号</param>
 /// <param name="pageIndex">页编码</param>
 /// <param name="pageSize">每页数目</param>
 /// <param name="schoolNo"></param>
 /// <returns></returns>
 public List <AJM_BlacklistLog> GetBlacklist(string studentNo, int pageIndex, int pageSize, string schoolNo)
 {
     try
     {
         IMobileAppDataObtianProxy appService = new MobileAppDataObtainProxy(schoolNo);
         string           result    = appService.GetBlacklist(studentNo, pageIndex, pageSize);
         AJM_HandleResult ajmResult = JSONSerializer.Deserialize <AJM_HandleResult>(result);
         if (ajmResult == null)
         {
             throw new Exception("获取黑名单记录失败!");
         }
         if (!ajmResult.Result)
         {
             throw new Exception(ajmResult.Msg);
         }
         List <AJM_BlacklistLog> ajmBlacklistLogs = JSONSerializer.Deserialize <List <AJM_BlacklistLog> >(ajmResult.Msg);
         return(ajmBlacklistLogs);
     }
     catch (Exception ex)
     {
         WriteLog.Write(string.Format("获取黑名单记录失败:{0}", ex.Message));
         return(null);
     }
 }
    public static TutorialReadData CreateAndLoad()
    {
        SaveData saveData = null;

        if (HasSave())
        {
            string @string = PlayerPrefs.GetString("TutorialProgress");
            saveData = JSONSerializer.Deserialize <SaveData>(@string);
            if (saveData == null)
            {
                Log.Error("JSONSerializer.Deserialize<TutorialReadData.SaveData> {0}", @string);
                return(null);
            }
        }
        else
        {
            saveData = new SaveData();
        }
        TutorialReadData tutorialReadData = new TutorialReadData();

        tutorialReadData.LoadSaveData();
        tutorialReadData.UpdateReadAllFlag();
        return(tutorialReadData);
    }
            private bool ParseReleaseInformation(string data)
            {
                bool ret = false;

                try
                {
                    GitHubReleaseJsonContract ghrjc = JSONSerializer.Deserialize <GitHubReleaseJsonContract>(data);
                    if (ghrjc != null)
                    {
                        if (!string.IsNullOrEmpty(ghrjc.tag_name))
                        {
                            this.LatestVersion = ghrjc.tag_name;
                        }
                        if (ghrjc.assets_info != null)
                        {
                            if (ghrjc.assets_info[0] != null)
                            {
                                if (!string.IsNullOrEmpty(ghrjc.assets_info[0].browser_download_url))
                                {
                                    this.LatestVersionUrl = ghrjc.assets_info[0].browser_download_url;
                                }
                            }
                        }
                        ret = ((this.LatestVersion != "") && (this.LatestVersionUrl != ""));
                    }
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine("GithubReleaseParser::GetReleaseInformation:: error - {0}", e.Message);
                    Console.Error.WriteLine(e.ToString());
                    data = "";
                    ret  = false;
                }

                return(ret);
            }
예제 #26
0
        public static void LoadData()
        {
            var dataPath = Path.Combine(Paths.ConfigPath, dataFileName);

            if (File.Exists(dataPath))
            {
                try
                {
                    var json = File.ReadAllText(dataPath);
                    data = JSONSerializer.Deserialize <TargetData>(json);
                    LockOnPluginCore.Logger.Log(LogLevel.Info, "Loading custom target data.");
                }
                catch (Exception)
                {
                    LockOnPluginCore.Logger.Log(LogLevel.Info, "Failed to deserialize custom target data. Loading default target data.");
                    LoadResourceData();
                }
            }
            else
            {
                LockOnPluginCore.Logger.Log(LogLevel.Debug, "Loading default target data.");
                LoadResourceData();
            }
        }
 /// <summary>
 /// 获取登录读者详细信息
 /// </summary>
 /// <param name="studentNo"></param>
 /// <param name="schoolNo"></param>
 /// <returns></returns>
 public AJM_WeiXinUserInfo GetUserInfo_WeiXin(string studentNo, string schoolNo)
 {
     try
     {
         IMobileAppDataObtianProxy appService = new MobileAppDataObtainProxy(schoolNo);
         string           result    = appService.GetUserInfo_WeiXin(studentNo);
         AJM_HandleResult ajmResult = JSONSerializer.Deserialize <AJM_HandleResult>(result);
         if (ajmResult == null)
         {
             throw new Exception("获取登录读者详细信息失败!");
         }
         if (!ajmResult.Result)
         {
             throw new Exception(ajmResult.Msg);
         }
         AJM_WeiXinUserInfo ajmWeiXinUserInfo = JSONSerializer.Deserialize <AJM_WeiXinUserInfo>(ajmResult.Msg);
         return(ajmWeiXinUserInfo);
     }
     catch (Exception ex)
     {
         WriteLog.Write("获取登录读者详细信息失败:" + ex.Message);
         return(null);
     }
 }
예제 #28
0
        private static void LoadResourceData()
        {
            var json = Resource.GetResourceAsString(typeof(LockOnPluginCore).Assembly, dataFileName);

            data = JSONSerializer.Deserialize <TargetData>(json);
        }
예제 #29
0
        void OnGUI()
        {
            GUI.skin.label.richText = true;
            EditorGUILayout.HelpBox("Here you can specify frequently used types for your project and for easier access wherever you need to select a type, like for example when you create a new blackboard variable or using any refelection based actions.\nFurthermore, it is essential when working with AOT platforms like iOS or WebGL, that you generate an AOT Classes and link.xml files with the relevant button bellow.\nTo add types in the list quicker, you can also Drag&Drop an object, or a Script file in this editor window.", MessageType.Info);

            if (GUILayout.Button("Add New Type"))
            {
                GenericMenu.MenuFunction2 Selected = delegate(object o){
                    if (o is System.Type)
                    {
                        AddType((System.Type)o);
                    }
                    if (o is string)                      //namespace
                    {
                        foreach (var type in alltypes)
                        {
                            if (type.Namespace == (string)o)
                            {
                                AddType(type);
                            }
                        }
                    }
                };

                var menu       = new GenericMenu();
                var Namespaces = new List <string>();
                menu.AddItem(new GUIContent("Classes/System/Object"), false, Selected, typeof(object));
                foreach (var t in alltypes)
                {
                    var friendlyName = (string.IsNullOrEmpty(t.Namespace)? "No namespace/" : t.Namespace.Replace(".", "/") + "/") + t.FriendlyName();
                    var category     = "Classes/";
                    if (t.IsValueType)
                    {
                        category = "Structs/";
                    }
                    if (t.IsInterface)
                    {
                        category = "Interfaces/";
                    }
                    if (t.IsEnum)
                    {
                        category = "Enumerations/";
                    }
                    var icon = UserTypePrefs.GetTypeIcon(t);
                    menu.AddItem(new GUIContent(category + friendlyName, icon), typeList.Contains(t), Selected, t);
                    if (t.Namespace != null && !Namespaces.Contains(t.Namespace))
                    {
                        Namespaces.Add(t.Namespace);
                    }
                }

                menu.AddSeparator("/");
                foreach (var ns in Namespaces)
                {
                    var path = "Whole Namespaces/" + ns.Replace(".", "/") + "/Add " + ns;
                    menu.AddItem(new GUIContent(path), false, Selected, ns);
                }

                menu.ShowAsBrowser("Add Preferred Type");
            }


            if (GUILayout.Button("Generate AOTClasses.cs and link.xml Files"))
            {
                if (EditorUtility.DisplayDialog("Generate AOT Classes", "A script relevant to AOT compatibility for certain platforms will now be generated.", "OK"))
                {
                    var path = EditorUtility.SaveFilePanelInProject("AOT Classes File", "AOTClasses", "cs", "");
                    if (!string.IsNullOrEmpty(path))
                    {
                        AOTClassesGenerator.GenerateAOTClasses(path, UserTypePrefs.GetPreferedTypesList(typeof(object), true).ToArray());
                    }
                }

                if (EditorUtility.DisplayDialog("Generate link.xml File", "A file relevant to 'code stripping' for platforms that have code stripping enabled will now be generated.", "OK"))
                {
                    var path = EditorUtility.SaveFilePanelInProject("AOT link.xml", "link", "xml", "");
                    if (!string.IsNullOrEmpty(path))
                    {
                        AOTClassesGenerator.GenerateLinkXML(path, UserTypePrefs.GetPreferedTypesList(typeof(object)).ToArray());
                    }
                }

                AssetDatabase.Refresh();
            }

            GUILayout.BeginHorizontal();

            if (GUILayout.Button("RESET DEFAULTS"))
            {
                if (EditorUtility.DisplayDialog("Reset Preferred Types", "Are you sure?", "Yes", "NO!"))
                {
                    UserTypePrefs.ResetTypeConfiguration();
                    typeList = UserTypePrefs.GetPreferedTypesList(typeof(object));
                    Save();
                }
            }

            if (GUILayout.Button("Save Preset"))
            {
                var path = EditorUtility.SaveFilePanelInProject("Save Types Preset", "", "typePrefs", "");
                if (!string.IsNullOrEmpty(path))
                {
                    System.IO.File.WriteAllText(path, JSONSerializer.Serialize(typeof(List <System.Type>), typeList, true));
                    AssetDatabase.Refresh();
                }
            }

            if (GUILayout.Button("Load Preset"))
            {
                var path = EditorUtility.OpenFilePanel("Load Types Preset", "Assets", "typePrefs");
                if (!string.IsNullOrEmpty(path))
                {
                    var json = System.IO.File.ReadAllText(path);
                    typeList = JSONSerializer.Deserialize <List <System.Type> >(json);
                    Save();
                }
            }

            GUILayout.EndHorizontal();
            GUILayout.Space(5);

            scrollPos = GUILayout.BeginScrollView(scrollPos);
            for (int i = 0; i < typeList.Count; i++)
            {
                GUILayout.BeginHorizontal("box");
                var type = typeList[i];
                if (type == null)
                {
                    GUILayout.Label("MISSING TYPE", GUILayout.Width(300));
                    GUILayout.Label("---");
                }
                else
                {
                    var name  = type.FriendlyName();
                    var icon  = UserTypePrefs.GetTypeIcon(type);
                    var color = icon != null && icon.name == UserTypePrefs.DEFAULT_TYPE_ICON_NAME? UserTypePrefs.GetTypeColor(type) : Color.white;
                    GUI.color = color;
                    GUILayout.Label(icon, GUILayout.Width(16), GUILayout.Height(16));
                    GUI.color = Color.white;
                    GUILayout.Label(name, GUILayout.Width(300));
                    GUILayout.Label(type.Namespace);
                }
                if (GUILayout.Button("X", GUILayout.Width(18)))
                {
                    RemoveType(type);
                }
                GUILayout.EndHorizontal();
            }
            GUILayout.EndScrollView();

            AcceptDrops();
            Repaint();
        }
예제 #30
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>
        /// Retrieves an oAuth authentication token to be used on the translate
        /// API request. The result string needs to be passed as a bearer token
        /// to the translate API.
        /// 
        /// You can find client ID and Secret (or register a new one) at:
        /// https://datamarket.azure.com/developer/applications/
        /// </summary>
        /// <param name="clientId">The client ID of your application</param>
        /// <param name="clientSecret">The client secret or password</param>
        /// <returns></returns>
        public string GetBingAuthToken(string clientId = null, string clientSecret = null)
        {
            string authBaseUrl = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";

            if (string.IsNullOrEmpty(clientId))
                clientId = DbResourceConfiguration.Current.BingClientId;
            if (string.IsNullOrEmpty(clientSecret))
                clientSecret = DbResourceConfiguration.Current.BingClientSecret;

            if (string.IsNullOrEmpty(clientId) || string.IsNullOrEmpty(clientSecret))
            {
                ErrorMessage = Resources.Resources.Client_Id_and_Client_Secret_must_be_provided;
                return null;
            }
            
            var postData = string.Format("grant_type=client_credentials&client_id={0}" +
                                         "&client_secret={1}" +
                                         "&scope=http://api.microsofttranslator.com",
                                         HttpUtility.UrlEncode(clientId),
                                         HttpUtility.UrlEncode(clientSecret));

            // POST Auth data to the oauth API
            string res, token;

            try
            {
                var web = new WebClient();
                web.Encoding = Encoding.UTF8;
                res = web.UploadString(authBaseUrl, postData);
            }
            catch (Exception ex)
            {
                ErrorMessage = ex.GetBaseException().Message;
                return null;
            }

            var ser = new JSONSerializer();
            var auth = ser.Deserialize<BingAuth>(res);
            if (auth == null)
                return null;
            
            token = auth.access_token;

            return token;
        }
        /// <summary>
        /// Executes the requested method. 
        /// to the proper types for execution.
        /// </summary>
        /// <param name="Method"></param>
        /// <param name="methodParameters">An array of the string json parameters to </param>
        /// <param name="target">The object to call the method on</param>
        /// <param name="parameters">An array of json Strings that make up the parameters for the method call. This value can be null in which case parms are parsed out of GET QueryString or POST values</param>
        /// <param name="callbackMethodAttribute">An optional instance of an CallbackAttribute that is set by this method</param>
        /// <returns>the result of the method execution</returns>
        internal object ExecuteMethod(string method, object target, string[] parameters,
                                      CallbackMethodParameterType paramType,
                                      ref CallbackMethodAttribute callbackMethodAttribute)
        {
            HttpRequest Request = HttpContext.Current.Request;
            HttpResponse Response = HttpContext.Current.Response;

            object Result = null;

            // Stores parsed parameters (from string JSON or QUeryString Values)
            object[] adjustedParms = null;

            Type PageType = target.GetType();
            MethodInfo MI = PageType.GetMethod(method, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            if (MI == null)
                throw new InvalidOperationException();

            object[] methods = MI.GetCustomAttributes(typeof(CallbackMethodAttribute), false);
            if (methods.Length < 1)
                throw new InvalidOperationException();

            if (callbackMethodAttribute != null)
                callbackMethodAttribute = methods[0] as CallbackMethodAttribute;

            // Check for supported HTTP Verbs
            if (callbackMethodAttribute.AllowedHttpVerbs != HttpVerbs.All &&
                !string.IsNullOrEmpty(Request.HttpMethod))
            {
                HttpVerbs val = HttpVerbs.None;
                Enum.TryParse<HttpVerbs>(Request.HttpMethod, out val);
                if (val == HttpVerbs.None || !callbackMethodAttribute.AllowedHttpVerbs.HasFlag(val))
                {
                    Response.StatusCode = (int)HttpStatusCode.MethodNotAllowed;
                    Response.StatusDescription = string.Format("NotAllowedMethodExpectsVerb");
                    throw new UnauthorizedAccessException(Response.StatusDescription);
                }
            }

            ParameterInfo[] parms = MI.GetParameters();

            JSONSerializer serializer = new JSONSerializer();

            RouteData routeData = null;
            if (target is CallbackHandler)
                routeData = ((CallbackHandler)target).RouteData;

            int parmCounter = 0;
            adjustedParms = new object[parms.Length];
            foreach (ParameterInfo parameter in parms)
            {
                // Retrieve parameters out of QueryString or POST buffer
                if (parameters == null)
                {
                    // look for parameters in the route
                    if (routeData != null)
                    {
                        string parmString = routeData.Values[parameter.Name] as string;
                        adjustedParms[parmCounter] = ReflectionUtils.StringToTypedValue(parmString, parameter.ParameterType);
                    }
                    // GET parameter are parsed as plain string values - no JSON encoding
                    else if (HttpContext.Current.Request.HttpMethod == "GET")
                    {
                        // Look up the parameter by name
                        string parmString = Request.QueryString[parameter.Name];
                        adjustedParms[parmCounter] = ReflectionUtils.StringToTypedValue(parmString, parameter.ParameterType);
                    }
                    // POST parameters are treated as methodParameters that are JSON encoded
                    else
                        if (paramType == CallbackMethodParameterType.Json)
                            //string newVariable = methodParameters.GetValue(parmCounter) as string;
                            adjustedParms[parmCounter] = serializer.Deserialize(Request.Params["parm" + (parmCounter + 1).ToString()], parameter.ParameterType);
                        else
                            adjustedParms[parmCounter] = SerializationUtils.DeSerializeObject(
                                Request.Params["parm" + (parmCounter + 1).ToString()],
                                parameter.ParameterType);
                }
                else
                    if (paramType == CallbackMethodParameterType.Json)
                        adjustedParms[parmCounter] = serializer.Deserialize(parameters[parmCounter], parameter.ParameterType);
                    else
                        adjustedParms[parmCounter] = SerializationUtils.DeSerializeObject(parameters[parmCounter], parameter.ParameterType);

                parmCounter++;
            }

            Result = MI.Invoke(target, adjustedParms);

            return Result;
        }
예제 #33
0
 public new static CandleRequest Deserialize(string serialized)
 {
     return(JSONSerializer.Deserialize <CandleRequest>(serialized));
 }
예제 #34
0
        internal async Task <T> Request <T>(HttpRequestMessage httpRequest, bool isFileDownload = false, bool returnAsString = false) where T : new()
        {
            // for retry in case of failure.
            var requestCopy = CreateHttpRequest(httpRequest.RequestUri.OriginalString, httpRequest.Method, true, isFileDownload);
            await Utility.CopyHttpRequestMessageContent(httpRequest, requestCopy);

            var response = await HttpClient.SendAsync(httpRequest);

            // Get rate limits from header values
            if (response.Headers.Contains("X-Rate-Limit-Remaining"))
            {
                RateLimitRemaining = int.Parse(response.Headers.GetValues("X-Rate-Limit-Remaining").First());
            }
            if (response.Headers.Contains("X-Rate-Limit-Limit"))
            {
                RateLimit = int.Parse(response.Headers.GetValues("X-Rate-Limit-Limit").First());
            }

            if (response.IsSuccessStatusCode)
            {
                if (isFileDownload)
                {
                    var fileResponse = new FileResponse();
                    fileResponse.FileContents = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);

                    fileResponse.ContentType   = response.Content.Headers.ContentType.ToString();
                    fileResponse.ContentLength = response.Content.Headers.ContentLength ?? 0;

                    return(fileResponse.ChangeType <T>());
                }
                else
                {
                    if (response.StatusCode == HttpStatusCode.NoContent)
                    {
                        return(default(T));
                    }

                    var responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                    if (returnAsString)
                    {
                        var stringResponse = new StringResponse {
                            Data = responseBody
                        };
                        return(stringResponse.ChangeType <T>());
                    }

                    return(JSONSerializer.Deserialize <T>(responseBody));
                }
            }
            else
            {
                var responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                var podioError = JSONSerializer.Deserialize <PodioError>(responseBody);

                if (response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    // If RefreshToken exists, refresh the access token and try the request again
                    if (OAuth is PodioOAuth podioOAuth && !string.IsNullOrEmpty(podioOAuth.RefreshToken) && podioError.ErrorDescription == "expired_token" || podioError.Error == "invalid_token")
                    {
                        var authInfo = await RefreshAccessToken().ConfigureAwait(false);

                        if (authInfo != null && !string.IsNullOrEmpty(authInfo.AccessToken))
                        {
                            requestCopy.Headers.Authorization = new AuthenticationHeaderValue("OAuth2", authInfo.AccessToken);
                            return(await Request <T>(requestCopy, isFileDownload, returnAsString));
                        }
                    }
                    else
                    {
                        OAuth = null;
                        throw new PodioAuthorizationException((int)response.StatusCode, podioError);
                    }
                }
예제 #35
0
파일: Chat.xaml.cs 프로젝트: jcteague/dtt
        public void ChatMessageArrived(string channel, string payload)
        {
            if (channel == currentChannel)
            {
                logger.TryOrLog(() => {
                    ISerializeJSON jsonSerializer = new JSONSerializer();
                    var chatMessageModel = jsonSerializer.Deserialize<ChatMessageModel>(payload);
                        
                    if(userProvider.GetUser().id == Convert.ToInt32(chatMessageModel.user_id) && chatMessageModel.chatMessageBody.source=="vs plugin") return;

                    var receivedMessage = chatRoomControlService.AddReceivedMessage(GetChatUIElements(), messageScroll, payload);

                    var activeWindow = GetForegroundWindow();
                    var mainWindowHandle = (IntPtr)dteStore.dte.MainWindow.HWnd;
                    if ((Convert.ToInt32(receivedMessage.user_id) != userProvider.GetUser().id) && (activeWindow != mainWindowHandle))
                    {
                        taskbarNotifierWindow.Dispatcher.Invoke(new Action(() =>{
                            if ((bool) (!chkMute.IsChecked))
                                System.Media.SystemSounds.Beep.Play();
                            var msg = (receivedMessage.chatMessageBody.message.Length > 8)?receivedMessage.chatMessageBody.message.Remove(8)+"...":receivedMessage.chatMessageBody.message;
                            taskbarNotifierWindow.NotifyContent.Clear();
                            taskbarNotifierWindow.Show();
                            taskbarNotifierWindow.NotifyContent.Add(new NotifyObject(msg, receivedMessage.name+" says:"));
                            taskbarNotifierWindow.Notify();
                        }));
                    }
                });
            }
        }
예제 #36
0
 /// <summary>
 /// Sets key values after we serialize
 /// </summary>
 public void OnAfterDeserialize()
 {
     _ValueType = (mSerializedType.Length == 0 ? null : Type.GetType(mSerializedType));
     _Value     = (mSerializedValue.Length == 0 ? null : JSONSerializer.Deserialize(mSerializedValue));
 }
예제 #37
0
        /// <summary>
        /// Parses a single object value from the Request input stream into the
        /// specified type
        /// </summary>
        /// <param name="dataType"></param>
        /// <returns></returns>
        protected internal object ParseObjectFromPostData(Type dataType)
        {
            StreamReader sr = new StreamReader(Request.InputStream);
            string data = sr.ReadToEnd();
            sr.Close();

            object result = null;

            if (Request.ContentType == "text/javascript" || Request.ContentType == "application/json")
            {
                JSONSerializer ser = new JSONSerializer(SupportedJsonParserTypes.WestWindJsonSerializer);
                result = ser.Deserialize(data, dataType);
            }
            else if (Request.ContentType == "text/xml")
            {
                result = SerializationUtils.DeSerializeObject(data, dataType);
            }
            else
                return ExceptionResult("Unsuppported data input format. Please provide input content-type as text/javascript, application/json or text/xml.");

            return result;
        }