protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            SetContentView(Resource.Layout.Main);

            var button = FindViewById <Button>(Resource.Id.button);
            var result = FindViewById <TextView>(Resource.Id.result);
            var input  = FindViewById <EditText>(Resource.Id.helloTo);

            button.Click += async delegate
            {
                result.Text = "Calling Cloud.....";
                var response = await FH.Cloud("hello", "GET", null, new Dictionary <string, string>() { { "hello", input.Text } });

                if (response.Error == null)
                {
                    Log.Debug(Tag, "cloudCall - success");
                    result.Text = (string)response.GetResponseAsDictionary()["msg"];
                }
                else
                {
                    Log.Debug(Tag, "cloudCall - fail");
                    Log.Error(Tag, response.Error.Message, response.Error);
                    result.Text = response.Error.Message;
                }
            };
        }
 public async void CastVote(string sessionName, User user)
 {
     await
     FH.Cloud("poker/vote", "POST", null,
              new Dictionary <string, object> {
         { "session", sessionName }, { "user", user }
     });
 }
        public async Task <List <Session> > GetSessions()
        {
            var response = await FH.Cloud("poker", "GET", null, null);

            if (response.Error != null)
            {
                throw response.Error;
            }

            return(JsonConvert.DeserializeObject <List <Session> >(response.RawResponse));
        }
        public async Task <Session> JoinSession(string sessionName, string userName)
        {
            var response = await FH.Cloud("poker/join", "POST", null, new Dictionary <string, string>() { { "session", sessionName }, { "user", userName } });

            if (response.Error != null)
            {
                throw response.Error;
            }

            _socket.Emit("room-join", () => { }, sessionName);

            return(JsonConvert.DeserializeObject <Session>(response.RawResponse));
        }
        public async void CallCloudAsync()
        {
            var response = await FH.Cloud("hello", "GET", null, new Dictionary <string, string> () { { "hello", name.Text } });

            if (response.Error == null)
            {
                Console.WriteLine("cloudCall - success");
                result.Text = (string)response.GetResponseAsDictionary() ["msg"];
            }
            else
            {
                Console.WriteLine("cloudCall - fail");
                Console.WriteLine(response.Error.Message, response.Error);
                result.Text = response.Error.Message;
            }
        }
Exemplo n.º 6
0
        private async void SayHello(object sender, RoutedEventArgs e)
        {
            Response.Text = "Calling Cloud.....";
            FirePropertyChanged("Response");
            var response = await FH.Cloud("hello", "GET", null, new Dictionary <string, string>() { { "hello", HelloTo.Text } });

            if (response.Error == null)
            {
                Response.Text = (string)response.GetResponseAsDictionary()["msg"];
                FirePropertyChanged("Response");
            }
            else
            {
                await new MessageDialog(response.Error.Message).ShowAsync();
            }
        }
        async partial void onCloudCallTouched(UIButton sender)
        {
            Dictionary <string, object> data = new Dictionary <string, object>();

            data.Add("hello", "world");
            string     message = null;
            FHResponse res     = await FH.Cloud("hello", "GET", null, data);

            if (res.StatusCode == System.Net.HttpStatusCode.OK)
            {
                message = (string)res.GetResponseAsDictionary()["msg"];
            }
            else
            {
                message = "Error";
            }

            ShowMessage(message);
        }
Exemplo n.º 8
0
        private async void CloudButton_Click(object sender, RoutedEventArgs e)
        {
            var data = new Dictionary <string, object>();

            data.Add("hello", "world");
            string message;
            var    res = await FH.Cloud("hello", "GET", null, data);

            if (res.StatusCode == HttpStatusCode.OK)
            {
                message = (string)res.GetResponseAsDictionary()["msg"];
            }
            else
            {
                message = "Error";
            }

            ShowMessage(message);
        }
Exemplo n.º 9
0
        private async Task TestCloud(string method)
        {
            var headers = new Dictionary <string, string>();

            headers["x-test-header"] = "testheader";
            var data = new Dictionary <string, string>();

            data["test"] = "test";
            var cloudRes = await FH.Cloud("echo", method, headers, data);

            var cloudResJson = cloudRes.GetResponseAsJObject();

            Assert.IsNotNull(cloudResJson["method"]);
            Assert.IsTrue(method.ToUpper().Equals((string)cloudResJson["method"]));

            Assert.IsNotNull(cloudResJson["headers"]);
            Assert.IsNotNull(cloudResJson["body"]);

            var resHeaders = (JObject)cloudResJson["headers"];

            Assert.IsNotNull(resHeaders["x-fh-cuid"]);
            Assert.IsNotNull(resHeaders["x-test-header"]);


            Assert.IsTrue("testheader".Equals((string)resHeaders["x-test-header"]));
            JObject resData = null;

            if ("GET".Equals(method))
            {
                Assert.IsNotNull(cloudResJson["query"]);
                resData = (JObject)cloudResJson["query"];
            }
            else
            {
                Assert.IsNotNull(cloudResJson["body"]);
                resData = (JObject)cloudResJson["body"];
            }

            Assert.IsNotNull(resData["test"]);
            Assert.IsTrue(((string)resData["test"]).Contains("test"));
        }
        public async Task <Session> CreateSession(Session session)
        {
            await FH.Cloud("poker", "POST", null, session);

            return(await JoinSession(session.Name, session.CreatedBy.Name));
        }
Exemplo n.º 11
0
        public async void TestFHSyncClient()
        #endif
        {
            //clear db
            var setupRes = await FH.Cloud(string.Format("/syncTest/{0}", DATASET_ID), "DELETE", null, null);

            Assert.IsTrue(HttpStatusCode.OK.Equals(setupRes.StatusCode));

            var syncConfig = new FHSyncConfig();

            syncConfig.SyncActive           = false;
            syncConfig.SyncFrequency        = 1;
            syncConfig.AutoSyncLocalUpdates = true;
            syncConfig.SyncCloud            = FHSyncConfig.SyncCloudType.Mbbas;

            //make sure no existing data file exist
            metaDataFilePath = FHSyncUtils.GetDataFilePath(DATASET_ID, ".sync.json");
            dataFilePath     = FHSyncUtils.GetDataFilePath(DATASET_ID, ".data.json");
            pendingFilePath  = FHSyncUtils.GetDataFilePath(DATASET_ID, ".pendings.json");

            TestUtils.DeleteFileIfExists(metaDataFilePath);
            TestUtils.DeleteFileIfExists(dataFilePath);
            TestUtils.DeleteFileIfExists(pendingFilePath);

            Assert.IsFalse(File.Exists(metaDataFilePath));
            Assert.IsFalse(File.Exists(dataFilePath));
            Assert.IsFalse(File.Exists(pendingFilePath));

            syncClient = FHSyncClient.GetInstance();
            syncClient.Initialise(syncConfig);
            syncClient.Manage <TaskModel>(DATASET_ID, syncConfig, null);

            var syncStarted   = false;
            var syncCompleted = false;

            syncClient.SyncStarted += (object sender, FHSyncNotificationEventArgs e) =>
            {
                if (e.DatasetId.Equals(DATASET_ID))
                {
                    syncStarted = true;
                }
            };

            syncClient.SyncCompleted += (object sender, FHSyncNotificationEventArgs e) =>
            {
                if (e.DatasetId.Equals(DATASET_ID))
                {
                    syncCompleted = true;
                }
            };

            var tasks = syncClient.List <TaskModel>(DATASET_ID);

            Assert.AreEqual(0, tasks.Count);

            var newTask = new TaskModel
            {
                TaksName  = "task1",
                Completed = false
            };

            newTask = syncClient.Create(DATASET_ID, newTask);
            //syncConfig.SyncActive = true;
            Assert.IsNotNull(newTask.UID);

            syncClient.ForceSync <TaskModel>(DATASET_ID);

            Thread.Sleep(2000);

            var cloudRes = await FH.Cloud(string.Format("/syncTest/{0}", DATASET_ID), "GET", null, null);

            Assert.IsNull(cloudRes.Error);
            var dbData = cloudRes.GetResponseAsJObject();

            Assert.AreEqual(1, (int)dbData["count"]);
            var taskNameInDb = (string)dbData["list"][0]["fields"]["taskName"];

            Assert.IsTrue(taskNameInDb.Equals("task1"));

            Assert.IsTrue(syncStarted);
            Assert.IsTrue(syncCompleted);

            syncClient.StopAll();
        }
Exemplo n.º 12
0
        protected async override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            FH.SetLogLevel((int)LogService.LogLevels.DEBUG);
            //use ModernHttpClient
            FHHttpClientFactory.Get = (() => new HttpClient(new OkHttpNetworkHandler()));

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);
            await FHClient.Init();

            ShowMessage("App Ready!");

            Button cloudButton = (Button)FindViewById(Resource.Id.button1);
            Button authButton  = (Button)FindViewById(Resource.Id.button2);
            Button mbaasButton = (Button)FindViewById(Resource.Id.button3);

            cloudButton.Click += async(object sender, EventArgs e) => {
                Dictionary <string, object> data = new Dictionary <string, object>();
                data.Add("hello", "world");
                string     message = null;
                FHResponse res     = await FH.Cloud("hello", "GET", null, data);

                if (res.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    message = (string)res.GetResponseAsDictionary()["msg"];
                }
                else
                {
                    message = "Error";
                }

                ShowMessage(message);
            };

            authButton.Click += async(object sender, EventArgs e) => {
                string     authPolicy = "TestGooglePolicy";
                FHResponse res        = await FH.Auth(authPolicy);

                ShowMessage(res.RawResponse);
            };

            mbaasButton.Click += async(object sender, EventArgs e) => {
                Dictionary <string, object> data = new Dictionary <string, object>();
                data.Add("act", "create");
                data.Add("type", COLLECTION_NAME);
                //create the collection first
                FHResponse createRes = await FH.Mbaas("db", data);

                ShowMessage(createRes.RawResponse);

                //read device id
                string deviceId = GetDeviceId();

                //check if it exists
                data = new Dictionary <string, object>();
                data.Add("type", COLLECTION_NAME);
                data.Add("act", "list");
                Dictionary <string, string> deviceIdField = new Dictionary <string, string>();
                deviceIdField.Add("deviceId", deviceId);
                data.Add("eq", deviceIdField);
                FHResponse listRes = await FH.Mbaas("db", data);

                ShowMessage(listRes.RawResponse);

                IDictionary <string, object> listResDic = listRes.GetResponseAsDictionary();
                if (Convert.ToInt16(listResDic["count"]) == 0)
                {
                    data = new Dictionary <string, object>();
                    data.Add("act", "create");
                    data.Add("type", COLLECTION_NAME);
                    data.Add("fields", GetDeviceInfo());

                    FHResponse dataCreateRes = await FH.Mbaas("db", data);

                    ShowMessage(dataCreateRes.RawResponse);
                }
                else
                {
                    ShowMessage("Device is already created!");
                }
            };
        }
Exemplo n.º 13
0
        public async void TestDatasetSync()
        #endif
        {
            //clear db
            var setupRes = await FH.Cloud(string.Format("/syncTest/{0}", DatasetId), "DELETE", null, null);

            Assert.IsTrue(HttpStatusCode.OK.Equals(setupRes.StatusCode));

            var syncConfig = new FHSyncConfig();

            syncConfig.SyncFrequency        = 1;
            syncConfig.AutoSyncLocalUpdates = true;
            syncConfig.SyncCloud            = FHSyncConfig.SyncCloudType.Mbbas;
            syncConfig.CrashedCountWait     = 0;
            syncConfig.ResendCrashedUpdated = true;

            //make sure no existing data file exist
            _metaDataFilePath = FHSyncUtils.GetDataFilePath(DatasetId, ".sync.json");
            _dataFilePath     = FHSyncUtils.GetDataFilePath(DatasetId, ".data.json");
            _pendingFilePath  = FHSyncUtils.GetDataFilePath(DatasetId, ".pendings.json");

            TestUtils.DeleteFileIfExists(_metaDataFilePath);
            TestUtils.DeleteFileIfExists(_dataFilePath);
            TestUtils.DeleteFileIfExists(_pendingFilePath);

            Assert.IsFalse(File.Exists(_metaDataFilePath));
            Assert.IsFalse(File.Exists(_dataFilePath));
            Assert.IsFalse(File.Exists(_pendingFilePath));


            var tasksDataset = FHSyncDataset <TaskModel> .Build <TaskModel>(DatasetId, syncConfig, null, null);

            //since the dataset is saved on creation, make sure the data files exist
            TestUtils.AssertFileExists(_metaDataFilePath);
            TestUtils.AssertFileExists(_dataFilePath);
            TestUtils.AssertFileExists(_pendingFilePath);

            //Try to create a new Task
            var taskName = "task1";
            var task     = new TaskModel
            {
                TaksName  = taskName,
                Completed = false
            };

            task = tasksDataset.Create(task);

            var taskId = task.UID;

            Debug.WriteLine("Created Task Id = {0}", taskId);
            Assert.IsNotNull(taskId);

            //Now there should be one pending record
            var pendings            = tasksDataset.GetPendingRecords();
            var pendingRecordsCount = pendings.List().Count;

            Assert.AreEqual(1, pendingRecordsCount);

            var taskRead = tasksDataset.Read(taskId);

            Assert.IsNotNull(taskRead);
            Assert.IsTrue(taskRead.TaksName.Equals(taskName));

            Assert.IsTrue(tasksDataset.ShouldSync());

            var updatedTaskName = "updatedTask1";

            task.TaksName = updatedTaskName;
            tasksDataset.Update(task);

            //verify data is updated
            var readUpdated = tasksDataset.Read(taskId);

            Assert.IsNotNull(readUpdated);
            Assert.IsTrue(readUpdated.TaksName.Equals(updatedTaskName));

            //test data list
            var tasks = tasksDataset.List();

            Assert.AreEqual(1, tasks.Count);
            var listedTask = tasks[0];

            Assert.IsTrue(listedTask.TaksName.Equals(updatedTaskName));
            Assert.IsTrue(listedTask.Completed == false);
            Assert.IsTrue(listedTask.UID.Equals(taskId));


            pendings = tasksDataset.GetPendingRecords();
            var pendingsList = pendings.List();

            //updating an existing pending, so there should be still only 1 pending record
            Assert.AreEqual(1, pendingsList.Count);

            var pending = pendingsList.First().Value;
            //verify the pendingRecord's postData is the new updated data
            var postData = pending.PostData;

            Assert.IsTrue(updatedTaskName.Equals(postData.Data.TaksName));

            //run the syncLoop
            await tasksDataset.StartSyncLoop();

            //verify the data is created in the remote db
            var cloudRes = await FH.Cloud(string.Format("/syncTest/{0}", DatasetId), "GET", null, null);

            Debug.WriteLine("Got response " + cloudRes.RawResponse);
            Assert.IsNull(cloudRes.Error);
            var dbData = cloudRes.GetResponseAsJObject();

            Assert.AreEqual(1, (int)dbData["count"]);
            var taskNameInDb = (string)dbData["list"][0]["fields"]["taskName"];

            Assert.IsTrue(taskNameInDb.Equals(updatedTaskName));

            //there should be no pending data
            pendings = tasksDataset.GetPendingRecords();
            Assert.AreEqual(0, pendings.List().Count);

            var newTaskUid = (string)dbData["list"][0]["guid"];

            Assert.IsFalse(newTaskUid.Equals(taskId));
            var tasklistAfterUpdate = tasksDataset.List();

            Debug.WriteLine(tasklistAfterUpdate[0].ToString());

            //since the data is now created in db, the uid should be updated
            var readUpdatedAfterSync = tasksDataset.Read(newTaskUid);

            Assert.IsNotNull(readUpdatedAfterSync);
            Debug.WriteLine("readUpdatedAfterSync = " + readUpdatedAfterSync);

            //create a new record in remote db
            var taskToCreate = new TaskModel
            {
                TaksName  = "anotherTask",
                Completed = false
            };
            var createRecordReq = await FH.Cloud(string.Format("/syncTest/{0}", DatasetId), "POST", null, taskToCreate);

            Debug.WriteLine("Got response for creating new record: {0}", createRecordReq.RawResponse);
            Assert.IsNull(createRecordReq.Error);

            Thread.Sleep(1500);
            Assert.IsTrue(tasksDataset.ShouldSync());

            //run a sync loop
            await tasksDataset.StartSyncLoop();

            Thread.Sleep(9000);

            await tasksDataset.StartSyncLoop();

            //now we should see the new record is created locally
            var updatedTaskList = tasksDataset.List();

            Assert.AreEqual(2, updatedTaskList.Count);
            Debug.WriteLine("updatedTaskList[0] = " + updatedTaskList[0]);
            Debug.WriteLine("updatedTaskList[1] = " + updatedTaskList[1]);

            //verify that the saved files can be loaded again and will construct the same dataset
            var anotherDataset = FHSyncDataset <TaskModel> .Build <TaskModel>(DatasetId, syncConfig, null, null);

            Assert.IsNotNull(anotherDataset.HashValue);
            var tasksListInAnotherDataset = anotherDataset.List();

            Assert.AreEqual(2, tasksListInAnotherDataset.Count);
            foreach (var taskInAnotherDataset in tasksListInAnotherDataset)
            {
                Assert.IsNotNull(taskInAnotherDataset.UID);
                Assert.IsTrue(taskInAnotherDataset.TaksName.Equals("updatedTask1") ||
                              taskInAnotherDataset.TaksName.Equals("anotherTask"));
            }

            //test some failure cases
            var taskToUpdate = updatedTaskList[0];

            taskToUpdate.Completed = true;

            tasksDataset.Update(taskToUpdate);

            //make sure the next syncLoop will fail
            var setFailureRes = await FH.Cloud("/setFailure/true", "GET", null, null);

            Assert.IsNull(setFailureRes.Error);
            Assert.IsTrue((bool)setFailureRes.GetResponseAsJObject()["current"]);

            //run the syncloop again, this time it will fail
            await tasksDataset.StartSyncLoop();

            pendings = tasksDataset.GetPendingRecords();
            Assert.AreEqual(1, pendings.List().Count);

            var pendingRecord = pendings.List().Values.First();

            Assert.IsTrue(pendingRecord.Crashed);

            setFailureRes = await FH.Cloud("/setFailure/false", "GET", null, null);

            Assert.IsNull(setFailureRes.Error);
            Assert.IsFalse((bool)setFailureRes.GetResponseAsJObject()["current"]);

            //run another sync loop, this time there will be no pendings sent as the current update is crashed
            await tasksDataset.StartSyncLoop();

            //at the end of last loop, since we set the crashCountWait to be 0, the updates should be marked as not-crashed and will be sent in next loop
            await tasksDataset.StartSyncLoop();

            //there should be no more pendings
            pendings = tasksDataset.GetPendingRecords();
            Assert.AreEqual(0, pendings.List().Count);

            //verify the update is sent to the cloud
            var verifyUpdateRes =
                await FH.Cloud(string.Format("/syncTest/{0}/{1}", DatasetId, taskToUpdate.UID), "GET", null, null);

            var taskInDBJson = verifyUpdateRes.GetResponseAsJObject();

            Assert.IsTrue((bool)taskInDBJson["fields"]["completed"]);
        }