示例#1
0
    public void SetResults(JSONObject jsonData)
    {
        spinDataResult = jsonData;
        resultsData    = jsonData.GetArray("items");
        winningGold    = jsonData.GetArray("wGold");
        // Calculate extra data (winning type, winning count from list result items)
        JSONObject extraData = SlotCombination.CalculateCombination(resultsData, GetNumLine());

        winningCount = extraData.GetArray("wCount");
        winningType  = extraData.GetArray("wType");
        //
        isJackpot    = jsonData.GetBoolean("isJP");
        freeSpinLeft = jsonData.GetInt("frLeft");
        isBigWin     = jsonData.GetBoolean("bWin");
        gotFreeSpin  = jsonData.GetInt("frCount") > 0;
        // bool[] winingItems = new bool[15];
        // for (int i = 0; i < winningGold.Length; i++) {
        //  if (winningGold[i].Number > 0) {
        //      for (int j = 0; j < SlotCombination.NUM_REELS; j++) {
        //          winingItems[SlotCombination.COMBINATION[i, j]] = true;
        //      }
        //  }
        // }
        for (int i = 0; i < slotReels.Length; i++)
        {
            slotReels[i].SetResults(new int[3] {
                (int)resultsData[i * 3].Number, (int)resultsData[i * 3 + 1].Number, (int)resultsData[i * 3 + 2].Number
            });
        }
    }
示例#2
0
 public void UpdateStructure(JSONArray tileDetails)
 {
     foreach (JSONValue j in tileDetails)
     {
         JSONObject tileJSON = j.Obj;
         Tile       tile     = tiles.Find(t => t.name == tileJSON.GetString("Name"));
         if (tile == null)
         {
             //Debug.Log("Tile is null");
             if (!tileJSON.GetBoolean("Destroyed"))
             {
                 tile = CreateTile(tileJSON);
                 tiles.Add(tile);
                 tile.FromJSON(tileJSON);
                 //Debug.Log("Creating" + tile.name);
             }
         }
         else if (tileJSON.GetBoolean("Destroyed"))
         {
             //Debug.Log("Destroying" + tile.name);
             tile.Destroy(false, false);
         }
         else
         {
             tile.FromJSON(tileJSON);
             //Debug.Log("Updating" + tile.name);
         }
     }
 }
示例#3
0
 public override void Deserialize(JSONObject obj)
 {
     Ranks              = (int)obj.GetNumber(cRanks);
     MiscModifier       = (int)obj.GetNumber(cModifier);
     CanBeUsedUntrained = obj.GetBoolean(cUntrained);
     ClassSkill         = obj.GetBoolean(cClassSkill);
     KeyAbility         = (DnDAbilities)(int)obj.GetNumber(cAbility);
 }
		public override void Deserialize(JSONObject obj)
		{
			Ranks = (int)obj.GetNumber(cRanks);
			MiscModifier = (int)obj.GetNumber(cModifier);
			CanBeUsedUntrained = obj.GetBoolean(cUntrained);
			ClassSkill = obj.GetBoolean(cClassSkill);
			KeyAbility = (DnDAbilities)(int)obj.GetNumber(cAbility);

		}
示例#5
0
    public bool SetServerConfig(ParseObject serverconfig)
    {
        if (serverconfig != null)
        {
            JSONObject jsonObject = JSONObject.Parse(serverconfig.RawJson);
            Debug.LogError("Setting to server config: " + jsonObject.GetString("name"));

            serverName               = jsonObject.GetString("ip");
            serverPort               = int.Parse(jsonObject.GetString("port"));
            zone                     = jsonObject.GetString("defaultZone");
            username                 = jsonObject.GetString("defaultGuestName");
            defaultLevel             = jsonObject.GetString("defaultLevel");
            bizsimType               = jsonObject.GetString("bizsimType");
            buildType                = jsonObject.GetString("buildType");
            guihtmlUrl               = jsonObject.GetString("guihtmlUrl");
            patchFileUrl             = jsonObject.GetString("patchFileUrl");
            patchFileVersion         = (int)jsonObject.GetNumber("patchFileVersion");
            clientVersionRequirement = jsonObject.GetString("clientVersionRequirement");
            voiceMinFreq             = jsonObject.GetString("voiceMinFreq");
            voiceDefault             = jsonObject.GetString("voiceDefault");
            shareTeams               = jsonObject.GetString("shareTeams");
            uploadUrl                = jsonObject.GetString("uploadUrl");
            nativeGUILevel           = (int)jsonObject.GetNumber("nativeGUI");
            redirectVideo            = jsonObject.GetBoolean("redirectVideo");
            teamRmLockdown           = jsonObject.GetBoolean("teamRmLockdown");
            parseScreens             = StringToIntList(jsonObject.GetString("parseScreens"));
        }

        // Level info may change based on new server config
        LevelInfo.Reset();

        // set build type from server config
        try{
            GameManager.buildType = (GameManager.BuildType)Enum.Parse(typeof(GameManager.BuildType), buildType, true);
        }
        catch (Exception) { Debug.LogError("Bad buildType: " + buildType); }

        if (GameGUI.Inst.guiLayer)
        {
            GameGUI.Inst.guiLayer.SetBuildType();
        }

        BizSimManager.SetPlayMode(CommunicationManager.bizsimType);
        GameManager.Inst.voiceToggleInitSetting = (voiceDefault == "on" || voiceDefault == "1" || voiceDefault == "true" || voiceDefault == "t");
        if (GameGUI.Inst.guiLayer != null && GameGUI.Inst.guiLayer.URL != guihtmlUrl && GameGUI.Inst.guiLayer.URL != "")
        {
            string errorMsg = "Compiled ServerConfig guilayer URL is different than user defined ServerConfig, this isn't supported at the moment. \n" + GameGUI.Inst.guiLayer.URL + " != " + guihtmlUrl;
            GameGUI.Inst.WriteToConsoleLog(errorMsg);
            Debug.LogError(errorMsg);
            GameGUI.Inst.guiLayer.ReloadLayer(true); // pulls url from CommunicationManager.guihtmlUrl
        }
        CommunicationManager.CurrentUserProfile.CheckLogin();
        return(serverconfig != null);
    }
示例#6
0
    public void UpdateReady(string isReadyJSON)
    {
        JSONObject isReady = JSONObject.Parse(isReadyJSON);

        if (ready.ContainsKey(isReady.GetString("userName")))
        {
            ready[isReady.GetString("userName")] = isReady.GetBoolean("isReady");
        }
        else
        {
            //Networker.Instance.players.Add(isReady.GetString("userName"));
            ready.Add(isReady.GetString("userName"), isReady.GetBoolean("isReady"));
        }
    }
 public void Deserialize(JSONObject j)
 {
     this.sfxVolume   = (float)j.GetNumber("sfxVolume");
     this.musicVolume = (float)j.GetNumber("musicVolume");
     this.ccEnabled   = j.GetBoolean("ccEnabled");
     this.language    = j.GetString("language");
 }
    public DrawQueueItem(string json)
    {
        JSONObject item = JSONObject.Parse(json);

        position = Vector3Utils.StringToVector3(item.GetString("position"));
        start    = item.GetBoolean("start");
        end      = item.GetBoolean("end");
        velocity = Vector3Utils.StringToVector3(item.GetString("velocity"));

        if (string.IsNullOrEmpty(item.GetString("character")) == false)
        {
            character = item.GetString("character");
        }

        touched = item.GetBoolean("touched");
    }
示例#9
0
  public void SetResults(JSONObject jsonData) {
		spinDataResult = jsonData;
    resultsData = jsonData.GetArray("items");
    winningGold = jsonData.GetArray("wGold");
		// Calculate extra data (winning type, winning count from list result items)
		JSONObject extraData = SlotCombination.CalculateCombination(resultsData, GetNumLine());
    winningCount = extraData.GetArray("wCount");
    winningType = extraData.GetArray("wType");
		//
    isJackpot = jsonData.GetBoolean("isJP");
		freeSpinLeft = jsonData.GetInt("frLeft");
		isBigWin = jsonData.GetBoolean("bWin");
		gotFreeSpin = jsonData.GetInt("frCount") > 0;
		// bool[] winingItems = new bool[15];
		// for (int i = 0; i < winningGold.Length; i++) {
		// 	if (winningGold[i].Number > 0) {
		// 		for (int j = 0; j < SlotCombination.NUM_REELS; j++) {
		// 			winingItems[SlotCombination.COMBINATION[i, j]] = true;
		// 		}
		// 	}
		// }
    for (int i = 0; i < slotReels.Length; i++) {
      slotReels[i].SetResults(new int[3] { (int)resultsData[i * 3].Number, (int)resultsData[i * 3 + 1].Number, (int)resultsData[i * 3 + 2].Number });
    }
  }
示例#10
0
        /// <summary>
        /// Gets the json, the ID and the type to return.
        /// </summary>
        /// <returns>The object from json with identifier.</returns>
        /// <param name="json">Json.</param>
        /// <param name="id">Identifier.</param>
        /// <param name="type">Type.</param>
        public static object GetObjectFromJsonWithId(string json, string id, ObjectType type = ObjectType.None)
        {
            if (string.IsNullOrEmpty(json) == true || string.IsNullOrEmpty(id))
            {
                throw new System.Exception("Missing values for json or id");
            }
            // Create a JSON Object from the json
            JSONObject obj = JSONObject.Parse(json);

            // If null, non valid json
            if (obj == null)
            {
                return(null);
            }
            // Split the id parameter from slashes
            string[]   splits = id.Split(new char[] { '/' });
            JSONObject temp   = obj;

            // the loop will iterate deeper in the json
            // Each iteration is one level
            // first_id/second_id/third_id
            // this will run three round (if all previous are found)
            for (int i = 0; i < splits.Length; i++)
            {
                // this the last run, so the deepest level required
                if (i == splits.Length - 1)
                {
                    string str = splits[i];
                    // Get the type to be returned
                    // This is due to the used plugin for parsing json
                    switch (type)
                    {
                    case ObjectType.None:
                        return(temp.GetValue(str));

                    case ObjectType.Boolean:
                        return(temp.GetBoolean(str));

                    case ObjectType.Number:
                        return(temp.GetNumber(str));

                    case ObjectType.String:
                        return(temp.GetString(str));

                    case ObjectType.Object:
                        return(temp.GetObject(str));
                    }
                }
                // Get the current level object
                temp = temp.GetObject(splits[i]);
                // if null, it was not found in the file
                if (temp == null)
                {
                    break;
                }
            }
            // Something went wrong
            return(null);
        }
示例#11
0
 public void FromJson(JSONObject json)
 {
     Title           = json.GetString("title");
     Url             = json.GetString("url");
     Type            = json.GetString("type");
     Enabled         = json.GetBoolean("enabled");
     VoiceCommand    = json.GetString("voiceCommand");
     UseTransparency = json.GetBoolean("useTransparency");
     Height          = json.GetFloat("height");
     Group           = json.GetString("group");
     IconUrl         = json.GetString("iconUrl");
     Scale           = json.GetInt("scale", 30);
     if (json.HasField("refresh"))
     {
         Refresh = json.GetInt("refresh");
     }
 }
示例#12
0
 public void FromJson(JSONObject json)
 {
     Title           = json.GetString("Title");
     Url             = json.GetString("Url");
     Type            = json.GetString("Type");
     Enabled         = json.GetBoolean("Enabled");
     VoiceCommand    = json.GetString("VoiceCommand");
     UseTransparency = json.GetBoolean("UseTransparency");
     Height          = json.GetFloat("Height");
     Group           = json.GetString("Group");
     IconUrl         = json.GetString("IconUrl");
     Scale           = json.GetInt("Scale", 30);
     if (json.HasField("Refresh"))
     {
         Refresh = json.GetInt("Refresh");
     }
 }
示例#13
0
    public void InitializePlayers(string jsonPlayers)
    {
        JSONArray players = JSONArray.Parse(jsonPlayers);

        for (int i = 0; i < players.Length; i++)
        {
            JSONObject player = players[i].Obj;
            ready.Add(player.GetString("userName"), player.GetBoolean("isReady"));
            //Networker.Instance.players.Add(player.GetString("userName"));
        }
    }
示例#14
0
        public ObjectDefinition(JSONValue record)
        {
            JSONObject recordObject = record.Obj;

            id                = recordObject.GetString("Id");
            name              = recordObject.GetString("Name");
            prefabPath        = recordObject.GetString("Prefab_path__c");
            category          = recordObject.GetString("Category__c");
            isClimateSpecific = recordObject.GetBoolean("Climate_Specific__c");
            modelVariations   = (int)recordObject.GetNumber("Model_Variations__c");
        }
示例#15
0
        private void SysIntegrity()
        {
            byte[] nonce = new byte[24];
            string appid = AGConnectServicesConfig.FromContext(Activity).GetString("client/app_id");

            SafetyDetect.GetClient(Activity).SysIntegrity(nonce, appid).AddOnSuccessListener(new OnSuccessListener((Result) =>
            {
                SysIntegrityResp response = (SysIntegrityResp)Result;
                string jwStr         = response.Result;
                string[] jwsSplit    = jwStr.Split(".");
                string jwsPayloadStr = jwsSplit[1];
                byte[] data          = Convert.FromBase64String(jwsPayloadStr);
                string jsonString    = Encoding.UTF8.GetString(data);
                JSONObject jObject   = new JSONObject(jsonString);
                Log.Info("SysIntegrity", jsonString.Replace(",", ",\n"));

                string basicIntegrityText = null;
                try
                {
                    bool basicIntegrity = jObject.GetBoolean("basicIntegrity");
                    if (basicIntegrity)
                    {
                        theButton.SetBackgroundResource(Resource.Drawable.btn_round_green);
                        basicIntegrityText = "Basic Integrity is Success.";
                    }
                    else
                    {
                        theButton.SetBackgroundResource(Resource.Drawable.btn_round_red);
                        basicIntegrityText  = "Basic Integrity is Failure.";
                        adviceTextView.Text = $"Advice: {jObject.GetString("advice")}";
                    }
                }
                catch (JSONException e)
                {
                    Android.Util.Log.Error("SysIntegrity", e.Message);
                }
                basicIntegrityTextView.Text = basicIntegrityText;
                theButton.SetText(Resource.String.rerun);
            })).AddOnFailureListener(new OnFailureListener((Result) =>
            {
                string errorMessage = null;
                if (Result is ApiException exception)
                {
                    errorMessage = $"{SafetyDetectStatusCodes.GetStatusCodeString(exception.StatusCode)}: {exception.Message}";
                }
                else
                {
                    errorMessage = ((Java.Lang.Exception)Result).Message;
                }
                Log.Error("SysIntegrity", errorMessage);
                theButton.SetBackgroundResource(Resource.Drawable.btn_round_yellow);
            }));
        }
示例#16
0
        /// <summary>
        /// Default ctor
        /// </summary>
        internal AirportStatus(JSONObject source)
        {
            Delay    = source.GetBoolean("delay");
            IataCode = source.GetString("IATA");
            State    = source.GetString("state");
            City     = source.GetString("city");
            Name     = source.GetString("name");

            var weather = source.GetJSONObject("weather");

            Temperature = weather.GetString("temp");
            Wind        = weather.GetString("wind");
        }
示例#17
0
        public override IEnumerator SendRequest(string controller, HttpMethodType t, Dictionary <string, object> p)
        {
            string url = String.Concat(SpeedClickHelpers.GetApiURL(), controller);
            WWW    www = null;

            if (p != null)
            {
                if (t == HttpMethodType.Post)
                {
                    WWWForm form = new WWWForm();
                    foreach (KeyValuePair <string, object> pair in p)
                    {
                        form.AddField(pair.Key, pair.Value.ToString());
                    }
                    www = new WWW(url, form);
                }
                else if (t == HttpMethodType.Get)
                {
                    url += "?";
                    url += SpeedClickHelpers.BuildURLParam(p);
                }
            }
            if (www == null)
            {
                www = new WWW(url);
            }
            yield return(www);

            this.response = new ResponseData();
            if (!String.IsNullOrEmpty(www.error))
            {
                this.response.Message = www.text;
                yield break;
            }
            if (www.size <= 2)
            {
                yield break;
            }
            else
            {
                JSONObject json = JSONObject.Parse(www.text);
                this.response.Data      = json.GetValue("Data");
                this.response.DataType  = this.response.Data.Type;
                this.response.DataArray = json.GetArray("Data");
                this.response.Message   = json.GetString("Message");
                this.response.Success   = json.GetBoolean("Success");
            }
            www.Dispose();
        }
示例#18
0
 public bool IsExistFinMissionOfStudent(string data)
 {
     try
     {
         JSONObject jsonObject = JSONObject.Parse(data);
         JSONObject obj        = jsonObject.GetObject("response");
         bool       exist      = obj.GetBoolean("Exist");
         return(exist);
     }
     catch (Exception e)
     {
         Debug.Log(e.ToString());
         return(false);
     }
 }
示例#19
0
	public void Init(JSONObject jsonData) {
		userId = jsonData.GetString("userId");
		seatIndex = jsonData.GetInt("seatIndex");
		isHost = jsonData.GetBoolean("isHost");
		state = (State)jsonData.GetInt("state");
		hand = new TLMBHand();

		if (SmartfoxClient.Instance.IsYou(userId)) {
			AddCards(jsonData.GetString("cards"));
		} else {
			int numCards = jsonData.GetInt("numCards");

			for (int i = 0; i < numCards; i++) {
				hand.AddCard(new TLMBCard(-1));
			}
		}
	}
示例#20
0
        public ObjectInstance(JSONValue record)
        {
            JSONObject recordObject = record.Obj;

            id = recordObject.GetString("Id");
            float x = (float)recordObject.GetNumber("x__c");
            float y = (float)recordObject.GetNumber("y__c");
            float z = (float)recordObject.GetNumber("z__c");

            position = new Vector3(x, y, z);
            yAngle   = (int)recordObject.GetNumber("y_Angle__c");
            isPlaced = recordObject.GetBoolean("Is_Placed__c");

            // Get configuration id
            if (recordObject.ContainsKey("Configuration__c"))
            {
                configurationId = recordObject.GetString("Configuration__c");
            }
            else
            {
                JSONObject configurationObject = recordObject.GetObject("Configuration__r");
                configurationId = configurationObject.GetValue("Id").Str;
            }
            // Get object definition id
            string definitionId;

            if (recordObject.ContainsKey("Object_Definition__c"))
            {
                definitionId = recordObject.GetString("Object_Definition__c");
            }
            else
            {
                JSONObject definitionObject = recordObject.GetObject("Object_Definition__r");
                definitionId = definitionObject.GetValue("Id").Str;
            }
            // Load object definition from cache
            definition = CacheManager.getObjectDefinitions().get(definitionId);
            if (definition == null)
            {
                throw new System.Exception("Could not find definition " + definitionId + " of object instance " + id + " in cache");
            }
        }
示例#21
0
    public void Init(JSONObject jsonData)
    {
        userId    = jsonData.GetString("userId");
        seatIndex = jsonData.GetInt("seatIndex");
        isHost    = jsonData.GetBoolean("isHost");
        state     = (State)jsonData.GetInt("state");
        hand      = new TLMBHand();

        if (SmartfoxClient.Instance.IsYou(userId))
        {
            AddCards(jsonData.GetString("cards"));
        }
        else
        {
            int numCards = jsonData.GetInt("numCards");

            for (int i = 0; i < numCards; i++)
            {
                hand.AddCard(new TLMBCard(-1));
            }
        }
    }
示例#22
0
        public virtual void ParseObject(JSONValue json)
        {
            JSONObject jsonObj           = json.Obj;
            IEnumerable <FieldInfo> info = this.GetType().GetFields();

            foreach (FieldInfo field in info)
            {
                if (jsonObj.ContainsKey(field.Name))
                {
                    TypeCode code = Type.GetTypeCode(field.FieldType);
                    switch (code)
                    {
                    case TypeCode.Int16: field.SetValue(this, Convert.ToInt16(jsonObj.GetNumber(field.Name))); break;

                    case TypeCode.Int32: field.SetValue(this, Convert.ToInt32(jsonObj.GetNumber(field.Name))); break;

                    case TypeCode.Int64: field.SetValue(this, Convert.ToInt64(jsonObj.GetNumber(field.Name))); break;

                    case TypeCode.Single: field.SetValue(this, Convert.ToSingle(jsonObj.GetNumber(field.Name))); break;

                    case TypeCode.Double: field.SetValue(this, jsonObj.GetNumber(field.Name)); break;

                    case TypeCode.Decimal: field.SetValue(this, Convert.ToDecimal(jsonObj.GetNumber(field.Name))); break;

                    case TypeCode.Boolean: field.SetValue(this, jsonObj.GetBoolean(field.Name)); break;

                    case TypeCode.DateTime: field.SetValue(this, Convert.ToDateTime(jsonObj.GetNumber(field.Name))); break;

                    case TypeCode.String: field.SetValue(this, jsonObj.GetString(field.Name)); break;

                    case TypeCode.Object: break;

                    default: field.SetValue(this, Convert.ChangeType(jsonObj.GetString(field.Name), field.FieldType)); break;
                    }
                }
            }
            this.ParseObjectField(jsonObj);
            this.DefineGameObjectName();
        }
示例#23
0
        /// <exception cref="Org.Codehaus.Jettison.Json.JSONException"/>
        public static void VerifyHsJob(JSONObject info, Org.Apache.Hadoop.Mapreduce.V2.App.Job.Job
                                       job)
        {
            NUnit.Framework.Assert.AreEqual("incorrect number of elements", 25, info.Length()
                                            );
            // everyone access fields
            VerifyHsJobGeneric(job, info.GetString("id"), info.GetString("user"), info.GetString
                                   ("name"), info.GetString("state"), info.GetString("queue"), info.GetLong("startTime"
                                                                                                            ), info.GetLong("finishTime"), info.GetInt("mapsTotal"), info.GetInt("mapsCompleted"
                                                                                                                                                                                 ), info.GetInt("reducesTotal"), info.GetInt("reducesCompleted"));
            string diagnostics = string.Empty;

            if (info.Has("diagnostics"))
            {
                diagnostics = info.GetString("diagnostics");
            }
            // restricted access fields - if security and acls set
            VerifyHsJobGenericSecure(job, info.GetBoolean("uberized"), diagnostics, info.GetLong
                                         ("avgMapTime"), info.GetLong("avgReduceTime"), info.GetLong("avgShuffleTime"), info
                                     .GetLong("avgMergeTime"), info.GetInt("failedReduceAttempts"), info.GetInt("killedReduceAttempts"
                                                                                                                ), info.GetInt("successfulReduceAttempts"), info.GetInt("failedMapAttempts"), info
                                     .GetInt("killedMapAttempts"), info.GetInt("successfulMapAttempts"));
        }
示例#24
0
        protected override IEnumerable <Datum> Poll(CancellationToken cancellationToken)
        {
            List <Datum> data = new List <Datum>();

            if (HasValidAccessToken)
            {
                string[] missingPermissions = GetRequiredPermissionNames().Where(p => !AccessToken.CurrentAccessToken.Permissions.Contains(p)).ToArray();
                if (missingPermissions.Length > 0)
                {
                    ObtainAccessToken(missingPermissions);
                }
            }
            else
            {
                ObtainAccessToken(GetRequiredPermissionNames());
            }

            if (HasValidAccessToken)
            {
                GraphRequestBatch graphRequestBatch = new GraphRequestBatch();

                foreach (Tuple <string, List <string> > edgeFieldQuery in GetEdgeFieldQueries())
                {
                    Bundle parameters = new Bundle();

                    if (edgeFieldQuery.Item2.Count > 0)
                    {
                        parameters.PutString("fields", string.Concat(edgeFieldQuery.Item2.Select(field => field + ",")).Trim(','));
                    }

                    GraphRequest request = new GraphRequest(
                        AccessToken.CurrentAccessToken,
                        "/me" + (edgeFieldQuery.Item1 == null ? "" : "/" + edgeFieldQuery.Item1),
                        parameters,
                        HttpMethod.Get);

                    graphRequestBatch.Add(request);
                }

                if (graphRequestBatch.Size() == 0)
                {
                    throw new Exception("User has not granted any Facebook permissions.");
                }
                else
                {
                    foreach (GraphResponse response in graphRequestBatch.ExecuteAndWait())
                    {
                        if (response.Error == null)
                        {
                            FacebookDatum datum = new FacebookDatum(DateTimeOffset.UtcNow);

                            JSONObject responseJSON = response.JSONObject;
                            JSONArray  jsonFields   = responseJSON.Names();
                            bool       valuesSet    = false;
                            for (int i = 0; i < jsonFields.Length(); ++i)
                            {
                                string jsonField = jsonFields.GetString(i);

                                PropertyInfo property;
                                if (FacebookDatum.TryGetProperty(jsonField, out property))
                                {
                                    object value = null;

                                    if (property.PropertyType == typeof(string))
                                    {
                                        value = responseJSON.GetString(jsonField);
                                    }
                                    else if (property.PropertyType == typeof(bool?))
                                    {
                                        value = responseJSON.GetBoolean(jsonField);
                                    }
                                    else if (property.PropertyType == typeof(DateTimeOffset?))
                                    {
                                        value = DateTimeOffset.Parse(responseJSON.GetString(jsonField));
                                    }
                                    else if (property.PropertyType == typeof(List <string>))
                                    {
                                        List <string> values     = new List <string>();
                                        JSONArray     jsonValues = responseJSON.GetJSONArray(jsonField);
                                        for (int j = 0; j < jsonValues.Length(); ++j)
                                        {
                                            values.Add(jsonValues.GetString(j));
                                        }

                                        value = values;
                                    }
                                    else
                                    {
                                        throw new SensusException("Unrecognized FacebookDatum property type:  " + property.PropertyType.ToString());
                                    }

                                    if (value != null)
                                    {
                                        property.SetValue(datum, value);
                                        valuesSet = true;
                                    }
                                }
                                else
                                {
                                    SensusServiceHelper.Get().Logger.Log("Unrecognized JSON field in Facebook query response:  " + jsonField, LoggingLevel.Verbose, GetType());
                                }
                            }

                            if (valuesSet)
                            {
                                data.Add(datum);
                            }
                        }
                        else
                        {
                            throw new Exception("Error received while querying Facebook graph API:  " + response.Error.ErrorMessage);
                        }
                    }
                }
            }
            else
            {
                throw new Exception("Attempted to poll Facebook probe without a valid access token.");
            }

            return(data);
        }
示例#25
0
    public void init(JSONObject json)
    {
        if (json.GetValue("Id") != null)
        {
            this.Id = json.GetString("Id");
        }
        if (json.GetValue("Acount") != null)
        {
            this.accountName = json.GetString("Acount");
        }
        if (json.GetValue("Amount") != null)
        {
            this.amount = json.GetString("Amount");
        }
        if (json.GetValue("CloseDate") != null)
        {
            this.closeDate = json.GetString("CloseDate");
        }
        //if(json.GetValue("Contract") != null ) {this.contract = json.GetString("Contract");}
        if (json.GetValue("CreatedBy") != null)
        {
            this.createdBy = json.GetString("CreatedBy");
        }
        if (json.GetValue("Description") != null)
        {
            this.description = json.GetString("Description");
        }
        if (json.GetValue("ExpectedRevenue") != null)
        {
            this.expectedRevenue = json.GetNumber("ExpectedRevenue");
        }
        if (json.GetValue("ForecastCategoryName") != null)
        {
            this.forecastCategoryName = json.GetString("ForecastCategoryName");
        }
        if (json.GetValue("LastModifiedBy") != null)
        {
            this.lastModifiedBy = json.GetString("LastModifiedBy");
        }
        if (json.GetValue("LeadSource") != null)
        {
            this.leadSource = json.GetString("LeadSource");
        }
        if (json.GetValue("NextStep") != null)
        {
            this.nextStep = json.GetString("NextStep");
        }
        if (json.GetValue("Name") != null)
        {
            this.oppName = json.GetString("Name");
        }
        if (json.GetValue("Owner") != null)
        {
            this.owner = json.GetString("Owner");
        }
        if (json.GetValue("Pricebook2") != null)
        {
            this.pricebook2 = json.GetString("Pricebook2");
        }
        if (json.GetValue("IsPrivate") != null)
        {
            this.isPrivate = json.GetBoolean("IsPrivate");
        }
        if (json.GetValue("Probability") != null)
        {
            this.probability = json.GetNumber("Probability");
        }
        if (json.GetValue("TotalOpportunityQuantity") != null)
        {
            this.quantity = json.GetNumber("TotalOpportunityQuantity");
        }
        if (json.GetValue("StageName") != null)
        {
            this.stageName = json.GetString("StageName");
        }
        if (json.GetValue("Type") != null)
        {
            this.type = json.GetString("Type");
        }
        if (json.GetValue("Urgent__c") != null)
        {
            this.urgent = (float)json.GetNumber("Urgent__c");
        }
        if (json.GetValue("Urgent__c") != null)
        {
            this.urgent = (float)json.GetNumber("Urgent__c");
        }

        //create and add account.
        if (json.GetObject("Account") != null)
        {
            Account account = Account.CreateInstance("Account") as Account;
            account.init(json.GetObject("Account"));

            this.account = account;
        }


        //create and add opportunitylineitems/oppProducts
        if (json.GetObject("OpportunityLineItems") != null)
        {
            JSONArray rowRecords = json.GetObject("OpportunityLineItems").GetArray("records");

            List <OpportunityProduct> oppProducts = new List <OpportunityProduct>();

            foreach (JSONValue row in rowRecords)
            {
                OpportunityProduct oppProduct = OpportunityProduct.CreateInstance("OpportunityProduct") as OpportunityProduct;
                Debug.Log("opp product" + row.ToString());
                JSONObject rec = JSONObject.Parse(row.ToString());
                oppProduct.init(rec);
                oppProducts.Add(oppProduct);
            }

            this.oppProducts = oppProducts;
        }

        //create and add campaign.
        if (json.GetObject("Campaign") != null)
        {
            Campaign campaign = Campaign.CreateInstance("Campaign") as Campaign;
            campaign.init(json.GetObject("Campaign"));

            this.campaign = campaign;
        }

        //create and add account.
        if (json.GetObject("Contract") != null)
        {
            Contract contract = Contract.CreateInstance("Contract") as Contract;
            contract.init(json.GetObject("Contract"));

            this.contract = contract;
        }
    }
示例#26
0
        public async Task <JsonValue> Fetchdata(string url)
        {
            lv = (ListView)FindViewById(Resource.Id.listView1);
            int id = Intent.GetIntExtra("ID", 46);

            cb = new CreateEventDatabase();
            var Tables = cb.Table();

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));

            request.ContentType = "application/json";
            request.Method      = "GET";

            try
            {
                // Send the request to the server and wait for the response:
                using (WebResponse response = await request.GetResponseAsync())
                {
                    // Get a stream representation of the HTTP web response:
                    using (System.IO.Stream stream = response.GetResponseStream())
                    {
                        JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));

                        JSONObject parentObject = new JSONObject(jsonDoc.ToString());
                        JSONArray  jsonArray    = parentObject.OptJSONArray("Apps");

                        for (int i = 0; i < jsonArray.Length(); i++)
                        {
                            JSONObject jsonObject = jsonArray.GetJSONObject(i);

                            //Declares the Class Events and inserts the respons from the api to the class variables.
                            //this structure of the method will be used as the standard in the other activity where a class will
                            //take the api response and add it to the view.
                            Events eventData = new Events()
                            {
                                ID           = int.Parse(id.ToString()),
                                Name         = jsonObject.GetString("ProjectName"),
                                Image        = jsonObject.GetString("Banner"),
                                ProjectID    = jsonObject.GetInt("ProjectID"),
                                BannerisIcon = jsonObject.GetBoolean("BannerIsIcon")
                            };
                            //add the class to and List
                            events.Add(eventData);
                            //Insert the list to SQLite
                            cb.InsertIntoTable(eventData);
                        }

                        lv.Adapter = new CustomListAdapter(this, events);

                        // Return the JSON document:
                        return(url);
                    }
                }
            }

            catch (Exception)
            {
                //Writes out a toast if id is wrong and goes back to MainActivity

                Toast.MakeText(this, "Kunde inte hitta Id: " + id.ToString(), ToastLength.Long).Show();
                var ValueActivity = new Intent(this, typeof(MainActivity));
                StartActivity(ValueActivity);
                return(null);
            }
        }
示例#27
0
        /// <exception cref="Org.Codehaus.Jettison.Json.JSONException"/>
        /// <exception cref="System.Exception"/>
        public virtual void VerifyNodeInfo(JSONObject json)
        {
            NUnit.Framework.Assert.AreEqual("incorrect number of elements", 1, json.Length());
            JSONObject info = json.GetJSONObject("nodeInfo");

            NUnit.Framework.Assert.AreEqual("incorrect number of elements", 16, info.Length()
                                            );
            VerifyNodeInfoGeneric(info.GetString("id"), info.GetString("healthReport"), info.
                                  GetLong("totalVmemAllocatedContainersMB"), info.GetLong("totalPmemAllocatedContainersMB"
                                                                                          ), info.GetLong("totalVCoresAllocatedContainers"), info.GetBoolean("vmemCheckEnabled"
                                                                                                                                                             ), info.GetBoolean("pmemCheckEnabled"), info.GetLong("lastNodeUpdateTime"), info
                                  .GetBoolean("nodeHealthy"), info.GetString("nodeHostName"), info.GetString("hadoopVersionBuiltOn"
                                                                                                             ), info.GetString("hadoopBuildVersion"), info.GetString("hadoopVersion"), info.GetString
                                      ("nodeManagerVersionBuiltOn"), info.GetString("nodeManagerBuildVersion"), info.GetString
                                      ("nodeManagerVersion"));
        }
示例#28
0
 public void FromJson(JSONObject json)
 {
     Title   = json.GetString("Title");
     Type    = json.GetString("Type");
     Enabled = json.GetBoolean("Enabled");
 }
示例#29
0
        /// <summary> The callback for the batch we tried to send </summary>
        IEnumerator BatchSendCallbackDelegate(string response, Exception e, int attemptsMadeSoFar)
        {
            // note when we finished sending a batch so we can calculate how long to wait before trying to automatically publish again
            lastBatchSendingCompletedTime = Time.realtimeSinceStartup;
            // update number of attempts made
            attemptsMadeSoFar++;

            // check for errors and handle accordingly
            if (e != null)
            {
                // handel the error by type
                if (e.Message.StartsWith("403"))                 // "403" error code means the api token is incorrect
                {
                    Debug.Log("BatchSendCallbackDelegate failed. 403");
                    setupState = SetupState.NotCalled;
                    alreadyTryingToSendBatch = false;
                    yield break;
                }
                // on all other error codes we reattempt to send unless limit reached
                else
                {
                    Debug.Log("BatchSendCallbackDelegate failed. " + e.Message);

                    // check if we have reached the retry limit
                    if (attemptsMadeSoFar >= int.Parse(defaults["maxTotalRequestRetries"]))
                    {
                        // Let all callbacks in batch know that attempt failed and what error codes we got
                        foreach (var item in batchQueue.GetFirstBatch())
                        {
                            if ((!string.IsNullOrEmpty(item.eventId)) && item.callback != null)
                            {
                                // set the proper error paramaters to each CoolaData delivery result we need to return to each callback
                                CoolaDataDeliveryResult coolaDataDeliveryResult = new CoolaDataDeliveryResult();
                                coolaDataDeliveryResult.eventId = item.eventId;
                                coolaDataDeliveryResult.status  = false;
                                int indexOfFirstSpace = e.Message.IndexOf(" ");
                                coolaDataDeliveryResult.deliveryStatusCode        = int.Parse(e.Message.Substring(0, indexOfFirstSpace));
                                coolaDataDeliveryResult.deliveryStatusDescription = e.Message.Substring(indexOfFirstSpace + 1, e.Message.Length - indexOfFirstSpace - 1);
                                // call the callback with the CoolaData delivery result
                                item.callback(coolaDataDeliveryResult);
                            }
                        }
                        // remove the first batch, and let the batch manager try again
                        batchQueue.RemoveFirstBatch();
                        alreadyTryingToSendBatch = false;
                        ManageBatchSending();
                        yield break;
                    }

                    // comply with failed attempt backoff interval
                    float backoffTimeBeforeReattempt = float.Parse(defaults["eventsOutageBackoffIntervalMillis"]) / 1000f;
                    if (Time.realtimeSinceStartup - batchSendStartTime < backoffTimeBeforeReattempt)
                    {
                        yield return(new WaitForSeconds(backoffTimeBeforeReattempt - Time.realtimeSinceStartup + batchSendStartTime));
                    }
                    // try to send the batch again
                    StartCoroutine(TrySendBacthFromQueue(attemptsMadeSoFar));
                    yield break;
                }
            }
            else
            {
                if (CoolaDataTracker.getInstance().operationComplete != null)
                {
                    CoolaDataTracker.getInstance().operationComplete(response);
                }

                Debug.Log("BatchSendCallbackDelegate soccess. response: " + response);
            }
            // send was sucessful

            // collect all callback trackEvents we have
            Dictionary <string, Action <CoolaDataDeliveryResult> > callbacks = new Dictionary <string, Action <CoolaDataDeliveryResult> >();

            foreach (var item in batchQueue.GetFirstBatch())
            {
                if ((!string.IsNullOrEmpty(item.eventId)) && item.callback != null)
                {
                    callbacks.Add(item.eventId, item.callback);
                }
            }
            // parse response into usable format
            JSONObject responseDictionary = JSONObject.Parse(response);

            // give the callbacks their answers
            foreach (var result in responseDictionary.GetObject("results"))
            {
                // Extract the specific CoolaData delivery result from the server response
                CoolaDataDeliveryResult coolaDataDeliveryResult = new CoolaDataDeliveryResult();
                coolaDataDeliveryResult.eventId                   = result.Key;
                coolaDataDeliveryResult.status                    = responseDictionary.GetBoolean("status");
                coolaDataDeliveryResult.deliveryStatusCode        = 200;          // succeffuly communication with server
                coolaDataDeliveryResult.deliveryStatusDescription = null;         // The description of the status state. e.g. “Failed to send event due to network issues”
                coolaDataDeliveryResult.responseProperties        = new Dictionary <string, string>();
                foreach (var pair in result.Value.Obj)
                {
                    coolaDataDeliveryResult.responseProperties.Add(pair.Key, pair.Value.ToString());
                }
                // call the appropriate callback eith the Cooladata deliviery result
                callbacks[result.Key](coolaDataDeliveryResult);
            }
            // remove first batch which we have sucessfully sent
            batchQueue.RemoveFirstBatch();
            // unlock batch sending
            alreadyTryingToSendBatch = false;
        }
示例#30
0
    public void init(JSONObject json)
    {
        if(json.GetValue("Id") != null ){this.Id = json.GetString("Id");}
        if(json.GetValue("Acount") != null ){this.accountName = json.GetString("Acount");}
        if(json.GetValue("Amount") != null ){this.amount = json.GetString("Amount");}
        if(json.GetValue("CloseDate") != null ) {this.closeDate = json.GetString("CloseDate");}
        //if(json.GetValue("Contract") != null ) {this.contract = json.GetString("Contract");}
        if(json.GetValue("CreatedBy") != null ) {this.createdBy = json.GetString("CreatedBy");}
        if(json.GetValue("Description") != null ) {this.description = json.GetString("Description");}
        if(json.GetValue("ExpectedRevenue") != null ) {this.expectedRevenue = json.GetNumber("ExpectedRevenue");}
        if(json.GetValue("ForecastCategoryName") != null ) {this.forecastCategoryName = json.GetString("ForecastCategoryName");}
        if(json.GetValue("LastModifiedBy") != null ) {this.lastModifiedBy = json.GetString("LastModifiedBy");}
        if(json.GetValue("LeadSource") != null ) {this.leadSource = json.GetString("LeadSource");}
        if(json.GetValue("NextStep") != null ) {this.nextStep = json.GetString("NextStep");}
        if(json.GetValue("Name") != null ) {this.oppName = json.GetString("Name");}
        if(json.GetValue("Owner") != null ) {this.owner = json.GetString("Owner");}
        if(json.GetValue("Pricebook2") != null ) {this.pricebook2 = json.GetString("Pricebook2");}
        if(json.GetValue("IsPrivate") != null ) {this.isPrivate = json.GetBoolean("IsPrivate");}
        if(json.GetValue("Probability") != null ) {this.probability = json.GetNumber("Probability");}
        if(json.GetValue("TotalOpportunityQuantity") != null ) {this.quantity = json.GetNumber("TotalOpportunityQuantity");}
        if(json.GetValue("StageName") != null ) {this.stageName = json.GetString("StageName");}
        if(json.GetValue("Type") != null ) {this.type = json.GetString("Type");}
        if(json.GetValue("Urgent__c") != null ) {this.urgent = (float)json.GetNumber("Urgent__c");}
        if(json.GetValue("Urgent__c") != null ) {this.urgent = (float)json.GetNumber("Urgent__c");}

        //create and add account.
        if(json.GetObject("Account") != null){

            Account account = Account.CreateInstance("Account") as Account;
            account.init(json.GetObject("Account"));

            this.account = account;

        }

        //create and add opportunitylineitems/oppProducts
        if(json.GetObject("OpportunityLineItems") != null){

            JSONArray rowRecords = json.GetObject("OpportunityLineItems").GetArray ("records");

            List <OpportunityProduct> oppProducts = new List<OpportunityProduct>();

            foreach (JSONValue row in rowRecords) {

                OpportunityProduct oppProduct = OpportunityProduct.CreateInstance("OpportunityProduct") as OpportunityProduct;
                Debug.Log("opp product" + row.ToString());
                JSONObject rec = JSONObject.Parse(row.ToString());
                oppProduct.init(rec);
                oppProducts.Add(oppProduct);

            }

            this.oppProducts = oppProducts;

        }

        //create and add campaign.
        if(json.GetObject("Campaign") != null){

            Campaign campaign = Campaign.CreateInstance("Campaign") as Campaign;
            campaign.init(json.GetObject("Campaign"));

            this.campaign = campaign;

        }

        //create and add account.
        if(json.GetObject("Contract") != null){

            Contract contract = Contract.CreateInstance("Contract") as Contract;
            contract.init(json.GetObject("Contract"));

            this.contract = contract;

        }
    }
示例#31
0
	// wemePush urlscheme parse
	public JSONObject getResultForWemePush(string scheme,string host,JSONObject jsonObject){
		host = host.ToLower();
		switch(host){
			case "isallowpushmessage":
				JSONObject pushallowResult = JSONObject.Parse(((TextAsset)Resources.Load("JSONRequests/"+scheme+"/"+host)).text);
				pushallowResult.Remove("allow");
				pushallowResult.Add("allow",onPush);
				return pushallowResult;

			case "requestallowpushmessage":
				if(jsonObject.ContainsKey("allow")){
					JSONObject requestPushResult = JSONObject.Parse(((TextAsset)Resources.Load("JSONRequests/"+scheme+"/"+host)).text);
					onPush = jsonObject.GetBoolean("allow");
					requestPushResult.Remove("allow");
					requestPushResult.Add("allow",onPush);
					return requestPushResult;
				}else{
					return jsonResultForError("WmInterfaceBroker",(long)WemeManager.WemeErrType.WM_ERR_INVALID_PARAMETER,"invalid_parameter",scheme+"://"+host);
				}
		}
		return jsonResultForError("WmInterfaceBroker",(long)WemeManager.WemeErrType.WM_ERR_INVALID_PARAMETER,"invalid_parameter",scheme+"://"+host);
	}
示例#32
0
        public async Task <JsonValue> FetchDataHeader(string url)
        {
            LinearLayout linearLayout = FindViewById <LinearLayout>(Resource.Id.ListLinearLayout);
            GridLayout   gridLayout   = FindViewById <GridLayout>(Resource.Id.viewLayout);
            ImageView    imageViewas  = (ImageView)FindViewById(Resource.Id.Imageview);

            navigationView = (NavigationView)FindViewById(Resource.Id.nav_view);
            string dbPath                   = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "mintdata.db3");
            var    db                       = new SQLiteAsyncConnection(dbPath);
            var    HomeButtonTalbe          = db.Table <HomeButton>();
            var    InfoContentTable         = db.Table <InfoContent>();
            var    IntroPageTable           = db.Table <Intropage>();
            var    BackgroundNADBUttonTABLE = db.Table <BackgGroundAndButton>();

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));

            request.ContentType = "application/json";
            request.Method      = "GET";

            try
            {
                // Send the request to the server and wait for the response:
                using (WebResponse response = await request.GetResponseAsync())
                {
                    // Get a stream representation of the HTTP web response:
                    using (System.IO.Stream stream = response.GetResponseStream())
                    {
                        JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));

                        JSONArray ja = new JSONArray(jsonDoc.ToString());

                        for (int i = 0; i < ja.Length(); i++)
                        {
                            JSONObject jo = ja.GetJSONObject(i);

                            BackgGroundAndButton BaB = new BackgGroundAndButton
                            {
                                image         = jo.GetString("BackgroundImg"),
                                IsTrueORfalse = jo.GetBoolean("ButtonInterface"),
                            };

                            BaBLisr.Add(BaB);
                            await db.InsertOrReplaceAsync(BaB);

                            InfoContent infoContent = new InfoContent
                            {
                                Content = jo.GetString("ContentText"),
                            };

                            infocontentlist.Add(infoContent);
                            await db.InsertOrReplaceAsync(infoContent);

                            Intropage intropage = new Intropage
                            {
                                LastChanged = jo.GetString("LastChanged"),
                            };

                            IntroPageList.Add(intropage);
                            await db.InsertOrReplaceAsync(intropage);


                            //Convert the Base64 from the api to and image and sets the image to the imageview
                            GetImage = BaB.image;
                            byte[] imgdata     = Convert.FromBase64String(GetImage);
                            var    imageBitmap = Android.Graphics.BitmapFactory.DecodeByteArray(imgdata, 0, imgdata.Length);
                            imageViewas.SetImageBitmap(imageBitmap);

                            //Check if buttoninterfece is false or true
                            if (BaB.IsTrueORfalse == false)
                            {
                                //Create listview

                                string    urlListView = Intent.GetStringExtra("APIListView");
                                JsonValue CreateList  = await FetchListView(urlListView);
                            }

                            else

                            {
                                //Creates imagebuttons
                                JSONArray jsonArray = ja.GetJSONObject(0).GetJSONArray("Buttons");
                                //Hides the linearlayout with the Listview
                                linearLayout.Visibility = ViewStates.Gone;


                                for (int init = 0; init < jsonArray.Length(); init++)
                                {
                                    JSONObject jsonObject = jsonArray.GetJSONObject(init);

                                    HomeButton homeButton = new HomeButton
                                    {
                                        Column        = jsonObject.GetInt("Column"),
                                        Image         = jsonObject.GetString("Image"),
                                        InfoContentId = jsonObject.GetString("InfoContentID"),
                                        ModuleId      = jsonObject.GetInt("ModuleID"),
                                        Row           = jsonObject.GetInt("Row"),
                                    };

                                    HomeButtonList.Add(homeButton);
                                    await db.InsertOrReplaceAsync(homeButton);

                                    GridLayout.LayoutParams paramms = new GridLayout.LayoutParams();
                                    paramms.RowSpec    = GridLayout.InvokeSpec(GridLayout.Undefined, 1f);
                                    paramms.ColumnSpec = GridLayout.InvokeSpec(GridLayout.Undefined, 1f);

                                    var buttons = new ImageButton(this);
                                    buttons.LayoutParameters = paramms;
                                    buttons.SetScaleType(ImageButton.ScaleType.FitXy);
                                    byte[] buttonimg      = Convert.FromBase64String(homeButton.Image);
                                    var    buttonimagemap = Android.Graphics.BitmapFactory.DecodeByteArray(buttonimg, 0, buttonimg.Length);
                                    buttons.SetImageBitmap(buttonimagemap);
                                    gridLayout.AddView(buttons);

                                    //Displays the ModuleID when a imagebutton is pressed.
                                    buttons.Click += delegate
                                    {
                                        Toast.MakeText(this, "ModuleId: " + homeButton.ModuleId.ToString(), ToastLength.Long).Show();
                                    };
                                }
                            }
                        }

                        // Return the JSON document:
                        Console.Out.WriteLine("Response: {0}", jsonDoc.ToString());
                        return(url);
                    }
                }
            }

            catch (Exception)
            {
                return(null);
            }
        }