Add() public method

public Add ( AddJSONConents content ) : void
content AddJSONConents
return void
Example #1
0
    public void LoadFriendRank(Action callback)
    {
        JSONArray friendList = new JSONArray ();

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

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

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

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

            string response = www.text;

            JSONObject obj = JSONObject.Parse(response);

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

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

            callback();

        });
    }
  public void Play(int betPerLineIndex, int numLines) {
    JSONObject jsonData = new JSONObject();
		jsonData.Add("betPerLine", betPerLineIndex);
		jsonData.Add("numLines", numLines);
		jsonData.Add("gameType", GetCommandByGameType(ScreenManager.Instance.CurrentSlotScreen.GetCrtGameType()));
		SmartfoxClient.Instance.HandleServerRequest(CreateExtensionRequest(Command.SLOT_MACHINE.SLOT_PLAY, jsonData));
  }
  public override void Init(object[] data) {
    base.Init(data);
    List<Buddy> buddyList = SmartfoxClient.Instance.GetBuddyList();
    if (buddyList.Count > 0) {
      Utils.SetActive(noFriendLabel, false);
      EventDelegate.Set(btnSendInvite.onClick, EventSendInvite);
			JSONObject friend;
			friendList = new JSONArray();
			for (int i = 0; i < buddyList.Count; i++) {
				friend = new JSONObject();
				if (buddyList[i].IsOnline) {
					friend.Add("displayName", buddyList[i].GetVariable("displayName").GetStringValue());
					friend.Add("cash", (long)buddyList[i].GetVariable("cash").GetDoubleValue());
					friend.Add("username", buddyList[i].Name);
					friendList.Add(friend);
				}
			}
			InitScrollViewData(friendList);
    } else {
			// TO DO - dont have friend message
      Utils.SetActive(scrollview.gameObject, false);
      Utils.SetActive(btnSendInvite.gameObject, false);
      Utils.SetActive(noFriendLabel, true);
      Debug.Log("----------- DONE HAVE ANY FRIEND ----------------");
    }
  }
Example #4
0
	public void Create() {
		TLMBGameConfig gameConfig = TLMBGameConfig.CreateCountGame(10);
		JSONObject jsonData = new JSONObject();
		jsonData.Add("gameConfig", gameConfig.ToJsonObject());
		jsonData.Add("seatIndex", 0);
		SmartfoxClient.Instance.HandleServerRequest(CreateExtensionRequest(Command.TLMB.CREATE, jsonData));
	}
  // Join user to game lobby room and join available room
	public void JoinRoom(BaseSlotMachineScreen.GameType gameType, string roomName = null) {
	  PopupManager.Instance.ShowLoadingPopup("LoadingText_JoinRoom");
	  JSONObject jsonData = new JSONObject();
		jsonData.Add("gameType", GetCommandByGameType(gameType));
		jsonData.Add("roomName", roomName);
		SmartfoxClient.Instance.HandleServerRequest(CreateExtensionRequest(Command.SLOT_MACHINE.SLOT_JOIN_ROOM, jsonData));
	}
	public JSONObject ToJsonObject() {
		JSONObject jsonData = new JSONObject();
		jsonData.Add("type", (int)type);
		jsonData.Add("coinPerCard", coinPerCard);
		jsonData.Add("firstRankRewardCoin", firstRankRewardCoin);
		jsonData.Add("secondRankRewardCoin", secondRankRewardCoin);
		return jsonData;
	}
Example #7
0
 public static JSONObject ToJson(this Vector3 vec)
 {
     var json = new JSONObject(JSONObject.Type.ARRAY);
     json.Add(vec.x);
     json.Add(vec.y);
     json.Add(vec.z);
     return json;
 }
  public void ClaimInboxReward(int type, long createdAt, string fromUsername) {
		PopupManager.Instance.ShowLoadingPopup("PopupInbox_Claiming", false);
    JSONObject data = new JSONObject();
    data.Add("username", AccountManager.Instance.username);
    data.Add("type", type);
    data.Add("createdAt", createdAt);
    data.Add("fromUsername", fromUsername);
    SmartfoxClient.Instance.HandleServerRequest(CreateExtensionRequest(Command.USER.CLAIM_INBOX_REWARD, "ClaimInboxRewardSuccess", data));
  }
		public override JSONObject Serialize()
		{
			JSONObject obj = new JSONObject();
			obj.Add(cRanks, Ranks);
			obj.Add(cModifier, MiscModifier);
			obj.Add(cUntrained, CanBeUsedUntrained);
			obj.Add(cClassSkill, ClassSkill);
			obj.Add(cAbility, (int)KeyAbility);
			return obj;
		}
Example #10
0
 public JSONObject to_json()
 {
     JSONObject rtv = new JSONObject();
     rtv.Add(SN.ID,_id);
     rtv.Add(SN.PLAYER_ID,_playerid);
     rtv.Add(SN.POS,_pos.to_json());
     rtv.Add(SN.VEL,_vel.to_json());
     rtv.Add(SN.ROT,_rot.to_json());
     return rtv;
 }
Example #11
0
 void EventRegister() {
   if (usernameInput.value != string.Empty && passwordInput.value != string.Empty && retypePasswordInput.value != string.Empty && displayNameInput.value != string.Empty) {
     Debug.Log("EventRegister");
     JSONObject jsonData = new JSONObject();
     jsonData.Add("username", usernameInput.value);
     jsonData.Add("password", passwordInput.value);
     jsonData.Add("displayName", displayNameInput.value);
     AccountManager.Instance.Register(jsonData);
   }
 }
Example #12
0
  public override void Init(object[] data) {
    base.Init(data);
    EventDelegate.Set(tabInvite.onClick, EventTabInvite);
    EventDelegate.Set(tabFriends.onClick, EventTabFriends);
		
		// Get list friends from smartfox buddy list
    List<Buddy> buddyList = SmartfoxClient.Instance.GetBuddyList();
    if (buddyList.Count > 0) {
			JSONObject friend;
			friendList = new JSONArray();
			for (int i = 0; i < buddyList.Count; i++) {
				friend = new JSONObject();
				if (buddyList[i].IsOnline) {
					friend.Add("displayName", buddyList[i].GetVariable("displayName").GetStringValue());
					friend.Add("cash", (long)buddyList[i].GetVariable("cash").GetDoubleValue());
					friend.Add("avatar", buddyList[i].GetVariable("avatar").GetStringValue());
					friend.Add("facebookId", buddyList[i].GetVariable("facebookId").GetStringValue());
				} else {
					friend.Add("displayName", buddyList[i].GetVariable("$displayName").GetStringValue());
					friend.Add("cash", (long)buddyList[i].GetVariable("$cash").GetDoubleValue());
					friend.Add("avatar", buddyList[i].ContainsVariable("$avatar") ? buddyList[i].GetVariable("$avatar").GetStringValue() : string.Empty);
					friend.Add("facebookId", buddyList[i].ContainsVariable("$facebookId") ? buddyList[i].GetVariable("$facebookId").GetStringValue() : string.Empty);
				}
				friend.Add("username", buddyList[i].Name);
				friendList.Add(friend);
			}
			InitScrollViewData(friendList);
    } else {
      Utils.SetActive(scrollview.gameObject, false);
      Debug.Log("----------- DONE HAVE ANY FRIEND ----------------");
    }
  }
Example #13
0
	/**
	 * Weme sdk loginWeme
	 * 
	 * @param oAuthString - 
	 * @param WmInterfaceBrokerDelegate
	 */
	public void loginWeme(string clientId,string clientSecret,WmInterfaceBroker.WmInterfaceBrokerDelegate callback){
		if(WemeManager.isEmpty(clientId)==true||WemeManager.isEmpty(clientSecret)==true){
			Debug.Log("must not null clientId or clientSecret");
			return;
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.Add(JSON_KEY_URI,JSON_VALUE_PREFIX_URI+WM_HOST_WEME);
		JSONObject paramsObject = new JSONObject();
		paramsObject.Add("clientId",clientId);
		paramsObject.Add("clientSecret",clientSecret);
		jsonObject.Add(JSON_KEY_PARAMS,paramsObject);
		WmInterfaceBroker.getInstance.requestAsync(jsonObject.ToString(),callback);
	}
Example #14
0
	public void SendChat() {
    if (chatInput.value != string.Empty) {
      string escapedString = Utils.ChatEscape(chatInput.value);
      // DisplayBubbleChat(escapedString, currentScreen.FindUserSlot(AccountManager.Instance.username));
      JSONObject data = new JSONObject();
      data.Add("message", escapedString);
      data.Add("senderId", AccountManager.Instance.username);
      data.Add("senderName", AccountManager.Instance.displayName);
      SmartfoxClient.Instance.HandleServerRequest(CreatePublicMessageRequest(Command.USER.CHAT_IN_ROOM, string.Empty, data));
			AddChatToList(data);
      chatInput.value = string.Empty;
			StartCoroutine(KeepKeyboardOpen());
    }
	}
 //Server sending server data to 3d environment
 public string GetDistanceToObject()
 {
     _serializedObject = new JSONObject (JSONObject.Type.OBJECT);
     JSONObject trainingCase = new JSONObject(JSONObject.Type.OBJECT);
     trainingCase.AddField("scaledSpeed", MoveCar.scaledSpeed);
     trainingCase.AddField("scaledForward", scaledForward);
     trainingCase.AddField("scaledLeftRightRatio", scaledLRRatio);
     _serializedObject.AddField("data", trainingCase);
     JSONObject types = new JSONObject(JSONObject.Type.ARRAY);
     types.Add ("motion");
     types.Add ("steering");
     _serializedObject.AddField("types", types);
     return _serializedObject.Print ();
 }
 // Event when hit send chat button
 private void SendChat() {
   // TO DO: verify chat before send
   if (chatInput.value != string.Empty) {
     string escapedString = Utils.ChatEscape(chatInput.value);
     Debug.Log("###### " + escapedString + " ---- " + Utils.ChatUnescape(escapedString));
     DisplayBubbleChat(escapedString, currentScreen.FindUserSlot(AccountManager.Instance.username));
     JSONObject data = new JSONObject();
     data.Add("message", escapedString);
     data.Add("senderId", AccountManager.Instance.username);
     data.Add("senderName", AccountManager.Instance.displayName);
     SmartfoxClient.Instance.HandleServerRequest(CreatePublicMessageRequest(Command.USER.CHAT_IN_ROOM, string.Empty, data));
     chatInput.value = string.Empty;
   }
   HideChatPanel();
 }
Example #17
0
        public static void Serialize(this Template template)
        {
            // Template
            var tplJs = new JSONObject(JSONObject.Type.OBJECT);

            // Operators
            var opsJs = new JSONObject(JSONObject.Type.ARRAY);
            tplJs.AddField("Operators", opsJs);

            foreach (KeyValuePair<string, Operator> kvp in template.Operators) {
                opsJs.Add(kvp.Value.Serialize());
            }

            // Connections
            var connsJs = new JSONObject(JSONObject.Type.ARRAY);
            tplJs.AddField("Connections", connsJs);

            foreach (IOConnection conn in template.Connections) {
                connsJs.Add(conn.Serialize());
            }

            template.JSON = tplJs.Print(true);

            #if UNITY_EDITOR
            EditorUtility.SetDirty(template);
            #endif
        }
Example #18
0
  public static void SaveToKeyChain(string keyName, string mValue) {
    #if UNITY_IPHONE
      if (Application.platform == RuntimePlatform.IPhonePlayer) {
        KeyChainBindings.SetStringForKey(keyName, mValue);
      }
		#endif
		#if UNITY_ANDROID
      if (Application.platform == RuntimePlatform.Android) {
        AndroidTools.SharedPreferencesSet(keyName, mValue);
      }
		#endif
		#if UNITY_EDITOR
		  string filePath = Path.Combine(Application.persistentDataPath, LOCAL_KEYCHAIN_FILE);
		  JSONObject data;
		  if (File.Exists(filePath)) {
  			string readText = File.ReadAllText(filePath);
  			data = JSONObject.Parse(readText);
  			data.Add(keyName, mValue);
  			File.WriteAllText(filePath, data.ToString());
  		} else {
  		  data = new JSONObject();
  		  data.Add(keyName, mValue);
  		  File.WriteAllText(filePath, data.ToString());
  		}
    #endif
  }
    //Creates a JSON from a resultModel and parses it to the POSTFacade
    public void ParseToJsonResult(ResultModel resultModel, string command)
    {
        JSONObject json = new JSONObject (JSONObject.Type.OBJECT);

            json.AddField("UserID", resultModel.UserID);
            json.AddField("UserType", resultModel.UserType);

            JSONObject arr = new JSONObject(JSONObject.Type.ARRAY);
            json.AddField("Answers",arr);
            foreach(QuizOptionModel qm in resultModel.Options){
            JSONObject ans = new JSONObject(JSONObject.Type.OBJECT);
                ans.AddField("ID",qm.Id);
                ans.AddField("Title",qm.Title);
                ans.AddField("Selected",qm.Selected);

            arr.Add(ans);
            }
        switch(command){
        case "SaveToServer":
        POSTFacade facade = gameObject.GetComponent<POSTFacade> ();
            facade.SaveQuizAnswers (json,resultModel.UserID.ToString());
            break;
        case "SaveLocal":
            PlayerPrefs.SetString("TestToSave_"+resultModel.UserID, json.Print());
            break;
        }
    }
Example #20
0
        public static void BuildManifest()
        {
            JSONObject json = new JSONObject(JSONObject.Type.ARRAY);
            string[] levels = Directory.GetFiles(Application.dataPath + "/Levels_Exported/", "*.json");

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

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

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

            TextWriter writer = new StreamWriter(Application.dataPath + "/Levels_Exported/levels_.manifest");
            writer.WriteLine(json.ToString(true));
            writer.Close();
            Debug.Log("Wrote manifest file");
        }
Example #21
0
    public void LoginFacebook()
    {
        FB.Init(delegate {
            FB.Login("",delegate(FBResult result) {

                Debug.Log (result.Text);

                JSONObject obj = JSONObject.Parse(result.Text);
                bool is_logged_in = obj["is_logged_in"].Boolean;
                UserSingleton.Instance.FacebookID = obj["user_id"].Str;
                UserSingleton.Instance.FacebookAccessToken = obj["access_token"].Str;

                if(is_logged_in){

                    JSONObject body = new JSONObject();
                    body.Add("FacebookID", UserSingleton.Instance.FacebookID);
                    body.Add("FacebookAccessToken", UserSingleton.Instance.FacebookAccessToken);
                    body.Add("FacebookName", "Chris");
                    body.Add("FacebookPhotoURL", "http://www/1.jpg");

                    HTTPClient.Instance.POST(Singleton.Instance.HOST + "/SignUp",
                                             body.ToString(),
                                             delegate(WWW www)
                    {

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

                        int ResultCode = (int)response["ResultCode"].Number;
                        if(ResultCode == 1000)
                        {
                            UserSingleton.Instance.UserID = (long)response["UserID"].Number;
                            UserSingleton.Instance.AccessToken = response["AccessToken"].Str;
                            Application.LoadLevel("Game");
                        }else{ // Login Failed

                        }

                    });

                }

            });
        },delegate(bool isUnityShown) {

        },"");
    }
Example #22
0
    private JSONObject difficultySettings; //time, dimensions, nodeCount, errorMargin

    #endregion Fields

    #region Methods

    public static void createNonExistentSettings()
    {
        JSONObject difficultySettings = new JSONObject();
        JSONObject easy = new JSONObject();
        easy.Add(time, new JSONValue(easyTime));
        easy.Add(nodeCount, new JSONValue(easyNodeCount));
        easy.Add(errorMargin, new JSONValue(easyErrorMargin));
        JSONObject vector = new JSONObject();
        vector.Add("x", new JSONValue(easyDimensionsX));
        vector.Add("y", new JSONValue(easyDimensionsY));
        easy.Add(dimensions, vector);
        difficultySettings.Add(Difficulty.Easy.ToString(), easy);

        JSONObject medium = new JSONObject();
        medium.Add(time, new JSONValue(mediumTime));
        medium.Add(nodeCount, new JSONValue(mediumNodeCount));
        medium.Add(errorMargin, new JSONValue(mediumErrorMargin));
        vector = new JSONObject();
        vector.Add("x", new JSONValue(mediumDimensionsX));
        vector.Add("y", new JSONValue(mediumDimensionsY));
        medium.Add(dimensions, vector);
        difficultySettings.Add(Difficulty.Medium.ToString(), medium);

        JSONObject hard = new JSONObject();
        hard.Add(time, new JSONValue(hardTime));
        hard.Add(nodeCount, new JSONValue(hardNodeCount));
        hard.Add(errorMargin, new JSONValue(hardErrorMargin));
        vector = new JSONObject();
        vector.Add("x", new JSONValue(hardDimensionsX));
        vector.Add("y", new JSONValue(hardDimensionsY));
        hard.Add(dimensions, vector);
        difficultySettings.Add(Difficulty.Hard.ToString(), hard);

        JSONObject extreme = new JSONObject();
        extreme.Add(time, new JSONValue(extremeTime));
        extreme.Add(nodeCount, new JSONValue(extremeNodeCount));
        extreme.Add(errorMargin, new JSONValue(extremeErrorMargin));
        vector = new JSONObject();
        vector.Add("x", new JSONValue(extremeDimensionsX));
        vector.Add("y", new JSONValue(extremeDimensionsY));
        extreme.Add(dimensions, vector);
        difficultySettings.Add(Difficulty.Extreme.ToString(), extreme);

        PlayerPrefs.SetString("difficultySettings", difficultySettings.ToString());
        PlayerPrefs.Save();
    }
Example #23
0
 private JSONObject generateJsonFormat(string document, string name, string lastNames, string email, string institution)
 {
     JSONObject player = new JSONObject();
     player.Add("id", "");
     player.Add("document", document);
     player.Add("name", name);
     player.Add("lastName", lastNames);
     player.Add("email", email);
     player.Add("institution", institution);
     player.Add("score", getScore());
     player.Add("playCount", 1);
     player.Add("lastDate", "");
     return player;
 }
Example #24
0
    public void FinishGame()
    {
        JSONObject body = new JSONObject();
        body.Add("UserID", UserSingleton.Instance.UserID);
        body.Add("Point", StagePoint.ToString());

        HTTPClient.Instance.POST (
            Singleton.Instance.HOST + "/UpdateResult/Post",
            body.ToString(),
            delegate(WWW obj) {
                JSONObject json = JSONObject.Parse(obj.text);
                Debug.Log("Response is : " + json.ToString());

                Application.LoadLevel("Lobby");

            }
        );
    }
 public JSONObject Serialize()
 {
     JSONObject retObj = new JSONObject(JSONObject.Type.ARRAY);
     foreach(OSRICCharacterModifier ocm in ModifierList)
     {
         retObj.Add(ocm.Serialize());
     }
     return retObj;
 }
Example #26
0
    public void FinishGame()
    {
        JSONObject body = new JSONObject();
        body.Add("UserID", "9876");
        body.Add("Point", StagePoint.ToString());

        HTTPClient.Instance.POST (
            "http://unity-action.azurewebsites.net/UpdateResult",
            body.ToString(),
            delegate(WWW obj) {
                JSONObject json = JSONObject.Parse(obj.text);
                Debug.Log("Response is : " + json.ToString());

                GetRanking();

            }
        );
    }
    // Use this for initialization
    void Start()
    {
        JSONObject configJSON = new JSONObject();
        JSONObject j = new JSONObject();
        JSONObject platforms = new JSONObject(JSONObject.Type.ARRAY);
        string thisDirectory = Directory.GetCurrentDirectory();
        bool platformDirectory = false;

        browser = browserContainer.GetComponent<Browser>();

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

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

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

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

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

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

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

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

                i++;
            }

            browser.CallFunction("Messaging.trigger", "platforms", configJSON.ToString());
            Debug.Log(configJSON.ToString());
        }
    }
    public void Upgrade(string UpgradeType)
    {
        JSONObject obj = new JSONObject();
        obj.Add("UserID", UserSingleton.Instance.UserID);
        obj.Add("UpgradeType", UpgradeType);
        HTTPClient.Instance.POST(Singleton.Instance.HOST + "/Upgrade",obj.ToString(),delegate(WWW www) {
            Debug.Log (www.text);
            JSONObject res = JSONObject.Parse(www.text);
            int ResultCode = (int)res["ResultCode"].Number;
            if(ResultCode == 1){ // Success!
                // Upgrade Success => Load User data again
                UserSingleton.Instance.Refresh(delegate() {
                    NotificationCenter.Instance.Notify(NotificationCenter.Subject.PlayerData);
                });
                // Alert Dialog
                DialogDataAlert alert = new DialogDataAlert(Language.Instance.GetLanguage("Upgrade Success Title"),
                                                            Language.Instance.GetLanguage("Upgrade Success"),delegate() {

                } );
                DialogManager.Instance.Push(alert);

            }else if (ResultCode == 4) // Max Level
            {
                // Alert Dialog
                DialogDataAlert alert = new DialogDataAlert(Language.Instance.GetLanguage("Upgrade Failed Title"),
                                                            Language.Instance.GetLanguage("Max Level"), delegate() {

                });
                DialogManager.Instance.Push(alert);

            }else if(ResultCode == 5) // Not enough diamond
            {
                // Alert Dialog
                DialogDataAlert alert = new DialogDataAlert(Language.Instance.GetLanguage("Upgrade Failed Title"),
                                                            Language.Instance.GetLanguage("Not Enouhg Diamond"), delegate() {

                });
                DialogManager.Instance.Push(alert);

            }
        });
    }
Example #29
0
    public void FinishGame()
    {
        JSONObject body = new JSONObject();
        body.Add("UserID", UserSingleton.Instance.UserID);
        body.Add("Point", StagePoint);

        HTTPClient.Instance.POST (
            "http://unity-action.azurewebsites.net/UpdateResult",
            body.ToString(),
            delegate(WWW obj) {
                JSONObject json = JSONObject.Parse(obj.text);
                Debug.Log("Response is : " + json.ToString());

                UserSingleton.Instance.Refresh(delegate() {
                    Application.LoadLevel ("Lobby"); //
                });

            }
        );
    }
 public void SavePlayerData()
 {
     JSONArray array = new JSONArray ();
     foreach (Player p in players) {
         JSONObject player = new JSONObject ();
         player.Add ("id", p.Id);
         player.Add ("name", p.Name);
         JSONArray levels = new JSONArray ();
         foreach (LevelData l in p.Levels.Values) {
             JSONObject jLevel = new JSONObject ();
             jLevel.Add ("id", l.Id);
             jLevel.Add ("stepCount", l.StepCount);
             levels.Add (jLevel);
         }
         player.Add ("levels", levels);
         array.Add (player);
     }
     PlayerPrefs.SetString ("players", array.ToString ());
     PlayerPrefs.Save ();
 }
Example #31
0
        public void Execute(JSONNode args)
        {
            var api            = ApiManager.Instance;
            var controlManager = SimulatorManager.Instance.ControllableManager;

            var name             = args["name"].Value;
            var position         = args["state"]["transform"]["position"].ReadVector3();
            var rotation         = args["state"]["transform"]["rotation"].ReadVector3();
            var velocity         = args["state"]["velocity"].ReadVector3();
            var angular_velocity = args["state"]["angular_velocity"].ReadVector3();

            Web.Config.Controllables.TryGetValue(name, out IControllable prefab);
            if (prefab == null)
            {
                api.SendError(this, $"Unknown '{name}' controllable prefab");
                return;
            }

            string uid;
            var    argsUid = args["uid"];

            if (argsUid == null)
            {
                uid = System.Guid.NewGuid().ToString();
                // Add uid key to arguments, as it will be distributed to the clients' simulations
                if (Loader.Instance.Network.IsMaster)
                {
                    args.Add("uid", uid);
                }
            }
            else
            {
                uid = argsUid.Value;
            }

            var controllable = controlManager.SpawnControllable(prefab.gameObject, uid, position,
                                                                Quaternion.Euler(rotation), velocity, angular_velocity);

            if (controllable == null)
            {
                api.SendError(this, $"Failed to spawn '{name}' controllable");
                return;
            }

            JSONArray validActions = new JSONArray();

            if (controllable.ValidStates != null)
            {
                foreach (var state in controllable.ValidStates)
                {
                    validActions.Add(state);
                }
            }

            if (controllable.ValidActions != null)
            {
                foreach (var action in controllable.ValidActions)
                {
                    validActions.Add(action);
                }
            }

            JSONObject j = new JSONObject();

            j.Add("uid", new JSONString(controllable.UID));
            j.Add("position", controllable.transform.position);
            j.Add("rotation", controllable.transform.rotation.eulerAngles);
            j.Add("type", new JSONString(controllable.ControlType));
            j.Add("valid_actions", validActions);
            j.Add("default_control_policy", Utility.SerializeControlPolicy(controllable.DefaultControlPolicy));

            api.SendResult(this, j);
        }
Example #32
0
        public void Execute(JSONNode args)
        {
            var uid = args["uid"].Value;
            var api = ApiManager.Instance;

            if (api.Agents.TryGetValue(uid, out GameObject obj))
            {
                List <SensorBase> sensors = obj.GetComponentsInChildren <SensorBase>().ToList();

                JSONArray result = new JSONArray();
                for (int i = 0; i < sensors.Count; i++)
                {
                    var sensor = sensors[i];

                    JSONObject j = null;

                    if (sensor is ColorCameraSensor)
                    {
                        var camera      = sensor as ColorCameraSensor;
                        var unityCamera = camera.GetComponent <Camera>();

                        j = new JSONObject();
                        j.Add("type", "camera");
                        j.Add("name", camera.Name);
                        j.Add("frequency", camera.Frequency);
                        j.Add("width", camera.Width);
                        j.Add("height", camera.Height);
                        j.Add("fov", camera.FieldOfView);
                        j.Add("near_plane", camera.MinDistance);
                        j.Add("far_plane", camera.MaxDistance);
                        j.Add("format", "RGB");
                    }
                    else if (sensor is DepthCameraSensor)
                    {
                        var camera = sensor as DepthCameraSensor;

                        j = new JSONObject();
                        j.Add("type", "camera");
                        j.Add("name", camera.Name);
                        j.Add("frequency", camera.Frequency);
                        j.Add("width", camera.Width);
                        j.Add("height", camera.Height);
                        j.Add("fov", camera.FieldOfView);
                        j.Add("near_plane", camera.MinDistance);
                        j.Add("far_plane", camera.MaxDistance);
                        j.Add("format", "DEPTH");
                    }
                    else if (sensor is SemanticCameraSensor)
                    {
                        var camera      = sensor as SemanticCameraSensor;
                        var unityCamera = camera.GetComponent <Camera>();

                        j = new JSONObject();
                        j.Add("type", "camera");
                        j.Add("name", camera.Name);
                        j.Add("frequency", camera.Frequency);
                        j.Add("width", camera.Width);
                        j.Add("height", camera.Height);
                        j.Add("fov", camera.FieldOfView);
                        j.Add("near_plane", camera.MinDistance);
                        j.Add("far_plane", camera.MaxDistance);
                        j.Add("format", "SEMANTIC");
                    }
                    else if (sensor is LidarSensor)
                    {
                        var lidar = sensor as LidarSensor;

                        j = new JSONObject();
                        j.Add("type", "lidar");
                        j.Add("name", lidar.Name);
                        j.Add("min_distance", lidar.MinDistance);
                        j.Add("max_distance", lidar.MaxDistance);
                        j.Add("rays", lidar.LaserCount);
                        j.Add("rotations", lidar.RotationFrequency);
                        j.Add("measurements", lidar.MeasurementsPerRotation);
                        j.Add("fov", lidar.FieldOfView);
                        j.Add("angle", lidar.CenterAngle);
                        j.Add("compensated", lidar.Compensated);
                    }
                    else if (sensor is ImuSensor)
                    {
                        var imu = sensor as ImuSensor;

                        j = new JSONObject();
                        j.Add("type", "imu");
                        j.Add("name", imu.Name);
                    }
                    else if (sensor is GpsSensor)
                    {
                        var gps = sensor as GpsSensor;

                        j = new JSONObject();
                        j.Add("type", "gps");
                        j.Add("name", gps.Name);
                        j.Add("frequency", new JSONNumber(gps.Frequency));
                    }
                    else if (sensor is RadarSensor)
                    {
                        var radar = sensor as RadarSensor;

                        j = new JSONObject();
                        j.Add("type", "radar");
                        j.Add("name", radar.Name);
                    }
                    else if (sensor is CanBusSensor)
                    {
                        var canbus = sensor as CanBusSensor;

                        j = new JSONObject();
                        j.Add("type", "canbus");
                        j.Add("name", canbus.Name);
                        j.Add("frequency", new JSONNumber(canbus.Frequency));
                    }

                    if (j != null)
                    {
                        j.Add("uid", api.SensorUID[sensor]);
                        result[result.Count] = j;
                    }
                }

                api.SendResult(result);
            }
            else
            {
                api.SendError($"Agent '{uid}' not found");
            }
        }
Example #33
0
        public JSONObject ToJson()
        {
            JSONObject obj = new JSONObject();

            obj.Add(nameof(Id), new JSONString(Id));
            obj.Add(nameof(IsSystemMessage), new JSONBool(IsSystemMessage));
            obj.Add(nameof(IsActionMessage), new JSONBool(IsActionMessage));
            obj.Add(nameof(IsActionMessage), new JSONBool(IsActionMessage));
            obj.Add(nameof(IsHighlighted), new JSONBool(IsHighlighted));
            obj.Add(nameof(IsPing), new JSONBool(IsPing));
            obj.Add(nameof(Message), new JSONString(Message));
            obj.Add(nameof(Sender), Sender.ToJson());
            obj.Add(nameof(Channel), Channel.ToJson());
            JSONArray emotes = new JSONArray();

            foreach (var emote in Emotes)
            {
                emotes.Add(emote.ToJson());
            }
            obj.Add(nameof(Emotes), emotes);
            obj.Add(nameof(Type), new JSONString(Type));
            obj.Add(nameof(Bits), new JSONNumber(Bits));
            return(obj);
        }
Example #34
0
        private void InferScaleType(string channel, string fieldDataType, ref JSONObject scaleSpecsObj)
        {
            string type = "";

            if (channel == "x" || channel == "y" || channel == "z" ||
                channel == "size" || channel == "opacity")
            {
                if (fieldDataType == "nominal" || fieldDataType == "ordinal")
                {
                    type = "point";
                }
                else if (fieldDataType == "quantitative")
                {
                    type = "linear";
                }
                else if (fieldDataType == "temporal")
                {
                    type = "time";
                }
                else
                {
                    throw new Exception("Invalid field data type: " + fieldDataType);
                }
            }
            else if (channel == "width" || channel == "height" || channel == "depth" || channel == "length" ||
                     channel == "xrotation" || channel == "yrotation" || channel == "zrotation" ||
                     channel == "xdirection" || channel == "ydirection" || channel == "zdirection")
            {
                if (fieldDataType == "nominal" || fieldDataType == "ordinal")
                {
                    type = "point";
                }
                else if (fieldDataType == "quantitative")
                {
                    type = "linear";
                }
                else if (fieldDataType == "temporal")
                {
                    type = "time";
                }
                else
                {
                    throw new Exception("Invalid field data type: " + fieldDataType);
                }
            }
            else if (channel == "color")
            {
                if (fieldDataType == "nominal" || fieldDataType == "ordinal")
                {
                    type = "ordinal";
                }
                else if (fieldDataType == "quantitative" || fieldDataType == "temporal")
                {
                    type = "sequential";
                }
                else
                {
                    throw new Exception("Invalid field data type: " + fieldDataType);
                }
            }
            else if (channel == "shape")
            {
                if (fieldDataType == "nominal" || fieldDataType == "ordinal")
                {
                    type = "ordinal";
                }
                else
                {
                    throw new Exception("Invalid field data type: " + fieldDataType + " for shape channel.");
                }
            }
            else
            {
                type = "none";
            }

            scaleSpecsObj.Add("type", new JSONString(type));
        }
Example #35
0
        public static void Initialize(IStoreAssets storeAssets)
        {
//			StoreUtils.LogDebug(TAG, "Adding currency");
            JSONObject currencies = new JSONObject(JSONObject.Type.ARRAY);

            foreach (VirtualCurrency vi in storeAssets.GetCurrencies())
            {
                currencies.Add(vi.toJSONObject());
            }

//			StoreUtils.LogDebug(TAG, "Adding packs");
            JSONObject packs = new JSONObject(JSONObject.Type.ARRAY);

            foreach (VirtualCurrencyPack vi in storeAssets.GetCurrencyPacks())
            {
                packs.Add(vi.toJSONObject());
            }

//			StoreUtils.LogDebug(TAG, "Adding goods");
            JSONObject suGoods = new JSONObject(JSONObject.Type.ARRAY);
            JSONObject ltGoods = new JSONObject(JSONObject.Type.ARRAY);
            JSONObject eqGoods = new JSONObject(JSONObject.Type.ARRAY);
            JSONObject upGoods = new JSONObject(JSONObject.Type.ARRAY);
            JSONObject paGoods = new JSONObject(JSONObject.Type.ARRAY);

            foreach (VirtualGood g in storeAssets.GetGoods())
            {
                if (g is SingleUseVG)
                {
                    suGoods.Add(g.toJSONObject());
                }
                else if (g is EquippableVG)
                {
                    eqGoods.Add(g.toJSONObject());
                }
                else if (g is UpgradeVG)
                {
                    upGoods.Add(g.toJSONObject());
                }
                else if (g is LifetimeVG)
                {
                    ltGoods.Add(g.toJSONObject());
                }
                else if (g is SingleUsePackVG)
                {
                    paGoods.Add(g.toJSONObject());
                }
            }
            JSONObject goods = new JSONObject(JSONObject.Type.OBJECT);

            goods.AddField(JSONConsts.STORE_GOODS_SU, suGoods);
            goods.AddField(JSONConsts.STORE_GOODS_LT, ltGoods);
            goods.AddField(JSONConsts.STORE_GOODS_EQ, eqGoods);
            goods.AddField(JSONConsts.STORE_GOODS_UP, upGoods);
            goods.AddField(JSONConsts.STORE_GOODS_PA, paGoods);

//			StoreUtils.LogDebug(TAG, "Adding categories");
            JSONObject categories = new JSONObject(JSONObject.Type.ARRAY);

            foreach (VirtualCategory vi in storeAssets.GetCategories())
            {
                categories.Add(vi.toJSONObject());
            }

//			StoreUtils.LogDebug(TAG, "Adding nonConsumables");
            JSONObject nonConsumables = new JSONObject(JSONObject.Type.ARRAY);

            foreach (NonConsumableItem vi in storeAssets.GetNonConsumableItems())
            {
                nonConsumables.Add(vi.toJSONObject());
            }

//			StoreUtils.LogDebug(TAG, "Preparing StoreAssets  JSONObject");
            JSONObject storeAssetsObj = new JSONObject(JSONObject.Type.OBJECT);

            storeAssetsObj.AddField(JSONConsts.STORE_CATEGORIES, categories);
            storeAssetsObj.AddField(JSONConsts.STORE_CURRENCIES, currencies);
            storeAssetsObj.AddField(JSONConsts.STORE_CURRENCYPACKS, packs);
            storeAssetsObj.AddField(JSONConsts.STORE_GOODS, goods);
            storeAssetsObj.AddField(JSONConsts.STORE_NONCONSUMABLES, nonConsumables);

            string storeAssetsJSON = storeAssetsObj.print();

#if UNITY_ANDROID && !UNITY_EDITOR
            StoreUtils.LogDebug(TAG, "pushing data to StoreAssets on java side");
            using (AndroidJavaClass jniStoreAssets = new AndroidJavaClass("com.soomla.unity.StoreAssets")) {
                jniStoreAssets.CallStatic("prepare", storeAssets.GetVersion(), storeAssetsJSON);
            }
            StoreUtils.LogDebug(TAG, "done! (pushing data to StoreAssets on java side)");
#elif UNITY_IOS && !UNITY_EDITOR
            StoreUtils.LogDebug(TAG, "pushing data to StoreAssets on ios side");
            storeAssets_Init(storeAssets.GetVersion(), storeAssetsJSON);
            StoreUtils.LogDebug(TAG, "done! (pushing data to StoreAssets on ios side)");
#endif
        }
Example #36
0
            // Early code... index a full zip archive.
            public static async void LoadZIPDirectory(string folder = @"d:\beatsaver")
            {
                if (MapDatabase.DatabaseLoading)
                {
                    return;
                }

                await Task.Run(() =>
                {
                    var startingmem = GC.GetTotalMemory(true);

                    Instance.QueueChatMessage($"Starting to read archive.");
                    int addcount = 0;
                    var StarTime = DateTime.Now;

                    var di = new DirectoryInfo(folder);

                    foreach (FileInfo f in di.GetFiles("*.zip"))
                    {
                        try
                        {
                            var x    = System.IO.Compression.ZipFile.OpenRead(f.FullName);
                            var info = x.Entries.First <ZipArchiveEntry>(e => (e.Name.EndsWith("info.json")));

                            string id      = "";
                            string version = "";
                            GetIdFromPath(f.Name, ref id, ref version);

                            if (MapDatabase.MapLibrary.ContainsKey(id))
                            {
                                if (MapLibrary[id].path != "")
                                {
                                    MapLibrary[id].path = f.FullName;
                                }
                                continue;
                            }

                            JSONObject song = JSONObject.Parse(readzipjson(x)).AsObject;

                            string hash;

                            JSONNode difficultylevels = song["difficultyLevels"].AsArray;
                            var FileAccumulator       = new StringBuilder();
                            foreach (var level in difficultylevels)
                            {
                                try
                                {
                                    FileAccumulator.Append(readzipjson(x, level.Value));
                                }
                                catch
                                {
                                    //Instance.QueueChatMessage($"key={level.Key} value={level.Value}");
                                    //throw;
                                }
                            }

                            hash = CreateMD5FromString(FileAccumulator.ToString());

                            string levelId = string.Join("∎", hash, song["songName"].Value, song["songSubName"].Value, song["authorName"], song["beatsPerMinute"].AsFloat.ToString()) + "∎";

                            if (LevelId.ContainsKey(levelId))
                            {
                                LevelId[levelId].path = f.FullName;
                                continue;
                            }

                            addcount++;

                            song.Add("id", id);
                            song.Add("version", version);
                            song.Add("hashMd5", hash);

                            new SongMap(song, levelId, f.FullName);

                            x = null;
                        }
                        catch (Exception)
                        {
                            Instance.QueueChatMessage($"Failed to process {f.FullName}");
                            //Instance.QueueChatMessage(ex.ToString());
                        }
                    }
                    Instance.QueueChatMessage($"Archive indexing done, {addcount} files added. ({(DateTime.Now-StarTime).TotalSeconds} secs.");
                    GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
                    GC.Collect();
                    Instance.QueueChatMessage($"hashentries: {SongMap.hashcount} memory: {(GC.GetTotalMemory(false) - startingmem) / 1048576} MB");
                });


                MapDatabase.DatabaseLoading = false;
            }
Example #37
0
        // TODO: Fix range computation to consider paddingOUter!!!
        // TODO: Fix range size.
        private void InferRange(ChannelEncoding channelEncoding, JSONNode specs, ref JSONObject scaleSpecsObj)
        {
            JSONArray range = new JSONArray();

            string channel = channelEncoding.channel;

            if (channel == "x" || channel == "width")
            {
                range.Add(new JSONString("0"));

                if (scaleSpecsObj["rangeStep"] == null)
                {
                    range.Add(new JSONString(specs["width"]));
                }
                else
                {
                    float rangeSize = float.Parse(scaleSpecsObj["rangeStep"]) * (float)scaleSpecsObj["domain"].Count;
                    range.Add(new JSONString(rangeSize.ToString()));
                    specs["width"] = rangeSize;
                }
            }
            else if (channel == "y" || channel == "height")
            {
                range.Add(new JSONString("0"));
                if (scaleSpecsObj["rangeStep"] == null)
                {
                    range.Add(new JSONString(specs["height"]));
                }
                else
                {
                    float rangeSize = float.Parse(scaleSpecsObj["rangeStep"]) * (float)scaleSpecsObj["domain"].Count;
                    range.Add(new JSONString(rangeSize.ToString()));
                    specs["height"] = rangeSize;
                }
            }
            else if (channel == "z" || channel == "depth")
            {
                range.Add(new JSONString("0"));
                if (scaleSpecsObj["rangeStep"] == null)
                {
                    range.Add(new JSONString(specs["depth"]));
                }
                else
                {
                    float rangeSize = float.Parse(scaleSpecsObj["rangeStep"]) * (float)scaleSpecsObj["domain"].Count;
                    range.Add(new JSONString(rangeSize.ToString()));
                    specs["depth"] = rangeSize;
                }
            }
            else if (channel == "opacity")
            {
                range.Add(new JSONString("0"));
                range.Add(new JSONString("1"));
            }
            else if (channel == "size" || channel == "length")
            {
                range.Add(new JSONString("0"));
                string maxDimSize = Math.Max(Math.Max(specs["width"].AsFloat, specs["height"].AsFloat),
                                             specs["depth"].AsFloat).ToString();

                range.Add(new JSONString(maxDimSize));
            }
            else if (channel == "color")
            {
                if (channelEncoding.fieldDataType == "nominal")
                {
                    scaleSpecsObj.Add("range", new JSONString("category"));
                }
                else if (channelEncoding.fieldDataType == "ordinal")
                {
                    scaleSpecsObj.Add("range", new JSONString("ordinal"));
                }
                else if (channelEncoding.fieldDataType == "quantitative" ||
                         channelEncoding.fieldDataType == "temporal")
                {
                    scaleSpecsObj.Add("range", new JSONString("ramp"));
                }
            }
            else if (channel == "shape")
            {
                range.Add(new JSONString("symbol"));
                throw new Exception("Not implemented yet.");
            }
            else if (channel == "xrotation" || channel == "yrotation" || channel == "zrotation")
            {
                range.Add(new JSONString("0"));
                range.Add(new JSONString("360"));
            }
            else if (channel == "xdirection" || channel == "ydirection" || channel == "zdirection")
            {
                range.Add(new JSONString("0"));
                range.Add(new JSONString("1"));
            }

            if (range.Count > 0)
            {
                scaleSpecsObj.Add("range", range);
            }
        }
Example #38
0
            public SongMap(JSONObject song, string LevelId = "", string path = "")
            {
                if (!song["version"].IsString)
                {
                    //RequestBot.Instance.QueueChatMessage($"{song["key"].Value}: {song["metadata"]}");
                    if (!song["key"].IsString)
                    {
                        song.Add("id", song["id"]);
                        song.Add("version", song["id"]);
                        song.Add("hash", song["versions"][0]["hash"]);
                        song.Add("downloadURL", song["versions"][0]["downloadURL"]);
                        song.Add("coverURL", song["versions"][0]["coverURL"]);
                        song.Add("previewURL", song["versions"][0]["previewURL"]);
                    }
                    else
                    {
                        song.Add("id", song["key"]);
                        song.Add("version", song["key"]);
                    }
                    var metadata        = song["metadata"];
                    var songName        = metadata["songName"].Value;
                    var songSubName     = metadata["songSubName"].Value;
                    var authorName      = metadata["songAuthorName"].Value;
                    var levelAuthorName = metadata["levelAuthorName"].Value;
                    song.Add("songName", songName);
                    song.Add("songSubName", songSubName);
                    song.Add("authorName", authorName);
                    song.Add("levelAuthor", levelAuthorName);
                    song.Add("rating", song["stats"]["rating"].AsFloat * 100);
                    bool authorIsMapper = authorName.Replace(" ", "").ToLower().Equals(levelAuthorName.Replace(" ", "").ToLower()) ||
                                          authorName.ToLower().Contains(levelAuthorName.ToLower());
                    if (authorIsMapper)
                    {
                        levelAuthorName = authorName;
                        authorName      = songSubName;
                        songSubName     = "";
                    }
                    if (songSubName.Length > 0)
                    {
                        songName = $"{songName} ({Regex.Replace(songSubName, @"\((.*)\)", @"$1")})";
                    }
                    song.Add("trueSongName", songName);
                    song.Add("trueSongAuthor", authorName);
                    song.Add("trueLevelAuthor", levelAuthorName);

                    bool degrees90  = false;
                    bool degrees360 = false;

                    try
                    {
                        var characteristics = metadata["characteristics"][0]["difficulties"];
                        var lenghtlabel     = "length";
                        if (!song["key"].IsString)
                        {
                            characteristics = song["versions"][0]["diffs"];
                            lenghtlabel     = "seconds";
                        }

                        //Instance.QueueChatMessage($"{characteristics}");

                        foreach (var entry in metadata["characteristics"])
                        {
                            if (entry.Value["name"] == "360Degree")
                            {
                                degrees360 = true;
                            }
                            if (entry.Value["name"] == "90Degree")
                            {
                                degrees90 = true;
                            }
                        }

                        int maxnjs = 0;
                        foreach (var entry in characteristics)
                        {
                            if (entry.Value.IsNull)
                            {
                                continue;
                            }

                            if (entry.Value["characteristic"] == "360Degree")
                            {
                                degrees360 = true;
                            }
                            if (entry.Value["characteristic"] == "90Degree")
                            {
                                degrees90 = true;
                            }
                            var diff = entry.Value[lenghtlabel].AsInt;
                            var njs  = entry.Value["njs"].AsInt;
                            if (njs > maxnjs)
                            {
                                maxnjs = njs;
                            }



                            if (diff > 0)
                            {
                                song.Add("songlength", $"{diff / 60}:{diff % 60:00}");
                                song.Add("songduration", diff);
                                //Instance.QueueChatMessage($"{diff / 60}:{diff % 60}");
                            }
                        }

                        if (maxnjs > 0)
                        {
                            song.Add("njs", maxnjs);
                        }
                        if (degrees360 || degrees90)
                        {
                            song.Add("maptype", "360");
                        }
                    }
                    catch
                    {
                    }
                }


                float songpp = 0;

                if (ppmap.TryGetValue(song["id"].Value, out songpp))
                {
                    song.Add("pp", songpp);
                }

                //SongMap oldmap;
                //if (MapDatabase.MapLibrary.TryGetValue(song["id"].Value,out oldmap))
                //{

                //    if (LevelId == oldmap.LevelId && song["version"].Value == oldmap.song["version"].Value)
                //    {
                //        oldmap.song = song;
                //        return;
                //    }

                //    int id = int.Parse(song["id"].Value.ToUpper(), System.Globalization.NumberStyles.HexNumber);

                //    oldmap.UnIndexSong(id);
                //}

                this.path = path;
                //this.LevelId = LevelId;
                IndexSong(song);
            }
Example #39
0
            // Update Database from Directory
            public static async Task LoadCustomSongs(string folder = "", string songid = "")
            {
                if (MapDatabase.DatabaseLoading)
                {
                    return;
                }

                DatabaseLoading = true;

                await Task.Run(() =>
                {
                    if (songid == "")
                    {
                        Instance.QueueChatMessage($"Starting song indexing {folder}");
                    }

                    var StarTime = DateTime.UtcNow;

                    if (folder == "")
                    {
                        folder = Path.Combine(Environment.CurrentDirectory, "Beat Saber_data\\customlevels");
                    }

                    List <FileInfo> files        = new List <FileInfo>();      // List that will hold the files and subfiles in path
                    List <DirectoryInfo> folders = new List <DirectoryInfo>(); // List that hold direcotries that cannot be accessed

                    DirectoryInfo di = new DirectoryInfo(folder);
                    FullDirList(di, "*");

                    if (RequestBotConfig.Instance.additionalsongpath != "")
                    {
                        di = new DirectoryInfo(RequestBotConfig.Instance.additionalsongpath);
                        FullDirList(di, "*");
                    }

                    void FullDirList(DirectoryInfo dir, string searchPattern)
                    {
                        try
                        {
                            foreach (FileInfo f in dir.GetFiles(searchPattern))
                            {
                                if (f.FullName.EndsWith("info.dat"))
                                {
                                    files.Add(f);
                                }
                            }
                        }
                        catch
                        {
                            Console.WriteLine("Directory {0}  \n could not be accessed!!!!", dir.FullName);
                            return;
                        }

                        foreach (DirectoryInfo d in dir.GetDirectories())
                        {
                            folders.Add(d);
                            FullDirList(d, searchPattern);
                        }
                    }

                    // This might need some optimization


                    Instance.QueueChatMessage($"Processing {files.Count} maps. ");
                    foreach (var item in files)
                    {
                        //msg.Add(item.FullName,", ");

                        string id = "", version = "0";

                        GetIdFromPath(item.DirectoryName, ref id, ref version);

                        try
                        {
                            if (MapDatabase.MapLibrary.ContainsKey(id))
                            {
                                continue;
                            }

                            JSONObject song = JSONObject.Parse(File.ReadAllText(item.FullName)).AsObject;

                            string hash;

                            JSONNode difficultylevels = song["difficultyLevels"].AsArray;
                            var FileAccumulator       = new StringBuilder();
                            foreach (var level in difficultylevels)
                            {
                                //Instance.QueueChatMessage($"key={level.Key} value={level.Value}");
                                try
                                {
                                    FileAccumulator.Append(File.ReadAllText($"{item.DirectoryName}\\{level.Value["jsonPath"].Value}"));
                                }
                                catch
                                {
                                    //Instance.QueueChatMessage($"key={level.Key} value={level.Value}");
                                    //throw;
                                }
                            }

                            hash = CreateMD5FromString(FileAccumulator.ToString());

                            string levelId = string.Join("∎", hash, song["songName"].Value, song["songSubName"].Value, song["authorName"], song["beatsPerMinute"].AsFloat.ToString()) + "∎";

                            if (LevelId.ContainsKey(levelId))
                            {
                                LevelId[levelId].path = item.DirectoryName;
                                continue;
                            }

                            song.Add("id", id);
                            song.Add("version", version);
                            song.Add("hashMd5", hash);

                            new SongMap(song, levelId, item.DirectoryName);
                        }
                        catch (Exception)
                        {
                            Instance.QueueChatMessage($"Failed to process {item}.");
                        }
                    }
                    var duration = DateTime.UtcNow - StarTime;
                    if (songid == "")
                    {
                        Instance.QueueChatMessage($"Song indexing done. ({duration.TotalSeconds} secs.");
                    }

                    DatabaseImported = true;
                    DatabaseLoading  = false;
                });
            }
Example #40
0
        public static JSONObject Serialize(this object component)
        {
            var node = new JSONObject();

            foreach (var property in component.GetType().GetProperties())
            {
                if (property.CanRead && property.CanWrite)
                {
                    if (property.PropertyType == typeof(int) || property.PropertyType.IsEnum)
                    {
                        node.Add(property.Name, new JSONNumber((int)property.GetValue(component, null)));
                        continue;
                    }
                    if (property.PropertyType == typeof(IntReactiveProperty))
                    {
                        var reactiveProperty = property.GetValue(component, null) as IntReactiveProperty;
                        if (reactiveProperty == null)
                        {
                            reactiveProperty = new IntReactiveProperty();
                        }
                        node.Add(property.Name, new JSONNumber((int)reactiveProperty.Value));
                        continue;
                    }
                    if (property.PropertyType == typeof(float))
                    {
                        node.Add(property.Name, new JSONNumber((float)property.GetValue(component, null)));
                        continue;
                    }
                    if (property.PropertyType == typeof(FloatReactiveProperty))
                    {
                        var reactiveProperty = property.GetValue(component, null) as FloatReactiveProperty;
                        if (reactiveProperty == null)
                        {
                            reactiveProperty = new FloatReactiveProperty();
                        }
                        node.Add(property.Name, new JSONNumber((float)reactiveProperty.Value));
                        continue;
                    }
                    if (property.PropertyType == typeof(bool))
                    {
                        node.Add(property.Name, new JSONBool((bool)property.GetValue(component, null)));
                        continue;
                    }
                    if (property.PropertyType == typeof(BoolReactiveProperty))
                    {
                        var reactiveProperty = property.GetValue(component, null) as BoolReactiveProperty;
                        if (reactiveProperty == null)
                        {
                            reactiveProperty = new BoolReactiveProperty();
                        }
                        node.Add(property.Name, new JSONBool((bool)reactiveProperty.Value));
                        continue;
                    }
                    if (property.PropertyType == typeof(string))
                    {
                        node.Add(property.Name, new JSONString((string)property.GetValue(component, null)));
                        continue;
                    }
                    if (property.PropertyType == typeof(StringReactiveProperty))
                    {
                        var reactiveProperty = property.GetValue(component, null) as StringReactiveProperty;
                        if (reactiveProperty == null)
                        {
                            reactiveProperty = new StringReactiveProperty();
                        }
                        node.Add(property.Name, new JSONString((string)reactiveProperty.Value));
                        continue;
                    }
                    if (property.PropertyType == typeof(Vector2))
                    {
                        var jsonObject = ((Vector2)property.GetValue(component, null)).AsJSONObject();
                        node.Add(property.Name, jsonObject);
                        continue;
                    }
                    if (property.PropertyType == typeof(Vector2ReactiveProperty))
                    {
                        var reactiveProperty = property.GetValue(component, null) as Vector2ReactiveProperty;
                        if (reactiveProperty == null)
                        {
                            reactiveProperty = new Vector2ReactiveProperty();
                        }

                        var jsonObject = reactiveProperty.Value.AsJSONObject();
                        node.Add(property.Name, jsonObject);
                        continue;
                    }
                    if (property.PropertyType == typeof(Vector3))
                    {
                        var jsonObject = ((Vector3)property.GetValue(component, null)).AsJSONObject();
                        node.Add(property.Name, jsonObject);
                        continue;
                    }
                    if (property.PropertyType == typeof(Vector3ReactiveProperty))
                    {
                        var reactiveProperty = property.GetValue(component, null) as Vector3ReactiveProperty;
                        if (reactiveProperty == null)
                        {
                            reactiveProperty = new Vector3ReactiveProperty();
                        }

                        var jsonObject = reactiveProperty.Value.AsJSONObject();
                        node.Add(property.Name, jsonObject);
                        continue;
                    }
                    if (property.PropertyType == typeof(Color))
                    {
                        var jsonObject = ((Color)property.GetValue(component, null)).AsJSONObject();
                        node.Add(property.Name, jsonObject);
                        continue;
                    }
                    if (property.PropertyType == typeof(ColorReactiveProperty))
                    {
                        var reactiveProperty = property.GetValue(component, null) as ColorReactiveProperty;
                        if (reactiveProperty == null)
                        {
                            reactiveProperty = new ColorReactiveProperty();
                        }

                        var jsonObject = reactiveProperty.Value.AsJSONObject();
                        node.Add(property.Name, jsonObject);
                        continue;
                    }
                }
            }
            return(node);
        }
    /// <summary>
    /// Raises the rejoin previous match event.
    /// </summary>
    /// <param name="data">Data.</param>
    void OnRejoinPrevMatch(JSONObject data)
    {
        Loading.Inst.HideLodingIndicator();

        int        over  = int.Parse(data.GetField("type").ToString().Trim(new char[] { '"' }));
        JSONObject uinfo = data.GetField("userInfo");

        GS.Inst.userInfo.name   = GS.GetTrimmed(uinfo.GetField("un"));
        GS.Inst.userInfo.PicUrl = GS.GetTrimmed(uinfo.GetField("pp"));

        uinfo = data.GetField("compInfo");
        GS.Inst.OppInfo.Name = GS.GetTrimmed(uinfo.GetField("un"));
        GS.Inst.OppInfo.Url  = GS.GetTrimmed(uinfo.GetField("pp"));

        GS.Inst.isTossSelPending = Boolean.Parse(GS.GetTrimmed(data.GetField("tsp")));
        bool isRematch = Boolean.Parse(GS.GetTrimmed(data.GetField("rmf")));

        GameMode mode = (GameMode)int.Parse(GS.GetTrimmed(data.GetField("gt")));

        GS.Inst.StartNewMatch(mode, over);
        GS.Inst.SetPrevMatch(1);

        //=================ReMatch=====
        if (isRematch && GS.Inst.isTossSelPending)
        {
            GS.Inst.curInningInfo.isgotRematch = true;
            GS.Inst.LoadNextScene("Menu");
            return;
        }

        //======================
        if (GS.Inst.isTossSelPending)
        {
            if (!SceneManager.GetActiveScene().name.Equals("Menu"))
            {
                GS.Inst.LoadNextScene("Menu");
            }
            return;
        }

        GS.Inst.isCanRejoin = Boolean.Parse(GS.GetTrimmed(data.GetField("rejoin")));

        if (!GS.Inst.isCanRejoin)
        {
            GS.Inst.SetPrevMatch(0);
            return;
        }

        // Setting previous inning data
        if (data.HasField("fi_score"))
        {
            GS.Inst.curInningInfo.isSecondInning = true;
            GS.Inst.prevInningInfo                = new MatchData();
            GS.Inst.prevInningInfo.score          = int.Parse(GS.GetTrimmed(data.GetField("fi_score")));
            GS.Inst.prevInningInfo.wicket         = int.Parse(data.GetField("fi_wicket").ToString().Trim(new char[] { '"' }));
            GS.Inst.prevInningInfo.overs          = int.Parse(data.GetField("fi_over").ToString().Trim(new char[] { '"' }));
            GS.Inst.prevInningInfo.isPlayingRobot = Boolean.Parse(data.GetField("is_robot").ToString().Trim(new char[] { '"' }));
        }
        //setting current inning data
        string recvIDBat = data.GetField("batting").ToString().Trim(new char[] { '"' });
        string recvIDBow = data.GetField("bowling").ToString().Trim(new char[] { '"' });


        GS.Inst.receivedFieldID = int.Parse(data.GetField("field").ToString().Trim(new char[] { '"' }));
        if (data.HasField("nbt"))
        {
            GS.Inst.receivedBallTimer = int.Parse(data.GetField("nbt").ToString().Trim(new char[] { '"' }));
        }

        if (GS.Inst.userInfo.ID != recvIDBat && GS.Inst.userInfo.ID != recvIDBow)
        {
        }
        else
        {
            if (recvIDBat.Equals(GS.Inst.userInfo.ID))
            {
                GS.Inst.curInningInfo.isMyBatting = true;
                GS.Inst.userInfo.handTyp          = (HandTyp)int.Parse(data.GetField("userInfo").GetField("htba").ToString().Trim(new char[] { '"' }));
                GS.Inst.curInningInfo.OppHandTyp  = (HandTyp)int.Parse(data.GetField("compInfo").GetField("htba").ToString().Trim(new char[] { '"' }));
                GS.Inst.receivedBowlingSide       = int.Parse(data.GetField("compInfo").GetField("htbo").ToString().Trim(new char[] { '"' }));
                GS.Inst.curInningInfo.OppID       = recvIDBow;
            }
            else
            {
                GS.Inst.curInningInfo.isMyBatting = false;
                GS.Inst.curInningInfo.OppHandTyp  = (HandTyp)int.Parse(data.GetField("compInfo").GetField("htba").ToString().Trim(new char[] { '"' }));
                GS.Inst.userInfo.handTyp          = (HandTyp)int.Parse(data.GetField("userInfo").GetField("htba").ToString().Trim(new char[] { '"' }));
                GS.Inst.receivedBowlingSide       = int.Parse(data.GetField("userInfo").GetField("htbo").ToString().Trim(new char[] { '"' }));
                GS.Inst.curInningInfo.OppID       = recvIDBat;
            }
        }

        GS.Inst.curInningInfo.isPlayingRobot = Boolean.Parse(data.GetField("is_robot").ToString().Trim(new char[] { '"' }));

        if (GS.Inst.curInningInfo.isPlayingRobot)
        {
            GS.Inst.SetRobotProbInfo(data.GetField("ROBOT_LEVEL"));
        }

        GS.Inst.curInningInfo.score      = int.Parse(data.GetField("live_score").ToString().Trim(new char[] { '"' }));
        GS.Inst.curInningInfo.wicket     = int.Parse(data.GetField("live_wicket").ToString().Trim(new char[] { '"' }));
        GS.Inst.curInningInfo.overs      = int.Parse(data.GetField("live_over").ToString().Trim(new char[] { '"' }));
        GS.Inst.curInningInfo.overBalls  = int.Parse(data.GetField("live_overball").ToString().Trim(new char[] { '"' }));
        GS.Inst.curInningInfo.isFreeHit  = Boolean.Parse(data.GetField("fh").ToString().Trim(new char[] { '"' }));
        GS.Inst.curInningInfo.isRejoined = true;

        JSONObject Data  = data.GetField("ball");
        JSONObject balls = new JSONObject(JSONObject.Type.ARRAY);

        for (int i = 0; i < Data.Count; i++)
        {
            balls.Add(Data [i]);
        }

        for (int i = 0; i < balls.Count; i++)
        {
            GS.Inst.curInningInfo.balls.Add(balls[i].ToString().Trim(new char[] { '"' }));
        }

        GS.Inst.LoadNextScene("Cricket");
    }
    void SetUserData(JSONObject e)
    {
        JSONObject data = e.GetField("data");

        if (GS.GetTrimmed(data.GetField("ult")).Equals("guest"))
        {
            PlayerPrefs.SetString("SSN", "GUEST");
        }
        else
        {
            PlayerPrefs.SetString("SSN", "FB");
        }
        LoginProcess.Inst.Session = PlayerPrefs.GetString("SSN");

        GS.Inst.userInfo.ID             = GS.GetTrimmed(data.GetField("id"));
        GS.Inst.userInfo.name           = GS.GetTrimmed(data.GetField("un"));
        GS.Inst.userInfo.PicUrl         = GS.GetTrimmed(data.GetField("pp"));
        GS.Inst.userInfo.coins          = GS.GetTrimmed(data.GetField("coins"));
        GS.Inst.userInfo.Run            = GS.GetTrimmed(data.GetField("run"));
        GS.Inst.userInfo.Notific        = GS.GetTrimmed(data.GetField("noticount"));
        GS.Inst.userInfo.Inbox          = GS.GetTrimmed(data.GetField("inboxcount"));
        GS.Inst.userInfo.handTyp        = (HandTyp)int.Parse(GS.GetTrimmed(data.GetField("ht")));
        GS.Inst.ShareURL                = GS.GetTrimmed(data.GetField("rfl"));
        GS.Inst.userInfo.Frndz          = GS.GetTrimmed(data.GetField("friend"));
        GS.Inst.userInfo.RateUs         = int.Parse(GS.GetTrimmed(data.GetField("rateus")));
        GS.Inst.userInfo.AdminCount     = int.Parse(GS.GetTrimmed(data.GetField("admincount")));
        GS.Inst.userInfo.isFeedBackSent = Boolean.Parse(GS.GetTrimmed(data.GetField("feedback")));
        GS.Inst.isCanRejoin             = Boolean.Parse(GS.GetTrimmed(data.GetField("rejoin")));

        //**************** User Dress config  **********************
        JSONObject obj1 = new JSONObject(JSONObject.Type.ARRAY);
        JSONObject pdc  = data.GetField("pdc");

        for (int m = 0; m < pdc.Count; m++)
        {
            obj1.Add(pdc[m]);
        }

        GS.Inst.P_rend_dress[1].SetColor("_Color", GS.Inst.HascodeToColor(GS.GetTrimmed(obj1[0])));
        GS.Inst.P_rend_dress[0].SetColor("_Color", GS.Inst.HascodeToColor(GS.GetTrimmed(obj1[2])));
        GS.Inst.P_rend_accessory[0].SetColor("_Color", GS.Inst.HascodeToColor(GS.GetTrimmed(obj1[3])));
        GS.Inst.P_rend_skin[0].SetColor("_Color", GS.Inst.HascodeToColor(GS.GetTrimmed(obj1[4])));

        //**************** Opponent Dress config  **********************
        int c = UnityEngine.Random.Range(0, ArtoonConfig.Inst.robotDress.Count);

        GS.Inst.O_rend_dress[1].SetColor("_Color", GS.Inst.HascodeToColor(ArtoonConfig.Inst.robotDress[c][0]));
        GS.Inst.O_rend_dress[0].SetColor("_Color", GS.Inst.HascodeToColor(ArtoonConfig.Inst.robotDress[c][2]));
        GS.Inst.O_rend_accessory[0].SetColor("_Color", GS.Inst.HascodeToColor(ArtoonConfig.Inst.robotDress[c][3]));
        GS.Inst.O_rend_skin[0].SetColor("_Color", GS.Inst.HascodeToColor(ArtoonConfig.Inst.robotDress[c][4]));
        //**************************************


        if (Boolean.Parse(GS.GetTrimmed(data.GetField("pushflag"))))
        {
            PlayerPrefs.SetString("NOTI", "ON");
        }
        else
        {
            PlayerPrefs.SetString("NOTI", "OFF");
        }

        GS.Inst.CoinsCount = int.Parse(GS.Inst.userInfo.coins);

        if (GS.Inst.isCanRejoin)
        {
            return;
        }

        if (SceneManager.GetActiveScene().name.Equals("Cricket"))
        {
            if (GS.Inst.gameMode != GameMode.Practice)
            {
                GS.Inst.LoadNextScene("Menu");
            }
            else
            {
                return;
            }
        }
        else
        {
            if (SceneManager.GetActiveScene().name.Equals("Menu"))
            {
                if (GS.Inst.gameMode == GameMode.Online)
                {
                    //GS.Inst.LoadNextScene("Menu");
                    //GS.Inst.SetPrevMatch(0);
                }
                else
                {
                }
                Loading.Inst.HideLodingIndicator();
            }
            else
            {
                GS.Inst.LoadNextScene("Menu");
            }
        }
    }
Example #43
0
        //public void Infer(Data data, ref JSONNode specs, string specsFilename) { }

        /*
         * public void Infer(Data data, ref JSONNode specs, string specsFilename)
         * {
         *  // Go through each channel and infer the missing specs.
         *  foreach (KeyValuePair<string, JSONNode> kvp in specs["encoding"].AsObject)
         *  {
         *      ChannelEncoding channelEncoding = new ChannelEncoding();
         *
         *      // Get minimum required values:
         *      channelEncoding.channel = kvp.Key;
         *      JSONNode channelSpecs = kvp.Value;
         *      if (channelSpecs["value"] == null)
         *      {
         *          if (channelSpecs["field"] == null)
         *          {
         *              throw new Exception("Missing field in channel " + channelEncoding.channel);
         *          }
         *          else
         *          {
         *              channelEncoding.field = channelSpecs["field"];
         *
         *              if (channelSpecs["type"] != null)
         *              {
         *                  channelEncoding.fieldDataType = channelSpecs["type"];
         *              }
         *              else
         *              {
         *                  throw new Exception("Missing field data type in channel " + channelEncoding.channel);
         *              }
         *          }
         *
         *          InferScaleSpecsForChannel(ref channelEncoding, ref specs, data);
         *
         *          if (channelEncoding.channel == "x" || channelEncoding.channel == "y" ||
         *              channelEncoding.channel == "z" || channelEncoding.channel == "width" ||
         *              channelEncoding.channel == "height" || channelEncoding.channel == "depth")
         *          {
         *              InferAxisSpecsForChannel(ref channelEncoding, ref specs, data);
         *          }
         *
         *          if(channelEncoding.channel == "color" || channelEncoding.channel == "size" ||
         *              channelEncoding.channel == "shape" || channelEncoding.channel == "opacity")
         *          {
         *              InferLegendSpecsForChannel(ref channelEncoding, ref specs);
         *          }
         *      }
         *  }
         *
         *  InferMarkSpecificSpecs(ref specs);
         *
         *  string inferResults = specs.ToString();
         *  string filename = "Assets/StreamingAssets/" + specsFilename.TrimEnd(".json".ToCharArray()) + "_inferred.json";
         *  WriteStringToFile(inferResults, filename);
         * }
         */

        private void InferLegendSpecsForChannel(ref ChannelEncoding channelEncoding, ref JSONNode specs)
        {
            string   channel      = channelEncoding.channel;
            JSONNode channelSpecs = specs["encoding"][channel];
            JSONNode legendSpecs  = channelSpecs["legend"];

            if (legendSpecs != null && legendSpecs.Value.ToString() == "none")
            {
                return;
            }

            JSONObject legendSpecsObj = (legendSpecs == null) ? new JSONObject() : legendSpecs.AsObject;

            if (legendSpecsObj["type"] == null)
            {
                string fieldDataType = channelSpecs["type"].Value.ToString();
                if (fieldDataType == "quantitative" || fieldDataType == "temporal")
                {
                    legendSpecsObj.Add("type", new JSONString("gradient"));
                }
                else
                {
                    legendSpecsObj.Add("type", new JSONString("symbol"));
                }
            }

            if (legendSpecsObj["filter"] == null)
            {
                legendSpecsObj.Add("filter", new JSONBool(false));
            }

            // TODO: Add proper inference.
            // HACK: For now, always use hard coded options.
            if (legendSpecsObj["gradientWidth"] == null)
            {
                legendSpecsObj.Add("gradientWidth", new JSONNumber(200));
            }

            if (legendSpecsObj["gradientHeight"] == null)
            {
                legendSpecsObj.Add("gradientHeight", new JSONNumber(50));
            }

            if (legendSpecsObj["face"] == null)
            {
                legendSpecsObj.Add("face", new JSONString("front"));
            }

            if (legendSpecsObj["orient"] == null)
            {
                legendSpecsObj.Add("orient", new JSONString("right"));
            }

            if (legendSpecsObj["face"] == null)
            {
                legendSpecsObj.Add("face", new JSONString("front"));
            }

            if (legendSpecsObj["x"] == null)
            {
                legendSpecsObj.Add("x", new JSONNumber(float.Parse(specs["width"].Value.ToString())));
            }

            if (legendSpecsObj["y"] == null)
            {
                legendSpecsObj.Add("y", new JSONNumber(float.Parse(specs["height"].Value.ToString())));
            }

            if (legendSpecsObj["z"] == null)
            {
                legendSpecsObj.Add("z", new JSONNumber(0));
            }

            if (legendSpecsObj["title"] == null)
            {
                legendSpecsObj.Add("title", new JSONString("Legend: " + channelSpecs["field"]));
            }

            specs["encoding"][channelEncoding.channel].Add("legend", legendSpecsObj);
        }
Example #44
0
        /// <summary>
        /// 输入收货通知编号,仓库id,库区id,货主id,输出收货通知详情
        /// </summary>
        /// <param name="billno">收货通知编号</param>
        /// <returns>返回服务结果。</returns>
        public ServiceResult ExecuteService(string whid, string areaid, string ownerid, string billno)
        {
            DynamicObjectCollection dataObjectCollection;
            var result = new ServiceResult <List <JSONObject> >();
            List <JSONObject> Final_data = new List <JSONObject>();
            var ctx = this.KDContext.Session.AppContext;

            // 检查上下文对象
            if (this.IsContextExpired(result))
            {
                return(result);
            }
            // 检查传入参数
            if (string.IsNullOrWhiteSpace(billno))
            {
                result.Code    = (int)ResultCode.Fail;
                result.Message = "收货通知编号不能为空!";
                return(result);
            }
            //获取相关信息
            try
            {
                string sqlSelect1 = string.Format(@"/*dialect*/
                                                    SELECT distinct t0.FID fid, t0.FBILLNO fbillno, t5.FNAME fbatchwhid_fname,t7.FNAME fbatchownerid_fname, t9.FNAME fcontactid_fname 
                FROM  dbo.BAH_T_WMS_INNOTICE t0
                LEFT JOIN dbo.BAH_T_WMS_INNOTICEENTRY t ON t0.FID = t.FID
	            LEFT JOIN dbo.BAH_T_BD_LOCATION_L t1 ON t.FLOCID = t1.FID
	            LEFT JOIN dbo.BAH_T_WMS_INNOTICEENTRY_W t2 ON t.FENTRYID = t2.FENTRYID
	            LEFT JOIN dbo.BAH_T_BD_LOCATION t3 ON t.FLOCID = t3.FID
	            LEFT JOIN dbo.BAH_T_BD_LOCBASE T30 ON T3.FID = T30.FID
	            LEFT JOIN dbo.BAH_T_BD_WAREHOUSE t4 on t0.FWHID = t4.FID
	            INNER JOIN dbo.BAH_T_BD_WAREHOUSE_L t5 on t4.FID = t5.FID
	            LEFT JOIN dbo.BAH_V_BD_OWNER t6 ON t0.FOWNERID = t6.FID
	            INNER JOIN dbo.BAH_V_BD_OWNER_L T7 ON T6.FID = T7.FID
	            LEFT JOIN dbo.BAH_V_BD_CONTACT T8 ON T0.FCONTACTID = T8.FID
	            INNER JOIN dbo.BAH_V_BD_CONTACT_L T9 ON T8.FID = T9.FID
                LEFT JOIN dbo.BAH_T_BD_MATERIAL t10 ON t.FMATERIALID = t10.FID
	            INNER JOIN dbo.BAH_T_BD_MATWAREHOUSE T11 ON T10.FID = T11.FID
                WHERE  T0.FWHID LIKE '%{0}%' AND T0.FOWNERID LIKE '%{2}%' AND T30.FAREAID LIKE '%{1}%' and (t0.FBILLNO = '{3}' or t2.FSOURCEBILLNO = '{3}' or t0.FORDERNO = '{3}' )
                AND t0.FDOCUMENTSTATUS = 'C' AND t2.FJOINSTATUS = 'A' AND t.FMANUALCLOSE = 'A' 
                AND ((T2.FHASINBOUNDMQTY >= 0 AND T2.FHASINBOUNDMQTY < T.FMQTY AND T11.FENABLECAPACITY = 0)  OR (T11.FENABLECAPACITY = 1 AND (T2.FHASINBOUNDCTY = 0 OR T2.FHASINBOUNDCTY < T.FCTY)) )      
                              
                 ;", whid, areaid, ownerid, billno); // or a.num is null
                                                     //库区为零的情况
                string sqlSelect2 = string.Format(@"/*dialect*/
                                                    SELECT distinct t0.FID fid, t0.FBILLNO fbillno, t5.FNAME fbatchwhid_fname,t7.FNAME fbatchownerid_fname, t9.FNAME fcontactid_fname 
                FROM  dbo.BAH_T_WMS_INNOTICE t0
                LEFT JOIN dbo.BAH_T_WMS_INNOTICEENTRY t ON t0.FID = t.FID
	            LEFT JOIN dbo.BAH_T_BD_LOCATION_L t1 ON t.FLOCID = t1.FID
	            LEFT JOIN dbo.BAH_T_WMS_INNOTICEENTRY_W t2 ON t.FENTRYID = t2.FENTRYID
	            LEFT JOIN dbo.BAH_T_BD_LOCATION t3 ON t.FLOCID = t3.FID
	            LEFT JOIN dbo.BAH_T_BD_LOCBASE T30 ON T3.FID = T30.FID
	            LEFT JOIN dbo.BAH_T_BD_WAREHOUSE t4 on t0.FWHID = t4.FID
	            INNER JOIN dbo.BAH_T_BD_WAREHOUSE_L t5 on t4.FID = t5.FID
	            LEFT JOIN dbo.BAH_V_BD_OWNER t6 ON t0.FOWNERID = t6.FID
	            INNER JOIN dbo.BAH_V_BD_OWNER_L T7 ON T6.FID = T7.FID
	            LEFT JOIN dbo.BAH_V_BD_CONTACT T8 ON T0.FCONTACTID = T8.FID
	            INNER JOIN dbo.BAH_V_BD_CONTACT_L T9 ON T8.FID = T9.FID
                LEFT JOIN dbo.BAH_T_BD_MATERIAL t10 ON t.FMATERIALID = t10.FID
	            INNER JOIN dbo.BAH_T_BD_MATWAREHOUSE T11 ON T10.FID = T11.FID
                WHERE  T0.FWHID LIKE '%{0}%' AND T0.FOWNERID LIKE '%{2}%' AND (t0.FBILLNO = '{3}' or t2.FSOURCEBILLNO = '{3}' or t0.FORDERNO = '{3}' )
                AND t0.FDOCUMENTSTATUS = 'C' AND t2.FJOINSTATUS = 'A' AND t.FMANUALCLOSE = 'A' 
                AND ((T2.FHASINBOUNDMQTY >= 0 AND T2.FHASINBOUNDMQTY < T.FMQTY AND T11.FENABLECAPACITY = 0)  OR (T11.FENABLECAPACITY = 1 AND (T2.FHASINBOUNDCTY = 0 OR T2.FHASINBOUNDCTY < T.FCTY)) )      
                                   
                 ;", whid, areaid, ownerid, billno); // or a.num is null
                //TODO:通过平台动态引擎获取数据
                if (areaid == "")
                {
                    dataObjectCollection = DBUtils.ExecuteDynamicObject(ctx, sqlSelect2, null, null);
                }
                else
                {
                    dataObjectCollection = DBUtils.ExecuteDynamicObject(ctx, sqlSelect1, null, null);
                }
                foreach (DynamicObject dataObject in dataObjectCollection)
                {
                    JSONObject return_data = new JSONObject();
                    return_data.Add("Fid", dataObject["Fid"]);
                    return_data.Add("FBillNo", billno);
                    return_data.Add("FInNoticeBillNo", dataObject["fbillno"]);
                    return_data.Add("FBatchWHName", dataObject["FBatchWHId_FName"]);
                    return_data.Add("FBatchOwnerIdName", dataObject["FBatchOwnerId_FName"]);
                    return_data.Add("FContactIdName", dataObject["FContactId_FName"]);
                    //客户编码和物料编码

                    string sqlSelect = string.Format(@"/*dialect*/
              SELECT t.FENTRYID, t.FSEQ, t.FLocId, t6.FNUMBER AS FlocIdNumber, t1.FNAME AS FlocIdName
	            ,t2.FID AS FMaterialFID, t2.FNUMBER AS FMaterialNumber, t3.FNAME AS FMaterialName, t3.FSPECIFICATION, t.FPackageId,T7.FNAME AS FPackageName, t.FQty
	            , t.FUnitId, t4.FNAME AS FUnitName,t.FMQty, T.FMUNITID,t9.FNAME AS FMUnitName,    t.FLotNo,
	            CASE T8.FENABLELOT WHEN 1 then 'True' ELSE 'False' END AS FENABLELOT ,
	            CASE T8.FENABLEEXPIRY WHEN 1 then 'True' ELSE 'False' END AS FENABLEEXPIRY,
	            CASE T8.FENABLECAPACITY WHEN 1 then 'True' ELSE 'False' END AS FENABLECAPACITY,
	            t8.FCAPACITYSCALE,t10.FCAPACITYUNIT,t8.FEXPPERIOD,t8.FEXPUNIT,
                t5.FHASINBOUNDMQTY,(t.FMQTY - t5.FHASINBOUNDMQTY) AS FNeedINBOUNDMQTY,
                t.FAVGCTY,t.FCty,t.FTRACKNO,
                 t5.FHASINBOUNDCTY,(t.FCTY - t5.FHASINBOUNDCTY) AS FNeedINBOUNDCTY
                FROM dbo.BAH_T_WMS_INNOTICEENTRY t
	            LEFT JOIN dbo.BAH_T_BD_LOCATION_L t1 ON t.FLOCID = t1.FID
	            LEFT JOIN dbo.BAH_T_BD_MATERIAL t2 ON t.FMATERIALID = t2.FID
	            LEFT JOIN dbo.BAH_T_BD_MATERIAL_L t3 ON t.FMATERIALID = t3.FID
	            LEFT JOIN dbo.BAH_V_BD_UNIT_L t4 ON t.FUNITID = t4.fid
	            LEFT JOIN dbo.BAH_T_WMS_INNOTICEENTRY_W t5 ON t.FENTRYID = t5.FENTRYID
	            LEFT JOIN dbo.BAH_T_BD_LOCATION t6 ON t.FLOCID = t6.FID
	            LEFT JOIN dbo.BAH_T_BD_PACKAGE_L T7 ON T.FPACKAGEID = T7.FID
	            INNER JOIN dbo.BAH_T_BD_MATWAREHOUSE T8 ON T2.FID = T8.FID
	            LEFT JOIN dbo.BAH_V_BD_UNIT_L t9 ON t.FMUNITID = t9.fid
	            LEFT JOIN dbo.BAH_T_BD_MATWAREHOUSE_L T10 ON T8.FENTRYID = T10.FENTRYID
                LEFT JOIN dbo.BAH_T_BD_PACKAGE T11 ON T.FPACKAGEID = T11.FID
	            
                WHERE t.FMANUALCLOSE = 'A'
	            AND t5.FJOINSTATUS = 'A'
	            AND t.FID = '{0}'
                AND ((T5.FHASINBOUNDMQTY >= 0 AND T5.FHASINBOUNDMQTY < T.FMQTY AND T8.FENABLECAPACITY = 0)  OR (T8.FENABLECAPACITY = 1 AND (T5.FHASINBOUNDCTY = 0 OR T5.FHASINBOUNDCTY < T.FCTY)))
                order by t.FSEQ 
                 ;", dataObject["Fid"].ToString());// or a.num is null
                    DynamicObjectCollection mat_objc = DBUtils.ExecuteDynamicObject(ctx, sqlSelect, null, null);
                    if (mat_objc.Count == 0)
                    {
                        result.Code    = (int)ResultCode.Fail;
                        result.Message = "未检索到对应信息!";
                    }
                    else
                    {
                        List <JSONObject> detail_list = new List <JSONObject>(); //明细信息
                        foreach (DynamicObject data in mat_objc)
                        {
                            JSONObject      each_detail = new JSONObject();
                            IPackageService pkgService  = null;
                            String          FMQtyForShow;
                            String          FHASINBOUNDMQTYForShow;
                            String          FNeedINBOUNDMQTYForShow;
                            try
                            {
                                FormMetadata          meta       = MetaDataServiceHelper.Load(ctx, "BAH_BD_Package") as FormMetadata;
                                QueryBuilderParemeter queryParam = new QueryBuilderParemeter();
                                queryParam.FormId              = "BAH_BD_Package";
                                queryParam.BusinessInfo        = meta.BusinessInfo;
                                queryParam.FilterClauseWihtKey = " FID ='" + data["FPackageId"].ToString() + "' ";
                                var objs = BusinessDataServiceHelper.Load(ctx,
                                                                          meta.BusinessInfo.GetDynamicObjectType(),
                                                                          queryParam).FirstOrDefault();
                                pkgService = PIBDServiceFactory.Instance.GetService <IPackageService>(ctx);
                                var Marray = pkgService.Expand(ctx, objs, decimal.Parse(data["FMQty"].ToString()));
                                var Harray = Convert.ToDecimal(data["FHASINBOUNDMQTY"]) == 0 ? null : pkgService.Expand(ctx, objs, decimal.Parse(data["FHASINBOUNDMQTY"].ToString()));
                                var Narray = pkgService.Expand(ctx, objs, decimal.Parse(data["FNeedINBOUNDMQTY"].ToString()));
                                FMQtyForShow            = string.Join("", Marray.Select(item => string.Concat(item.Qty.ToTrimEndZeroString(), item.Name.Value(ctx))).ToArray());
                                FHASINBOUNDMQTYForShow  = Convert.ToDecimal(data["FHASINBOUNDMQTY"]) == 0 ? "0" + data["FMUnitName"] : string.Join("", Harray.Select(item => string.Concat(item.Qty.ToTrimEndZeroString(), item.Name.Value(ctx))).ToArray());
                                FNeedINBOUNDMQTYForShow = string.Join("", Narray.Select(item => string.Concat(item.Qty.ToTrimEndZeroString(), item.Name.Value(ctx))).ToArray());
                                if (Narray.Count() == 1)
                                {
                                    each_detail.Add("FNeedQTY", Narray.FirstOrDefault().Qty);
                                    each_detail.Add("FNeedUNITID", Narray.FirstOrDefault().Id);
                                    each_detail.Add("FNeedName", Narray.FirstOrDefault().Name.Value(2052));
                                }
                                else
                                {
                                    each_detail.Add("FNeedQTY", data["FNeedINBOUNDMQTY"]);
                                    each_detail.Add("FNeedUNITID", data["FMUNITID"]);
                                    each_detail.Add("FNeedName", data["FMUnitName"]);
                                }
                            }
                            finally
                            {
                                PIBDServiceFactory.Instance.CloseService(pkgService);
                            }

                            each_detail.Add("FENTRYID", data["FENTRYID"]);
                            each_detail.Add("FSEQ", data["FSEQ"]);
                            each_detail.Add("FLocId", data["FLocId"]);
                            each_detail.Add("FlocIdNumber", data["FlocIdNumber"]);
                            each_detail.Add("FlocIdName", data["FlocIdName"]);
                            each_detail.Add("FMaterialFID", data["FMaterialFID"]);
                            each_detail.Add("FMaterialNumber", data["FMaterialNumber"]);
                            each_detail.Add("FMaterialName", data["FMaterialName"]);
                            each_detail.Add("FSPECIFICATION", data["FSPECIFICATION"]);
                            each_detail.Add("FPackageId", data["FPackageId"]);
                            each_detail.Add("FPackageName", data["FPackageName"]);
                            each_detail.Add("FQty", data["FQty"]);
                            each_detail.Add("FUnitId", data["FUnitId"]);
                            each_detail.Add("FUnitName", data["FUnitName"]);
                            each_detail.Add("FMQty", data["FMQty"]);
                            each_detail.Add("FMUNITID", data["FMUNITID"]);
                            each_detail.Add("FMUnitName", data["FMUnitName"]);
                            each_detail.Add("FMQtyForShow", FMQtyForShow);
                            each_detail.Add("FHASINBOUNDMQTYForShow", FHASINBOUNDMQTYForShow);
                            each_detail.Add("FNeedINBOUNDMQTYForShow", FNeedINBOUNDMQTYForShow);
                            each_detail.Add("FNeedINBOUNDMQTY", data["FNeedINBOUNDMQTY"]);
                            each_detail.Add("FLotNo", data["FLotNo"]);
                            each_detail.Add("FENABLELOT", data["FENABLELOT"]);
                            each_detail.Add("FENABLEEXPIRY", data["FENABLEEXPIRY"]);
                            each_detail.Add("FENABLECAPACITY", data["FENABLECAPACITY"]);
                            each_detail.Add("FCAPACITYUNIT", data["FCAPACITYUNIT"]);
                            each_detail.Add("FCAPACITYSCALE", data["FCAPACITYSCALE"]);
                            each_detail.Add("FAVGCTY", data["FAVGCTY"]);
                            each_detail.Add("FCTY", data["FCTY"]);
                            each_detail.Add("FEXPPERIOD", data["FEXPPERIOD"]);
                            each_detail.Add("FEXPUNIT", data["FEXPUNIT"]);
                            each_detail.Add("FTRACKNO", data["FTRACKNO"]);
                            each_detail.Add("FHASINBOUNDCTY", data["FHASINBOUNDCTY"]);
                            each_detail.Add("FNeedINBOUNDCTY", data["FNeedINBOUNDCTY"]);

                            int count = ReturnFLOCID(whid, areaid, ownerid, data["FMaterialFID"].ToString()).Count;
                            if (count == 0)
                            {
                                each_detail.Add("InventeryForAdvise", ReturnInventery(whid, areaid, ownerid, data["FMaterialFID"].ToString()));
                            }
                            else
                            {
                                each_detail.Add("InventeryForAdvise", ReturnFLOCID(whid, areaid, ownerid, data["FMaterialFID"].ToString()));
                            }
                            detail_list.Add(each_detail);
                        }
                        return_data.Add("DetailList", detail_list);
                    }
                    //返回数据
                    Final_data.Add(return_data);
                }
                //循环以外
                result.Code    = (int)ResultCode.Success;
                result.Data    = Final_data;
                result.Message = "成功返回数据!";
            }
            catch (Exception ex)
            {
                result.Code    = (int)ResultCode.Fail;
                result.Message = ex.Message;
            }
            if (result.Message == "未将对象引用设置到对象的实例。")
            {
                result.Message = "未检索到对应信息!";
            }
            return(result);
        }
Example #45
0
        private void InferAxisSpecsForChannel(ref ChannelEncoding channelEncoding, ref JSONNode specs, Data data)
        {
            string   channel      = channelEncoding.channel;
            JSONNode channelSpecs = specs["encoding"][channel];
            JSONNode axisSpecs    = channelSpecs["axis"];

            if (axisSpecs != null && axisSpecs.Value.ToString() == "none")
            {
                return;
            }

            JSONObject axisSpecsObj = (axisSpecs == null) ? new JSONObject() : axisSpecs.AsObject;

            if (axisSpecsObj["filter"] == null)
            {
                axisSpecsObj.Add("filter", new JSONBool(false));
            }

            if (axisSpecsObj["face"] == null)
            {
                if (channel == "x" || channel == "y")
                {
                    axisSpecsObj.Add("face", new JSONString("front"));
                }
                else if (channel == "z")
                {
                    axisSpecsObj.Add("face", new JSONString("left"));
                }
            }

            if (axisSpecsObj["orient"] == null)
            {
                if (channel == "x" || channel == "z")
                {
                    axisSpecsObj.Add("orient", new JSONString("bottom"));
                }
                else if (channel == "y")
                {
                    axisSpecsObj.Add("orient", new JSONString("left"));
                }
            }

            if (axisSpecsObj["title"] == null)
            {
                axisSpecsObj.Add("title", new JSONString(channelEncoding.field));
            }

            if (axisSpecsObj["length"] == null)
            {
                float axisLength = 0.0f;
                switch (channelEncoding.channel)
                {
                case "x":
                    //case "width":
                    axisLength = specs["width"].AsFloat;
                    break;

                case "y":
                    //case "height":
                    axisLength = specs["height"].AsFloat;
                    break;

                case "z":
                    //case "depth":
                    axisLength = specs["depth"].AsFloat;
                    break;

                default:
                    axisLength = 0.0f;
                    break;
                }

                axisSpecsObj.Add("length", new JSONNumber(axisLength));
            }

            if (axisSpecs["color"] == null)
            {
                axisSpecsObj.Add("color", new JSONString("#bebebe"));
            }

            /*
             * if(axisSpecs["color"] == null)
             * {
             *  string color = "";
             *  switch (channelEncoding.channel)
             *  {
             *      case "x":
             *          color = "#ff0000";
             *          break;
             *      case "y":
             *          color = "#00ff00";
             *          break;
             *      case "z":
             *          color = "#0000ff";
             *          break;
             *      default:
             *          break;
             *  }
             *
             *  axisSpecsObj.Add("color", new JSONString(color));
             * }
             */

            if (axisSpecsObj["grid"] == null)
            {
                axisSpecsObj.Add("grid", new JSONBool(false));
            }

            if (axisSpecs["ticks"] == null)
            {
                axisSpecsObj.Add("ticks", new JSONBool(true));
            }

            if (axisSpecsObj["values"] == null)
            {
                JSONArray tickValues = new JSONArray();
                JSONNode  domain     = specs["encoding"][channelEncoding.channel]["scale"]["domain"];
                JSONNode  values     = channelEncoding.fieldDataType == "quantitative" ? new JSONArray() : domain;

                if (channelEncoding.fieldDataType == "quantitative" &&
                    (channel == "x" || channel == "y" || channel == "z"))
                {
                    // Round domain into a nice number.
                    //float maxDomain = RoundNice(domain.AsArray[1].AsFloat - domain.AsArray[0].AsFloat);

                    int numDecimals = Math.Max(GetNumDecimalPlaces(domain.AsArray[0].AsFloat), GetNumDecimalPlaces(domain.AsArray[1].AsFloat));
                    //Debug.Log("NUM DEC " + numDecimals);
                    // Add number of ticks.
                    int   defaultNumTicks = 6;
                    int   numTicks        = axisSpecsObj["tickCount"] == null ? defaultNumTicks : axisSpecsObj["tickCount"].AsInt;
                    float intervals       = Math.Abs(domain.AsArray[1].AsFloat - domain.AsArray[0].AsFloat) / (numTicks - 1.0f);


                    for (int i = 0; i < numTicks; i++)
                    {
                        float tickVal = (float)Math.Round(domain.AsArray[0].AsFloat + (intervals * (float)(i)), numDecimals);
                        //Debug.Log(tickVal);
                        values.Add(new JSONString(tickVal.ToString()));
                    }
                }

                axisSpecsObj.Add("values", values.AsArray);
            }

            if (axisSpecsObj["tickCount"] == null)
            {
                axisSpecsObj.Add("tickCount", new JSONNumber(axisSpecsObj["values"].Count));
            }

            if (axisSpecsObj["labels"] == null)
            {
                axisSpecsObj.Add("labels", new JSONBool(true));
            }

            specs["encoding"][channelEncoding.channel].Add("axis", axisSpecsObj);
        }
Example #46
0
    void Start()
    {
        infoText.gameObject.SetActive(false);

        //JSONObject usage example:

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

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

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

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

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

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

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

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

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

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

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

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

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

        newObject.Clear();
        Debug.Log("newObject cleared: " + newObject.ToString());
    }
Example #47
0
        private void InferDomain(ChannelEncoding channelEncoding, JSONNode specs, ref JSONObject scaleSpecsObj, Data data)
        {
            string sortType = "ascending";

            if (specs != null && specs["encoding"][channelEncoding.channel]["sort"] != null)
            {
                sortType = specs["encoding"][channelEncoding.channel]["sort"].Value.ToString();
            }

            string    channel = channelEncoding.channel;
            JSONArray domain  = new JSONArray();

            if (channelEncoding.fieldDataType == "quantitative" &&
                (channel == "x" || channel == "y" || channel == "z" ||
                 channel == "width" || channel == "height" || channel == "depth" || channel == "length" ||
                 channel == "color" || channel == "xrotation" || channel == "yrotation" ||
                 channel == "zrotation" || channel == "size" || channel == "xdirection") ||
                channel == "ydirection" || channel == "zdirection" || channel == "opacity")
            {
                List <float> minMax = new List <float>();
                GetExtent(data, channelEncoding.field, ref minMax);

                /*
                 * // For positive minimum values, set the baseline to zero.
                 * // TODO: Handle logarithmic scale with undefined 0 value.
                 * if(minMax[0] >= 0)
                 * {
                 *  minMax[0] = 0;
                 * }
                 *
                 * float roundedMaxDomain = RoundNice(minMax[1] - minMax[0]);
                 */

                if (sortType == "none" || sortType == "ascending")
                {
                    //domain.Add(new JSONString(minMax[0].ToString()));
                    domain.Add(new JSONString("0"));
                    domain.Add(new JSONString(minMax[1].ToString()));
                }
                else
                {
                    domain.Add(new JSONString(minMax[1].ToString()));
                    domain.Add(new JSONString("0"));
                    //domain.Add(new JSONString(minMax[0].ToString()));
                }
            }
            else
            {
                List <string> uniqueValues = new List <string>();
                GetUniqueValues(data, channelEncoding.field, ref uniqueValues);

                if (sortType == "ascending")
                {
                    uniqueValues.Sort();
                }
                else if (sortType == "descending")
                {
                    uniqueValues.Sort();
                    uniqueValues.Reverse();
                }

                foreach (string val in uniqueValues)
                {
                    domain.Add(val);
                }
            }

            scaleSpecsObj.Add("domain", domain);
        }
    public void SendPoints(int points, string source = null, JSONObject pointsJsonData = null)
    {
        int    offlinePoints     = PreferencesFactory.GetInt(Constants.KeyOfflinePoints, 0);
        string _pointsDataString = PreferencesFactory.GetString(Constants.KeyOfflinePointsData, null);

        if (pointsJsonData != null && source != null)
        {
            pointsJsonData.Add("source", source);
        }

        JSONArray _pointsData = new JSONArray();

        if (!string.IsNullOrEmpty(_pointsDataString))
        {
            try
            {
                _pointsData = JSONArray.Parse(_pointsDataString);
            } catch (Exception e) {}
        }

        if (pointsJsonData != null)     // add new record
        {
            _pointsData.Add(pointsJsonData);
        }

        if (Reachability.Instance.IsReachable() == false || IsUserLoggedIn() == false)
        {
            PreferencesFactory.SetInt(Constants.KeyOfflinePoints, points + offlinePoints);
            PreferencesFactory.SetString(Constants.KeyOfflinePointsData, _pointsData.ToString());

            return;
        }

        if (points + offlinePoints <= 0)
        {
            return;
        }

        int levelNumber = -1;

        try
        {
            Level level = LevelController.FirstUnplayedLevel();

            if (level != null)
            {
                levelNumber = level.Number - 1;
            }
        } catch (Exception e) {}

        GSRequestData requestData = new GSRequestData();

        requestData.AddNumber("offlinePoints", offlinePoints);
        requestData.AddNumber("score", points);
        requestData.AddNumber("lastPlayedLevel", levelNumber);

        if (_pointsData != null)
        {
            requestData.AddJSONStringAsObject("pointsData", _pointsData.ToString());
        }

        if (source != null)
        {
            requestData.AddString("source", source);
        }

        new LogEventRequest()
        .SetEventKey("SubmitScoreV2")
        .SetEventAttribute("score", points + offlinePoints)
        .SetEventAttribute("data", requestData)
        .Send((response) => {
            if (!response.HasErrors)
            {
                PreferencesFactory.DeleteKey(Constants.KeyOfflinePoints);
                PreferencesFactory.DeleteKey(Constants.KeyOfflinePointsData);
            }
        });
    }
Example #49
0
        public static string Serialize()
        {
            var config = new JSONObject();

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

            return(config.ToString());
        }
Example #50
0
    /**
     * @author David
     *
     * Saving the current state of DataModel in the data.json file
     **/
    public static void Save(string filepath)
    {
        JSONObject dataJson = new JSONObject();

        dataJson.Add("Quizname", QuizName);
        dataJson.Add("CurTopicName", CurTopicName);
        dataJson.Add("RoundNumber", RoundNumber);
        // indexes
        dataJson.Add("IroundCur", IroundCur);
        dataJson.Add("ItopicCur", ItopicCur);
        dataJson.Add("IquestionCur", IquestionCur);

        for (int i = 0; i < Scores.Length; i++)
        {
            dataJson.Add("Score" + i, Scores[i]);
            dataJson.Add("Joker" + i, Jokers[i]);
        }

        JSONArray roundsJsonArray = new JSONArray();

        foreach (RoundData rd in Rounds)
        {
            JSONObject roundJson = new JSONObject();
            roundJson.Add("Type", rd.Type);
            roundJson.Add("IsBuzzActivate", rd.IsBuzzRound);
            JSONArray topicsJsonArray = new JSONArray();
            foreach (TopicData td in rd.Topics)
            {
                JSONObject topicJson = new JSONObject();

                topicJson.Add("Name", td.Name);
                topicJson.Add("IsAvailable", td.IsAvailable);

                JSONArray questionsJsonArray = new JSONArray();
                foreach (QuestionData qd in td.Questions)
                {
                    JSONObject questionJson = new JSONObject();

                    switch (qd.GetType().ToString())
                    {
                    case "MusicQuestion":
                        MusicQuestion mq = (MusicQuestion)qd;
                        questionJson.Add("MusicPath", mq.MusicPath);
                        questionJson.Add("StartTrack", mq.StartTrack);
                        questionJson.Add("Volume", mq.Volume);
                        questionJson.Add("Fade", mq.Fade);
                        break;

                    case "ImageQuestion":
                        ImageQuestion iq = (ImageQuestion)qd;
                        questionJson.Add("ImagePath", iq.ImagePath);
                        break;

                    case "TextQuestion":
                        TextQuestion tq = (TextQuestion)qd;
                        questionJson.Add("Question", tq.Question);
                        break;

                    case "TrueFalseQuestion":
                        TrueFalseQuestion tfq = (TrueFalseQuestion)qd;
                        questionJson.Add("Question", tfq.Question);
                        break;

                    default: Debug.LogError("Type de question non-reconnu"); break;
                    }

                    JSONArray answersJsonArray = new JSONArray();

                    foreach (AnswerData ad in qd.Answers)
                    {
                        JSONObject answerJson = new JSONObject();

                        answerJson.Add("AnswerText", ad.AnswerText);
                        answerJson.Add("IsTrue", ad.IsTrue);

                        answersJsonArray.Add(answerJson);
                    }
                    questionJson.Add("Answers", answersJsonArray);

                    questionsJsonArray.Add(questionJson);
                }
                topicJson.Add("Questions", questionsJsonArray);

                topicsJsonArray.Add(topicJson);
            }

            roundJson.Add("Topics", topicsJsonArray);

            roundsJsonArray.Add(roundJson);
        }

        dataJson.Add("Rounds", roundsJsonArray);

        File.WriteAllText(filepath, dataJson.ToString());
    }
Example #51
0
    /// <summary>
    /// Updates data
    /// <summary>
    /// <param name="rawData">Raw socket response</param>
    private void UpdateData(string rawData)
    {
        JSONNode parsedData = JSON.Parse(rawData.Substring(4));

        if ("sync".Equals(parsedData ["name"]))
        {
            args    = parsedData ["args"] [0];
            oldData = data;
            data    = Utils.MergeDict(data, args);

            // update on attempt
            if (args ["attempt"] != null)
            {
                buzzUid = args ["attempt"] ["user"];
                correct = args ["attempt"] ["correct"];

                // log on done
                if (args ["attempt"] ["done"] && !args["attempt"]["prompt"])
                {
                    JSONNode entry = new JSONObject();
                    entry.Add("user", args ["attempt"] ["user"]);
                    entry.Add("verb", "guessed " + args ["attempt"] ["text"] + " (" + (args["attempt"]["correct"] ? "CORRECT" : "WRONG") + ")");
                    lock (logStack) {
                        logStack.Push(entry);
                    }
                }
            }

            // Determine if user can claim buzz
            if (awaitConfirmBuzz)
            {
                hasRecvBuzzer    = true;
                hasBuzz          = uid.Equals(buzzUid);
                awaitConfirmBuzz = false;
            }
        }
        else if ("joined".Equals(parsedData ["name"]))
        {
            uid = parsedData ["args"] [0] ["id"];
        }
        else if ("log".Equals(parsedData ["name"]))
        {
            JSONNode logData = parsedData ["args"] [0];
            lock (logStack) {
                logStack.Push(logData);
            }
        }
        else if ("chat".Equals(parsedData ["name"]))
        {
            args = parsedData ["args"] [0];

            // log on done
            if (args ["done"])
            {
                JSONNode entry = new JSONObject();
                entry.Add("user", args ["user"]);
                entry.Add("verb", ": " + args ["text"]);
                lock (logStack) {
                    logStack.Push(entry);
                }
            }
        }
    }
Example #52
0
 public void AddNewProperty(string property, string value)
 {
     userJSON.Add(property, value);
 }
Example #53
0
        /**
         * <div style='width: 100%;text-align: right'> ارسال داده های بازی</div>
         * @param Params
         *      <ul>
         *          <li>{JSONObject|string} sendData - داده ارسالی</li>
         *          <li>{string} [dataId] - شناسه داده</li>
         *      </ul>
         *
         * @param  callback
         * events : onReceive - بعد از دریافت پیام توسط حریف , این متد فراخوانی می شود
         *
         * @throws ServiceException خطای پارامتر های ورودی
         * @return id شناسه داده ارسال شده
         * */
        public JSONObject SendData(JSONObject Params, Action <JSONObject> onReceive)
        {
            var retData = new JSONObject();

            Debug.Log("sendData_1");

            var dataId = (Params.HasKeyNotNull("dataId")) ? Params["dataId"].ToString() : Guid.NewGuid().ToString();
            //            bool sequential = (Params.has("dataId") && !Params.isNull("sequential")) && Params.getBoolean("sequential");
            string matchId = Params["matchId"];

            var receiversPeerIdPeerId = new JSONArray();

            receiversPeerIdPeerId.Add(_opponentPeerId);
            var ackObj = _sendDataAckState[dataId];

            Debug.Log("sendData_2");
            if (ackObj != null)
            {
                var state = (bool)ackObj["state"];
                Debug.Log("sendData_3 " + state);
                if (state)
                {
                    return(null);
                }
            }
            else
            {
                Debug.Log("sendData_4");
                ackObj = new Dictionary <string, object> {
                    { "state", false }, { "sendTryCount", 0 }
                };

                if (onReceive != null)
                {
                    ackObj.Add("callback", onReceive);
                }

                _sendDataAckState.Add(dataId, ackObj);

                ackObj.Add("sendTryCount", (int)ackObj["sendTryCount"] + 1);

                var emitData = new JSONObject();
                emitData.Add("receivers", receiversPeerIdPeerId);

                var pushContent = new JSONObject();
                pushContent.Add("type", PushMessageContentTypes.DataPack);

                var gameContent = new JSONObject();
                gameContent.Add("dataId", dataId);
                gameContent.Add("matchId", matchId);
                gameContent.Add("data", Params["sendData"]);

                pushContent.Add("content", gameContent);

                emitData.Add("content", pushContent);

                var timeoutId = Util.SetTimeout(() =>
                {
                    var ackObjTemp = _sendDataAckState[dataId];
                    Debug.Log("sendData_6 ");
                    if (!(Boolean)ackObjTemp["state"])
                    {
                        Debug.Log("sendData_7 ");
                        if (_isFinished && (int)ackObjTemp["sendTryCount"] > ConfigData.Msdtc)
                        {
                            Debug.Log("sendData_8 ");
                            return;
                        }

                        try
                        {
                            Params.Add("resend", true);
                            SendData(Params, onReceive);
                        }
                        catch (Exception e)
                        {
                            Debug.LogError("Exception: " + e.Message);
                        }
                    }
                }, ConfigData.Pmto);

                var reqData = new JSONObject();
                reqData.Add("type", 5);
                reqData.Add("content", emitData);
                Debug.Log("sendData_5 " + reqData);

                var t1 = DateTime.Now;
                _network.Emit(reqData, result =>
                {
                    try
                    {
                        var diff = DateTime.Now.Subtract(t1);
                        Debug.Log("sendData_9 " + (diff));
                        var ackObjTemp = _sendDataAckState[dataId];
                        if (!(bool)ackObjTemp["state"])
                        {
                            ackObjTemp.Add("state", true);

                            if (!_isFinished)
                            {
                                var recDataAck = new JSONObject();
                                recDataAck.Add("dataId", dataId);
                                if (Params.HasKeyNotNull("sequential"))
                                {
                                    recDataAck.Add("sequential", Params["sequential"]);
                                }

                                OnReceiveDataAck(recDataAck);
                            }

                            Util.ClearTimeout(timeoutId);

                            var retDataTemp = new JSONObject();
                            retDataTemp.Add("dataId", dataId);
                            Debug.Log("sendData_10 " + retDataTemp);
                            if (onReceive != null)
                            {
                                onReceive(retDataTemp);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Debug.LogError("Exception: " + e.Message);
                    }
                });

                if (Params.HasKeyNotNull("resend") && !Params["resend"].AsBool)
                {
                    var sentData = new JSONObject();
                    sentData.Add("dataId", dataId);
                    if (Params.HasKeyNotNull("sequential"))
                    {
                        sentData.Add("sequential", Params["sequential"]);
                    }

                    var sequentialDataQueueLength = 0;
                    if (Params.HasKeyNotNull("sequentialDataQueueLength") &&
                        Params["sequentialDataQueueLength"].AsInt > 0)
                    {
                        sequentialDataQueueLength = Params["sequentialDataQueueLength"].AsInt;
                    }

                    sentData.Add("sequentialDataQueueLength", sequentialDataQueueLength);
                    OnSentData(sentData);
                }
            }

            retData.Add("dataId", dataId);
            return(retData);
        }
            public SongMap(JSONObject song, string LevelId = "", string path = "")
            {
                if (!song["version"].IsString)
                {
                    //RequestBot.Instance.QueueChatMessage($"{song["key"].Value}: {song["metadata"]}");
                    song.Add("id", song["key"]);
                    song.Add("version", song["key"]);

                    var metadata = song["metadata"];
                    song.Add("songName", metadata["songName"].Value);
                    song.Add("songSubName", metadata["songSubName"].Value);
                    song.Add("authorName", metadata["songAuthorName"].Value);
                    song.Add("levelAuthor", metadata["levelAuthorName"].Value);
                    song.Add("rating", song["stats"]["rating"].AsFloat * 100);

                    bool degrees90  = false;
                    bool degrees360 = false;

                    try
                    {
                        var characteristics = metadata["characteristics"][0]["difficulties"];

                        //Instance.QueueChatMessage($"{characteristics}");

                        foreach (var entry in metadata["characteristics"])
                        {
                            if (entry.Value["name"] == "360Degree")
                            {
                                degrees360 = true;
                            }
                            if (entry.Value["name"] == "90Degree")
                            {
                                degrees90 = true;
                            }
                        }

                        int maxnjs = 0;
                        foreach (var entry in characteristics)
                        {
                            if (entry.Value.IsNull)
                            {
                                continue;
                            }
                            var diff = entry.Value["length"].AsInt;
                            var njs  = entry.Value["njs"].AsInt;
                            if (njs > maxnjs)
                            {
                                maxnjs = njs;
                            }



                            if (diff > 0)
                            {
                                song.Add("songlength", $"{diff / 60}:{diff % 60:00}");
                                song.Add("songduration", diff);
                                //Instance.QueueChatMessage($"{diff / 60}:{diff % 60}");
                            }
                        }

                        if (maxnjs > 0)
                        {
                            song.Add("njs", maxnjs);
                        }
                        if (degrees360 || degrees90)
                        {
                            song.Add("maptype", "360");
                        }
                    }
                    catch
                    {
                    }
                }


                float songpp = 0;

                if (ppmap.TryGetValue(song["id"].Value, out songpp))
                {
                    song.Add("pp", songpp);
                }

                //SongMap oldmap;
                //if (MapDatabase.MapLibrary.TryGetValue(song["id"].Value,out oldmap))
                //{

                //    if (LevelId == oldmap.LevelId && song["version"].Value == oldmap.song["version"].Value)
                //    {
                //        oldmap.song = song;
                //        return;
                //    }

                //    int id = int.Parse(song["id"].Value.ToUpper(), System.Globalization.NumberStyles.HexNumber);

                //    oldmap.UnIndexSong(id);
                //}

                this.path = path;
                //this.LevelId = LevelId;
                IndexSong(song);
            }
Example #55
0
        private void CancelMatchRequest(int type, Action <JSONObject> onResult)
        {
            try
            {
                var requestData = new JSONObject();
                requestData.Add("matchId", _matchId);
                requestData.Add("type", type);

                _service.HttpPostRequest(RequestUrls.MatchCancel, requestData, result =>
                {
                    try
                    {
                        var hasError = result["hasError"].AsBool;

                        var errorCode = 0;
                        if (result.HasKeyNotNull("errorCode"))
                        {
                            errorCode = result["errorCode"].AsInt;
                        }

                        if (hasError && (errorCode == ErrorCodes.Runtime || errorCode == ErrorCodes.RequestFailed))
                        {
                            Util.SetTimeout(() =>
                            {
                                try
                                {
                                    CancelMatchRequest(type, onResult);
                                }
                                catch (ServiceException e)
                                {
                                    Debug.LogError("Exception: " + e.Message);
                                }
                            }, ConfigData.Smit);
                        }
                        else
                        {
                            var retData = new JSONObject();
                            retData.Add("hasError", hasError);
                            if (hasError)
                            {
                                retData.Add("errorMessage", errorCode);
                                retData.Add("errorCode", errorCode);
                            }

                            if (onResult != null)
                            {
                                onResult(retData);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Debug.LogError("Exception: " + e.Message);
                    }
                });
            }
            catch (Exception e)
            {
                Debug.LogError("Exception: " + e.Message);
                //throw new ServiceException(e);
            }
        }
Example #56
0
        public static void StartHttpServer()
        {
            var route_config = new List <Route>()
            {
                new Route {
                    Name     = "Score Receiver",
                    UrlRegex = @"^/submit/$",
                    Method   = "POST",
                    Callable = (HttpRequest request) => {
                        try
                        {
                            //Get JSON object from request content
                            JSONNode node = JSON.Parse(WebUtility.UrlDecode(request.Content));

                            //Get Score object from JSON
                            Score s = Score.FromString(node["pb"]);

                            if (RSA.SignScore(Convert.ToUInt64(s.UserId), s.SongHash, s.Difficulty, s.Characteristic, s.FullCombo, s.Score_, s.PlayerOptions, s.GameOptions) == s.Signed &&
                                Song.Exists(s.SongHash, (LevelDifficulty)s.Difficulty, s.Characteristic, true) &&
                                !new Song(s.SongHash, (LevelDifficulty)s.Difficulty, s.Characteristic).Old&&
                                Player.Exists(s.UserId) &&
                                Player.IsRegistered(s.UserId))
                            {
                                Logger.Info($"RECEIVED VALID SCORE: {s.Score_} FOR {new Player(s.UserId).DiscordName} {s.SongHash} {s.Difficulty} {s.Characteristic}");
                            }
                            else
                            {
                                Logger.Error($"RECEIVED INVALID SCORE {s.Score_} FROM {new Player(s.UserId).DiscordName} FOR {s.UserId} {s.SongHash} {s.Difficulty} {s.Characteristic}");
                                return(new HttpResponse()
                                {
                                    ReasonPhrase = "Bad Request",
                                    StatusCode = "400"
                                });
                            }

#if BEATKHANA
                            PostToBeatKhana(s.UserId, s.SongHash, s.Score_.ToString(), new EventServer.BeatSaver.Song(s.SongHash).GetMaxScore(s.Characteristic, (LevelDifficulty)s.Difficulty).ToString());
#endif

                            Database.Score oldScore = null;
                            if (Database.Score.Exists(s.SongHash, s.UserId, (LevelDifficulty)s.Difficulty, s.Characteristic))
                            {
                                oldScore = new Database.Score(s.SongHash, s.UserId, (LevelDifficulty)s.Difficulty, s.Characteristic);
                            }

                            if (oldScore == null ^ (oldScore != null && oldScore.GetScore() < s.Score_))
                            {
                                Player player = new Player(s.UserId);

                                long oldScoreNumber = oldScore == null ? 0 : oldScore.GetScore();
                                oldScore?.SetOld();

                                //Player stats
                                if (oldScoreNumber > 0)
                                {
                                    player.IncrementPersonalBestsBeaten();
                                }
                                else
                                {
                                    player.IncrementSongsPlayed();
                                }
                                player.IncrementSongsPlayed();
                                player.TotalScore += s.Score_ - oldScoreNumber; //Increment total score only by the amount the score has increased

                                Database.Score newScore = new Database.Score(s.SongHash, s.UserId, (LevelDifficulty)s.Difficulty, s.Characteristic);
                                newScore.SetScore(s.Score_, s.FullCombo);

                                //Only send message if player is registered
                                if (Player.Exists(s.UserId))
                                {
                                    CommunityBot.SendToScoreChannel($"User \"{player.DiscordMention}\" has scored {s.Score_} on {new Song(s.SongHash, (LevelDifficulty)s.Difficulty, s.Characteristic).SongName} ({(LevelDifficulty)s.Difficulty}) ({s.Characteristic})!");
                                }
                            }

                            return(new HttpResponse()
                            {
                                ReasonPhrase = "OK",
                                StatusCode = "200"
                            });
                        }
                        catch (Exception e)
                        {
                            Logger.Error($"{e}");
                        }

                        return(new HttpResponse()
                        {
                            ReasonPhrase = "Bad Request",
                            StatusCode = "400"
                        });
                    }
                },
                new Route {
                    Name     = "Rank Receiver",
                    UrlRegex = @"^/requestrank/$",
                    Method   = "POST",
                    Callable = (HttpRequest request) => {
                        try
                        {
                            //Get JSON object from request content
                            JSONNode node = JSON.Parse(WebUtility.UrlDecode(request.Content));

                            //Get Score object from JSON
                            RankRequest r = RankRequest.FromString(node["pb"]);

                            if (RSA.SignRankRequest(Convert.ToUInt64(r.UserId), r.RequestedTeamId, r.InitialAssignment) == r.Signed &&
                                Player.Exists(r.UserId) &&
                                Player.IsRegistered(r.UserId) &&
                                Team.Exists(r.RequestedTeamId))
                            {
                                Logger.Info($"RECEIVED VALID RANK REQUEST: {r.RequestedTeamId} FOR {r.UserId} {r.RequestedTeamId} {r.InitialAssignment}");

                                var player = new Player(r.UserId);
                                var team   = new Team(r.RequestedTeamId);

                                //The rank up system will ignore requets where the player doesn't have the required tokens,
                                //or is requesting a rank higher than the one above their current rank (if it's not an inital rank assignment)
                                if (r.InitialAssignment && player.Team == "-1")
                                {
                                    CommunityBot.ChangeTeam(player, team);
                                }
                                else if (player.Team != "gold")
                                {
                                    var oldTeam  = new Team(player.Team);
                                    var nextTeam = new Team(oldTeam.NextPromotion);
                                    if (player.Tokens >= nextTeam.RequiredTokens)
                                    {
                                        CommunityBot.ChangeTeam(player, nextTeam);
                                    }
                                }
                                else if (player.Team == "gold" && player.Tokens >= new Team("blue").RequiredTokens)   //Player is submitting for Blue
                                {
                                    new Vote(player.UserId, r.OstScoreInfo);
                                }
                                else
                                {
                                    return(new HttpResponse()
                                    {
                                        ReasonPhrase = "Bad Request",
                                        StatusCode = "400"
                                    });
                                }

                                return(new HttpResponse()
                                {
                                    ReasonPhrase = "OK",
                                    StatusCode = "200"
                                });
                            }
                            else
                            {
                                Logger.Warning($"RECEIVED INVALID RANK REQUEST {r.RequestedTeamId} FROM {r.UserId}");
                            }
                        }
                        catch (Exception e)
                        {
                            Logger.Error($"{e}");
                        }

                        return(new HttpResponse()
                        {
                            ReasonPhrase = "Bad Request",
                            StatusCode = "400"
                        });
                    }
                },
                new Route {
                    Name     = "Song Getter",
                    UrlRegex = @"^/songs/",
                    Method   = "GET",
                    Callable = (HttpRequest request) => {
                        string[] requestData = request.Path.Substring(1).Split('/');
                        string   userId      = requestData[1];
                        userId = Regex.Replace(userId, "[^a-zA-Z0-9- ]", "");

                        //If the userid is null, we'll give them e+ everything. It's likely the leaderboard site
                        if (!string.IsNullOrEmpty(userId) && (!Player.Exists(userId) || !Player.IsRegistered(userId)))
                        {
                            return(new HttpResponse()
                            {
                                ReasonPhrase = "Bad Request",
                                StatusCode = "400"
                            });
                        }

                        JSONNode             json  = new JSONObject();
                        List <SongConstruct> songs = GetActiveSongs();

                        songs.ForEach(x => {
                            //If the request doesn't include a player id, we can't be sure which difficulty the player is supposed to play, so we'll just leave
                            //the difficulty set to Auto because it's probably the website asking
                            if (x.Difficulty == LevelDifficulty.Auto && !string.IsNullOrEmpty(userId))
                            {
                                if (OstHelper.IsOst(x.SongHash))
                                {
                                    x.Difficulty = new Player(userId).GetPreferredDifficulty(OstHelper.IsOst(x.SongHash));
                                }
                                else
                                {
                                    var preferredDifficulty = new Player(userId).GetPreferredDifficulty(OstHelper.IsOst(x.SongHash));
                                    x.Difficulty            = new BeatSaver.Song(x.SongHash).GetClosestDifficultyPreferLower(preferredDifficulty);
                                }
                            }

                            var item               = new JSONObject();
                            item["songName"]       = x.Name;
                            item["songHash"]       = x.SongHash;
                            item["difficulty"]     = (int)x.Difficulty;
                            item["gameOptions"]    = (int)x.GameOptions;
                            item["playerOptions"]  = (int)x.PlayerOptions;
                            item["characteristic"] = x.Characteristic;
                            json.Add(x.SongHash + (int)x.Difficulty, item);
                        });

                        return(new HttpResponse()
                        {
                            ContentAsUTF8 = json.ToString(),
                            ReasonPhrase = "OK",
                            StatusCode = "200"
                        });
                    }
                },
                new Route {
                    Name     = "Team Getter",
                    UrlRegex = @"^/teams/",
                    Method   = "GET",
                    Callable = (HttpRequest request) => {
                        string source = request.Path.Substring(request.Path.LastIndexOf("/") + 1);
                        if (!string.IsNullOrEmpty(source))
                        {
                            Logger.Success("Team Request from Duo's Site");
                        }

                        JSONNode    json  = new JSONObject();
                        List <Team> teams = GetAllTeams();

                        foreach (var team in teams)
                        {
                            var item = new JSONObject();
                            item["captainId"]      = team.Captain;
                            item["teamName"]       = team.TeamName;
                            item["color"]          = team.Color;
                            item["requiredTokens"] = team.RequiredTokens;
                            item["nextPromotion"]  = team.NextPromotion;
                            json.Add(team.TeamId, item);
                        }

                        return(new HttpResponse()
                        {
                            ContentAsUTF8 = json.ToString(),
                            ReasonPhrase = "OK",
                            StatusCode = "200"
                        });
                    }
                },
                new Route {
                    Name     = "Player Stats Getter",
                    UrlRegex = @"^/playerstats/",
                    Method   = "GET",
                    Callable = (HttpRequest request) => {
                        string userId = request.Path.Substring(request.Path.LastIndexOf("/") + 1);
                        userId = Regex.Replace(userId, "[^a-zA-Z0-9]", "");

                        if (!(userId.Length == 17 || userId.Length == 16 || userId.Length == 15)) //17 = vive, 16 = oculus, 15 = sfkwww
                        {
                            Logger.Error($"Invalid id size: {userId.Length}");
                            return(new HttpResponse()
                            {
                                ReasonPhrase = "Bad Request",
                                StatusCode = "400"
                            });
                        }

                        JSONNode json = new JSONObject();

                        if (Player.Exists(userId) && Player.IsRegistered(userId))
                        {
#if QUALIFIER
                            var isRegistered = true;
                            if (userId != "76561198063268251")
                            {
                                var registrationCheck = IsPlayerRegisteredInBSWC(userId);
                                registrationCheck.Wait();
                                isRegistered = registrationCheck.Result;
                            }
#else
                            var isRegistered = true;
#endif

                            if ((Config.ServerFlags.HasFlag(ServerFlags.Teams) && new Player(userId).Team == "-1") || !isRegistered)
                            {
                                json["message"] = "Please be sure you're assigned to a team before playing";
                            }
                            else
                            {
                                Player player = new Player(userId);
                                json["version"]        = VersionCode;
                                json["team"]           = player.Team;
                                json["tokens"]         = player.Tokens;
                                json["serverSettings"] = (int)Config.ServerFlags;
                            }
                        }
                        else if (Player.Exists(userId) && !Player.IsRegistered(userId))
                        {
                            json["message"] = "You have been banned from this event.";
                        }
                        else
                        {
                            json["message"] = "Please register with the bot before playing. Check #plugin-information for more info. Sorry for the inconvenience.";
                        }

                        return(new HttpResponse()
                        {
                            ContentAsUTF8 = json.ToString(),
                            ReasonPhrase = "OK",
                            StatusCode = "200"
                        });
                    }
                },
                new Route {
                    Name     = "Song Leaderboard Getter",
                    UrlRegex = @"^/leaderboards/",
                    Method   = "GET",
                    Callable = (HttpRequest request) => {
                        string[] requestData = request.Path.Substring(1).Split('/');
                        string   songHash    = requestData[1];
                        JSONNode json        = new JSONObject();

#if HIDDENNOTES
                        return(new HttpResponse()
                        {
                            ContentAsUTF8 = json.ToString(),
                            ReasonPhrase = "OK",
                            StatusCode = "200"
                        });
#endif

                        if (songHash == "all")
                        {
                            int    take   = 10;
                            string teamId = "-1";

                            if (requestData.Length > 2)
                            {
                                take = Convert.ToInt32(requestData[2]);
                            }
                            if (requestData.Length > 3)
                            {
                                teamId = requestData[3];
                            }

                            List <SongConstruct> songs = GetAllScores(teamId);
                            songs.ToList().ForEach(x =>
                            {
                                JSONNode songNode          = new JSONObject();
                                songNode["levelId"]        = x.SongHash;
                                songNode["songName"]       = x.Name;
                                songNode["difficulty"]     = (int)x.Difficulty;
                                songNode["characteristic"] = x.Characteristic;
                                songNode["scores"]         = new JSONObject();

                                int place = 1;
                                x.Scores.Take(take).ToList().ForEach(y =>
                                {
                                    JSONNode scoreNode     = new JSONObject();
                                    scoreNode["score"]     = y.Score;
                                    scoreNode["player"]    = new Player(y.UserId).DiscordName;
                                    scoreNode["place"]     = place;
                                    scoreNode["fullCombo"] = y.FullCombo ? "true" : "false";
                                    scoreNode["userId"]    = y.UserId;
                                    scoreNode["team"]      = y.TeamId;
                                    songNode["scores"].Add(Convert.ToString(place++), scoreNode);
                                });

                                json.Add(x.SongHash + ":" + (int)x.Difficulty, songNode);
                            });
                        }
                        else
                        {
                            int    take           = 10;
                            int    difficulty     = Convert.ToInt32(requestData[2]);
                            string characteristic = requestData[3];
                            string teamId         = requestData[4];
                            if (requestData.Length > 5)
                            {
                                take = Convert.ToInt32(requestData[5]);
                            }

                            songHash = Regex.Replace(songHash, "[^a-zA-Z0-9- ]", "");
                            teamId   = Regex.Replace(teamId, "[^a-zA-Z0-9- ]", "");

                            SongConstruct songConstruct = new SongConstruct()
                            {
                                SongHash       = songHash,
                                Difficulty     = (LevelDifficulty)difficulty,
                                Characteristic = characteristic
                            };

                            if (!Song.Exists(songHash, (LevelDifficulty)difficulty, characteristic, true))
                            {
                                Logger.Error($"Song doesn't exist for leaderboards: {songHash}");
                                return(new HttpResponse()
                                {
                                    ReasonPhrase = "Bad Request",
                                    StatusCode = "400"
                                });
                            }

                            List <ScoreConstruct> scores = GetScoresForSong(songConstruct, teamId);

                            int place = 1;
                            scores.Take(take).ToList().ForEach(x =>
                            {
                                JSONNode node     = new JSONObject();
                                node["score"]     = x.Score;
                                node["player"]    = new Player(x.UserId).DiscordName;
                                node["place"]     = place;
                                node["fullCombo"] = x.FullCombo ? "true" : "false";
                                node["userId"]    = x.UserId;
                                node["team"]      = x.TeamId;
                                json.Add(Convert.ToString(place++), node);
                            });
                        }

                        return(new HttpResponse()
                        {
                            ContentAsUTF8 = json.ToString(),
                            ReasonPhrase = "OK",
                            StatusCode = "200"
                        });
                    }
                }
            };

            Logger.Info($"HTTP Server listening on {Dns.GetHostName()}");

#if (TEAMSABER)
            int port = 3707;
#elif (DISCORDCOMMUNITY)
            int port = 3703;
#elif (TRUEACCURACY)
            int port = 3711;
#elif (ASIAVR)
            int port = 3709;
#elif (QUALIFIER)
            int port = 3713;
#elif (BTH)
            int port = 3715;
#elif (FENCINGQUALIFIER)
            int port = 3717;
#elif (BEATKHANA)
            int port = 3719;
#elif (HIDDENNOTES)
            int port = 3721;
#elif BETA
            int port = 3704; //My vhost is set up to direct to 3708 when the /api-beta/ route is followed
#endif
            HttpServer httpServer = new HttpServer(port, route_config);
            httpServer.Listen();
        }
        /// <summary>
        /// 获取未完成发货通知和部分发货的发货通知
        /// </summary>
        ///参数为三个:仓库FID ,库区FID,货主FID
        /// <returns>返回服务结果。</returns>
        public ServiceResult ExecuteService(string whid, string areaid, string ownerid)
        {
            DynamicObjectCollection dataObjectCollection;
            var result = new ServiceResult <List <JSONObject> >();
            var ctx    = this.KDContext.Session.AppContext;

            // 检查上下文对象
            if (this.IsContextExpired(result))
            {
                return(result);
            }


            //获取相关信息
            try
            {
                JSONObject        Finaldata   = new JSONObject();
                List <JSONObject> return_data = new List <JSONObject>();
                // TODO: 通过平台动态引擎获取数据
                string sqlSelect = string.Format(@"/*dialect*/
                                                    SELECT CASE t0.FDIRECTION WHEN 'General' THEN '普通' ELSE '退回' END AS FDIRECTION, 
 t0.FBILLNO,t0.FMODIFYDATE AS FMODIFYDATE,t0.FCREATEDATE AS FCREATEDATE,t4.FID as FWHID,T4.FNUMBER AS FWHNUMBER,T5.FNAME AS FWHNAME,
 T6.FID AS FOWNERID,T6.FNUMBER AS FOWNERNUMBER,T7.FNAME AS FOWNERNAME ,
 T8.FID AS FCONTACTID,T8.FNUMBER AS FCONTACTNUMBER,T9.FNAME AS FCONTACTNAME,T8.fformid AS FCONTACTFORMID,'未拣货' AS FStatus, COUNT(t.FENTRYID) as COUNT
                FROM  dbo.BAH_T_WMS_OUTNOTICE t0
                LEFT JOIN dbo.BAH_T_WMS_OUTNOTICEENTRY t ON t0.FID = t.FID
	            LEFT JOIN dbo.BAH_T_BD_LOCATION_L t1 ON t.FLOCID = t1.FID
	            LEFT JOIN dbo.BAH_T_WMS_OUTNOTICEENTRY_W t2 ON t.FENTRYID = t2.FENTRYID
	            LEFT JOIN dbo.BAH_T_BD_LOCATION t3 ON t.FLOCID = t3.FID
                LEFT JOIN dbo.BAH_T_BD_LOCBASE T30 ON T3.FID = T30.FID
	            LEFT JOIN dbo.BAH_T_BD_WAREHOUSE t4 on t0.FWHID = t4.FID
	            INNER JOIN dbo.BAH_T_BD_WAREHOUSE_L t5 on t4.FID = t5.FID
	            LEFT JOIN dbo.BAH_V_BD_OWNER t6 ON t0.FOWNERID = t6.FID
	            INNER JOIN dbo.BAH_V_BD_OWNER_L T7 ON T6.FID = T7.FID
	            LEFT JOIN dbo.BAH_V_BD_CONTACT T8 ON T0.FCONTACTID = T8.FID
	            INNER JOIN dbo.BAH_V_BD_CONTACT_L T9 ON T8.FID = T9.FID
                WHERE t0.FDOCUMENTSTATUS = 'C'
                AND T0.FWHID LIKE '%{0}%' AND T0.FOWNERID LIKE '%{1}%' AND T30.FAREAID LIKE '%{2}%' AND T2.FHasPickupMQty = 0
                group by t0.FBILLNO,T0.FMODIFYDATE,t4.FID,T4.FNUMBER,T5.FNAME,T6.FID,T6.FNUMBER,T7.FNAME,T8.FID,T8.FNUMBER,T9.FNAME,T8.fformid ,t0.FDIRECTION,t0.FCREATEDATE
                UNION ALL 
                SELECT CASE t0.FDIRECTION WHEN 'General' THEN '普通' ELSE '退回' END AS FDIRECTION, 
                 t0.FBILLNO,t0.FMODIFYDATE AS FMODIFYDATE,t0.FCREATEDATE AS FCREATEDATE,t4.FID as FWHID,T4.FNUMBER AS FWHNUMBER,T5.FNAME AS FWHNAME,
 T6.FID AS FOWNERID,T6.FNUMBER AS FOWNERNUMBER,T7.FNAME AS FOWNERNAME ,
 T8.FID AS FCONTACTID,T8.FNUMBER AS FCONTACTNUMBER,T9.FNAME AS FCONTACTNAME,T8.fformid AS FCONTACTFORMID,'部分拣货' AS FStatus, COUNT(t.FENTRYID) as COUNT
                FROM  dbo.BAH_T_WMS_OUTNOTICE t0
                LEFT JOIN dbo.BAH_T_WMS_OUTNOTICEENTRY t ON t0.FID = t.FID
	            LEFT JOIN dbo.BAH_T_BD_LOCATION_L t1 ON t.FLOCID = t1.FID
	            LEFT JOIN dbo.BAH_T_WMS_OUTNOTICEENTRY_W t2 ON t.FENTRYID = t2.FENTRYID
	            LEFT JOIN dbo.BAH_T_BD_LOCATION t3 ON t.FLOCID = t3.FID
                LEFT JOIN dbo.BAH_T_BD_LOCBASE T30 ON T3.FID = T30.FID
	            LEFT JOIN dbo.BAH_T_BD_WAREHOUSE t4 on t0.FWHID = t4.FID
	            INNER JOIN dbo.BAH_T_BD_WAREHOUSE_L t5 on t4.FID = t5.FID
	            LEFT JOIN dbo.BAH_V_BD_OWNER t6 ON t0.FOWNERID = t6.FID
	            INNER JOIN dbo.BAH_V_BD_OWNER_L T7 ON T6.FID = T7.FID
	            LEFT JOIN dbo.BAH_V_BD_CONTACT T8 ON T0.FCONTACTID = T8.FID
	            INNER JOIN dbo.BAH_V_BD_CONTACT_L T9 ON T8.FID = T9.FID
                WHERE  t0.FDOCUMENTSTATUS = 'C'
                AND T0.FWHID LIKE '%{0}%' AND T0.FOWNERID LIKE '%{1}%' AND T30.FAREAID LIKE '%{2}%' AND T2.FHasPickupMQty < t.FMQTY AND T2.FHasPickupMQty > 0
                group by t0.FBILLNO,T0.FMODIFYDATE,t4.FID,T4.FNUMBER,T5.FNAME,T6.FID,T6.FNUMBER,T7.FNAME,T8.FID,T8.FNUMBER,T9.FNAME,T8.fformid ,t0.FDIRECTION,t0.FCREATEDATE 
                order by FMODIFYDATE              


                   
                 ;", whid, ownerid, areaid); // or a.num is null

                string sqlSelect1 = string.Format(@"/*dialect*/
                                                    SELECT CASE t0.FDIRECTION WHEN 'General' THEN '普通' ELSE '退回' END AS FDIRECTION, 
 t0.FBILLNO,t0.FMODIFYDATE AS FMODIFYDATE,t0.FCREATEDATE AS FCREATEDATE,t4.FID as FWHID,T4.FNUMBER AS FWHNUMBER,T5.FNAME AS FWHNAME,
 T6.FID AS FOWNERID,T6.FNUMBER AS FOWNERNUMBER,T7.FNAME AS FOWNERNAME ,
 T8.FID AS FCONTACTID,T8.FNUMBER AS FCONTACTNUMBER,T9.FNAME AS FCONTACTNAME,T8.fformid AS FCONTACTFORMID,'未拣货' AS FStatus, COUNT(t.FENTRYID) as COUNT
                FROM  dbo.BAH_T_WMS_OUTNOTICE t0
                LEFT JOIN dbo.BAH_T_WMS_OUTNOTICEENTRY t ON t0.FID = t.FID
	            LEFT JOIN dbo.BAH_T_BD_LOCATION_L t1 ON t.FLOCID = t1.FID
	            LEFT JOIN dbo.BAH_T_WMS_OUTNOTICEENTRY_W t2 ON t.FENTRYID = t2.FENTRYID
	            LEFT JOIN dbo.BAH_T_BD_LOCATION t3 ON t.FLOCID = t3.FID
                LEFT JOIN dbo.BAH_T_BD_LOCBASE T30 ON T3.FID = T30.FID
	            LEFT JOIN dbo.BAH_T_BD_WAREHOUSE t4 on t0.FWHID = t4.FID
	            INNER JOIN dbo.BAH_T_BD_WAREHOUSE_L t5 on t4.FID = t5.FID
	            LEFT JOIN dbo.BAH_V_BD_OWNER t6 ON t0.FOWNERID = t6.FID
	            INNER JOIN dbo.BAH_V_BD_OWNER_L T7 ON T6.FID = T7.FID
	            LEFT JOIN dbo.BAH_V_BD_CONTACT T8 ON T0.FCONTACTID = T8.FID
	            INNER JOIN dbo.BAH_V_BD_CONTACT_L T9 ON T8.FID = T9.FID
                WHERE t0.FDOCUMENTSTATUS = 'C'
                AND T0.FWHID LIKE '%{0}%' AND T0.FOWNERID LIKE '%{1}%' AND T2.FHasPickupMQty = 0
                group by t0.FBILLNO,T0.FMODIFYDATE,t4.FID,T4.FNUMBER,T5.FNAME,T6.FID,T6.FNUMBER,T7.FNAME,T8.FID,T8.FNUMBER,T9.FNAME,T8.fformid ,t0.FDIRECTION,t0.FCREATEDATE
                UNION ALL 
                SELECT CASE t0.FDIRECTION WHEN 'General' THEN '普通' ELSE '退回' END AS FDIRECTION, 
                 t0.FBILLNO,t0.FMODIFYDATE AS FMODIFYDATE,t0.FCREATEDATE AS FCREATEDATE,t4.FID as FWHID,T4.FNUMBER AS FWHNUMBER,T5.FNAME AS FWHNAME,
 T6.FID AS FOWNERID,T6.FNUMBER AS FOWNERNUMBER,T7.FNAME AS FOWNERNAME ,
 T8.FID AS FCONTACTID,T8.FNUMBER AS FCONTACTNUMBER,T9.FNAME AS FCONTACTNAME,T8.fformid AS FCONTACTFORMID,'部分拣货' AS FStatus, COUNT(t.FENTRYID) as COUNT
                FROM  dbo.BAH_T_WMS_OUTNOTICE t0
                LEFT JOIN dbo.BAH_T_WMS_OUTNOTICEENTRY t ON t0.FID = t.FID
	            LEFT JOIN dbo.BAH_T_BD_LOCATION_L t1 ON t.FLOCID = t1.FID
	            LEFT JOIN dbo.BAH_T_WMS_OUTNOTICEENTRY_W t2 ON t.FENTRYID = t2.FENTRYID
	            LEFT JOIN dbo.BAH_T_BD_LOCATION t3 ON t.FLOCID = t3.FID
                LEFT JOIN dbo.BAH_T_BD_LOCBASE T30 ON T3.FID = T30.FID
	            LEFT JOIN dbo.BAH_T_BD_WAREHOUSE t4 on t0.FWHID = t4.FID
	            INNER JOIN dbo.BAH_T_BD_WAREHOUSE_L t5 on t4.FID = t5.FID
	            LEFT JOIN dbo.BAH_V_BD_OWNER t6 ON t0.FOWNERID = t6.FID
	            INNER JOIN dbo.BAH_V_BD_OWNER_L T7 ON T6.FID = T7.FID
	            LEFT JOIN dbo.BAH_V_BD_CONTACT T8 ON T0.FCONTACTID = T8.FID
	            INNER JOIN dbo.BAH_V_BD_CONTACT_L T9 ON T8.FID = T9.FID
                WHERE  t0.FDOCUMENTSTATUS = 'C'
                AND T0.FWHID LIKE '%{0}%' AND T0.FOWNERID LIKE '%{1}%' AND  T2.FHasPickupMQty < t.FMQTY AND T2.FHasPickupMQty > 0
                group by t0.FBILLNO,T0.FMODIFYDATE,t4.FID,T4.FNUMBER,T5.FNAME,T6.FID,T6.FNUMBER,T7.FNAME,T8.FID,T8.FNUMBER,T9.FNAME,T8.fformid ,t0.FDIRECTION,t0.FCREATEDATE 
                order by FMODIFYDATE              


                   
                 ;", whid, ownerid);         // or a.num is null

                if (areaid == "")
                {
                    dataObjectCollection = DBUtils.ExecuteDynamicObject(ctx, sqlSelect1, null, null);
                }
                else
                {
                    dataObjectCollection = DBUtils.ExecuteDynamicObject(ctx, sqlSelect, null, null);
                }

                if (dataObjectCollection.Count == 0)
                {
                    result.Code    = (int)ResultCode.Fail;
                    result.Message = "未检索到对应信息!";
                }
                else
                {
                    foreach (DynamicObject dataObject in dataObjectCollection)
                    {
                        JSONObject data = new JSONObject();



                        data.Add("FBillNo", dataObject["FBILLNO"]);
                        data.Add("FDIRECTION", dataObject["FDIRECTION"]);
                        data.Add("FMODIFYDATE", Convert.ToDateTime(dataObject["FMODIFYDATE"].ToString()).ToString("yyyy-MM-dd HH:mm:ss:fff"));
                        data.Add("FDate", Convert.ToDateTime(dataObject["FCREATEDATE"].ToString()).ToString("yyyy-MM-dd HH:mm:ss:fff"));
                        //表头仓库信息
                        data.Add("FBatchWHId", dataObject["FWHID"]);
                        data.Add("FBatchWHNumber", dataObject["FWHNUMBER"]);
                        data.Add("FBatchWHName", dataObject["FWHNAME"]);
                        //表头货主信息
                        data.Add("FBatchOwnerId", dataObject["FOWNERID"]);
                        data.Add("FBatchOwnerNumber", dataObject["FOWNERNUMBER"]);
                        data.Add("FBatchOwnerName", dataObject["FOWNERNAME"]);
                        //表头客户信息
                        data.Add("FContactId", dataObject["FCONTACTID"]);
                        data.Add("FContactNumber", dataObject["FCONTACTNUMBER"]);
                        data.Add("FContactName", dataObject["FCONTACTNAME"]);
                        data.Add("FContactFormName", dataObject["FCONTACTFORMID"]);
                        data.Add("FStatus", dataObject["FStatus"]);
                        data.Add("FCOUNT", dataObject["COUNT"]);

                        return_data.Add(data);
                    }
                }

                //返回数据
                result.Code    = (int)ResultCode.Success;
                result.Data    = return_data;
                result.Message = "成功返回数据!";
            }
            catch (Exception ex)
            {
                result.Code    = (int)ResultCode.Fail;
                result.Message = ex.Message;
            }
            return(result);
        }
Example #58
0
        private IEnumerator SetUpgrades()
        {
            JSONObject json = new JSONObject();

            json.Add("name", _master.GetComponent <MasterCounter>().getName());

            JSONArray arr = new JSONArray();

            if (_master.GetComponent <DamagePower>())
            {
                JSONObject damage = new JSONObject();
                damage.Add("name", "damage");
                damage.Add("level", _master.GetComponent <DamagePower>().getLevel());

                arr.Add(damage);
            }

            if (_master.GetComponent <MoneyPower>())
            {
                JSONObject money = new JSONObject();
                money.Add("name", "money");
                money.Add("level", _master.GetComponent <MoneyPower>().getLevel());

                arr.Add(money);
            }

            if (_master.GetComponent <SlimePower>())
            {
                JSONObject slime = new JSONObject();
                slime.Add("name", "slime");
                slime.Add("level", _master.GetComponent <SlimePower>().getLevel());

                arr.Add(slime);
            }

            if (_master.GetComponent <ShieldPower>())
            {
                JSONObject shield = new JSONObject();
                shield.Add("name", "shield");
                shield.Add("level", _master.GetComponent <ShieldPower>().getLevel());

                arr.Add(shield);
            }

            json.Add("upgrades", arr);

            Debug.Log(json.ToString());
            byte[] bytes = Encoding.ASCII.GetBytes(json.ToString());

            UnityWebRequest request = UnityWebRequest.Post(link + "/player", UnityWebRequest.kHttpVerbPOST);

            UploadHandlerRaw uH = new UploadHandlerRaw(bytes);

            request.uploadHandler = uH;

            request.SetRequestHeader("Authorization", _master.GetComponent <MasterCounter>().getToken());
            request.SetRequestHeader("Content-Type", "application/json");

            yield return(request.SendWebRequest());

            if (request.isNetworkError)
            {
                Debug.Log(request.error);
            }
            else
            {
                Debug.Log(request.downloadHandler.text);
            }
        }
        void SendTelemetry()
        {
            if (client == null)
            {
                return;
            }

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

            json.AddField("msg_type", "telemetry");

            json.AddField("steering_angle", car.GetSteering() / steer_to_angle);
            json.AddField("throttle", car.GetThrottle());
            json.AddField("speed", car.GetVelocity().magnitude);
            json.AddField("image", Convert.ToBase64String(camSensor.GetImageBytes()));

            if (camSensorB != null && camSensorB.gameObject.activeInHierarchy)
            {
                json.AddField("imageb", Convert.ToBase64String(camSensorB.GetImageBytes()));
            }

            if (lidar != null && lidar.gameObject.activeInHierarchy)
            {
                json.AddField("lidar", lidar.GetOutputAsJson());
            }

            if (odom.Length > 0)
            {
                JSONObject odom_arr = JSONObject.Create();

                foreach (Odometry o in odom)
                {
                    odom_arr.Add(o.GetOutputAsJson());
                }

                json.AddField("odom", odom_arr);
            }

            json.AddField("hit", car.GetLastCollision());
            car.ClearLastCollision();
            json.AddField("time", Time.timeSinceLevelLoad);

            Vector3 accel = car.GetAccel();

            json.AddField("accel_x", accel.x);
            json.AddField("accel_y", accel.y);
            json.AddField("accel_z", accel.z);

            Quaternion gyro = car.GetGyro();

            json.AddField("gyro_x", gyro.x);
            json.AddField("gyro_y", gyro.y);
            json.AddField("gyro_z", gyro.z);
            json.AddField("gyro_w", gyro.w);


            // not intended to use in races, just to train
            if (extendedTelemetry)
            {
                Transform tm = car.GetTransform();
                json.AddField("pos_x", tm.position.x);
                json.AddField("pos_y", tm.position.y);
                json.AddField("pos_z", tm.position.z);

                Vector3 velocity = car.GetVelocity();
                json.AddField("vel_x", velocity.x);
                json.AddField("vel_y", velocity.y);
                json.AddField("vel_z", velocity.z);

                if (pm != null)
                {
                    float cte = 0.0f;
                    if (pm.path.GetCrossTrackErr(tm.position, ref cte))
                    {
                        json.AddField("cte", cte);
                    }
                    else
                    {
                        pm.path.ResetActiveSpan();
                        json.AddField("cte", 0.0f);
                    }
                    json.AddField("activeNode", pm.path.iActiveSpan);
                    json.AddField("totalNodes", pm.path.nodes.Count);
                }


                if (pm.path.nodes.Count > 10)
                {
                    NavMeshHit hit       = new NavMeshHit();
                    Vector3    position  = carObj.transform.position;
                    bool       onNavMesh = NavMesh.SamplePosition(position, out hit, 5, NavMesh.AllAreas);
                    json.AddField("on_road", onNavMesh ? 1 : 0);
                    if (onNavMesh)
                    {
                        Vector3 target               = pm.path.nodes[(pm.path.iActiveSpan + pm.path.nodes.Count + pm.path.nodes.Count / 3) % (pm.path.nodes.Count)].pos;
                        double  currentDistance      = pm.path.getDistance(position, target);
                        double  distanceToLastTarget = pm.path.getDistance(position, this.lastTarget);
                        if (this.lastTarget.x == 0 || Math.Abs(currentDistance) < 0.001 || Math.Abs(distanceToLastTarget) < 0.001 || Math.Abs(this.lastDistance) < 0.001)
                        {
                            this.lastDistance = currentDistance;
                        }
                        json.AddField("progress_on_shortest_path", (float)(this.lastDistance - distanceToLastTarget));
                        this.lastDistance = currentDistance;
                        this.lastTarget   = target;
                    }
                    else
                    {
                        this.lastTarget   = new Vector3(0, 0, 0);
                        this.lastDistance = 0.0;
                        json.AddField("progress_on_shortest_path", 0.0f);
                    }
                }
            }
            client.SendMsg(json);
        }
Example #60
0
 protected override void DumpExtraDataToJson(ref JSONObject jsonEventType)
 {
     base.DumpExtraDataToJson(ref jsonEventType);
     jsonEventType.Add("DamageValue", this.damage);
 }