Example #1
0
        public object Convert(int operation, string packet)
        {
            object _packet = null;

            CharacterOperation key = (CharacterOperation)operation;

            JsonReaderSettings settings = new JsonReaderSettings();
            settings.AddTypeConverter (new VectorConverter());
            settings.AddTypeConverter (new QuaternionConverter());

            JsonReader jsonReader = new JsonReader(packet, settings);

            switch(key)
            {
                case CharacterOperation.GROUNDCLICK:
                    _packet = jsonReader.Deserialize<GroundClick>();
                    break;
                case CharacterOperation.INSTANTIATE:
                    _packet = jsonReader.Deserialize<InstantiateChar>();
                    break;
                case CharacterOperation.DESTROY:
                    _packet = jsonReader.Deserialize<DestroyChar>();
                    break;
                default:
                    break;
            }

            return _packet;
        }
Example #2
0
        public object Convert(int operation, string packet)
        {
            object _packet = null;
            UserOperation userOperation = (UserOperation)operation;

            JsonReader jsonReader = new JsonReader(packet);

            switch(userOperation)
            {
                case UserOperation.LOGIN:
                    _packet = jsonReader.Deserialize<LoginReply>();
                    break;
                case UserOperation.REGISTER:
                    _packet = jsonReader.Deserialize<RegisterReply>();
                    break;
                case UserOperation.CHARSELECT:
                case UserOperation.CREATECHAR:
                case UserOperation.DELETECHAR:
                case UserOperation.SELECTCHAR:
                    _packet = jsonReader.Deserialize<CharSelectPacket>();
                    break;
                default:
                    break;
            }

            return _packet;
        }
Example #3
0
        public string CreateJob(string jsondata)
        {
            var newjob = new WorkerJob();

            newjob.ID = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10);

            var jr = new JsonReader(jsondata);
            var jo = jr.Deserialize() as Dictionary<string, object>;

            if (jo.ContainsKey("callback"))
                newjob.CallbackUrl = jo["callback"].ToString();

            if (jo.ContainsKey("jobtype"))
                newjob.JobType = jo["jobtype"].ToString();

            // parse args...
            if (jo.ContainsKey("jobargs"))
                Utilities.FillArgsFromJson(newjob.JobArgs, jo["jobargs"]);

            newjob.MyUrl = "http://" + _worker.Config.Hostname + ":" + _worker.Config.Port;

            Console.WriteLine("WorkerJobController: Created job #" + newjob.ID + " with callback url " + newjob.CallbackUrl);

            m_jobs.Add(newjob);
            return newjob.ID;
        }
 public PresetData Load(string fileName) {
     // ファイル読み込み
     try {
         using (FileStream fs = File.OpenRead(fileName))  {
             var reader = new JsonFx.Json.JsonReader(fs);
             return (PresetData)reader.Deserialize(typeof(PresetData));
         }
     } catch(Exception e) {
         LogUtil.Log("ACCプリセットの読み込みに失敗しました", e);
         return null;
     }
 }
Example #5
0
    /// <summary>
    ///
    /// </summary>
    /// <param name="rawResponse"></param>
    /// <returns></returns>
    public static MatchIDList fromJSON(object rawResponse)
    {
        if (rawResponse is String)
        {
            String json = (String)rawResponse;
            JsonFx.Json.JsonReader reader = JSONUtils.getJsonReader(json);
            long[] matchArray             = reader.Deserialize <long[]>();

            return(new MatchIDList(new List <long>(matchArray)));
        }

        return(new MatchIDList());
    }
Example #6
0
 public PresetData Load(string fileName)
 {
     // ファイル読み込み
     try {
         using (FileStream fs = File.OpenRead(fileName))  {
             var reader = new JsonFx.Json.JsonReader(fs);
             return((PresetData)reader.Deserialize(typeof(PresetData)));
         }
     } catch (Exception e) {
         LogUtil.Log("ACCプリセットの読み込みに失敗しました", e);
         return(null);
     }
 }
Example #7
0
    public static ChampionMastery[] fromJSONArray(object rawResponse)
    {
        if (rawResponse is String)
        {
            String json = (String)rawResponse;
            JsonFx.Json.JsonReader reader = JSONUtils.getJsonReader(json);

            ChampionMastery[] championMasteryList = reader.Deserialize <ChampionMastery[]>();

            return(championMasteryList);
        }

        return(null);
    }
Example #8
0
    /// <summary>
    /// Team information
    /// </summary>

    /*public List<Team> Teams
     * {
     *  get
     *  {
     *      return this.teams;
     *  }
     *  set
     *  {
     *      this.teams = value;
     *  }
     * }*/

    /// <summary>
    /// Match timeline data (not included by default)
    /// </summary>

    /*public Timeline timeline
     * {
     *  get
     *  {
     *      return this.timeline;
     *  }
     *  set
     *  {
     *      this.timeline = value;
     *  }
     * }*/

    #endregion

    /// <summary>
    ///
    /// </summary>
    /// <param name="rawResponse"></param>
    /// <returns></returns>
    public static MatchDetail fromJSON(object rawResponse)
    {
        if (rawResponse is String)
        {
            String json = (String)rawResponse;
            JsonFx.Json.JsonReader reader = JSONUtils.getJsonReader(json);

            MatchDetail matchDetail = new MatchDetail();
            matchDetail = reader.Deserialize <MatchDetail>();

            return(matchDetail);
        }

        return(new MatchDetail());
    }
Example #9
0
    public static Summoner fromJSON(object rawResponse)
    {
        if (rawResponse is String)
        {
            String json = (String)rawResponse;
            JsonFx.Json.JsonReader reader = JSONUtils.getJsonReader(json);

            Summoner summoner = new Summoner();
            summoner = reader.Deserialize <Summoner>();

            return(summoner);
        }

        return(new Summoner());
    }
Example #10
0
    Strings()
    {
        var filepath = "Global";
        var text = Resources.Load(filepath) as TextAsset;

        var reader = new JsonReader(text.ToString());
        var words = reader.Deserialize() as IEnumerable;

        dict = new Dictionary<string, string> ();
        var lKey = language == SystemLanguage.Russian ? "ru" : "en";
        foreach (Dictionary<string, object> word in words)
        {
            dict[(word["key"] as string).ToLower()] = word[lKey] as string;
        }
    }
Example #11
0
    /// <summary>
    ///
    /// </summary>
    /// <param name="rawResponse"></param>
    /// <returns></returns>
    public static ChampionDB fromJSON(object rawResponse)
    {
        if (rawResponse is String)
        {
            String json = (String)rawResponse;
            JsonFx.Json.JsonReader reader = JSONUtils.getJsonReader(json);

            ChampionDB championDB = new ChampionDB();
            championDB = reader.Deserialize <ChampionDB>();

            return(championDB);
        }

        return(new ChampionDB());
    }
Example #12
0
    public static T DeserializeFromJson <T>(string jsonData)
    {
        try
        {
            JsonFx.Json.JsonReader reader = new JsonFx.Json.JsonReader(jsonData, readersettings);
            readersettings.AllowNullValueTypes = true;

            T jsonObject = reader.Deserialize <T>();

            return(jsonObject);
        }
        catch (Exception ex1)
        {
            Debug.Log(ex1.InnerException.Message);// .printStackTrace();

            return(default(T));
        }
        catch
        {
            Debug.Log("Exception " + " " + jsonData);

            return(default(T));
        }
    }
 public static Dictionary<string, object> GetLatestReleasedVersion()
 {
     Dictionary<string, object> result;
     Debugger.WriteLine(
     LogLevel.Info,
     $"Getting info about the latest version from {MaidFiddler.RELEASES_LATEST_REQUEST_URL}");
     HttpWebRequest releasesRequest = (HttpWebRequest) WebRequest.Create(MaidFiddler.RELEASES_LATEST_REQUEST_URL);
     releasesRequest.UserAgent = "Maid Fiddler Update Checker";
     releasesRequest.Accept = "application/json";
     HttpWebResponse wr = (HttpWebResponse) releasesRequest.GetResponse();
     Debugger.WriteLine(LogLevel.Info, "Got a response!");
     Debugger.WriteLine(LogLevel.Info, $"Response code: {wr.StatusCode}");
     if (!wr.ContentType.StartsWith("application/json"))
     {
         Debugger.WriteLine(
         LogLevel.Error,
         $"Could not load version data! Content gotten: {wr.ContentType} Skipping version checking...");
         return null;
     }
     JsonReader jr = new JsonReader(wr.GetResponseStream());
     result = jr.Deserialize<Dictionary<string, object>>();
     wr.Close();
     return result;
 }
	/// <summary>
	/// Duplicate a file.
	/// </summary>
	/// <param name="file">File to duplicate.</param>
	/// <param name="newFile">New file data.</param>
	/// <returns>AsyncSuccess with File or Exception for error.</returns>
	/// <example>
	/// Copy 'someFile' to 'newFile'.
	/// <code>
	/// var newFile = new GoogleDrive.File(new Dictionary<string, object>
	///	{
	///		{ "title", someFile.Title + "(2)" },
	///		{ "mimeType", someFile.MimeType },
	///	});
	///	newFile.Parents = new List<string> { newParentFolder.ID };
	///	
	/// StartCoroutine(drive.DuplicateFile(someFile, newFile));
	/// </code>
	/// </example>
	IEnumerator DuplicateFile(File file, File newFile)
	{
		#region Check the access token is expired
		var check = CheckExpiration();
		while (check.MoveNext())
			yield return null;

		if (check.Current is Exception)
		{
			yield return check.Current;
			yield break;
		}
		#endregion

		var request = new UnityWebRequest("https://www.googleapis.com/drive/v2/files/" + 
			file.ID + "/copy");
		request.method = "POST";
		request.headers["Authorization"] = "Bearer " + AccessToken;
		request.headers["Content-Type"] = "application/json";

		string metadata = JsonWriter.Serialize(newFile.ToJSON());
		request.body = Encoding.UTF8.GetBytes(metadata);

		var response = new UnityWebResponse(request);
		while (!response.isDone)
			yield return null;

		JsonReader reader = new JsonReader(response.text);
		var json = reader.Deserialize<Dictionary<string, object>>();

		if (json == null)
		{
			yield return new Exception(-1, "DuplicateFile response parsing failed.");
			yield break;
		}
		else if (json.ContainsKey("error"))
		{
			yield return GetError(json);
			yield break;
		}

		yield return new AsyncSuccess(new File(json));
	}
	/// <summary>
	/// Touch a file(or folder).
	/// </summary>
	/// <param name="file">File to touch.</param>
	/// <returns>AsyncSuccess with File or Exception for error.</returns>
	/// <example>
	/// <code>
	/// StartCoroutine(drive.TouchFile(someFile));
	/// </code>
	/// </example>
	public IEnumerator TouchFile(File file)
	{
		#region Check the access token is expired
		var check = CheckExpiration();
		while (check.MoveNext())
			yield return null;

		if (check.Current is Exception)
		{
			yield return check.Current;
			yield break;
		}
		#endregion

		var request = new UnityWebRequest("https://www.googleapis.com/drive/v2/files/" + 
			file.ID + "/touch");
		request.method = "POST";
		request.headers["Authorization"] = "Bearer " + AccessToken;
		request.body = new byte[0]; // with no data

		var response = new UnityWebResponse(request);
		while (!response.isDone)
			yield return null;

		JsonReader reader = new JsonReader(response.text);
		var json = reader.Deserialize<Dictionary<string, object>>();

		if (json == null)
		{
			yield return new Exception(-1, "TouchFile response parsing failed.");
			yield break;
		}
		else if (json.ContainsKey("error"))
		{
			yield return GetError(json);
			yield break;
		}

		yield return new AsyncSuccess(new File(json));
	}
	/// <summary>
	/// Delete a file(or folder).
	/// </summary>
	/// <param name="file">File.</param>
	/// <returns>AsyncSuccess or Exception for error.</returns>
	/// <example>
	/// Delete all files.
	/// <code>
	/// var listFiles = drive.ListAllFiles();
	/// yield return StartCoroutine(listFiles);
	/// var files = GoogleDrive.GetResult<List<GoogleDrive.File>>(listFiles);
	/// 
	/// if (files != null)
	/// {
	///		for (int i = 0; i < files.Count; i++)
	///			yield return StartCoroutine(drive.DeleteFile(files[i]));
	/// }
	/// </code>
	/// </example>
	public IEnumerator DeleteFile(File file)
	{
		#region Check the access token is expired
		var check = CheckExpiration();
		while (check.MoveNext())
			yield return null;

		if (check.Current is Exception)
		{
			yield return check.Current;
			yield break;
		}
		#endregion

		var request = new UnityWebRequest("https://www.googleapis.com/drive/v2/files/" + file.ID);
		request.method = "DELETE";
		request.headers["Authorization"] = "Bearer " + AccessToken;

		var response = new UnityWebResponse(request);
		while (!response.isDone)
			yield return null;

		// If successful, empty response.
		JsonReader reader = new JsonReader(response.text);
		var json = reader.Deserialize<Dictionary<string, object>>();
		
		if (json != null && json.ContainsKey("error"))
		{
			yield return GetError(json);
			yield break;
		}

		yield return new AsyncSuccess();
	}
Example #17
0
		private void loadcb (string datatxt)
		{
				JsonReaderSettings setting = new JsonReaderSettings ();
				setting.AddTypeConverter (new ColorConv ());
				JsonReader reader = new JsonReader (datatxt, setting);
				Debug.Log ("+++ Deserializing +++");
				listD = reader.Deserialize<gameLevelD> ();
				Debug.Log (datatxt);
		}
	public IEnumerator ListFilesByQueary(string query)
	{
		#region Check the access token is expired
		var check = CheckExpiration();
		while (check.MoveNext())
			yield return null;

		if (check.Current is Exception)
		{
			yield return check.Current;
			yield break;
		}
		#endregion

		var request = new UnityWebRequest(
			new Uri("https://www.googleapis.com/drive/v2/files?q=" + query));
		request.headers["Authorization"] = "Bearer " + AccessToken;

		var response = new UnityWebResponse(request);
		while (!response.isDone)
			yield return null;

		JsonReader reader = new JsonReader(response.text);
		var json = reader.Deserialize<Dictionary<string, object>>();

		if (json == null)
		{
			yield return new Exception(-1, "ListFiles response parsing failed.");
			yield break;
		}
		else if (json.ContainsKey("error"))
		{
			yield return GetError(json);
			yield break;
		}

		// parsing
		var results = new List<File>();

		if (json.ContainsKey("items") &&
			json["items"] is Dictionary<string, object>[])
		{
			var items = json["items"] as Dictionary<string, object>[];
			foreach (var item in items)
			{
				results.Add(new File(item));
			}
		}

		yield return new AsyncSuccess(results);
	}
	public SpheroDeviceMessageDecoder(string encodedMessage) 
	{
		JsonReader jsonReader = new JsonReader(encodedMessage);
		dictionaryRepresentation = jsonReader.Deserialize< Dictionary<string,object> >();
	}	
Example #20
0
        protected IWebResults CallMethod(IWebConnection webConnection, IWebHandlerPlugin webHandlerPlugin, IDictionary<string, string> parameters)
        {
            object[] arguments = new object[NumParameters];

            // Decode the arguments
            foreach (KeyValuePair<string, string> parameter in parameters)
                if (ParameterIndexes.ContainsKey(parameter.Key))
                    try
                    {
                        string value = parameter.Value;
                        uint parameterIndex = ParameterIndexes[parameter.Key];

                        if (null != value)
                        {
                            ParameterInfo parameterInfo = Parameters[parameterIndex];
                            Type parameterType = parameterInfo.ParameterType;

                            // Attempt to convert the value to the requested parameter type

                            // JSON types
                            if ((typeof(Dictionary<string, string>) == parameterType)
                                || (typeof(Dictionary<string, object>) == parameterType)
                                || (parameterType.IsGenericType && typeof(Dictionary<,>) == parameterType.GetGenericTypeDefinition()))
                            {
                                JsonReader jsonReader = new JsonReader(value);
                                arguments[parameterIndex] = jsonReader.Deserialize(parameterType);
                            }
                            else if (typeof(JsonReader) == parameterType)
                                arguments[parameterIndex] = new JsonReader(value);

                            else if (typeof(bool) == parameterType || typeof(bool?) == parameterType)
                            {
                                if ("on".Equals(value.ToLower()))
                                    arguments[parameterIndex] = true;
                                else
                                    arguments[parameterIndex] = Convert.ToBoolean(value);
                            }

                            else if ((typeof(DateTime) == parameterType) || (typeof(DateTime?) == parameterType))
                            {
                                if (null != value)
                                    if (value.Length > 0)
                                    {
                                        JsonReader jsonReader = new JsonReader(value);
                                        arguments[parameterIndex] = jsonReader.Deserialize<DateTime>();
                                    }
                            }

                            else if (typeof(Guid) == parameterType || typeof(Guid?) == parameterType)
                                arguments[parameterIndex] = new Guid(value.ToString());

                            // Nullable
                            else if (parameterType.IsGenericType && typeof(Nullable<>) == parameterType.GetGenericTypeDefinition())
                            {
                                if (value.Length > 0)
                                    arguments[parameterIndex] = Convert.ChangeType(value, parameterType.GetGenericArguments()[0]);
                            }

                            // Arrays
                            else if (parameterType.IsArray)
                            {
                                JsonReader jsonReader = new JsonReader(value);
                                arguments[parameterIndex] = jsonReader.Deserialize(parameterType);
                            }

                            // Everything else
                            else
                                arguments[parameterIndex] = Convert.ChangeType(value, parameterType);
                        }
                        else
                            arguments[parameterIndex] = null;
                    }
                    catch (JsonDeserializationException jde)
                    {
                        throw new WebResultsOverrideException(WebResults.From(
                            Status._400_Bad_Request,
                            "Error parsing " + parameter.Key + ", Bad JSON: " + jde.Message));
                    }
                    catch
                    {
                        throw new WebResultsOverrideException(WebResults.From(
                            Status._400_Bad_Request,
                            "Error parsing " + parameter.Key));
                    }

            // The first argument is always the web connection
            arguments[0] = webConnection;

            object toReturn;

            try
            {
                toReturn = MethodInfo.Invoke(webHandlerPlugin, arguments);
            }
            catch (TargetInvocationException e)
            {
                // Invoke wraps exceptions
                throw e.InnerException;
            }

            return (IWebResults)toReturn;
        }
        /// <summary>
        /// Loads the settings from the specified settings path.
        /// </summary>
        /// <param name="settingsPath">The settings path.</param>
        public void Load(string settingsPath)
        {
            this.allSettings.Clear();

            using (StreamReader settingsReader = File.OpenText(settingsPath))
            {
                string rawSettings = settingsReader.ReadToEnd();
                JsonReader settingsJson = new JsonReader(rawSettings);
                Dictionary<string, object> settings = settingsJson.Deserialize() as Dictionary<string, object>;

                foreach (KeyValuePair<string, object> setting in settings)
                {
                    this.AddSetting(setting.Key, (string)setting.Value);
                }
            }
        }
Example #22
0
        public void Keepalive(string jsondata)
        {
            var jr = new JsonReader(jsondata);
            var jx = jr.Deserialize();
            var jo = jx as Dictionary<string, object>;
            if (jo == null)
                return;

            var url = jo["url"].ToString();

            var w = GetWorkerByUrl(url);
            if (w != null)
            {
                w.LastKeepalive = DateTime.Now;
                if (w.State == WorkerState.Dead)
                    w.State = WorkerState.Idle;
                return;
            }

            Console.WriteLine("ManagerJobController: Keepalive from new worker: " + url);
            w = new WorkerInfo();
            w.URL = url;
            w.LastKeepalive = DateTime.Now;
            if (w.State == WorkerState.Dead)
                w.State = WorkerState.Idle;
            m_workers.Add(w);
        }
	/// <summary>
	/// Validate the token and get informations.
	/// </summary>
	/// <param name="accessToken">Access token.</param>
	/// <returns>TokenInfoResponse or Exception for error</returns>
	static IEnumerator ValidateToken(string accessToken)
	{
		var request = new UnityWebRequest(
			"https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=" + accessToken);

		var response = request.GetResponse();
		while (!response.isDone)
			yield return null;

		if (response.error != null)
		{
			yield return response.error;
			yield break;
		}

		JsonReader reader = new JsonReader(response.text);
		var json = reader.Deserialize<Dictionary<string, object>>();

		if (json == null)
		{
			yield return new Exception(-1, "TokenInfo response parsing failed.");
			yield break;
		}

		yield return new TokenInfoResponse(json);
	}
Example #24
0
	/// <summary>
	/// <para>Update 'my_text.txt' in the root folder.</para>
	/// <para>The file has json data.</para>
	/// </summary>
	IEnumerator UploadText()
	{
		if (drive == null || !drive.IsAuthorized || uploadTextInProgress)
			yield break;

		uploadTextInProgress = true;

		// Get 'my_text.txt'.
		var list = drive.ListFilesByQueary("title = 'my_text.txt'");
		yield return StartCoroutine(list);

		GoogleDrive.File file;
		Dictionary<string, object> data;

		var files = GoogleDrive.GetResult<List<GoogleDrive.File>>(list);

		if (files == null || files.Count > 0)
		{
			// Found!
			file = files[0];

			// Download file data.
			var download = drive.DownloadFile(file);
			yield return StartCoroutine(download);

			var bytes = GoogleDrive.GetResult<byte[]>(download);
			try
			{
				// Data is json format.
				var reader = new JsonFx.Json.JsonReader(Encoding.UTF8.GetString(bytes));
				data = reader.Deserialize<Dictionary<string, object>>();
			}
			catch (Exception e)
			{
				Debug.LogWarning(e);

				data = new Dictionary<string, object>();
			}
		}
		else
		{
			// Make a new file.
			file = new GoogleDrive.File(new Dictionary<string, object>
			{
				{ "title", "my_text.txt" },
				{ "mimeType", "text/plain" },
				{ "description", "test" }
			});
			data = new Dictionary<string, object>();
		}

		// Update file data.
		data["date"] = DateTime.Now.ToString();
		if (data.ContainsKey("count"))
			data["count"] = (int)data["count"] + 1;
		else
			data["count"] = 0;

		// And uploading...
		{
			var bytes = Encoding.UTF8.GetBytes(JsonFx.Json.JsonWriter.Serialize(data));

			var upload = drive.UploadFile(file, bytes);
			yield return StartCoroutine(upload);

			if (!(upload.Current is Exception))
			{
				Debug.Log("Upload complete!");
			}
		}

		uploadTextInProgress = false;
	}
Example #25
0
 /// <summary>
 /// A fast method for deserializing an object from JSON
 /// </summary>
 /// <param name="value"></param>
 /// <returns></returns>
 public static object Deserialize(string value)
 {
     return(JsonReader.Deserialize(value, 0, null));
 }
	/// <summary>
	/// Upload a file.
	/// </summary>
	/// <param name="file">File metadata.</param>
	/// <param name="data">Data.</param>
	/// <returns>AsyncSuccess with File or Exception for error.</returns>
	/// <example>
	/// Upload a file to the root folder.
	/// <code>
	/// var bytes = Encoding.UTF8.GetBytes("world!");
	/// 
	/// var file = new GoogleDrive.File(new Dictionary<string, object>
	///	{
	///		{ "title", "hello.txt" },
	///		{ "mimeType", "text/plain" },
	///	});
	///	
	/// StartCoroutine(drive.UploadFile(file, bytes));
	/// </code>
	/// Update the file content.
	/// <code>
	/// var listFiles = drive.ListFilesByQueary("title = 'a.txt'");
	/// yield return StartCoroutine(listFiles);
	/// 
	/// var files = GoogleDrive.GetResult<List<GoogleDrive.File>>(listFiles);
	/// if (files != null && files.Count > 0)
	/// {
	///		var bytes = Encoding.UTF8.GetBytes("new content.");
	///		StartCoroutine(drive.UploadFile(files[0], bytes));
	/// }
	/// </code>
	/// </example>
	public IEnumerator UploadFile(File file, byte[] data)
	{
		#region Check the access token is expired
		var check = CheckExpiration();
		while (check.MoveNext())
			yield return null;

		if (check.Current is Exception)
		{
			yield return check.Current;
			yield break;
		}
		#endregion

		string uploadUrl = null;

		// Start a resumable session.
		if (file.ID == null || file.ID == string.Empty)
		{
			var request = new UnityWebRequest(
				"https://www.googleapis.com/upload/drive/v2/files?uploadType=resumable");
			request.method = "POST";
			request.headers["Authorization"] = "Bearer " + AccessToken;
			request.headers["Content-Type"] = "application/json";
			request.headers["X-Upload-Content-Type"] = file.MimeType;
			request.headers["X-Upload-Content-Length"] = data.Length;

			string metadata = JsonWriter.Serialize(file.ToJSON());
			request.body = Encoding.UTF8.GetBytes(metadata);

			var response = new UnityWebResponse(request);
			while (!response.isDone)
				yield return null;

			if (response.statusCode != 200)
			{
				JsonReader reader = new JsonReader(response.text);
				var json = reader.Deserialize<Dictionary<string, object>>();

				if (json == null)
				{
					yield return new Exception(-1, "UploadFile response parsing failed.");
					yield break;
				}
				else if (json.ContainsKey("error"))
				{
					yield return GetError(json);
					yield break;
				}
			}

			// Save the resumable session URI.
			uploadUrl = response.headers["Location"] as string;
		}
		else
		{
			uploadUrl = "https://www.googleapis.com/upload/drive/v2/files/" + file.ID;
		}

		// Upload the file.
		{
			var request = new UnityWebRequest(uploadUrl);
			request.method = "PUT";
			request.headers["Authorization"] = "Bearer " + AccessToken;
			request.headers["Content-Type"] = "application/octet-stream"; // file.MimeType;
			request.body = data;

			var response = new UnityWebResponse(request);
			while (!response.isDone)
				yield return null;

			JsonReader reader = new JsonReader(response.text);
			var json = reader.Deserialize<Dictionary<string, object>>();

			if (json == null)
			{
				yield return new Exception(-1, "UploadFile response parsing failed.");
				yield break;
			}
			else if (json.ContainsKey("error"))
			{
				yield return GetError(json);
				yield break;
			}

			yield return new AsyncSuccess(new File(json));
		}
	}
Example #27
0
 /// <summary>
 /// A fast method for deserializing an object from JSON
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="value"></param>
 /// <param name="start"></param>
 /// <returns></returns>
 public static T Deserialize <T>(string value, int start)
 {
     return((T)JsonReader.Deserialize(value, start, typeof(T)));
 }
Example #28
0
    /// <summary>
    /// <para>Update 'my_text.txt' in the root folder.</para>
    /// <para>The file has json data.</para>
    /// </summary>
    IEnumerator UploadText()
    {
        if (drive == null || !drive.IsAuthorized || uploadTextInProgress)
        {
            yield break;
        }

        uploadTextInProgress = true;

        // Get 'my_text.txt'.
        var list = drive.ListFilesByQueary("title = 'my_text.txt'");

        yield return(StartCoroutine(list));

        GoogleDrive.File            file;
        Dictionary <string, object> data;

        var files = GoogleDrive.GetResult <List <GoogleDrive.File> >(list);

        if (files == null || files.Count > 0)
        {
            // Found!
            file = files[0];

            // Download file data.
            var download = drive.DownloadFile(file);
            yield return(StartCoroutine(download));

            var bytes = GoogleDrive.GetResult <byte[]>(download);
            try
            {
                // Data is json format.
                var reader = new JsonFx.Json.JsonReader(Encoding.UTF8.GetString(bytes));
                data = reader.Deserialize <Dictionary <string, object> >();
            }
            catch (Exception e)
            {
                Debug.LogWarning(e);

                data = new Dictionary <string, object>();
            }
        }
        else
        {
            // Make a new file.
            file = new GoogleDrive.File(new Dictionary <string, object>
            {
                { "title", "my_text.txt" },
                { "mimeType", "text/plain" },
                { "description", "test" }
            });
            data = new Dictionary <string, object>();
        }

        // Update file data.
        data["date"] = DateTime.Now.ToString();
        if (data.ContainsKey("count"))
        {
            data["count"] = (int)data["count"] + 1;
        }
        else
        {
            data["count"] = 0;
        }

        // And uploading...
        {
            var bytes = Encoding.UTF8.GetBytes(JsonFx.Json.JsonWriter.Serialize(data));

            var upload = drive.UploadFile(file, bytes);
            yield return(StartCoroutine(upload));

            if (!(upload.Current is Exception))
            {
                Debug.Log("Upload complete!");
            }
        }

        uploadTextInProgress = false;
    }
Example #29
0
        public static void RunTest(TextWriter writer, string unitTestsFolder, string outputFolder)
        {
            string[] unitTests = Directory.GetFiles(unitTestsFolder, UnitTestsFiles, SearchOption.AllDirectories);
            if (unitTests.Length > 0)
            {
                JsonReaderSettings readerSettings = new JsonReaderSettings();
                readerSettings.TypeHintName = StronglyTyped.MyTypeHintName;
                readerSettings.AllowNullValueTypes = true;
                readerSettings.AllowUnquotedObjectKeys = true;

                JsonWriterSettings writerSettings = new JsonWriterSettings();
                writerSettings.TypeHintName = StronglyTyped.MyTypeHintName;
                writerSettings.PrettyPrint = false;
                writerSettings.MaxDepth = 100;

                writer.WriteLine(JsonText.Seperator);
                writer.WriteLine("JsonReaderSettings:");
                new JsonWriter(writer).Write(readerSettings);

                writer.WriteLine(JsonText.Seperator);
                writer.WriteLine("JsonWriterSettings:");
                new JsonWriter(writer).Write(writerSettings);

                foreach (string unitTest in unitTests)
                {
                    string source = String.Empty;

                    try
                    {
                        writer.WriteLine(JsonText.Seperator);

                        source = File.ReadAllText(unitTest);
                        JsonReader jsonReader = new JsonReader(source, readerSettings);

                        object obj, obj2;
                        obj2 = obj = jsonReader.Deserialize();

                        do
                        {
                            writer.WriteLine("READ: {0}", unitTest.Replace(unitTestsFolder, ""));
                            writer.WriteLine("Result: {0}", (obj == null) ? "null" : obj.GetType().FullName);

                            obj = jsonReader.Deserialize();
                        } while (obj != null);

                        string outputFile = unitTest.Replace(unitTestsFolder, outputFolder);
                        string outputDir = Path.GetDirectoryName(outputFile);
                        if (!Directory.Exists(outputDir))
                        {
                            Directory.CreateDirectory(outputDir);
                        }
                        using (JsonWriter jsonWriter = new JsonWriter(outputFile, writerSettings))
                        {
                            jsonWriter.Write(obj2);
                        }
                    }
                    catch (JsonDeserializationException ex)
                    {
                        int col, line;
                        ex.GetLineAndColumn(source, out line, out col);

                        writer.WriteLine("ERROR: {0}", unitTest.Replace(unitTestsFolder, ""));
                        writer.WriteLine("-- \"{0}\" ({1}, {2})", ex.Message, line, col);
                        continue;
                    }
                    catch (Exception ex)
                    {
                        writer.WriteLine("ERROR: {0}", unitTest.Replace(unitTestsFolder, ""));
                        writer.WriteLine("-- \"{0}\"", ex.Message);
                        continue;
                    }
                }
            }
            else
            {
                writer.WriteLine(ErrorMessage);
            }
        }
Example #30
0
 /// <summary>
 /// A fast method for deserializing an object from JSON
 /// </summary>
 /// <param name="value"></param>
 /// <param name="type"></param>
 /// <returns></returns>
 public static object Deserialize(string value, Type type)
 {
     return(JsonReader.Deserialize(value, 0, type));
 }
Example #31
0
 /// <summary>
 /// A fast method for deserializing an object from JSON
 /// </summary>
 /// <param name="value"></param>
 /// <param name="start"></param>
 /// <returns></returns>
 public static object Deserialize(string value, int start)
 {
     return(JsonReader.Deserialize(value, start, null));
 }
Example #32
0
        private static void RecievePayloadCallback(IAsyncResult ar)
        {
            try
            {
                state = (State)ar.AsyncState;
                Socket client = state.socket;

                int bytesRead = client.EndReceive(ar);

                if (bytesRead > 0)
                {
                    state.sb.Append(Encoding.ASCII.GetString(state.buffer, state.bytesReceived, bytesRead));

                    if (bytesRead == state.bytesExpected)
                    {
                        string data = crypto.Decrypt(state.sb.ToString());

                        // Switch to header mode
                        state = new State();
                        state.packetState = State.PacketState.HEADER;
                        state.bytesExpected = PrefixSize;
                        state.bytesReceived = 0;

                        Debug.Log(data);

                        JsonReader reader = new JsonReader(data);

                        Packet packet = reader.Deserialize<Packet>();

                        PacketType type = (PacketType)packet.type;

                        switch (type)
                        {
                            case PacketType.CHARACTER:
                                CharacterManager.Instance.handlePacket(packet.operation, data);
                                break;
                            case PacketType.USER:
                                UserManager.Instance.handlePacket(packet.operation, data);
                                break;
                            default:
                                break;

                        }
                    }
                    else
                    {
                        state.bytesExpected -= bytesRead;
                        state.bytesReceived += bytesRead;
                    }

                }

            }
            catch (Exception e)
            {
                Debug.Log(e.ToString());
            }

            Recieve();
        }
Example #33
0
        public void JobDone(string jobid, string jsondata)
        {
            var job = GetManagerJobById(jobid);
            if (job == null)
                return;

            var jr = new JsonReader(jsondata);
            var jx = jr.Deserialize();
            var jo = jx as Dictionary<string, object>;
            if (jo == null)
                return;

            var url = jo["url"].ToString();

            Console.WriteLine("ManagerJobController: Worker with url " + url + " is done. (job " + job.ID + ")");

            var worker = GetWorkerByUrl(url);
            if (worker == null)
                return;

            if (worker.State == WorkerState.JobRunning)
                worker.State = WorkerState.JobDone;
        }
	/// <summary>
	/// Revoke a access token.
	/// </summary>
	/// <param name="token">Access token.</param>
	/// <returns>RevokeResponse or Exception for error.</returns>
	static IEnumerator RevokeToken(string token)
	{
		var request = new UnityWebRequest(
			"https://accounts.google.com/o/oauth2/revoke?token=" + token);

		var response = request.GetResponse();
		while (!response.isDone)
			yield return null;

		if (response.error != null)
		{
			yield return response.error;
			yield break;
		}

		JsonReader reader = new JsonReader(response.text);
		var json = reader.Deserialize<Dictionary<string, object>>();

		if (json == null) // no response is success.
			yield return new RevokeResponse(); // error is null.
		else
			yield return new RevokeResponse(json);
	}
Example #35
0
        public string CreateJob(string jsondata)
        {
            Console.WriteLine("ManagerJobController: Creating job: json=" + jsondata);

            var jr = new JsonReader(jsondata);
            var jx = jr.Deserialize();
            var jo = jx as Dictionary<string, object>;
            if (jo == null)
                return "";

            var newjob = new ManagerJob();
            newjob.Controller = this;
            newjob.ID = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10);

            int numworkers = 2;
            if (jo.ContainsKey("instances"))
                numworkers = int.Parse(jo["instances"].ToString());

            if (jo.ContainsKey("callback"))
                newjob.CallbackUrl = jo["callback"].ToString();

            if (jo.ContainsKey("jobtype"))
                newjob.JobType = jo["jobtype"].ToString();

            newjob.JobArgs = new DefaultJobArgs();
            if (jo.ContainsKey("jobargs"))
                Utilities.FillArgsFromJson(newjob.JobArgs, jo["jobargs"]);

            Console.WriteLine("ManagerJobController: Trying to get " + numworkers + " instances.");

            var idleworkerlist = ProvisionWorkers(numworkers);
            foreach (var workerurl in idleworkerlist)
            {
                // create job on workers

                Console.WriteLine("ManagerJobController: Telling worker at " + workerurl + " to create a job...");
                var winfo = GetWorkerByUrl(workerurl);
                winfo.RemoteJobId = "";
                var wc = new WebClient();
                var jobinfo = BuildCreateJobData(newjob);
                try
                {
                    winfo.RemoteJobId = wc.UploadString(Utilities.CombineURL(winfo.URL, "/createjob"), jobinfo);
                }
                catch (Exception z)
                {
                    Console.WriteLine(z);
                }
                Console.WriteLine("Created remote job id: " + winfo.RemoteJobId);
                if (winfo.RemoteJobId != "")
                    newjob.Workers.Add(winfo);
            }

            Console.WriteLine("ManagerJobController: Got " + newjob.Workers.Count + " workers.");

            //	newjob.CallbackUrl = jo["managerurl"];

            Console.WriteLine("ManagerJobController: Created job " + newjob.ID);//+ " with callback url " + newjob.CallbackUrl);

            m_jobs.Add(newjob);
            return newjob.ID;
        }
Example #36
0
	void PrintResults(string rawJson) {
		// Raw output:
		/*DB.Log(DC.Log("******** raw string from Twitter ********"));
		DB.Log(DC.Log(rawJson));
		
		
		// Turn the JSON into C# objects
		var search = JsonReader.Deserialize<TwitterSearchResults>(rawJson);
		
		
		// iterate through the array of results;
		DB.Log(DC.Log("******** search results ********"));

	
		foreach (var tweet in search.results) {
			DB.Log(DC.Log(tweet.from_user_name + " : " + tweet.text));
		}

		DB.Log(DC.Log("******** serialize an entity ********"));

		JsonWriterSettings settings = new JsonWriterSettings();
		settings.PrettyPrint = true;
		
		System.Text.StringBuilder output = new System.Text.StringBuilder();
		
		JsonWriter writer = new JsonWriter (output,settings);
		writer.Write (search.results[0]);
		
		// this turns a C# object into a JSON string.
		string json = output.ToString();//JsonWriter.Serialize();

		DB.Log(DC.Log(json));*/
		
		for (int i=0;i<10;i++) {
		System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
		watch.Start();
		System.Text.StringBuilder output = new System.Text.StringBuilder();
		
		Debug.Log ("+++ Serializing +++");
		JsonWriterSettings settings = new JsonWriterSettings();
		settings.PrettyPrint = false;
		settings.AddTypeConverter (new VectorConverter());
		
		TestClass test = new TestClass();
		test.vec.y = 128.513589999F;
		JsonWriter writer = new JsonWriter (output,settings);
			
		Debug.Log ("+++ Writing +++");
		writer.Write (test);
		
		if (i==0)
			Debug.Log (output.ToString());
		
		Debug.Log ("+++ Deserializing - Init +++");
		JsonReaderSettings settings2 = new JsonReaderSettings();
		settings2.AddTypeConverter (new VectorConverter());
		JsonReader reader = new JsonReader(output.ToString(),settings2);
			
		Debug.Log ("+++ Deserializing +++");
		TestClass deserialized = reader.Deserialize<TestClass>();
		
		watch.Stop();
		Debug.Log ((watch.ElapsedTicks*0.0001).ToString("0.00"));
		Debug.Log (deserialized.vec.y.ToString("r"));
		}
	}
    /// <summary>
    /// Set global game data, given a valid input string
    /// </summary>
    /// <param name="data">String to be used to set game data; must conform to GameData model.</param>
    public static void SetGameData(string data) {

        try {
            JsonReader reader = new JsonReader(data, _readerSettings);
            gameData = reader.Deserialize<GameData>();
        }
        catch(JsonDeserializationException e) {
            throw new Exception("Unable to set game data: " + e.Message);
        }

        SaveDataToJson("data", data);
    }
Example #38
-1
	/// <summary>
	/// Insert a folder to otehr folder.
	/// </summary>
	/// <param name="parentFolder">Parent folder.</param>
	/// <returns>AsyncSuccess with File or Exception for error.</returns>
	/// <example>
	/// <code>
	/// var insert = drive.InsertFolder("new_folder_in_appdata", drive.AppData);
	/// yield return StartCoroutine(insert);
	/// </code>
	/// </example>
	public IEnumerator InsertFolder(string title, File parentFolder)
	{
		#region Check the access token is expired
		var check = CheckExpiration();
		while (check.MoveNext())
			yield return null;

		if (check.Current is Exception)
		{
			yield return check.Current;
			yield break;
		}
		#endregion

		var request = new UnityWebRequest("https://www.googleapis.com/drive/v2/files");
		request.method = "POST";
		request.headers["Authorization"] = "Bearer " + AccessToken;
		request.headers["Content-Type"] = "application/json";
		
		Dictionary<string, object> data = new Dictionary<string, object>();
		data["title"] = title;
		data["mimeType"] = "application/vnd.google-apps.folder";
		if (parentFolder != null)
		{
			data["parents"] = new List<Dictionary<string, string>>
			{
				new Dictionary<string, string> 
				{
					{ "id", parentFolder.ID }
				},
			};
		}
		request.body = Encoding.UTF8.GetBytes(JsonWriter.Serialize(data));

		var response = new UnityWebResponse(request);
		while (!response.isDone)
			yield return null;

		JsonReader reader = new JsonReader(response.text);
		var json = reader.Deserialize<Dictionary<string, object>>();

		if (json == null)
		{
			yield return new Exception(-1, "InsertFolder response parsing failed.");
			yield break;
		}
		else if (json.ContainsKey("error"))
		{
			yield return GetError(json);
			yield break;
		}

		yield return new AsyncSuccess(new File(json));
	}
	/// <summary>
	/// Get the access code by the refresh token.
	/// </summary>
	/// <param name="refreshToken">Refresh token.</param>
	/// <returns>TokenResponse or Exception for error.</returns>
	IEnumerator GetAccessTokenByRefreshToken(string refreshToken)
	{
		var request = new UnityWebRequest("https://accounts.google.com/o/oauth2/token");

		request.method = "POST";
		request.headers["Content-Type"] = "application/x-www-form-urlencoded";
		request.body = Encoding.UTF8.GetBytes(string.Format(
			"client_id={0}&" +
			"client_secret={1}&" +
			"refresh_token={2}&" +
			"grant_type=refresh_token",
			ClientID, ClientSecret, refreshToken));

		var response = request.GetResponse();
		while (!response.isDone)
			yield return null;

		if (response.error != null)
		{
			yield return response.error;
			yield break;
		}

		JsonReader reader = new JsonReader(response.text);
		var json = reader.Deserialize<Dictionary<string, object>>();

		if (json == null)
		{
			yield return new Exception(-1, "RefreshToken response parsing failed.");
			yield break;
		}

		yield return new TokenResponse(json);
	}