Exemple #1
0
        /// <summary>
        /// Check for any MoBack reserved columns, and then process them.
        /// </summary>
        /// <returns>The metadata.</returns>
        /// <param name="jsonObject">A JSON object.</param>
        /// <param name="sourceTableID">Source table ID.</param>
        private static MoBackRow ExtractMetadata(SimpleJSONClass jsonObject, string sourceTableID)
        {
            string   objIO     = null;
            DateTime createdOn = default(DateTime);
            DateTime updatedOn = default(DateTime);

            if (jsonObject.dict.ContainsKey("objectId"))
            {
                objIO = jsonObject["objectId"];
            }
            if (jsonObject.dict.ContainsKey("createdAt"))
            {
                createdOn = MoBackDate.DateFromString(jsonObject["createdAt"]);
            }
            if (jsonObject.dict.ContainsKey("updatedAt"))
            {
                updatedOn = MoBackDate.DateFromString(jsonObject["updatedAt"]);
            }

            return(new MoBackRow(sourceTableID, objIO, createdOn, updatedOn));
        }
Exemple #2
0
        /// <summary>
        /// Gets the user info.
        /// </summary>
        /// <returns>A MoBackRequest with a MoBackUser type.</returns>
        public MoBackRequest GetUserInfo()
        {
            // If there is not sessiontoken means user hasn't logged in yet, just exit.
            if (!IsLoggedIn)
            {
                Debug.LogError("There is no current login user.");
                return(null);
            }

            MoBackRequest.ResponseProcessor GetCurrentUserInfoProcessor = (SimpleJSONNode jsonObject) =>
            {
                SimpleJSONClass userInfoJson = jsonObject["user"] as SimpleJSONClass;

                foreach (KeyValuePair <string, SimpleJSONNode> entry in userInfoJson.dict)
                {
                    // we stored these outside of storeValues.
                    if (entry.Key == "userId" || entry.Key == "createdAt" || entry.Key == "updatedAt" || entry.Key == "objectId")
                    {
                        continue;
                    }

                    MoBackValueType moBackType;
                    object          data = MoBackUtils.MoBackTypedObjectFromJSON(entry.Value, out moBackType);
                    // This should always be equivalent to calling SetValue() with the appropriate type; if SetValue() functions are refactored then so too should this, and vice-versa.
                    this.SetColumnType(entry.Key, moBackType);
                    this.storeValues[entry.Key] = data;
                }

                UserName    = userInfoJson["userId"];
                ObjectId    = userInfoJson["objectId"];
                CreatedDate = MoBackDate.DateFromString(userInfoJson["createdAt"]);
                UpdatedDate = MoBackDate.DateFromString(userInfoJson["updatedAt"]);
            };

            return(new MoBackRequest(GetCurrentUserInfoProcessor, MoBackURLS.User, HTTPMethod.GET, null, null));
        }
Exemple #3
0
            /// <summary>
            /// Saves multiple objects with one single call to server.
            /// </summary>
            /// <returns>The MobackRequest.</returns>
            /// <param name="rowsToSave">MoBack Rows need to save.</param>
            public MoBackRequest SaveMultipleObjects(List <MoBackRow> rowsToSave)
            {
                string          uri           = MoBackURLS.Batch + table.TableName;
                SimpleJSONArray jsonArray     = new SimpleJSONArray();
                SimpleJSONClass jsonStructure = new SimpleJSONClass();

                for (int i = 0; i < rowsToSave.Count; i++)
                {
                    SimpleJSONClass jsonToSave = rowsToSave[i].GetJSON();

                    if (rowsToSave[i].ObjectId != null)
                    {
                        jsonToSave.Add("objectId", rowsToSave[i].ObjectId);
                    }

                    jsonArray.Add(jsonToSave);
                }

                jsonStructure.Add("objects", jsonArray);
                Debug.Log(jsonStructure.ToString());
                byte[] bytes = jsonStructure.ToString().ToByteArray();

                // Construct a callback to update all rowsToSave.
                MoBackRequest.ResponseProcessor objUpdater = (SimpleJSONNode responseJson) =>
                {
                    SimpleJSONClass allObjectsInJsonFormat = responseJson["batchResponse"].AsObject;

                    // The response should have the same amount as of the request body.
                    if (allObjectsInJsonFormat.Count != rowsToSave.Count)
                    {
                        Debug.LogError(string.Format("Response objects count: {0}. Request objects count: {1}", allObjectsInJsonFormat.Count, rowsToSave.Count));
                        Debug.LogError("Response doesn't have the same object as Request Body. Something wrong!");
                        return;
                    }

                    for (int i = 0; i < rowsToSave.Count; i++)
                    {
                        SimpleJSONClass jsonAtCurrentIndex = allObjectsInJsonFormat[i] as SimpleJSONClass;

                        if (!jsonAtCurrentIndex["success"].AsBool)
                        {
                            Debug.LogError("Unable to save: " + jsonAtCurrentIndex["objectId"]);
                            continue;
                        }

                        if (!string.IsNullOrEmpty(jsonAtCurrentIndex["createdAt"].ToString()))
                        {
                            string   objectId    = jsonAtCurrentIndex["objectId"];
                            DateTime createdTime = MoBackDate.DateFromString(jsonAtCurrentIndex["createdAt"]);

                            rowsToSave[i].UpdateAfterSave(objectId, createdTime, createdTime);
                        }
                        else if (!string.IsNullOrEmpty(jsonAtCurrentIndex["updatedAt"].ToString()))
                        {
                            string   objectId   = jsonAtCurrentIndex["objectId"];
                            DateTime updateTime = MoBackDate.DateFromString(jsonAtCurrentIndex["updatedAt"]);
                            rowsToSave[i].UpdateAfterSave(objectId, null, updateTime);
                        }
                    }
                };

                /*
                 * Sample uri: https://api.moback.com/objectmgr/api/collections/batch/{tableName}
                 * Sample Json Request Body:
                 * {
                 *  "objects" : [{ "Name" : "Joe", "FavoriteFood" : ["pizza", "fried eggs", "ham sandwich"]}]
                 * }
                 */
                return(new MoBackRequest(objUpdater, uri, HTTPMethod.POST, null, bytes));
            }
Exemple #4
0
            /// <summary>
            /// Saves the object.
            /// </summary>
            /// <returns>Returns the status of the request.</returns>
            /// <param name="toSave">To save.</param>
            /// <param name="objectDataUpdater">Object data updater.</param>
            public MoBackRequest SaveObject(MoBackRow toSave, Action <string, DateTime?, DateTime> objectDataUpdater)
            {
                string uri = MoBackURLS.TablesDefault + table.TableName;

                byte[] bytes = toSave.GetJSON().ToString().ToByteArray();

                // Make a new object
                if (string.IsNullOrEmpty(toSave.ObjectId))
                {
                    // Declare a callback inline so we can store the MoBackRow in it without creating a bunch of extra infrastructure:
                    MoBackRequest.ResponseProcessor objUpdater = (SimpleJSONNode json) =>
                    {
                        /*
                         * Sample Json response:
                         * {
                         *  "createdAt": "2016-01-18T18:41:39.475Z",
                         *  "objectId": "Vp0x4-Swp23tC3Ap",
                         *  "success": true,
                         *  "__acl":
                         *  {
                         *      "globalRead": true,
                         *      "globalWrite": true
                         *  }
                         * }
                         */

                        string   objId       = json["objectId"];
                        DateTime createdDate = MoBackDate.DateFromString(json["createdAt"]);
                        objectDataUpdater(objId, createdDate, createdDate);
                    };

                    /*
                     * Sample uri: https://api.moback.com/objectmgr/api/collections/{tableName}
                     * Sample Json Request Body:
                     * {
                     * "Score" : 10,
                     * "Name" : "Locke",
                     * "Over21" : yes
                     * }
                     */
                    return(new MoBackRequest(objUpdater, uri, HTTPMethod.POST, null, bytes));
                }
                else
                {
                    // Update the object and declare a callback inline so we can store the MoBackRow in it without creating a bunch of extra infrastructure:
                    MoBackRequest.ResponseProcessor objUpdater = (SimpleJSONNode json) =>
                    {
                        /*
                         * Sample Json response:
                         * {
                         *  {
                         *      "updatedAt": "2016-01-21T23:27:18.209Z",
                         *      "__acl":
                         *      {
                         *          "globalRead": true,
                         *          "globalWrite": true
                         *      }
                         *  }
                         * }
                         */
                        DateTime updatedDate = MoBackDate.DateFromString(json["updatedAt"]);
                        objectDataUpdater(null, null, updatedDate);
                    };

                    uri += "/" + toSave.ObjectId;

                    /*
                     * Sample uri: https://api.moback.com/objectmgr/api/collections/{tableName}/{objectID}
                     * Sample Json Request Body:
                     * {
                     * "Name" : "George"
                     * }
                     */
                    return(new MoBackRequest(objUpdater, uri, HTTPMethod.PUT, null, bytes));
                }
            }