ToString() 공개 메소드

public ToString ( ) : string
리턴 string
예제 #1
0
파일: God.cs 프로젝트: vorrin/store-game
    IEnumerator PostData(JSONObject json)
    {
        //WWWForm testWWW = new WWWForm();
        //testWWW.AddField("Score","12");
        //testWWW.AddField("ContentKey","91FA1062-255B-40FB-A108-3FA783BFF6CD");
        //testWWW.AddField("Level","31");
        //testWWW.AddField("User","0980808A-2AFC-411D-96A5-009487091A61");
        //testWWW.AddField("Date","2014-06-06 00,00,00Z");
        //testWWW.AddField("Powerbar","21");
        //WWW www = new WWW(url, testWWW);

        //string input = @"{""Date"":""" + System.DateTime.Now.ToString("mm/dd/yyyyTHH:mm:ss") +@"""}";
        Hashtable headers = new Hashtable();
        headers.Add("Content-Type", "application/json");

        print("Exact Json: \n" + json.ToString(true));
        byte[] body = System.Text.Encoding.UTF8.GetBytes(json.ToString());
        WWW www = new WWW(url, body, headers);
        
        yield return www;
        if (www.error != null)
        {
            print("Platform posting - SUCCESS");
        }
    }
예제 #2
0
    // Use this for initialization
    void Start()
    {
        JSONObject configJSON = new JSONObject();
        JSONObject j = new JSONObject();
        JSONObject platforms = new JSONObject(JSONObject.Type.ARRAY);
        string thisDirectory = Directory.GetCurrentDirectory();
        bool platformDirectory = false;

        browser = browserContainer.GetComponent<Browser>();

        DirectoryInfo dir = new DirectoryInfo(thisDirectory + @"\Platforms");

        try {
            if (dir.Exists) {
                platformDirectory = true;
            } else {
                dir.Create();
                platformDirectory = true;
            }
        } catch (Exception e) {
            platformDirectory = false;
            Debug.Log(e);
        }

        if (platformDirectory) {
            FileInfo[] info = dir.GetFiles("*.png");
            platformTextures = new Texture2D[info.Length];
            platformNames = new string[info.Length];
            platformIdentities = new int[info.Length][];

            configJSON.AddField("player", "Bloodyaugust");
            configJSON.AddField("platforms", platforms);

            int i = 0;
            foreach (FileInfo f in info) {
                j = new JSONObject();
                WWW currentTexture = new WWW("file:///" + f);

                platformTextures[i] = currentTexture.texture;
                platformNames[i] = Path.GetFileNameWithoutExtension(f + "");
                platformIdentities[i] = TextureToIdentity(platformTextures[i]);

                platforms.Add(j);
                j.AddField("name", platformNames[i]);
                j.AddField("value", i.ToString());

                Debug.Log(Path.GetFileNameWithoutExtension(f + ""));

                i++;
            }

            browser.CallFunction("Messaging.trigger", "platforms", configJSON.ToString());
            Debug.Log(configJSON.ToString());
        }
    }
예제 #3
0
  public static void SaveToKeyChain(string keyName, string mValue) {
    #if UNITY_IPHONE
      if (Application.platform == RuntimePlatform.IPhonePlayer) {
        KeyChainBindings.SetStringForKey(keyName, mValue);
      }
		#endif
		#if UNITY_ANDROID
      if (Application.platform == RuntimePlatform.Android) {
        AndroidTools.SharedPreferencesSet(keyName, mValue);
      }
		#endif
		#if UNITY_EDITOR
		  string filePath = Path.Combine(Application.persistentDataPath, LOCAL_KEYCHAIN_FILE);
		  JSONObject data;
		  if (File.Exists(filePath)) {
  			string readText = File.ReadAllText(filePath);
  			data = JSONObject.Parse(readText);
  			data.Add(keyName, mValue);
  			File.WriteAllText(filePath, data.ToString());
  		} else {
  		  data = new JSONObject();
  		  data.Add(keyName, mValue);
  		  File.WriteAllText(filePath, data.ToString());
  		}
    #endif
  }
예제 #4
0
    public void LoadFriendRank(Action callback)
    {
        JSONArray friendList = new JSONArray ();

        foreach(JSONValue item in UserSingleton.Instance.FriendList){
            JSONObject friend = item.Obj;
            friendList.Add (friend ["id"]);
        }

        JSONObject requestBody = new JSONObject ();
        requestBody.Add ("UserID", UserSingleton.Instance.UserID);
        requestBody.Add ("FriendList", friendList);

        HTTPClient.Instance.POST (Singleton.Instance.HOST + "/Rank/Friend", requestBody.ToString(), delegate(WWW www) {

            Debug.Log("LoadFriendRank" + www.text);

            string response = www.text;

            JSONObject obj = JSONObject.Parse(response);

            JSONArray arr = obj["Data"].Array;

            foreach(JSONValue item in arr){
                int rank = (int)item.Obj["Rank"].Number;
                if(FriendRank.ContainsKey(rank)){
                    FriendRank.Remove(rank);
                }
                FriendRank.Add(rank,item.Obj);
            }

            callback();

        });
    }
예제 #5
0
 private void RequestFunction(string function, JSONObject data, Action<bool, string> callback)
 {
     HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.parse.com/1/functions/" + function);
     string postData = data.ToString();
     byte[] byteData = Encoding.ASCII.GetBytes(postData);
     request.ContentType = "application/json";
     request.ContentLength = byteData.Length;
     request.Method = "POST";
     request.Headers.Add("X-Parse-Application-Id", parseApplicationID);
     request.Headers.Add("X-Parse-REST-API-Key", parseRestAPIKey);
     request.Credentials = CredentialCache.DefaultCredentials;
     using (Stream stream = request.GetRequestStream()) { stream.Write(byteData, 0, byteData.Length); }
     try
     {
         request.BeginGetResponse(new AsyncCallback(delegate(IAsyncResult result)
         {
             HttpWebResponse response = (result.AsyncState as HttpWebRequest).EndGetResponse(result) as HttpWebResponse;
             using (Stream stream = response.GetResponseStream())
             {
                 StreamReader reader = new StreamReader(stream);
                 if (callback != null) callback(true, reader.ReadToEnd());
                 reader.Close();
                 response.Close();
             }
         }), request);
     }
     catch (Exception e)
     {
         Debug.Log(string.Format("Exception Cached: {0}|{1}", e.Source, e.Message));
         if (callback != null) callback(false, e.Message);
     }
 }
 public void OnCompleted(JSONObject @object, GraphResponse response)
 {
     try
     {
         if (response.Error != null)
         {
             System.Diagnostics.Debug.WriteLine(response.Error.ErrorMessage.ToString());
             var fbArgs = new FBEventArgs <string>(null, FacebookActionStatus.Error, response.Error.ErrorMessage.ToString());
             _onUserData?.Invoke(CrossFacebookClient.Current, fbArgs);
             _userDataTcs?.TrySetResult(new FacebookResponse <string>(fbArgs));
         }
         else
         {
             var fbArgs = new FBEventArgs <string>(@object?.ToString(), FacebookActionStatus.Completed);
             _onUserData?.Invoke(CrossFacebookClient.Current, fbArgs);
             _userDataTcs?.TrySetResult(new FacebookResponse <string>(fbArgs));
         }
     }
     catch (JSONException ex)
     {
         System.Diagnostics.Debug.WriteLine(ex.ToString());
         var fbArgs = new FBEventArgs <string>(null, FacebookActionStatus.Error, ex.ToString());
         _onUserData?.Invoke(CrossFacebookClient.Current, fbArgs);
         _userDataTcs?.TrySetResult(new FacebookResponse <string>(fbArgs));
     }
 }
예제 #7
0
        public static void BuildManifest()
        {
            JSONObject json = new JSONObject(JSONObject.Type.ARRAY);
            string[] levels = Directory.GetFiles(Application.dataPath + "/Levels_Exported/", "*.json");

            for (int i = 0; i < levels.Length; i++) {
                JSONObject data = new JSONObject(JSONObject.Type.OBJECT);
                string fileContents = File.ReadAllText(levels[i]);
                string hash = LevelManagementUtils.Hash(fileContents);
                data.AddField("Hash", hash);
                string url = levels[i].Replace(Application.dataPath, "http://podshot.github.io/TwoTogether" /*"http://127.0.0.1:8000/"*/);
                url = url.Replace("_Exported", "");
                data.AddField("URL", url);
                data.AddField("Name", levels[i].Replace(Application.dataPath + "/Levels_Exported/", ""));

                JSONObject thumb = new JSONObject(JSONObject.Type.OBJECT);
                thumb.AddField("URL", "http://podshot.github.io/TwoTogether/Thumbnails/" + levels[i].Replace(Application.dataPath + "/Levels_Exported/", "").Replace(".json", ".png"));
                thumb.AddField("Name", levels[i].Replace(Application.dataPath + "/Levels_Exported/", "").Replace(".json", ".png"));

                data.AddField("Thumbnail", thumb);
                json.Add(data);
            }

            TextWriter writer = new StreamWriter(Application.dataPath + "/Levels_Exported/levels_.manifest");
            writer.WriteLine(json.ToString(true));
            writer.Close();
            Debug.Log("Wrote manifest file");
        }
 private ISFSObject CreatePublicMessageObject(JSONObject jsonData, string commandId) {
   ISFSObject objOut = new SFSObject();
   objOut.PutByteArray("jsonData", Utils.ToByteArray(jsonData.ToString()));
   objOut.PutUtfString("message", jsonData.GetString("message"));
   objOut.PutUtfString("cmd", commandId);
   return objOut;
 }
 public void JoinLobby(int size)
 {
     JSONObject data = new JSONObject();
     data.AddField("size", size);
     Debug.Log("Join Lobby " + data.ToString());
     sendRequest(ServerAPI.RequestType.JoinLobby, data);
 }
예제 #10
0
	public virtual void Post(string url, Dictionary<string, string> data, System.Action<HttpResult> onResult) {
	
		this.MakeRequest(url, HttpMethods.POST, onResult, (r) => {

			JSONObject js = new JSONObject(data);
			var requestPayload = js.ToString();

			UTF8Encoding encoding = new UTF8Encoding();
			r.ContentLength = encoding.GetByteCount(requestPayload);
			r.Credentials = CredentialCache.DefaultCredentials;
			r.Accept = "application/json";
			r.ContentType = "application/json";
			
			//Write the payload to the request body.
			using ( Stream requestStream = r.GetRequestStream())
			{
				requestStream.Write(encoding.GetBytes(requestPayload), 0,
				                    encoding.GetByteCount(requestPayload));
			}

			return false;

		});

	}
예제 #11
0
    void OnGUI()
    {
        JSON = EditorGUILayout.TextArea(JSON);
        GUI.enabled = !string.IsNullOrEmpty(JSON);
        if(GUILayout.Button("Check JSON")) {
        #if PERFTEST
            Profiler.BeginSample("JSONParse");
            j = JSONObject.Create(JSON);
            Profiler.EndSample();
            Profiler.BeginSample("JSONStringify");
            j.ToString(true);
            Profiler.EndSample();
        #else
            j = JSONObject.Create(JSON);
        #endif
            Debug.Log(j.ToString(true));
        }
        if(j) {
            //Debug.Log(System.GC.GetTotalMemory(false) + "");
            if(j.type == JSONObject.Type.NULL)
                GUILayout.Label("JSON fail:\n" + j.ToString(true));
            else
                GUILayout.Label("JSON success:\n" + j.ToString(true));

        }
    }
예제 #12
0
 public void GetRoomStatus()
 {
     JSONObject data = new JSONObject();
     Prefs pref = new Prefs();
     data.AddField("token", pref.getToken());
     Debug.Log("GetRoomStatus" + data.ToString());
     sendRequest(ServerAPI.RequestType.GetGameStatus, data);
 }
예제 #13
0
 public void UpdateLobby()
 {
     JSONObject data = new JSONObject();
     Prefs pref = new Prefs();
     data.AddField("token", pref.getToken());
     Debug.Log("Update Lobby" + data.ToString());
     sendRequest(ServerAPI.RequestType.UpdateLobby, data);
 }
	private void DataCallBack (JSONObject result)
	{	
		Debug.Log ("Result " + result.ToString ());
		id.text = "id " + result.GetField ("userid").ToString (); 
		name.text = "name " + result.GetField ("name").ToString ();
		username.text = "username " + result.GetField ("username").ToString ();
		position.text = "position " + result.GetField ("position").ToString ();
	}
예제 #15
0
 void JsonThreadCallback(System.Object stateInfo)
 {
     SocketListener.start(listenPort, (writer, line) => {
         var json = new JSONObject(line);
         Debug.Log("Request : " + json.ToString());
         writer.WriteLine("Server reqponse");
         writer.Flush();
     });
 }
 private static string GetAdminToken()
 {
     JSONObject request = new JSONObject();
     request.AddField("client_id", CLIENT_ID);
     request.AddField("client_secret", CLIENT_SECRET);
     string response = SendRequestSync ("/oauth2/token", "POST", "application/json", null, null, request.ToString());
     JSONObject json = new JSONObject(response);
     return json.GetField("access_token").str;
 }
 void LoadLeaderboardDataSuccess(JSONObject data) {
   LeaderboardScreen.Tab selectedTab = (LeaderboardScreen.Tab)data.GetInt("type");
   LeaderboardScreen.SetData( data.GetArray("users"), selectedTab);
   Debug.Log("LoadLeaderboardDataSuccess " + data.ToString());
   if (ScreenManager.Instance.LeaderboardScreen != null) {
     ScreenManager.Instance.LeaderboardScreen.ShowTopPlayer(selectedTab);
   }
   PopupManager.Instance.CloseLoadingPopup();
 }
예제 #18
0
	public void SendJson(JSONObject json)
	{
		if (!playable) {
			//Debug.Log("Send JSON failed");
			return;
		}

		switch (communicateTheme)
		{
		case CommunicateTheme.bluetooth:
			Bluetooth.Instance().Send(json.ToString().Replace("\n",""));
			break;
		case CommunicateTheme.network:
			networkManager.Send(json.ToString().Replace("\n",""));

			break;
		}
	}
예제 #19
0
    public string ParseTo(Dictionary<string, string> data)
    {
        string rawdata = string.Empty;

        JSONObject jsonObj = new JSONObject(data);
        rawdata = jsonObj.ToString();

        return rawdata;
    }
 private void autocompleteCallback(JSONObject response)
 {
     JSONArray arr = JSON.Parse(response.ToString()).AsArray;
     foreach (JSONNode jn in arr)
     {
         if (!main.Instance.ingredientsManager.hasIngredient((string)jn))
             newButton(jn);   
     }
 }
예제 #21
0
	public static string SerializeStringIndDictionary(Dictionary <string, string> DICT )

	{
		_serializedObject = new JSONObject (JSONObject.Type.OBJECT);
		foreach (string Key in DICT.Keys) 
		{
		_serializedObject.AddField(Key.ToString(),DICT[Key].ToString());		
		}
		return _serializedObject.ToString ();
	}
        protected override void _pushEventGetContactsFinished(Provider provider, SocialPageData<UserProfile> contactsPage, string payload)
        {
            if (SoomlaProfile.IsProviderNativelyImplemented(provider)) return;
            List<JSONObject> profiles = new List<JSONObject>();
            foreach (var profile in contactsPage.PageData) {
                profiles.Add(profile.toJSONObject());
            }
            JSONObject contacts = new JSONObject(profiles.ToArray());

            soomlaProfile_PushEventGetContactsFinished(provider.ToString(), contacts.ToString(), payload, contactsPage.HasMore);
        }
예제 #23
0
    private string GetAndSetPlayerData()
    {
        // Setup the player data to send to the server.
        JSONObject objJSON_PlayerData = new JSONObject();

        objJSON_PlayerData.AddField("last_update_time", System.DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss"));
        objJSON_PlayerData.AddField("isMale", GLOBAL.Player.progress["isMale"].b);
        objJSON_PlayerData.AddField("index_BodyModel", GLOBAL.Player.progress["index_BodyModel"].i);
        objJSON_PlayerData.AddField("index_HairModel", GLOBAL.Player.progress["index_HairModel"].i);

        return objJSON_PlayerData.ToString();
    }
예제 #24
0
	public static string SerializeList(List<string> LST)
{
		_serializedObject = new JSONObject (JSONObject.Type.ARRAY);
		foreach (string s in LST)
		{
			_serializedObject.Add(s);
		
		}
		return _serializedObject.ToString ();


}
예제 #25
0
 public static void FormatJSON()
 {
     string[] files = Directory.GetFiles(Application.dataPath + "/Levels_Exported/", "*.json");
     for (int i = 0; i < files.Length; i++) {
         string content = File.ReadAllText(files[i]);
         JSONObject data = new JSONObject(content);
         File.Move(files[i], files[i].Replace(".json", ".raw_json"));
         TextWriter writer = new StreamWriter(files[i]);
         writer.Write(data.ToString());
         writer.Close();
     }
 }
예제 #26
0
파일: UserManager.cs 프로젝트: goodzsq/xyj
 private IEnumerator HttpRequest(string router, JSONObject args, Action<int, JSONObject> cb)
 {
     var formData = new WWWForm();
     formData.AddField("data", args.ToString());
     var www = new WWW(baseUrl + router, formData);
     yield return www;
     Debug.Log(www.text);
     var result = new JSONObject(www.text);
     var err = (int)result["err"].i;
     var data = result["data"];
     cb(err, data);
 }
예제 #27
0
		/// <summary>
		/// Fetches the friends' state from the server.
		/// The friends' state contains relevant information on completed levels
		/// and highscores for the provided list of users.
		/// </summary>
		/// <returns><c>true</c>, if the operation has started, <c>false</c> if it cannot.</returns>
		/// <param name="providerId">The social provider ID for which to get the friends'
		/// state</param>
		/// <param name="friendsProfileIds">a List of friends' profile IDs in the social
		/// network provided</param>
		public static bool FetchFriendsStates(int providerId, IList<string> friendsProfileIds) {
			SoomlaUtils.LogDebug (TAG, "SOOMLA/UNITY Fetching Friends States");

			JSONObject friendsProfileIdsJSON = new JSONObject(JSONObject.Type.ARRAY);
			foreach (string profileId in friendsProfileIds) {
				friendsProfileIdsJSON.Add(profileId);
			}
			bool result = false;

			#if UNITY_ANDROID && !UNITY_EDITOR
			AndroidJNI.PushLocalFrame(100);
			using(AndroidJavaClass jniGrowLeaderboardClass = new AndroidJavaClass("com.soomla.highway.unity.GrowLeaderboards")) {

				result = jniGrowLeaderboardClass.CallStatic<bool>("unityFetchFriendsStates", providerId, friendsProfileIdsJSON.ToString());
			}
			AndroidJNI.PopLocalFrame(IntPtr.Zero);
			#elif UNITY_IOS && !UNITY_EDITOR
			growLeaderboards_fetchFriendsStates(providerId, friendsProfileIdsJSON.ToString(), out result);
			#endif

			return result;
		}
예제 #28
0
	/**
	 * Weme sdk loginWeme
	 * 
	 * @param oAuthString - 
	 * @param WmInterfaceBrokerDelegate
	 */
	public void loginWeme(string clientId,string clientSecret,WmInterfaceBroker.WmInterfaceBrokerDelegate callback){
		if(WemeManager.isEmpty(clientId)==true||WemeManager.isEmpty(clientSecret)==true){
			Debug.Log("must not null clientId or clientSecret");
			return;
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.Add(JSON_KEY_URI,JSON_VALUE_PREFIX_URI+WM_HOST_WEME);
		JSONObject paramsObject = new JSONObject();
		paramsObject.Add("clientId",clientId);
		paramsObject.Add("clientSecret",clientSecret);
		jsonObject.Add(JSON_KEY_PARAMS,paramsObject);
		WmInterfaceBroker.getInstance.requestAsync(jsonObject.ToString(),callback);
	}
예제 #29
0
	void OnGUI() {
		JSON = EditorGUILayout.TextArea(JSON);
		GUI.enabled = JSON != "";
		if(GUILayout.Button("Check JSON")) {
			j = new JSONObject(JSON);
			Debug.Log(j.ToString(true));
		}
		if(j) {
			if(j.type == JSONObject.Type.NULL)
				GUILayout.Label("JSON fail:\n" + j.ToString(true));
			else
				GUILayout.Label("JSON success:\n" + j.ToString(true));
		}
	}
예제 #30
0
    public void sendMove(Vector3 move, bool crouch, bool jump)
    {
        JSONObject json = new JSONObject ();
        json.AddField ("action", "moveChar");
        JSONObject pos = new JSONObject();

        pos.AddField ("X", move.x.ToString());
        pos.AddField ("Y", move.y.ToString());
        pos.AddField ("Z", move.z.ToString());
        json.AddField ("position", pos);
        json.AddField ("id", id);
        json.AddField ("crouch", crouch);
        json.AddField ("jump", jump);
        send (json.ToString());
    }
        protected override void _pushEventGetContactsFinished(Provider provider, SocialPageData<UserProfile> contactsPage, string payload)
        {
            if (SoomlaProfile.IsProviderNativelyImplemented(provider)) return;
            List<JSONObject> profiles = new List<JSONObject>();
            foreach (var profile in contactsPage.PageData) {
                profiles.Add(profile.toJSONObject());
            }
            JSONObject contacts = new JSONObject(profiles.ToArray());

            AndroidJNI.PushLocalFrame(100);
            using(AndroidJavaClass jniSoomlaProfile = new AndroidJavaClass("com.soomla.profile.unity.ProfileEventHandler")) {
                ProfileJNIHandler.CallStaticVoid(jniSoomlaProfile, "pushEventGetContactsFinished",
                                                 provider.ToString(), contacts.ToString(), payload, contactsPage.HasMore);
            }
            AndroidJNI.PopLocalFrame(IntPtr.Zero);
        }
예제 #32
0
    IEnumerator getClip()
    {
        yield return(StartCoroutine(GetUserId()));

        UnityWebRequest www = UnityWebRequest.Get("https://api.twitch.tv/helix/clips?broadcaster_id=" + userId + "&first=5");

        www.SetRequestHeader("Client-Id", clientId);


        yield return(www.SendWebRequest());

        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log(www.error);
        }
        else
        {
            JSONObject obj = new JSONObject(www.downloadHandler.text);
            Debug.Log(obj.ToString());

            JSONObject data = obj["data"];

            foreach (JSONObject clipObject in data.list)
            {
                // Note: there is usually only one object here
                JSONObject embedObject = clipObject["embed_url"];
                Debug.Log("Embed URL: " + embedObject.str);



                Debug.Log("THUMBNAIL HACK");

                double     offset       = -1;
                JSONObject thumbNailObj = clipObject["thumbnail_url"];


                // Hacky way to get offset: https://clips-media-assets2.twitch.tv/28009905440-offset-40124-preview-480x272.jpg

                string thumbNailURL = thumbNailObj.str;

                int i = thumbNailURL.IndexOf("offset-");
                if (i >= 0)
                {
                    string rest = thumbNailURL.Substring(i);
                    // offset-40124-preview-480x272.jpg
                    i = rest.IndexOf("-") + 1;
                    if (i >= 0)
                    {
                        rest = rest.Substring(i);
                        int j = rest.IndexOf("-");
                        Debug.Log(rest);

                        if (j >= 0)
                        {
                            string finalOffset = rest.Substring(0, j);
                            Debug.Log("Final offset: " + finalOffset);
                            offset = double.Parse(finalOffset);
                        }
                    }
                }
                else
                {
                    Debug.Log("Thumbnail timestamp not found");
                }


                if (offset != -1)
                {
                    JSONObject videoIdObject = clipObject["video_id"];
                    Debug.Log("TYPE: " + videoIdObject.type + " " + videoIdObject.str);

                    // Deleted vods have empty video ids
                    if (videoIdObject.str != "")
                    {
                        int videoId = int.Parse(videoIdObject.str);
                        Debug.Log("video id: " + videoId);
                        yield return(StartCoroutine(GetChatLog(videoId, offset)));
                    }
                }
            }
        }
    }
예제 #33
0
        public IEnumerator SendCoroutine()
        {
            Spil spil = GameObject.FindObjectOfType <Spil>();

            platform = EditorUserBuildSettings.activeBuildTarget.ToString().Trim().ToLower();

#if UNITY_5_6_OR_NEWER
            bundleIdentifier = PlayerSettings.applicationIdentifier;
#elif UNITY_5_3_OR_NEWER
            bundleIdentifier = PlayerSettings.bundleIdentifier;
                        #endif

            AddDefaultParameters();

            WWWForm requestForm = new WWWForm();
            requestForm.AddField("name", eventName);
            requestForm.AddField("data", data.ToString());
            requestForm.AddField("customData", !customData.IsNull ? customData.Print() : "{}");


            var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            var time  = (long)(DateTime.Now.ToUniversalTime() - epoch).TotalMilliseconds;

            requestForm.AddField("ts", time.ToString());
            requestForm.AddField("queued", 0);
            if (Spil.Instance.GetPrivValue() > -1)
            {
                requestForm.AddField("priv", Spil.Instance.GetPrivValue());
            }


            if (spil.EditorDebugMode)
            {
                requestForm.AddField("debugMode", Convert.ToString(spil.EditorDebugMode).ToLower());
            }

            if (SpilUnityEditorImplementation.spilToken != null)
            {
                requestForm.AddField("spilToken", SpilUnityEditorImplementation.spilToken);
            }

            WWW request =
                new WWW(
                    "https://apptracker.spilgames.com/v1/native-events/event/" + platform + "/" + Spil.BundleIdEditor +
                    "/" + eventName, requestForm);
            yield return(request);

            SpilLogging.Log("Sending event: " + "Name: " + eventName + " \nData: " + data + " \nCustom Data: " +
                            customData.Print() + " \nTimestamp: " + time);

            if (request.error != null && !request.error.Equals(""))
            {
                if (Spil.BundleIdEditor == null || Spil.BundleIdEditor.Equals(""))
                {
                    SpilLogging.Error(
                        "Spil Initialize might not have been called! Please make sure you call Spil.Initialize() at app start!");
                }
                else if (request.responseHeaders != null && request.responseHeaders.Count > 0)
                {
                    foreach (KeyValuePair <string, string> entry in request.responseHeaders)
                    {
                        if (entry.Key.Equals("STATUS"))
                        {
                            if (entry.Value.Contains("401"))
                            {
                                SocialLoginManager.ProcessUnauthorizedResponse(request.text);
                                SpilLogging.Error("Unauthorized 401 event! Error: " + request.text);
                            }
                            else
                            {
                                SpilLogging.Error("Error getting data: " + request.error);
                                SpilLogging.Error("Error getting data: " + request.text);
                            }
                        }
                    }
                }
                else
                {
                    SpilLogging.Error("Error getting data: " + request.error);
                    SpilLogging.Error("Error getting data: " + request.text);
                }
            }
            else
            {
                JSONObject serverResponse = new JSONObject(request.text);
                SpilLogging.Log("Data returned: \n" + serverResponse);
                ResponseEvent.Build(serverResponse);
            }
            GameObject.Destroy(this);
        }
예제 #34
0
    void SubscribeEvents()
    {
        socket.On("open", (e) => {
            ui.Show(GameUI.View.GameSessionView);
            Debug.Log("Connnected...");
        });

        socket.On("connect", (e) => {
            ui.Show(GameUI.View.GameSessionView);
            Debug.Log("Connnected...");
            // RequestPlayersList();
            TryCreateNewPlayer();
            // RequestAddPlayer(GameClient.PlayerName);
            // RequestCurrentScore(GameClient.PlayerName);
        });

        socket.On("game.respondJoinedPlayers", (e) => {
            Debug.Log("Get player info...");
            JSONObject json = e.data;

            playerList.Clear();

            foreach (var key in json.keys)
            {
                var value = json[key];
                playerList.Add(value.str);
            }

            gameSessionUI.UpdatePlayerList(playerList);
        });

        socket.On("game.respondLeaderBoard", (e) => {
            List <JSONObject> info = e.data["info"].list;
            leaderBoardList.Clear();

            foreach (var obj in info)
            {
                leaderBoardList.Add(new Score(
                                        obj["name"].str,
                                        Convert.ToInt32(obj["tryCount"].n)
                                        ));
            }

            gameSessionUI.UpdateLeaderBoard(leaderBoardList);
            ui.Show(GameUI.View.LeaderBoardView);

            Debug.Log("Show leader board...");
        });

        socket.On("game.respondScore", (e) => {
            try
            {
                if (e.data.HasField("tryCount"))
                {
                    score = Mathf.Abs((int)e.data["tryCount"].n);
                    Debug.Log("Current Score : " + score);
                }
                else
                {
                    score = MAX_SCORE;
                }
            }
            catch (Exception ex)
            {
                score = MAX_SCORE;
                Debug.Log("What the f**k happen in score...?");
            }
        });

        socket.On("game.respondToStart", (e) => {
            Debug.Log("Game can start....");
            try
            {
                JSONObject jSON  = e.data["chooseNumber"];
                string strNumber = jSON.ToString();

                number = (int)Convert.ToDecimal(strNumber);
                Debug.Log("Get number : " + number);

                ui.Show(GameUI.View.InGameView);
            }
            catch (Exception ex)
            {
                Debug.Log("F**k...");
            }
        });

        socket.On("message.send", (e) => {
            string msg = e.data["message"].str;
            Debug.Log(msg);
            gameSessionUI.AddChatHistory(msg);
        });

        socket.On("disconnect", (e) => {
            ui.Show(GameUI.View.ConnectView);
            Debug.Log("Disconnect...");
        });

        socket.On("game.changePlayState", (e) => {
            IsGameStart = (e.data["isStart"].str == "1") ? true : false;
        });

        socket.On("game.hasWinner", (e) => {
            gameSessionUI.AddChatHistory("Winner is : " + e.data["winner"]);
        });
    }
        public async void OnCompleted(JSONObject json, GraphResponse response)
        {
            try
            {
                var data   = json.ToString();
                var result = JsonConvert.DeserializeObject <FacebookResult>(data);
                //var FbEmail = result.Email;
                Console.WriteLine(result);

                var accessToken = AccessToken.CurrentAccessToken;
                if (accessToken != null)
                {
                    FbAccessToken = accessToken.Token;

                    var(apiStatus, respond) = await RequestsAsync.Global.Get_SocialLogin(FbAccessToken, "facebook", UserDetails.DeviceId);

                    if (apiStatus == 200)
                    {
                        if (respond is AuthObject auth)
                        {
                            SetDataLogin(auth);

                            if (AppSettings.ShowWalkTroutPage)
                            {
                                Intent newIntent = new Intent(this, typeof(AppIntroWalkTroutPage));
                                newIntent.PutExtra("class", "login");
                                StartActivity(newIntent);
                            }
                            else
                            {
                                StartActivity(new Intent(this, typeof(TabbedMainActivity)));
                            }
                            Finish();
                        }
                    }
                    else if (apiStatus == 400)
                    {
                        if (respond is ErrorObject error)
                        {
                            var errorText = error.Error.ErrorText;

                            Methods.DialogPopup.InvokeAndShowDialog(this, GetText(Resource.String.Lbl_Security), errorText, GetText(Resource.String.Lbl_Ok));
                        }
                    }
                    else if (apiStatus == 404)
                    {
                        var error = respond.ToString();
                        Methods.DialogPopup.InvokeAndShowDialog(this, GetText(Resource.String.Lbl_Security), error, GetText(Resource.String.Lbl_Ok));
                    }

                    ProgressBar.Visibility       = ViewStates.Gone;
                    MButtonViewSignIn.Visibility = ViewStates.Visible;
                }
            }
            catch (Exception exception)
            {
                ProgressBar.Visibility       = ViewStates.Gone;
                MButtonViewSignIn.Visibility = ViewStates.Visible;
                Methods.DialogPopup.InvokeAndShowDialog(this, GetText(Resource.String.Lbl_Security), exception.Message, GetText(Resource.String.Lbl_Ok));
                Console.WriteLine(exception);
            }
        }
예제 #36
0
        private static void Save(JSONObject newJson)
        {
            string jsonString = newJson.ToString(JSON_INDENT_SPACE_COUNT);

            File.WriteAllText(RegistryToolSettings.Instance().ProjectManifestPath, jsonString);
        }
        protected override void _pushEventGetScoresFinished(GetScoresFinishedEvent ev)
        {
            if (SoomlaProfile.IsProviderNativelyImplemented(ev.Provider))
            {
                return;
            }
            List <JSONObject> scoreList = new List <JSONObject>();

            foreach (var sc in ev.Scores.PageData)
            {
                scoreList.Add(sc.toJSONObject());
            }
            JSONObject jsonSc = new JSONObject(scoreList.ToArray());

            soomlaProfile_PushEventGetScoresFinished(ev.Provider.ToString(), ev.From.toJSONObject().ToString(), jsonSc.ToString(), ev.Payload, ev.Scores.HasMore);
        }
 public void SaveVersionJson()
 {
     File.WriteAllText(_versionJsonPath, _versionJson.ToString());
 }
예제 #39
0
 protected void saveData()
 {
     File.WriteAllText(Path.Combine(filePath, "data.json"), json.ToString());
 }
예제 #40
0
 public static string ToJson(JSONObject obj)
 {
     return(obj.ToString());
 }
예제 #41
0
 public static string String()
 {
     return(jsonObject.ToString());
 }
예제 #42
0
 public void Save(JSONObject json)
 {
     try
     {
         File.WriteAllText(PersistentDataPath.Get() + "/ARLevel.idl", Encryptor.Encrypt(json.ToString()));
     }
     catch (IOException)
     {
         SaveLoad.ShowDiskFullDialog();
     }
 }
예제 #43
0
        private static void AddEventToStore(JSONObject eventData)
#endif
        {
            // Check if datastore is available
            if (!GAStore.IsTableReady)
            {
                GALogger.W("Could not add event: SDK datastore error");
                return;
            }

            // Check if we are initialized
            if (!GAState.Initialized)
            {
                GALogger.W("Could not add event: SDK is not initialized");
                return;
            }

            try
            {
                // Check db size limits (10mb)
                // If database is too large block all except user, session and business
                if (GAStore.IsDbTooLargeForEvents && !GAUtilities.StringMatch(eventData["category"].Value, "^(user|session_end|business)$"))
                {
                    GALogger.W("Database too large. Event has been blocked.");
                    return;
                }

                // Get default annotations
                JSONObject ev = GAState.GetEventAnnotations();

                // Merge with eventData
                foreach (KeyValuePair <string, JSONNode> pair in eventData)
                {
                    ev.Add(pair.Key, pair.Value);
                }

                // Create json string representation
                string json = ev.ToString();

                // output if VERBOSE LOG enabled

                GALogger.II("Event added to queue: " + json);

                // Add to store
                Dictionary <string, object> parameters = new Dictionary <string, object>();
                parameters.Add("$status", "new");
                parameters.Add("$category", ev["category"].Value);
                parameters.Add("$session_id", ev["session_id"].Value);
                parameters.Add("$client_ts", ev["client_ts"].Value);
                parameters.Add("$event", ev.SaveToBinaryBase64());
                string sql = "INSERT INTO ga_events (status, category, session_id, client_ts, event) VALUES($status, $category, $session_id, $client_ts, $event);";

                GAStore.ExecuteQuerySync(sql, parameters);

                // Add to session store if not last
                if (eventData["category"].Value.Equals(CategorySessionEnd))
                {
                    parameters.Clear();
                    parameters.Add("$session_id", ev["session_id"].Value);
                    sql = "DELETE FROM ga_session WHERE session_id = $session_id;";
                    GAStore.ExecuteQuerySync(sql, parameters);
                }
                else
                {
                    UpdateSessionTime();
                }
            }
            catch (Exception e)
            {
                GALogger.E("addEventToStoreWithEventData: error using json");
                GALogger.E(e.ToString());
            }
        }
예제 #44
0
    void Start()
    {
        //infoText.gameObject.active = false;
        infoText.gameObject.SetActive(false);

        //JSONObject usage example:

        //Parse string into a JSONObject:
        JSONObject jsonObject = JSONObject.Parse(stringToEvaluate);

        if (jsonObject == null)           //Just to shut up Unity's 'unused variable' warning
        {
        }

        //You can also create an "empty" JSONObject
        JSONObject emptyObject = new JSONObject();

        //Adding values is easy (values are implicitly converted to JSONValues):
        emptyObject.Add("key", "value");
        emptyObject.Add("otherKey", 123);
        emptyObject.Add("thirdKey", false);
        emptyObject.Add("fourthKey", new JSONValue(JSONValueType.Null));

        //You can iterate through all values with a simple for-each loop
        foreach (KeyValuePair <string, JSONValue> pair in emptyObject)
        {
            Debug.Log("key : value -> " + pair.Key + " : " + pair.Value);

            //Each JSONValue has a JSONValueType that tells you what type of value it is. Valid values are: String, Number, Object, Array, Boolean or Null.
            Debug.Log("pair.Value.Type.ToString() -> " + pair.Value.Type.ToString());

            if (pair.Value.Type == JSONValueType.Number)
            {
                //You can access values with the properties Str, Number, Obj, Array and Boolean
                Debug.Log("Value is a number: " + pair.Value.Number);
            }
        }

        //JSONObject's can also be created using this syntax:
        JSONObject newObject = new JSONObject {
            { "key", "value" },
            { "otherKey", 123 },
            { "thirdKey", false }
        };

        //JSONObject overrides ToString() and outputs valid JSON
        Debug.Log("newObject.ToString() -> " + newObject.ToString());

        //JSONObjects support array accessors
        Debug.Log("newObject[\"key\"].Str -> " + newObject["key"].Str);

        //It also has a method to do the same
        Debug.Log("newObject.GetValue(\"otherKey\").ToString() -> " + newObject.GetValue("otherKey").ToString());

        //As well as a method to determine whether a key exists or not
        Debug.Log("newObject.ContainsKey(\"NotAKey\") -> " + newObject.ContainsKey("NotAKey"));

        //Elements can removed with Remove() and the whole object emptied with Clear()
        newObject.Remove("key");
        Debug.Log("newObject with \"key\" removed: " + newObject.ToString());

        newObject.Clear();
        Debug.Log("newObject cleared: " + newObject.ToString());
    }
예제 #45
0
        private async void BtnOnClick(object sender, EventArgs e)
        {
            Utils.HideKeyboard(this);
            _progressBarDialog.Show();
            await Task.Run(async() =>
            {
                try
                {
                    JSONObject dataToSend = new JSONObject().Put("email", _usernameEditText.Text)
                                            .Put("password", _passwordEditText.Text).Put("imei",
                                                                                         Utils.GetDeviceIdentificator(this));

                    string response =
                        await WebServices.WebServices.Post(Constants.PublicServerAddress + "/api/login",
                                                           dataToSend);
                    Log.Error("LoginActivity", response);
                    if (response != null)
                    {
                        var responseJson = new JSONObject(response);
                        Log.Error("LoginActivity", "req response: " + responseJson);
                        switch (responseJson.GetInt("status"))
                        {
                        case 0:
                            Snackbar.Make(_layout, "Nu esti autorizat sa faci acest request!",
                                          Snackbar.LengthLong).Show();
                            break;

                        case 1:
                            Snackbar.Make(_layout, "Eroare la comunicarea cu serverul",
                                          Snackbar.LengthLong).Show();
                            break;

                        case 2:
                            string token      = new JSONObject(response).GetString("token");
                            string nume       = new JSONObject(response).GetString("nume");
                            bool logins       = new JSONObject(response).GetBoolean("logins");
                            string avatar     = new JSONObject(response).GetString("avatar");
                            string id         = new JSONObject(response).GetString("id");
                            string idClient   = new JSONObject(response).GetString("idClient");
                            string idPersoana = new JSONObject(response).GetString("idPersAsisoc");
                            string type       = new JSONObject(response).GetString("tip");

                            Utils.SetDefaults("Token", token);
                            Utils.SetDefaults("Imei", Utils.GetDeviceIdentificator(this));
                            Utils.SetDefaults("Email", _usernameEditText.Text);
                            Utils.SetDefaults("Logins", logins.ToString());
                            Utils.SetDefaults("Name", nume);
                            Utils.SetDefaults("Avatar", $"{Constants.PublicServerAddress}/{avatar}");
                            Utils.SetDefaults("Id", id);
                            Utils.SetDefaults("IdClient", idClient ?? "");
                            Utils.SetDefaults("IdPersoana", idPersoana ?? "");
                            Utils.SetDefaults("UserType", type);

                            StartActivity(logins ? typeof(MainActivity) : typeof(FirstSetup));

                            if (logins)
                            {
                                if (int.Parse(Utils.GetDefaults("UserType")) == 3)
                                {
                                    var _medicationServerServiceIntent = new Intent(this, typeof(MedicationServerService));
                                    StartService(_medicationServerServiceIntent);
                                    startConfigReceiver();
                                }
                            }


                            Finish();
                            break;

                        case 3:
                            Snackbar.Make(_layout, "Dispozitivul nu este inregistrat!",
                                          Snackbar.LengthLong).Show();
                            break;

                        case 4:
                            Snackbar.Make(_layout, "Nume de utilizator sau parola incorecte!",
                                          Snackbar.LengthLong).Show();
                            break;

                        case 5:
                            string cod = new JSONObject(response).GetString("codActiv");
                            ShowInactiveUserDialog(cod);
                            break;
                        }
                    }
                    else
                    {
                        var snack = Snackbar.Make(_layout, "Nu se poate conecta la server!",
                                                  Snackbar.LengthLong);
                        snack.Show();
                    }
                }
                catch (Exception ex)
                {
                    Log.Error("Eroare la parsarea Jsonului", ex.Message);
                }
            });

            _progressBarDialog.Dismiss();
        }
예제 #46
0
 public void SendJson(JSONObject json)
 {
     Send(json.ToString());
 }
예제 #47
0
        public async void OnCompleted(JSONObject json, GraphResponse response)
        {
            try
            {
                var data   = json.ToString();
                var result = JsonConvert.DeserializeObject <FacebookResult>(data);
                FbEmail = result.Email;

                ProgressBar.Visibility = ViewStates.Visible;
                BtnSignIn.Visibility   = ViewStates.Gone;

                var accessToken = AccessToken.CurrentAccessToken;
                if (accessToken != null)
                {
                    FbAccessToken = accessToken.Token;

                    //Login Api
                    var(apiStatus, respond) = await RequestsAsync.Auth.SocialLoginAsync(FbAccessToken, "facebook", UserDetails.DeviceId);

                    if (apiStatus == 200)
                    {
                        if (respond is LoginObject auth)
                        {
                            SetDataLogin(auth);

                            StartActivity(new Intent(this, typeof(BoardingActivity)));
                            Finish();
                        }
                    }
                    else if (apiStatus == 400)
                    {
                        if (respond is ErrorObject error)
                        {
                            string errorText = error.Error;
                            switch (errorText)
                            {
                            case "Please check your details":
                                Methods.DialogPopup.InvokeAndShowDialog(this, GetText(Resource.String.Lbl_Security), GetText(Resource.String.Lbl_ErrorPleaseCheckYourDetails), GetText(Resource.String.Lbl_Ok));
                                break;

                            case "Incorrect username or password":
                                Methods.DialogPopup.InvokeAndShowDialog(this, GetText(Resource.String.Lbl_Security), GetText(Resource.String.Lbl_ErrorLogin2), GetText(Resource.String.Lbl_Ok));
                                break;

                            case "Your account is not activated yet, please check your inbox for the activation link":
                                Methods.DialogPopup.InvokeAndShowDialog(this, GetText(Resource.String.Lbl_Security), GetText(Resource.String.Lbl_ErrorLogin3), GetText(Resource.String.Lbl_Ok));
                                break;

                            default:
                                Methods.DialogPopup.InvokeAndShowDialog(this, GetText(Resource.String.Lbl_Security), errorText, GetText(Resource.String.Lbl_Ok));
                                break;
                            }
                        }

                        ProgressBar.Visibility = ViewStates.Gone;
                        BtnSignIn.Visibility   = ViewStates.Visible;
                    }
                    else if (apiStatus == 404)
                    {
                        ProgressBar.Visibility = ViewStates.Gone;
                        BtnSignIn.Visibility   = ViewStates.Visible;
                        Methods.DialogPopup.InvokeAndShowDialog(this, GetText(Resource.String.Lbl_Security), respond.ToString(), GetText(Resource.String.Lbl_Ok));
                    }
                }
            }
            catch (Exception e)
            {
                ProgressBar.Visibility = ViewStates.Gone;
                BtnSignIn.Visibility   = ViewStates.Visible;
                Methods.DialogPopup.InvokeAndShowDialog(this, GetText(Resource.String.Lbl_Security), e.Message, GetText(Resource.String.Lbl_Ok));
                Console.WriteLine(e);
            }
        }
예제 #48
0
        private static void SendMessageLoop()
        {
            while (!Globals.IsApplicationExiting)
            {
                Thread.Sleep(500);
                if (_sendQueue.Count > 0 && _sendQueue.TryPeek(out var messageToSend))
                {
                    try
                    {
                        HttpWebRequest web = (HttpWebRequest)WebRequest.Create($"https://www.googleapis.com/youtube/v3/liveChat/messages?part=snippet");
                        web.Method = "POST";
                        web.Headers.Add("Authorization", $"{YouTubeOAuthToken.tokenType} {YouTubeOAuthToken.accessToken}");
                        web.ContentType = "application/json";

                        JSONObject container = new JSONObject();
                        container["snippet"] = new JSONObject();
                        container["snippet"]["liveChatId"]         = new JSONString(YouTubeLiveBroadcast.currentBroadcast.snippet.liveChatId);
                        container["snippet"]["type"]               = new JSONString("textMessageEvent");
                        container["snippet"]["textMessageDetails"] = new JSONObject();
                        container["snippet"]["textMessageDetails"]["messageText"] = new JSONString(messageToSend.Value);
                        string snippetString = container.ToString();
                        Plugin.Log($"Sending {snippetString}");
                        var postData = Encoding.ASCII.GetBytes(snippetString);
                        web.ContentLength = postData.Length;

                        using (var stream = web.GetRequestStream())
                            stream.Write(postData, 0, postData.Length);

                        using (HttpWebResponse resp = (HttpWebResponse)web.GetResponse())
                        {
                            if (resp.StatusCode != HttpStatusCode.OK)
                            {
                                using (Stream dataStream = resp.GetResponseStream())
                                {
                                    using (StreamReader reader = new StreamReader(dataStream))
                                    {
                                        var response = reader.ReadToEnd();
                                        Plugin.Log($"Status: {resp.StatusCode} ({resp.StatusDescription}), Response: {response}");
                                        continue;
                                    }
                                }
                            }

                            using (Stream dataStream = resp.GetResponseStream())
                            {
                                using (StreamReader reader = new StreamReader(dataStream))
                                {
                                    // Read the response into a JSON objecet
                                    var json = JSON.Parse(reader.ReadToEnd()).AsObject;

                                    // Then create a new YouTubeMessage object from it and send it along to the other StreamCore clients, excluding the assembly that sent the message
                                    var newMessage = new YouTubeMessage();
                                    newMessage.Update(json);

                                    var assemblyHash = messageToSend.Key.ToString();
                                    // Invoke YouTube message received callbacks
                                    YouTubeMessageHandlers.InvokeHandler(newMessage, assemblyHash);

                                    _sendQueue.TryDequeue(out var gone);
                                }
                            }
                        }
                    }
                    catch (ThreadAbortException ex)
                    {
                        return;
                    }
                    catch (Exception ex)
                    {
                        // Failed the send the message for some other reason, it will be retried next iteration
                        Plugin.Log($"Failed to send YouTube message, trying again in a few seconds! {ex.ToString()}");
                        Thread.Sleep(2500);
                    }
                }
            }
        }
        protected override void _pushEventInviteFinished(Provider provider, string requestId, List <string> invitedIds, string payload)
        {
            if (SoomlaProfile.IsProviderNativelyImplemented(provider))
            {
                return;
            }
            List <JSONObject> invited = new List <JSONObject>();

            foreach (var id in invitedIds)
            {
                invited.Add(JSONObject.StringObject(id));
            }
            JSONObject jsonInvited = new JSONObject(invited.ToArray());

            soomlaProfile_PushEventInviteFinished(provider.ToString(), SocialActionType.INVITE.ToString(), requestId, jsonInvited.ToString(), payload);
        }
예제 #50
0
    // [MenuItem("AssetBundles/Create Assets Map")]
    private static string CreateAssetsMap(string outputPath)
    {
        AssetDatabase.RemoveUnusedAssetBundleNames();

        string manifestPath = string.Format("{0}/{1}", outputPath, ABConfig.MANIFEST_NAME); // manifest文件自动生成的,没有后缀名
        string manifestMD5  = string.Empty;

        if (File.Exists(manifestPath))
        {
            manifestMD5 = FileUtility.GetFileHash(manifestPath);
        }
        JSONObject jsonManifest = new JSONObject();

        jsonManifest.Add(ABConfig.MANIFEST_NAME, manifestMD5);

        string[]   assetBundleNames     = AssetDatabase.GetAllAssetBundleNames();
        JSONObject jsonAssetBundleNames = new JSONObject();

        for (int i = 0; i < assetBundleNames.Length; i++)
        {
            string abPath = string.Format("{0}/{1}.{2}", outputPath, assetBundleNames[i], AB_FILE_EXTENSION);
            string abMD5  = string.Empty;
            if (File.Exists(abPath))
            {
                abMD5 = FileUtility.GetFileHash(abPath);
            }

            jsonAssetBundleNames.Add(string.Format("{0}.{1}", assetBundleNames[i], AB_FILE_EXTENSION), abMD5);
        }

        JSONObject jsonAssets = new JSONObject();

        for (int i = 0; i < assetBundleNames.Length; i++)
        {
            string[] assetPaths = AssetDatabase.GetAssetPathsFromAssetBundle(assetBundleNames[i]);
            for (int j = 0; j < assetPaths.Length; j++)
            {
                jsonAssets.Add(assetPaths[j], i);
            }
        }

        JSONObject jsonObject = new JSONObject
        {
            { ABConfig.KEY_SERVER, ABConfig.SERVER_URL },
            { ABConfig.KEY_VERSION, ABConfig.VERSION },
            { ABConfig.KEY_MANIFEST, jsonManifest },
            { ABConfig.KEY_ASSETBUNDLES, jsonAssetBundleNames },
            { ABConfig.KEY_ASSETS, jsonAssets }
        };

        string json = jsonObject.ToString();
        string assetsMapFullName = Application.streamingAssetsPath + "/" + ABConfig.NAME_ASSETSMAP;

        if (!Directory.Exists(Application.streamingAssetsPath))
        {
            Directory.CreateDirectory(Application.streamingAssetsPath);
        }
        StreamWriter sw = new StreamWriter(assetsMapFullName, false, Encoding.UTF8);

        try
        {
            sw.Write(json);
            sw.Flush();
            sw.Close();
        }
        catch (Exception e)
        {
            Debug.Log(e);
            sw.Close();
        }

        AssetDatabase.Refresh();

        return(assetsMapFullName);
    }
        //  FIXME: Generic export when recieves ignore field parameters
        // Add attribute like IgnoreExport or similar
        // For linked types do similar
        public override string ExportData(NodeGraphData data, List <Type> referenceTypes)
        {
            JSONObject exportJSON = new JSONObject();

            JSONObject graph = new JSONObject();

            JSONArray graphNodesReferences = new JSONArray();

            referenceTypes.Add(typeof(Node));
            referenceTypes.Add(typeof(NodeGraph));
            referenceTypes.Add(typeof(NodePort));

            graph.Add("type", new JSONString(data.graph.GetType().AssemblyQualifiedName));
            graph.Add("name", new JSONString(data.graph.name));
            graph.Add("id", new JSONNumber(data.graph.GetHashCode()));
            NodeGraph g = data.graph;

            graph = (JSONObject)SimpleJSONExtension.ToJSON(g, graph, new List <string>()
            {
                "sceneVariables"
            }, referenceTypes);

            JSONArray connections = new JSONArray();

            for (int c = 0; c < data.connections.Count; c++)
            {
                JSONObject connection = new JSONObject();
                connection.Add("port1ID", data.connections[c].port1ID);
                connection.Add("port2ID", data.connections[c].port2ID);
                connections.Add(connection);
            }

            JSONArray nodes = new JSONArray();

            for (int n = 0; n < data.nodes.Count; n++)
            {
                Node       node     = data.nodes[n].node;
                JSONObject nodeJSON = new JSONObject();
                nodeJSON.Add("name", node.name);
                nodeJSON.Add("type", node.GetType().AssemblyQualifiedName);
                nodeJSON.Add("position", node.position);
                nodeJSON.Add("id", node.GetHashCode());

                JSONArray nodePorts = new JSONArray();

                for (int np = 0; np < data.nodes[n].ports.Count; np++)
                {
                    NodePort port = data.nodes[n].ports[np].port;

                    JSONObject nodePortJSON = new JSONObject();
                    nodePortJSON.Add("name", port.fieldName);
                    nodePortJSON.Add("id", port.GetHashCode());
                    nodePortJSON.Add("dynamic", port.IsDynamic);
                    nodePortJSON.Add("valueType", port.ValueType.AssemblyQualifiedName);
                    nodePortJSON.Add("typeConstraint", (int)port.typeConstraint);
                    nodePortJSON.Add("connectionType", (int)port.connectionType);
                    nodePortJSON.Add("direction", (int)port.direction);

                    nodePorts.Add(nodePortJSON);
                }

                nodeJSON.Add("ports", nodePorts);

                nodeJSON = (JSONObject)SimpleJSONExtension.ToJSON(node, nodeJSON, new List <string>(), referenceTypes);

                nodes.Add(nodeJSON);
            }

            exportJSON.Add("graph", graph);
            exportJSON.Add("connections", connections);
            exportJSON.Add("nodes", nodes);

            return(exportJSON.ToString());
        }
예제 #52
0
        public static string Serialize()
        {
            var config = new JSONObject();

            try
            {
                config.Add("gca", Gca);
                config.Add("psa", Psa);
                config.Add("psat", Psat);
                config.Add("csa", Csa);
                config.Add("csat", Csat);
                config.Add("isa", Isa);
                config.Add("domainName", DomainName);
                config.Add("gcpn", Gcpn);
                config.Add("malv", Malv);
                config.Add("mamv", Mamv);
                config.Add("malvcl", Malvcl);
                config.Add("malvdl", Malvdl);
                config.Add("sba", Sba);
                config.Add("rba", Rba);
                config.Add("cu", Cu);
                config.Add("ecpn", Ecpn);
                config.Add("uppu", Uppu);
                config.Add("sucpn", Sucpn);
                config.Add("icu", Icu);
                config.Add("bglp", Bglp);
                config.Add("bllp", Bllp);
                config.Add("bvl", Bvl);
                config.Add("qpl", Qpl);
                config.Add("gclpu", Gclpu);
                config.Add("gcru", Gcru);
                config.Add("gcuph", Gcuph);
                config.Add("ehd", Ehd);
                config.Add("ssoleu", Ssoleu);
                config.Add("ssolu", Ssolu);
                config.Add("ssosu", Ssosu);
                config.Add("ssoiau", Ssoiau);
                config.Add("ssolou", Ssolou);
                config.Add("ssogbu", Ssogbu);
                config.Add("ahrrn", Ahrrn);
                config.Add("adurl", Adurl);
                config.Add("gcid", Gcid);
                config.Add("gcsid", Gcsid);
                config.Add("gcv", Gcv);
                config.Add("gcau", Gcau);
                config.Add("PCCT", Pcct);
                config.Add("PCCTT", Pcctt);
                config.Add("wsto", Wsto);
                config.Add("searchto", Searchto);
                config.Add("getConfigTimeout", GetConfigTimeout);
                config.Add("pmto", Pmto);
                config.Add("smit", Smit);
                config.Add("pmttl", Pmttl);
                config.Add("WSCWTI", Wscwti);
                config.Add("mrt", Mrt);
                config.Add("mmrc", Mmrc);
                config.Add("pcrit", Pcrit);
                config.Add("gcrt", Gcrt);
                config.Add("rvt", Rvt);
                config.Add("businessId", BusinessId);
                config.Add("bcpid", Bcpid);
                config.Add("dmt", Dmt);
                config.Add("gchc", Gchc);
                config.Add("cevid", Cevid);
                config.Add("gldc", Gldc);
                config.Add("mtml", Mtml);
                config.Add("meim", Meim);
                config.Add("glms", Glms);
                config.Add("gous", Gous);
                config.Add("gsus", Gsus);
                config.Add("ormm", Ormm);
                config.Add("mormd", Mormd);
                config.Add("gtdt", Gtdt);
                config.Add("qmt", Qmt);
                config.Add("glma", Glma);
                config.Add("glt", Glt);
                config.Add("glit", Glit);
                config.Add("siadi", Siadi);
                config.Add("glrdd", Glrdd);
                config.Add("cmp", Cmp);
                config.Add("cf", Cf);
                config.Add("hrt", Hrt);
                config.Add("msdtc", Msdtc);
                config.Add("gctmhp", Gctmhp);
                config.Add("gciv", Gciv);
                config.Add("malvfu", Malvfu);
                config.Add("rctam", Rctam);
                config.Add("suml", Suml);
                config.Add("cmc", Cmc);
                config.Add("vbif", Vbif);
                config.Add("nsu", Nsu);
                config.Add("lep", Lep);
                config.Add("dlor", Dlor);
                config.Add("ufs", Ufs);
                config.Add("har", Har);
                config.Add("harfs", Harfs);
                config.Add("ure", Ure);
                config.Add("utc", Utc);
                config.Add("ciid", Ciid);
                config.Add("ehet", Ehet);
                config.Add("pt", Pt);
                config.Add("gcd", Gcd);
                config.Add("lcd", Lcd);
            }
            catch (Exception e)
            {
                Debug.LogError("Exception: " + e.Message);
                //throw new ServiceException(e);
            }

            return(config.ToString());
        }
    private static string GetAdminToken()
    {
        JSONObject request = new JSONObject();

        request.AddField("client_id", CLIENT_ID);
        request.AddField("client_secret", CLIENT_SECRET);
        string     response = SendRequestSync("/oauth2/token", "POST", "application/json", null, null, request.ToString());
        JSONObject json     = new JSONObject(response);

        return(json.GetField("access_token").str);
    }
예제 #54
0
 public override string ToString()
 {
     return(jsonObject.ToString());
 }
    public void LoginGameServer()
    {
        // 페이스북 로그인 정보를 우리 게임 서버로 보내겠습니다.
        JSONObject body = new JSONObject();

        body.Add("FacebookID", UserSingleton.Instance.FacebookID);
        body.Add("FacebookAccessToken", UserSingleton.Instance.FacebookAccessToken);
        body.Add("FacebookName", UserSingleton.Instance.Name);
        body.Add("FacebookPhotoURL", UserSingleton.Instance.FacebookPhotoURL);

        Debug.Log("Send To Server:" + body.ToString());

        HTTPClient.Instance.POST(Singleton.Instance.HOST + "/Login/Facebook",
                                 body.ToString(),
                                 delegate(WWW www)
        {
            Debug.Log("LoginGameServer ( www.text ) :" + www.text);

            /*
             * :{ "Data":
             *    { "UserID":4,
             *      "FacebookID":"1499107166845512",
             *      "FacebookName":"???",
             *      "FacebookPhotoURL":"http://graph.facebook.com/1499107166845512/picture?type=square",
             *      "FacebookAccessToken":null,
             *      "Point":0,
             *      "AccessToken":"faff052f-d5a0-4df9-acf1-6817823e42b7",
             *      "CreatedAt":"2018-09-10T13:56:22",
             *      "Diamond":0,
             *      "Health":0,
             *      "Defense":0,
             *      "Damage":0,
             *      "Speed":0,
             *      "HealthLevel":0,
             *      "DefenseLevel":0,
             *      "DamageLevel":0,
             *      "SpeedLevel":0,
             *      "Level":0,
             *      "Experience":0,
             *      "ExpForNextLevel":0,
             *      "ExpAfterLastLevel":0},
             * "Message":"New User",
             * "ResultCode":2}
             */

            JSONObject response = JSONObject.Parse(www.text);

            int ResultCode = (int)response["ResultCode"].Number;
            if (ResultCode == 1 || ResultCode == 2)
            {
                JSONObject Data = response.GetObject("Data");
                UserSingleton.Instance.UserID      = (int)Data["UserID"].Number;
                UserSingleton.Instance.AccessToken = Data["AccessToken"].Str;
                StartCoroutine(LoadDataFromGameServer());
            }
            else
            {
                // 로그인 실패
            }
        });
    }
예제 #56
0
    /// <summary>
    /// 스크립트로 가장먼저 서버의 ack 를 받는 코드
    /// </summary>
    /// <param name="Ans"></param>
    public void Receiver(JSONObject jsonObject, NetCallBack callback)
    {
        PROTOCOL protocol = (PROTOCOL)jsonObject["cmd"].n;

        Debug.Log(protocol + ": " + jsonObject.ToString());

        int errno = (int)jsonObject["errno"].n;

        if (errno == 0)
        {
            switch (protocol)
            {
            case PROTOCOL.P_SERVICE_INFO:
                P_SERVICE_INFO(jsonObject);
                break;

            case PROTOCOL.P_USER_LOGIN:
                P_USER_LOGIN(jsonObject);
                break;

            case PROTOCOL.P_USER_INFO:
                P_USER_INFO(jsonObject);
                break;

            case PROTOCOL.P_USER_LIST:
                P_USER_LIST(jsonObject);
                break;

            case PROTOCOL.P_USER_SETPW:
                P_USER_SETPW(jsonObject);
                break;

            case PROTOCOL.P_USER_UPGRADE:
                P_USER_UPGRADE(jsonObject);
                break;

            case PROTOCOL.P_USER_NOTIFY:
                P_USER_NOTIFY(jsonObject);
                break;

            case PROTOCOL.P_USER_NICKNAME:
                P_USER_NICKNAME(jsonObject);
                break;

            case PROTOCOL.P_GAME_START:
                P_GAME_START(jsonObject);
                break;

            case PROTOCOL.P_GAME_RESULT:
                P_GAME_RESULT(jsonObject);
                break;

            case PROTOCOL.P_GAME_LOG:
                P_GAME_LOG(jsonObject);
                break;

            case PROTOCOL.P_GAME_REVENGE:
                P_GAME_REVENGE(jsonObject);
                break;

            default:
                Debug.LogError("not found protocol");
                break;
            }
        }
        else
        {
            // 팝업으로 에러 띄움
            //ShowErrorPopup(errno);
            UIManager.instance.CreateOKPopup(errno);
            Debug.Log("ErrNo : " + protocol.ToString() + "(" + errno + ")");
        }

        if (callback != null)
        {
            callback(jsonObject);
        }
    }
예제 #57
0
    private readonly string kafkaURL    = "192.168.160.20:9093";  // "localhost:9092"

    void executeOrder()
    {
        if (GameObject.Find("Btn Open Session").GetComponent <Animator>().GetCurrentAnimatorStateInfo(0).IsName("press"))
        {
            print("open Session");             ///////////////////////////////////////////////////////////////////////////////////////////////////////////////

            TMP_InputField titleInput    = GameObject.Find("TitleInput").GetComponent <TMP_InputField>();
            TMP_InputField durationInput = GameObject.Find("DurationInput").GetComponent <TMP_InputField>();
            TMP_InputField wordsInput    = GameObject.Find("WordsInput").GetComponent <TMP_InputField>();

            titleInput.text    = "test01";
            durationInput.text = "600";
            wordsInput.text    = "tree,ball";

            if (int.TryParse(durationInput.text, out int durationInput_int))
            {
                JSONArray words     = new JSONArray();
                string[]  words_raw = wordsInput.text.Split(',');
                for (int i = 0; i < words_raw.Length; i++)
                {
                    words.Add(words_raw[i]);
                }

                JSONObject body = new JSONObject();
                body["title"]    = titleInput.text;
                body["duration"] = durationInput_int;
                body["words"]    = words;

                StartCoroutine(PostGameSession(baseURL + "session", body.ToString(), LoginData.Token, sessionIdStr => {
                    Debug.Log(sessionIdStr);
                    JSONNode sessionIdJSON = JSONObject.Parse(sessionIdStr);
                    int sessionId          = sessionIdJSON["id"];
                    Debug.Log(sessionId);
                    SessionData.SessionId = sessionId;
                }));
            }
        }
        else if (GameObject.Find("Btn Start").GetComponent <Animator>().GetCurrentAnimatorStateInfo(0).IsName("press"))
        {
            print("Start");                                                //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            StartCoroutine(GetGameSession(commandsURL + "session/" + SessionData.SessionId + "/action/start", authenticate(LoginData.Username, "12345678"), response => {
                SessionData.KafkaTopic = "esp54_" + SessionData.SessionId; //"esp54_1"; //"actor0002";
                SessionData.KafkaProps = new Dictionary <string, string> {
                    { "group.id", "test" },
                    { "bootstrap.servers", kafkaURL },
                    { "enable.auto.commit", "false" },
                    { "auto.offset.reset", "latest" }
                };
                changeScene("Actor_Scene");
            }));
        }
        else if (GameObject.Find("Btn Invite Player").GetComponent <Animator>().GetCurrentAnimatorStateInfo(0).IsName("press"))
        {
            print("Invite Player");             //////////////////////////////////////////////////////////////////////////////////////////////////////////////
        }
        else if (GameObject.Find("Btn Go Back").GetComponent <Animator>().GetCurrentAnimatorStateInfo(0).IsName("press"))
        {
            print("Go Back");
            changeScene("Main_Menu_Scene");              /////////////////////////////////////////////////////////////////////////////////////////////////////
        }
    }
예제 #58
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="customerNo">客户编码</param>
        /// <param name="customerLevel">客户等级(1-8,默认1)</param>
        /// <param name="countryNo">国家编码</param>
        /// <param name="city">城市</param>
        /// <param name="zipCode">邮编</param>
        /// <param name="currencyNo">币别</param>
        /// <param name="inLogisWay">发货方式</param>
        public static Dictionary <string, object> GetFrei123(Context ctx, AbsSynchroDataInfo info)
        {
            #region 参数
            Dictionary <string, object> dict = null;

            if (info != null)
            {
                K3SalOrderInfo order = info as K3SalOrderInfo;

                if (order != null)
                {
                    long   timeStamp = GetTimeStamp(DateTime.Now);                                              //时间戳
                    string phpKey    = "ERPSHIPPINGFREE";                                                       //签名key
                    string signMsg   = MD5Encrypt(order.FCustId + timeStamp + phpKey, Encoding.UTF8).ToUpper(); //签名(需大写)

                    JSONObject jObj = new JSONObject();
                    jObj.Add("customer_id", order.FCustId);
                    jObj.Add("whole", !string.IsNullOrWhiteSpace(order.FCustLevel) ? order.FCustLevel.Substring(order.FCustLevel.Length - 1, 1) : "");
                    jObj.Add("country", order.F_HS_RecipientCountry.ToUpper()); //国家代号(例如:US)
                    jObj.Add("city", order.F_HS_DeliveryCity);                  //收货地址城市
                    jObj.Add("code", order.F_HS_PostCode);                      //收货地址邮编
                    jObj.Add("currency", order.FSettleCurrId);                  //货币类型(例如:USD)(首字母要大写)
                    jObj.Add("time_stamp", timeStamp);                          //时间戳
                    jObj.Add("signMsg", signMsg);                               //签名

                    JSONArray  rows      = null;
                    JSONObject products  = null;
                    JSONObject row       = null;
                    string     dlcHSName = string.Empty;

                    if (order.OrderEntry != null && order.OrderEntry.Count > 0)
                    {
                        var groups = from o in order.OrderEntry
                                     where !string.IsNullOrWhiteSpace(o.FMaterialId) && !string.IsNullOrWhiteSpace(o.FStockId)
                                     group o by o.FStockId
                                     into g
                                     select g;

                        if (groups != null && groups.Count() > 0)
                        {
                            products = new JSONObject();

                            foreach (var group in groups)
                            {
                                if (group != null && group.Count() > 0)
                                {
                                    rows      = new JSONArray();
                                    dlcHSName = GetStockName(ctx, group.FirstOrDefault().FStockId);

                                    foreach (var item in group)
                                    {
                                        if (item != null && !item.FMaterialId.StartsWith("99."))
                                        {
                                            row = new JSONObject();
                                            row.Add("fix_id", item.FMaterialId);
                                            row.Add("quantity", item.FQTY);

                                            rows.Add(row);
                                        }
                                    }

                                    if (!string.IsNullOrWhiteSpace(dlcHSName) && rows.Count > 0)
                                    {
                                        products.Add(dlcHSName, rows);
                                    }
                                }
                            }

                            jObj.Add("products", products);
                        }
                    }


                    #endregion

                    //获取运费
                    HttpClient http = new HttpClient()
                    {
                        IsProxy = true
                    };
                    //http.Url = "https://test.healthcabin.net/index.php?t_method=shipping";  //测试地址
                    http.Url     = "https://www.healthcabin.net/index.php?t_method=shipping"; //正式地址
                    http.Content = "";                                                        //清除之前的记录
                    http.Content = string.Concat("&ERP=", jObj.ToString());                   //线上那边要求以键值对参数的形式传过去
                    string result = "";
                    try
                    {
                        result = http.PostData();
                    }
                    catch (Exception)
                    {
                        //服务器在美国,存在连不上远程服务器的情况,此时等待一秒再请求
                        System.Threading.Thread.Sleep(1000);
                        result = http.PostData();
                    }
                    StringBuilder errorMes = new StringBuilder();
                    List <Dictionary <string, string> > lstFreiInfo = AnalysisResult(result, ref errorMes);
                    if (errorMes.Length > 0)
                    {
                    }

                    var freiData = lstFreiInfo.Where(o => o["F_HS_FreTiltle"].Contains(order.F_HS_DropShipDeliveryChannel)).FirstOrDefault();

                    if (freiData != null)
                    {
                        dict = new Dictionary <string, object>();

                        string outLogisWay   = freiData["F_HS_FreTiltle"];     //线上发货方式
                        string freiAmount    = freiData["F_HS_FreAmount"];     //运费金额(结算币别)
                        string freiAmountUSD = freiData["F_HS_AmountNoteUSD"]; //各发货仓运费(USD)


                        dict.Add("F_HS_FreTiltle", outLogisWay == null ? "": outLogisWay);
                        dict.Add("F_HS_FreAmount", freiAmount);
                        dict.Add("F_HS_AmountNoteUSD", freiAmountUSD == null ?"": freiAmountUSD);
                    }
                }
            }

            return(dict);
        }
예제 #59
0
    IEnumerator GetUpdates()
    {
        result.text = "Getting updates \n\n Loading ...";

        JSONObject myData = new JSONObject(JSONObject.Type.OBJECT);

        myData.AddField("username", playerName.value);

        using (UnityWebRequest www = UnityWebRequest.Put(serverAddress.value + endPoint, myData.ToString()))
        {
            www.method = UnityWebRequest.kHttpVerbGET;
            www.SetRequestHeader("Content-Type", "application/json");
            www.SetRequestHeader("Accept", "application / json");

            yield return(www.SendWebRequest());

            next.interactable = true;
            JSONObject res = new JSONObject(www.downloadHandler.text);

            if (res["error"] && res["error"].b)
            {
                result.text = res["message"].str;
                yield break;
            }

            if (www.result != UnityWebRequest.Result.Success)
            {
                result.text = errorMessage.value;
                Debug.Log(www.error);
                yield break;
            }

            result.text = res["message"].str;

            foreach (JSONObject update in res["updates"].list)
            {
                GameObject up = Instantiate(updatePrefab, new Vector3(0, 0, 0), Quaternion.identity);
                up.transform.SetParent(updateContainer);
                up.transform.Find("Content").GetComponent <TMP_Text>().text = update["content"].str;
                up.GetComponent <RectTransform>().localScale = new Vector3(1, 1, 1);
                updates.Add(up);
            }

            result.gameObject.SetActive(false);
            updateMenu.SetActive(true);
            StartCoroutine(UpdatePosY(res["updates"].list.Count));
        }
    }
예제 #60
0
        public KeyValuePair <EGAHTTPApiResponse, JSONObject> RequestInitReturningDict(string configsHash)
#endif
        {
            JSONObject         json;
            EGAHTTPApiResponse result  = EGAHTTPApiResponse.NoResponse;
            string             gameKey = GAState.GameKey;

            // Generate URL
            string url = remoteConfigsBaseUrl + "/" + initializeUrlPath + "?game_key=" + gameKey + "&interval_seconds=0&configs_hash=" + configsHash;

            GALogger.D("Sending 'init' URL: " + url);

            JSONObject initAnnotations = GAState.GetInitAnnotations();

            // make JSON string from data
            string JSONstring = initAnnotations.ToString();

            if (string.IsNullOrEmpty(JSONstring))
            {
                result = EGAHTTPApiResponse.JsonEncodeFailed;
                json   = null;
                return(new KeyValuePair <EGAHTTPApiResponse, JSONObject>(result, json));
            }

            string         body                = "";
            HttpStatusCode responseCode        = (HttpStatusCode)0;
            string         responseDescription = "";
            string         authorization       = "";

            try
            {
                byte[]         payloadData = CreatePayloadData(JSONstring, false);
                HttpWebRequest request     = CreateRequest(url, payloadData, false);
                authorization = request.Headers[HttpRequestHeader.Authorization];
#if WINDOWS_UWP || WINDOWS_WSA
                using (Stream dataStream = await request.GetRequestStreamAsync())
#else
                using (Stream dataStream = request.GetRequestStream())
#endif
                {
                    dataStream.Write(payloadData, 0, payloadData.Length);
                }

#if WINDOWS_UWP || WINDOWS_WSA
                using (HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse)
#else
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
#endif
                {
                    using (Stream dataStream = response.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(dataStream))
                        {
                            string responseString = reader.ReadToEnd();

                            responseCode        = response.StatusCode;
                            responseDescription = response.StatusDescription;

                            // print result
                            body = responseString;
                        }
                    }
                }
            }
            catch (WebException e)
            {
                if (e.Response != null)
                {
                    using (HttpWebResponse response = (HttpWebResponse)e.Response)
                    {
                        using (Stream streamResponse = response.GetResponseStream())
                        {
                            using (StreamReader streamRead = new StreamReader(streamResponse))
                            {
                                string responseString = streamRead.ReadToEnd();

                                responseCode        = response.StatusCode;
                                responseDescription = response.StatusDescription;

                                body = responseString;
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                GALogger.E(e.ToString());
            }

            // process the response
            GALogger.D("init request content : " + body + ", JSONstring: " + JSONstring);

            JSONNode           requestJsonDict     = JSON.Parse(body);
            EGAHTTPApiResponse requestResponseEnum = ProcessRequestResponse(responseCode, responseDescription, body, "Init");

            // if not 200 result
            if (requestResponseEnum != EGAHTTPApiResponse.Ok && requestResponseEnum != EGAHTTPApiResponse.Created && requestResponseEnum != EGAHTTPApiResponse.BadRequest)
            {
                GALogger.D("Failed Init Call. URL: " + url + ", Authorization: " + authorization + ", JSONString: " + JSONstring);
                result = requestResponseEnum;
                json   = null;
                return(new KeyValuePair <EGAHTTPApiResponse, JSONObject>(result, json));
            }

            if (requestJsonDict == null)
            {
                GALogger.D("Failed Init Call. Json decoding failed");
                result = EGAHTTPApiResponse.JsonDecodeFailed;
                json   = null;
                return(new KeyValuePair <EGAHTTPApiResponse, JSONObject>(result, json));
            }

            // print reason if bad request
            if (requestResponseEnum == EGAHTTPApiResponse.BadRequest)
            {
                GALogger.D("Failed Init Call. Bad request. Response: " + requestJsonDict.ToString());
                // return bad request result
                result = requestResponseEnum;
                json   = null;
                return(new KeyValuePair <EGAHTTPApiResponse, JSONObject>(result, json));
            }

            // validate Init call values
            JSONObject validatedInitValues = GAValidator.ValidateAndCleanInitRequestResponse(requestJsonDict, requestResponseEnum == EGAHTTPApiResponse.Created);

            if (validatedInitValues == null)
            {
                result = EGAHTTPApiResponse.BadResponse;
                json   = null;
                return(new KeyValuePair <EGAHTTPApiResponse, JSONObject>(result, json));
            }

            // all ok
            result = requestResponseEnum;
            json   = validatedInitValues;
            return(new KeyValuePair <EGAHTTPApiResponse, JSONObject>(result, json));
        }