public async Task DefineTable_Throws_WhenStoreIsInitialized()
 {
     var store = new MobileServiceSQLiteStore(TestDbName);
     await store.InitializeAsync();
     var ex = Throws<InvalidOperationException>(() => store.DefineTable(TestTable, new JObject()));
     Assert.AreEqual(ex.Message, "Cannot define a table after the store has been initialized.");
 }
        public async Task InitializeAsync_Throws_WhenStoreIsAlreadyInitialized()
        {
            var store = new MobileServiceSQLiteStore(TestDbName);
            await store.InitializeAsync();

            var ex = await ThrowsAsync<InvalidOperationException>(() => store.InitializeAsync());

            Assert.AreEqual(ex.Message, "The store is already initialized.");
        }
        public async Task InitializeAsync_InitializesTheStore()
        {
            TestUtilities.DropTestTable(TestDbName, TestTable);

            var store = new MobileServiceSQLiteStore(TestDbName);
            store.DefineTable(TestTable, new JObject()
            {
                {"id", String.Empty },
                {"createdAt", DateTime.UtcNow}
            });
            await store.InitializeAsync();
        }
Example #4
0
        private TodoItemManager()
        {
            this.client = new MobileServiceClient(Constants.ApplicationURL);

            //List<TodoItem> todoItems = await todoItems.Where(todoItems => todoItems.Name == "Teadog").to

#if OFFLINE_SYNC_ENABLED
            var store = new MobileServiceSQLiteStore(offlineDbPath);
            store.DefineTable <TodoItem>();

            //Initializes the SyncContext using the default IMobileServiceSyncHandler.
            this.client.SyncContext.InitializeAsync(store);

            this.todoTable = client.GetSyncTable <TodoItem>();
#else
            this.todoTable = client.GetTable <TodoItem>();
#endif
        }
Example #5
0
        public async Task Initialize()
        {
            if (_mobileServiceClient?.SyncContext?.IsInitialized ?? false)
            {
                return;
            }

            const string path = "syncstore11.db";
            //setup our local sqlite store and intialize our table
            var store = new MobileServiceSQLiteStore(path);

            store.DefineTable <Message>();
            //store.DefineTable<ContactsInfo>();
            await _mobileServiceClient.SyncContext.InitializeAsync(store, new MobileServiceSyncHandler());

            //Get our sync table that will call out to azure
            _messageTable = _mobileServiceClient.GetSyncTable <Message>();
        }
Example #6
0
        private async Task InitializeAsync()
        {
            if (_avisoTable != null)
            {
                return;
            }

            // Inicialización de SQLite local
            var store = new MobileServiceSQLiteStore(GlobalSettings.Database);

            store.DefineTable <Aviso>();

            await _client.SyncContext.InitializeAsync(store, new MobileServiceSyncHandler());

            _avisoTable = _client.GetSyncTable <Aviso>();
            // Limpiar registros offline.
            await _avisoTable.PurgeAsync(true);
        }
Example #7
0
        async Task InitializeAsync()
        {
            if (client != null)
            {
                return;
            }

            var store = new MobileServiceSQLiteStore("survey.db");

            store.DefineTable <SurveyQuestion> ();
            store.DefineTable <SurveyResponse> ();

            client = new MobileServiceClient(AzureUrl);
            await client.SyncContext.InitializeAsync(store, new MobileServiceSyncHandler());

            questionsTable = client.GetSyncTable <SurveyQuestion> ();
            responseTable  = client.GetSyncTable <SurveyResponse> ();
        }
Example #8
0
        /*should be called once after login*/

        public async Task SyncClientAndStore()
        {
            try
            {
                if (!_client.SyncContext.IsInitialized)
                {
                    var store = new MobileServiceSQLiteStore(Constants.OfflineDbName);
                    DefineTables(store);

                    // Initialize the SyncContext using the default IMobileServiceSyncHandler
                    await _client.SyncContext.InitializeAsync(store, StoreTrackingOptions.NotifyLocalAndServerOperations);
                }
            }
            catch (System.Exception exception)
            {
                Debug.WriteLine(exception.Message);
            }
        }
        public async Task Initialize()
        {
            if (client?.SyncContext?.IsInitialized ?? false)
            {
                return;
            }


            string DbPath = Path.Combine(MobileServiceClient.DefaultDatabasePath, "focac-book.db");

            var store = new MobileServiceSQLiteStore(DbPath);

            //definisco la tabella
            store.DefineTable <FocaccePost>();

            //Initialize SyncContext
            await client.SyncContext.InitializeAsync(store);
        }
Example #10
0
        public async Task Initialize()
        {
            if (MobileService?.SyncContext?.IsInitialized ?? false)
            {
                return;
            }
            MobileService = new MobileServiceClient("https://eucmuxamarin.azurewebsites.net");

            var path = "syncstore.db";

            path = Path.Combine(MobileServiceClient.DefaultDatabasePath, path);
            var store = new MobileServiceSQLiteStore(path);

            store.DefineTable <Listado>();
            await MobileService.SyncContext.InitializeAsync(store, new MobileServiceSyncHandler());

            table = MobileService.GetSyncTable <Listado>();
        }
        public async Task InitializeDataStore()
        {
            // Create the mobile client
            _isInitialized = true;

            _client = new MobileServiceClient("YOUR_URL_HERE",
                                              "YOUR_KEY_HERE");

            // Define the SQLite Store
            var store = new MobileServiceSQLiteStore("cheese.db3");

            // Create the tables in the local database
            store.DefineTable <Cheese> ();
            store.DefineTable <Rating> ();

            // Register the local SQLite database with Azure's synchronization context
            await _client.SyncContext.InitializeAsync(store);
        }
        public TodoItemManager()
        {
            this.client = new MobileServiceClient(
                Constants.ApplicationURL,
                Constants.ApplicationKey);

#if OFFLINE_SYNC_ENABLED
            var store = new MobileServiceSQLiteStore("localstore.db");
            store.DefineTable <TodoItem>();

            //Initializes the SyncContext using the default IMobileServiceSyncHandler.
            this.client.SyncContext.InitializeAsync(store);

            this.todoTable = client.GetSyncTable <TodoItem>();
#else
            this.todoTable = client.GetTable <TodoItem>();
#endif
        }
Example #13
0
        private DBConnection()
        {
            Client = new MobileServiceClient(Constants.ApplicationURL);

            const string offlineDbPath = @"localstore.db";
            var          store         = new MobileServiceSQLiteStore(offlineDbPath);

            store.DefineTable <WorkoutItem>();
            store.DefineTable <UserItem>();
            store.DefineTable <MapPointItem>();
            //Initializes the SyncContext using the default IMobileServiceSyncHandler.This class executes the async calls to synchronize the database
            Client.SyncContext.InitializeAsync(store, new MobileServiceSyncHandler());

            WorkoutItem = new WorkoutItemManager(Client);
            MapPoint    = new MapPointManager(Client);
            UserItem    = new UserItemManager(Client);
            UserLogin   = DependencyService.Get <ILoginSupplier>();
        }
        /// <summary>
        /// Resets the local store.
        /// </summary>
        async Task ResetLocalStoreAsync()
        {
            _clientTable       = null;
            _notificationTable = null;

            // On UWP, it's necessary to Dispose() and nullify the MobileServiceSQLiteStore before
            // trying to delete the database file, otherwise an access exception will occur
            // because of an open file handle. It's okay to do for iOS and Android as well, but not necessary.
            _MobileServiceSQLiteStore?.Dispose();
            _MobileServiceSQLiteStore = null;


            await DeleteOldLocalDatabase().ConfigureAwait(false);

            _IsInitialized = false;
            Settings.LocalDataResetIsRequested = false;
            Settings.DataIsSeeded = false;
        }
Example #15
0
        public AzureService()
        {
            var url   = new Uri(Keys.AzureDomain);
            var store = new MobileServiceSQLiteStore($"{url.Host}.db");

            store.DefineTable <Athlete>();
            store.DefineTable <League>();
            store.DefineTable <Membership>();
            store.DefineTable <Challenge>();
            store.DefineTable <GameResult>();
            Client.SyncContext.InitializeAsync(store);

            LeagueManager     = new LeagueManager();
            MembershipManager = new MembershipManager();
            AthleteManager    = new AthleteManager();
            ChallengeManager  = new ChallengeManager();
            GameResultManager = new GameResultManager();
        }
Example #16
0
        public AzureService()
        {
            var url   = new Uri(AppSettings.ApiAddress);
            var store = new MobileServiceSQLiteStore($"{url.Host}.db");

            store.DefineTable <Product>();
            //store.DefineTable<League>();
            //store.DefineTable<Membership>();
            //store.DefineTable<Challenge>();
            //store.DefineTable<GameResult>();
            Client.SyncContext.InitializeAsync(store);

            //LeagueManager = new LeagueManager();
            //MembershipManager = new MembershipManager();
            ProductManager = new ProductManager();
            AuthManager    = new AuthManager();
            //GameResultManager = new GameResultManager();
        }
        /// <summary>
        ///     Initialize the service and retrieve the offline synch. table.
        /// </summary>
        /// <returns></returns>
        private async Task InitializeAsync()
        {
            if (diaryTable != null)
            {
                return;
            }

            var store = new MobileServiceSQLiteStore(localDatabaseFile);

            store.DefineTable <DiaryEntry>();

            await azureClient.SyncContext.InitializeAsync(store, new MobileServiceSyncHandler());

            diaryTable = azureClient.GetSyncTable <DiaryEntry>();

            // Lab1: added call to purge any offline records.
            await diaryTable.PurgeAsync(true);
        }
Example #18
0
        private async Task InitLocalStoreAsync()
        {
            // new code to initialize the SQLite store
            string path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), localDbFilename);

            if (!File.Exists(path))
            {
                File.Create(path).Dispose();
            }

            var store = new MobileServiceSQLiteStore(path);

            store.DefineTable <User>();

            // Uses the default conflict handler, which fails on conflict
            // To use a different conflict handler, pass a parameter to InitializeAsync. For more details, see http://go.microsoft.com/fwlink/?LinkId=521416
            await client.SyncContext.InitializeAsync(store);
        }
Example #19
0
        public async Task InitializeAsync()
        {
            MobileServiceSQLiteStore store;

            lock (locker)
            {
                if (IsInitialized)
                {
                    return;
                }
#if AUTH
                UseAuth = true;

                Client = new MobileServiceClient(Keys.AppUrl, new AuthHandler());

                if (!string.IsNullOrWhiteSpace(Settings.AzureAuthToken) && !string.IsNullOrWhiteSpace(Settings.AzureUserId))
                {
                    Client.CurrentUser = new MobileServiceUser(Settings.AzureUserId)
                    {
                        MobileServiceAuthenticationToken = Settings.AzureAuthToken
                    };
                }
#else
                //Create our client
                Client = new MobileServiceClient(Keys.AppUrl);
#endif

                //setup our local sqlite store and intialize our table
                SQLitePCL.Batteries.Init();
                store = new MobileServiceSQLiteStore(DbPath);

                //Define tables
                store.DefineTable <Game>();
                store.DefineTable <Team>();
                store.DefineTable <Player>();
                store.DefineTable <GameField>();
                store.DefineTable <GameResult>();

                IsInitialized = true;
            }

            //InitializeAsync SyncContext
            await Client.SyncContext.InitializeAsync(store, new MobileServiceSyncHandler()).ConfigureAwait(false);
        }
        public DataManager()
        {
            ReadOnlyCollection <MobileServiceTableOperationError> syncErrors = null;

            try
            {
                _client = new MobileServiceClient(Constants.ApplicationUrl);

                var store = new MobileServiceSQLiteStore("localstore.db");
                store.DefineTable <Location>();

                _client.SyncContext.InitializeAsync(store);

                _locationTable = _client.GetSyncTable <Location>();

                _locationTable.PullAsync(null, _locationTable.CreateQuery());
            }

            catch (MobileServiceInvalidOperationException ioe)
            {
                Debug.WriteLine(ioe.Message);
            }

            catch (MobileServicePushFailedException exc)
            {
                if (exc.PushResult != null)
                {
                    syncErrors = exc.PushResult.Errors;
                }
            }

            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }

            if (syncErrors != null)
            {
                foreach (var error in syncErrors)
                {
                    Debug.WriteLine(@"Error executing sync opertation. Item: {0} ({1}). Operation discarded.", error.TableName, error.Item["id"]);
                }
            }
        }
        public async Task Initialize()
        {
            if (isInitialized)
            {
                return;
            }

            MobileService = new MobileServiceClient("http://mis-amigos-app.azurewebsites.net");

            const string path = "syncstore-amigos.db";

            var store = new MobileServiceSQLiteStore(path);

            store.DefineTable <Amigos>();
            await MobileService.SyncContext.InitializeAsync(store, new MobileServiceSyncHandler());

            tablaAmigos   = MobileService.GetSyncTable <Amigos>();
            isInitialized = true;
        }
Example #22
0
        public async Task InitializeAsync()
        {
            if (isInitialized)
            {
                return;
            }

            var store = new MobileServiceSQLiteStore("xamarintodo.db");

            store.DefineTable <TodoItem>();
            store.DefineTable <Models.Image>();

            // Initialize File Sync
            MobileService.InitializeFileSyncContext(new TodoItemFileSyncHandler(), store);

            // Initialize the sync context
            await MobileService.SyncContext.InitializeAsync(store,
                                                            new MobileServiceSyncHandler(),
                                                            StoreTrackingOptions.NotifyLocalAndServerOperations);

            // Get a reference to the sync table
            itemTable  = MobileService.GetSyncTable <TodoItem>();
            imageTable = MobileService.GetSyncTable <Models.Image>();

            isInitialized = true;

            // Add a single item into the image table if there aren't any
            // This forces creation.
            var list = await imageTable.ToListAsync();

            if (list.Count == 0)
            {
                var image = new Models.Image
                {
                    Id       = Guid.NewGuid().ToString(),
                    Filename = "dummy",
                    Height   = 0,
                    Width    = 0
                };
                await imageTable.InsertAsync(image);
                await SynchronizeServiceAsync();
            }
        }
        public async Task InitializeAsync()
        {
            if (isInitialized)
            {
                return;
            }

            var store = new MobileServiceSQLiteStore("client.db");

            store.DefineTable <TodoItem>();
            store.DefineTable <Tag>();

            await client.SyncContext.InitializeAsync(store, new MobileServiceSyncHandler());

            itemTable = client.GetSyncTable <TodoItem>();
            tagTable  = client.GetSyncTable <Tag>();

            isInitialized = true;
        }
Example #24
0
        private void Initialize()
        {
            try
            {
                //RemoveTokenFromSecureStore();
                //Client = new MobileServiceClient(appURL, new ExpiredAzureRequestInterceptors(this));
                Client = new MobileServiceClient(appURL);
                var dbName = "goodBuy347.db";
                Store = new MobileServiceSQLiteStore(Path.Combine(MobileServiceClient.DefaultDatabasePath, dbName));
                DefineTables(Store);

                Tables = new Dictionary <string, object>();
                Task.Run(() => DoSSOLoginAsync());
            }
            catch (Exception err)
            {
                Log.Log.Instance.AddLog(err);
            }
        }
Example #25
0
        public async Task PushAsync_PushesAllTables_WhenEmptyListIsGiven()
        {
            ResetDatabase(TestTable);
            TestUtilities.DropTestTable(TestDbName, "someTable");
            TestUtilities.DropTestTable(TestDbName, "StringIdType");

            var hijack = new TestHttpHandler();

            hijack.AddResponseContent("{\"id\":\"abc\",\"String\":\"Hey\"}");
            hijack.AddResponseContent("{\"id\":\"abc\",\"String\":\"Hey\"}");

            var store = new MobileServiceSQLiteStore(TestDbName);

            store.DefineTable("someTable", new JObject()
            {
                { "id", String.Empty }
            });
            store.DefineTable <StringIdType>();

            IMobileServiceClient client = await CreateClient(hijack, store);

            // insert item in pull table
            IMobileServiceSyncTable table1 = client.GetSyncTable("someTable");
            await table1.InsertAsync(new JObject()
            {
                { "id", "abc" }
            });

            // then insert item in other table
            MobileServiceSyncTable <StringIdType> table2 = client.GetSyncTable <StringIdType>() as MobileServiceSyncTable <StringIdType>;
            var item = new StringIdType()
            {
                Id = "abc", String = "what?"
            };
            await table2.InsertAsync(item);

            await(client.SyncContext as MobileServiceSyncContext).PushAsync(CancellationToken.None);

            Assert.Equal(2, hijack.Requests.Count);
            QueryEquals(hijack.Requests[0].RequestUri.AbsolutePath, "/tables/someTable");
            QueryEquals(hijack.Requests[1].RequestUri.AbsolutePath, "/tables/StringIdType");
            Assert.Equal(0L, client.SyncContext.PendingOperations);
        }
Example #26
0
        async Task InitializeAsync()
        {
            // Short circuit - local database is already initialized
            if (Client.SyncContext.IsInitialized)
            {
                return;
            }

            // Create a reference to the local sqlite store
            var store = new MobileServiceSQLiteStore("offlinecache.db");

            // Define the database schema
            store.DefineTable <Organization>();
            store.DefineTable <Announcement>();

            // Actually create the store and update the schema
            // Little hack to avoid initializing the SyncContext more than once: We wait for the task to finish
            Task.Run(async() => await Client.SyncContext.InitializeAsync(store)).Wait();
        }
Example #27
0
        public async Task Init()
        {
            initialized = true;

            const string path  = "syncstore.db";
            var          store = new MobileServiceSQLiteStore(path);

            // store.DefineTable<Store>();
            store.DefineTable <CommonYelpClass>();

            store.DefineTable <Feedback>();

            await MobileService.SyncContext.InitializeAsync(store, new MobileServiceSyncHandler());

            // storeTable = MobileService.GetSyncTable<Store>();
            storeTable = MobileService.GetSyncTable <CommonYelpClass>();

            feedbackTable = MobileService.GetSyncTable <Feedback>();
        }
        private TodoItemManager()
        {
            this.client = new MobileServiceClient(Constants.ApplicationURL);
            //var user = Logi
#if OFFLINE_SYNC_ENABLED
            var store = new MobileServiceSQLiteStore(offlineDbPath);
            store.DefineTable <TodoItem>();

            //Initializes the SyncContext using the default IMobileServiceSyncHandler.
            this.client.SyncContext.InitializeAsync(store);

            this.todoTable = client.GetSyncTable <TodoItem>();
#else
            this.todoTable = client.GetTable <TodoItem>();
            //this.users = client.GetTable<User>();
            //this.homes = client.GetTable<Home>();
            //LoginButtonClicked();
#endif
        }
Example #29
0
        public ErpService(IMvxMessenger messenger)
        {
            this.messenger = messenger;
            this.client    = new MobileServiceClient(Constants.ApplicationURL);

            var store = new MobileServiceSQLiteStore(offlineDbPath);

            store.DefineTable <Vendor>();
            store.DefineTable <Product>();
            store.DefineTable <Order>();
            store.DefineTable <Customer>();

            this.client.SyncContext.InitializeAsync(store, new ErpMobileServiceSyncHandler());

            this.vendorTable   = client.GetSyncTable <Vendor>();
            this.productTable  = client.GetSyncTable <Product>();
            this.orderTable    = client.GetSyncTable <Order>();
            this.customerTable = client.GetSyncTable <Customer>();
        }
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            Xamarin.Forms.Forms.Init(this, bundle);

            #region Azure stuff
            CurrentPlatform.Init();

            Client = new MobileServiceClient(
                Constants.Url,
                Constants.Key);


            #region Azure Sync stuff
            // http://azure.microsoft.com/en-us/documentation/articles/mobile-services-xamarin-android-get-started-offline-data/
            // new code to initialize the SQLite store
            string path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "test1.db");

            if (!File.Exists(path))
            {
                File.Create(path).Dispose();
            }

            var store = new MobileServiceSQLiteStore(path);
            store.DefineTable <TodoItem>();

            Client.SyncContext.InitializeAsync(store).Wait();
            #endregion


            todoTable       = Client.GetSyncTable <TodoItem>();
            todoItemManager = new TodoItemManager(Client, todoTable);

            App.SetTodoItemManager(todoItemManager);
            #endregion region

            #region Text to Speech stuff
            App.SetTextToSpeech(new Speech());
            #endregion

            SetPage(App.GetMainPage());
        }
Example #31
0
        public async Task UpsertAsync_InsertsTheRow_WhenItemHasNullValues()
        {
            TestUtilities.DropTestTable(TestDbName, TestTable);

            // insert a row and make sure it is inserted
            using (var store = new MobileServiceSQLiteStore(TestDbName))
            {
                store.DefineTable(TestTable, new JObject()
                {
                    { "id", String.Empty },
                    { "dob", DateTime.UtcNow },
                    { "age", 0 },
                    { "weight", 3.5 },
                    { "code", Guid.NewGuid() },
                    { "options", new JObject()
                      {
                      } },
                    { "friends", new JArray()
                      {
                      } },
                    { "__version", String.Empty }
                });

                await store.InitializeAsync();

                var inserted = new JObject()
                {
                    { "id", "abc" },
                    { "dob", null },
                    { "age", null },
                    { "weight", null },
                    { "code", null },
                    { "options", null },
                    { "friends", null },
                    { "__version", null }
                };
                await store.UpsertAsync(TestTable, new[] { inserted }, ignoreMissingColumns : false);

                JObject read = await store.LookupAsync(TestTable, "abc");

                Assert.AreEqual(inserted.ToString(), read.ToString());
            }
        }
        public async Task <bool> Initialize()
        {
            if (initializerTask != null)
            {
                return(await initializerTask.Task);
            }

            if (initializerTask == null)
            {
                initializerTask = new TaskCompletionSource <bool>();
            }

            if (Client?.SyncContext?.IsInitialized ?? false)
            {
                return(await initializerTask.Task);
            }

            Client = Locator.Current.GetService <MobileServiceClient>();

            //InitializeDatabase for path
            var path = "syncstore.db";

            path = Path.Combine(MobileServiceClient.DefaultDatabasePath, path);

            //setup our local sqlite store and intialize our table
            var store = new MobileServiceSQLiteStore(path);

            //Define table
            store.DefineTable <Category>();
            store.DefineTable <ShoppingItem>();
            store.DefineTable <MealItem>();

            //Initialize SyncContext
            await Client.SyncContext.InitializeAsync(store);

            //Get our sync table that will call out to azure
            CategoryTable     = Client.GetSyncTable <Category>();
            ShoppingItemTable = Client.GetSyncTable <ShoppingItem>();
            MealItemTable     = Client.GetSyncTable <MealItem>();

            initializerTask.SetResult(true);
            return(initializerTask.Task.Result);
        }
Example #33
0
        public async Task UpsertAsync_DoesNotThrow_WhenItemIsEmpty()
        {
            TestUtilities.DropTestTable(TestDbName, TestTable);

            using (var store = new MobileServiceSQLiteStore(TestDbName))
            {
                store.DefineTable(TestTable, new JObject()
                {
                    { "id", String.Empty },
                    { "dob", DateTime.UtcNow }
                });

                await store.InitializeAsync();

                await store.UpsertAsync(TestTable, new[] { new JObject() }, ignoreMissingColumns : true);

                await store.UpsertAsync(TestTable, new[] { new JObject() }, ignoreMissingColumns : false);
            }
        }
        public async Task LookupAsync_ReadsItem()
        {
            await PrepareTodoTable();

            long date = (long)(testDate - epoch).TotalSeconds;

            // insert a row and make sure it is inserted
            TestUtilities.ExecuteNonQuery(TestDbName, "INSERT INTO todo (id, createdAt) VALUES ('abc', " + date + ")");
            long count = TestUtilities.CountRows(TestDbName, TestTable);
            Assert.AreEqual(count, 1L);

            using (var store = new MobileServiceSQLiteStore(TestDbName))
            {
                DefineTestTable(store);
                await store.InitializeAsync();

                JObject item = await store.LookupAsync(TestTable, "abc");
                Assert.IsNotNull(item);
                Assert.AreEqual(item.Value<string>("id"), "abc");
                Assert.AreEqual(item.Value<DateTime>("createdAt"), testDate);
            }
        }
        public async Task UpsertAsync_ThenReadAsync_AllTypes()
        {
            TestUtilities.DropTestTable(TestDbName, TestTable);

            // first create a table called todo
            using (MobileServiceSQLiteStore store = new MobileServiceSQLiteStore(TestDbName))
            {
                store.DefineTable(TestTable, JObjectTypes.GetObjectWithAllTypes());

                await store.InitializeAsync();

                var upserted = new JObject()
                {
                    { "id", "xyz" },
                    { "Object", new JObject() { {"id", "abc"} }},
                    { "Array", new JArray() { new JObject(){{"id", 3}} } },
                    { "Integer", 123L },
                    { "Float", 12.5m },
                    { "String", "def" },
                    { "Boolean", true },
                    { "Date", new DateTime(2003, 5, 6, 4, 5, 1, DateTimeKind.Utc) },
                    { "Bytes", new byte[] { 1, 2, 3} },
                    { "Guid", new Guid("AB3EB1AB-53CD-4780-928B-A7E1CB7A927C") },
                    { "TimeSpan", new TimeSpan(1234) }
                };
                await store.UpsertAsync(TestTable, new[] { upserted }, false);

                var query = new MobileServiceTableQueryDescription(TestTable);
                var items = await store.ReadAsync(query) as JArray;
                Assert.IsNotNull(items);
                Assert.AreEqual(items.Count, 1);

                var lookedup = items.First as JObject;
                Assert.AreEqual(upserted.ToString(Formatting.None), lookedup.ToString(Formatting.None));
            }
        }
        public async Task UpsertAsync_InsertsTheRow_WhenItDoesNotExist()
        {
            await PrepareTodoTable();

            // insert a row and make sure it is inserted
            using (var store = new MobileServiceSQLiteStore(TestDbName))
            {
                DefineTestTable(store);
                await store.InitializeAsync();
                await store.UpsertAsync(TestTable, new[]{new JObject() 
                { 
                    { "id", "abc" }, 
                    { "createdAt", DateTime.Now } 
                }}, ignoreMissingColumns: false);
            }
            long count = TestUtilities.CountRows(TestDbName, TestTable);
            Assert.AreEqual(count, 1L);
        }
 public static void DefineTestTable(MobileServiceSQLiteStore store)
 {
     store.DefineTable(TestTable, new JObject()
     {
         { "id", String.Empty },
         { "text", String.Empty },
         { "createdAt", DateTime.Now }
     });
 }
        public async Task UpsertAsync_Throws_WhenColumnInItemIsNotDefinedAndItIsLocal()
        {
            TestUtilities.DropTestTable(TestDbName, TestTable);

            using (var store = new MobileServiceSQLiteStore(TestDbName))
            {
                store.DefineTable(TestTable, new JObject()
                {
                    { "id", String.Empty },
                    { "dob", DateTime.UtcNow }
                });

                await store.InitializeAsync();

                var ex = await ThrowsAsync<InvalidOperationException>(() => store.UpsertAsync(TestTable, new[] { new JObject() { { "notDefined", "okok" } } }, ignoreMissingColumns: false));

                Assert.AreEqual(ex.Message, "Column with name 'notDefined' is not defined on the local table 'todo'.");
            }
        }
 private void TestStoreThrowOnUninitialized(Action<MobileServiceSQLiteStore> storeAction)
 {
     var store = new MobileServiceSQLiteStore(TestDbName);
     var ex = Throws<InvalidOperationException>(() => storeAction(store));
     Assert.AreEqual(ex.Message, "The store must be initialized before it can be used.");
 }
        public async Task UpsertAsync_CanProcessManyRecordsAtOnce()
        {
            TestUtilities.DropTestTable(TestDbName, TestTable);

            using (var store = new MobileServiceSQLiteStore(TestDbName))
            {
                var template = new JObject 
                {
                    { "id", 0 },
                    { "value1", "Hello, world" },
                    { "value2", "Hello, world" },
                    { "value3", "Hello, world" },
                    { "value4", "Hello, world" },
                    { "value5", "Hello, world" }
                };

                store.DefineTable(TestTable, template);

                //create the table
                await store.InitializeAsync();

                //add a whole bunch of items. We want {number of items} * {number of fields} to exceed sqlite's parameter limit
                const int insertedItemCount = 500;

                var itemsToInsert = Enumerable.Range(1, insertedItemCount)
                                              .Select(id =>
                                              {
                                                  var o = new JObject(template);
                                                  o["id"] = id;
                                                  return o;
                                              })
                                              .ToArray();

                //Insert the items
                await store.UpsertAsync(TestTable, itemsToInsert, ignoreMissingColumns: false);

                JArray records = (JArray)await store.ReadAsync(MobileServiceTableQueryDescription.Parse(TestTable, "$orderby=id"));

                //Verify that all 500 records were inserted
                Assert.AreEqual(records.Count, insertedItemCount);

                //Verify that all fields are intact
                for (var i = 0; i < insertedItemCount; i++)
                {
                    Assert.IsTrue(JToken.DeepEquals(itemsToInsert[i], records[i]), "Results retrieved from DB do not match input");
                }
            }
        }
        public async Task Upsert_ThenLookup_ThenUpsert_ThenDelete_ThenLookup()
        {
            TestUtilities.DropTestTable(TestDbName, TestTable);

            using (var store = new MobileServiceSQLiteStore(TestDbName))
            {
                // define item with all type of supported fields
                var originalItem = new JObject()
                {
                    { "id", "abc" },
                    { "bool", true },
                    { "int", 45 },
                    { "double", 123.45d },
                    { "guid", Guid.NewGuid() },
                    { "date", testDate },
                    { "options", new JObject(){ {"class", "A"} } },  
                    { "friends", new JArray(){ "Eric", "Jeff" } }
                };
                store.DefineTable(TestTable, originalItem);

                // create the table
                await store.InitializeAsync();

                // first add an item
                await store.UpsertAsync(TestTable, new[] { originalItem }, ignoreMissingColumns: false);

                // read the item back
                JObject itemRead = await store.LookupAsync(TestTable, "abc");

                // make sure everything was persisted the same
                Assert.AreEqual(originalItem.ToString(), itemRead.ToString());

                // change the item
                originalItem["double"] = 111.222d;

                // upsert the item
                await store.UpsertAsync(TestTable, new[] { originalItem }, ignoreMissingColumns: false);

                // read the updated item
                JObject updatedItem = await store.LookupAsync(TestTable, "abc");

                // make sure the float was updated
                Assert.AreEqual(updatedItem.Value<double>("double"), 111.222d);

                // make sure the item is same as updated item
                Assert.AreEqual(originalItem.ToString(), updatedItem.ToString());

                // make sure item is not same as its initial state
                Assert.AreNotEqual(originalItem.ToString(), itemRead.ToString());

                // now delete the item
                await store.DeleteAsync(TestTable, new[] { "abc" });

                // now read it back
                JObject item4 = await store.LookupAsync(TestTable, "abc");

                // it should be null because it doesn't exist
                Assert.IsNull(item4);
            }
        }
        public async Task UpsertAsync_Throws_WhenInsertingRecordsWhichAreTooLarge()
        {
            TestUtilities.DropTestTable(TestDbName, TestTable);

            using (var store = new MobileServiceSQLiteStore(TestDbName))
            {
                var template = new JObject
                {
                    { "id", 0 },
                };

                //SQLite limits us to 999 "parameters" per prepared statement
                for (var i = 0; i < 1000; i++)
                {
                    template["column" + i] = "Hello, world";
                }

                store.DefineTable(TestTable, template);

                //create the table
                await store.InitializeAsync();

                //attempt to insert a couple of items
                var item1 = new JObject(template);
                item1["id"] = 1;

                var item2 = new JObject(template);
                item1["id"] = 2;

                InvalidOperationException ex = await AssertEx.Throws<InvalidOperationException>(() => store.UpsertAsync(TestTable, new[] { item1, item2 }, ignoreMissingColumns: false));

                Assert.AreEqual("The number of fields per entity in an upsert operation is limited to 800.", ex.Message);
            }
        }
        public async Task UpsertAsync_DoesNotThrow_WhenItemIsEmpty()
        {
            TestUtilities.DropTestTable(TestDbName, TestTable);

            using (var store = new MobileServiceSQLiteStore(TestDbName))
            {
                store.DefineTable(TestTable, new JObject()
                {
                    { "id", String.Empty },
                    { "dob", DateTime.UtcNow }
                });

                await store.InitializeAsync();

                await store.UpsertAsync(TestTable, new[] { new JObject() }, ignoreMissingColumns: true);
                await store.UpsertAsync(TestTable, new[] { new JObject() }, ignoreMissingColumns: false);
            }
        }
        public async Task UpsertAsync_UpdatesTheRow_WhenItExists()
        {
            await PrepareTodoTable();

            // insert a row and make sure it is inserted
            using (var store = new MobileServiceSQLiteStore(TestDbName))
            {
                DefineTestTable(store);
                await store.InitializeAsync();

                await store.UpsertAsync(TestTable, new[]{new JObject() 
                { 
                    { "id", "abc" }, 
                    { "text", "xyz" },
                    { "createdAt", DateTime.Now } 
                }}, ignoreMissingColumns: false);

                await store.UpsertAsync(TestTable, new[]{new JObject() 
                { 
                    { "id", "abc" }, 
                    { "createdAt", new DateTime(200,1,1) } 
                }}, ignoreMissingColumns: false);

                JObject result = await store.LookupAsync(TestTable, "abc");

                Assert.AreEqual(result.Value<string>("id"), "abc");
                Assert.AreEqual(result.Value<string>("text"), "xyz");
                Assert.AreEqual(result.Value<string>("createdAt"), "01/01/0200 00:00:00");
            }
            long count = TestUtilities.CountRows(TestDbName, TestTable);
            Assert.AreEqual(count, 1L);
        }
        public async Task DeleteAsync_DeletesTheRow()
        {
            await PrepareTodoTable();

            // insert a row and make sure it is inserted
            TestUtilities.ExecuteNonQuery(TestDbName, "INSERT INTO todo (id, createdAt) VALUES ('abc', 123)");
            long count = TestUtilities.CountRows(TestDbName, TestTable);
            Assert.AreEqual(count, 1L);

            // delete the row
            using (var store = new MobileServiceSQLiteStore(TestDbName))
            {
                DefineTestTable(store);
                await store.InitializeAsync();
                await store.DeleteAsync(TestTable, new[] { "abc" });
            }

            // rows should be zero now
            count = TestUtilities.CountRows(TestDbName, TestTable);
            Assert.AreEqual(count, 0L);
        }
        private static async Task PrepareTodoTable()
        {
            TestUtilities.DropTestTable(TestDbName, TestTable);

            // first create a table called todo
            using (MobileServiceSQLiteStore store = new MobileServiceSQLiteStore(TestDbName))
            {
                DefineTestTable(store);

                await store.InitializeAsync();
            }
        }
        public async Task ReadAsync_ReadsItems()
        {
            await PrepareTodoTable();

            // insert rows and make sure they are inserted
            TestUtilities.ExecuteNonQuery(TestDbName, "INSERT INTO todo (id, createdAt) VALUES ('abc', 1), ('def', 2), ('ghi', 3)");
            long count = TestUtilities.CountRows(TestDbName, TestTable);
            Assert.AreEqual(count, 3L);

            using (var store = new MobileServiceSQLiteStore(TestDbName))
            {
                DefineTestTable(store);
                await store.InitializeAsync();

                var query = MobileServiceTableQueryDescription.Parse(TestTable, "$filter=createdAt gt 1&$inlinecount=allpages");
                JToken item = await store.ReadAsync(query);
                Assert.IsNotNull(item);
                var results = item["results"].Value<JArray>();
                long resultCount = item["count"].Value<long>();

                Assert.AreEqual(results.Count, 2);
                Assert.AreEqual(resultCount, 2L);
            }
        }
        public async Task UpsertAsync_InsertsTheRow_WhenItemHasNullValues()
        {
            TestUtilities.DropTestTable(TestDbName, TestTable);

            // insert a row and make sure it is inserted
            using (var store = new MobileServiceSQLiteStore(TestDbName))
            {
                store.DefineTable(TestTable, new JObject()
                {
                    { "id", String.Empty },
                    { "dob", DateTime.UtcNow },
                    { "age", 0},
                    { "weight", 3.5 },
                    { "code", Guid.NewGuid() },   
                    { "options", new JObject(){} },  
                    { "friends", new JArray(){} },  
                    { "version", String.Empty }
                });

                await store.InitializeAsync();

                var inserted = new JObject() 
                { 
                    { "id", "abc" }, 
                    { "dob", null },
                    { "age", null },
                    { "weight", null },
                    { "code", null }, 
                    { "options", null },  
                    { "friends", null },  
                    { "version", null }
                };
                await store.UpsertAsync(TestTable, new[] { inserted }, ignoreMissingColumns: false);

                JObject read = await store.LookupAsync(TestTable, "abc");

                Assert.AreEqual(inserted.ToString(), read.ToString());
            }
        }
        public async Task DeleteAsync_DeletesTheRow_WhenTheyMatchTheQuery()
        {
            await PrepareTodoTable();

            // insert rows and make sure they are inserted
            TestUtilities.ExecuteNonQuery(TestDbName, "INSERT INTO todo (id, createdAt) VALUES ('abc', 1), ('def', 2), ('ghi', 3)");
            long count = TestUtilities.CountRows(TestDbName, TestTable);
            Assert.AreEqual(count, 3L);

            // delete the row
            using (var store = new MobileServiceSQLiteStore(TestDbName))
            {
                DefineTestTable(store);
                await store.InitializeAsync();
                var query = MobileServiceTableQueryDescription.Parse(TestTable, "$filter=createdAt gt 1");
                await store.DeleteAsync(query);
            }

            // 1 row should be left
            count = TestUtilities.CountRows(TestDbName, TestTable);
            Assert.AreEqual(count, 1L);
        }
        private static async Task<MobileServiceSyncSettingsManager> GetSettingManager(bool resetDb = true)
        {
            if (resetDb)
            {
                TestUtilities.ResetDatabase(TestDbName);
            }

            var store = new MobileServiceSQLiteStore(TestDbName);
            await store.InitializeAsync();

            var settings = new MobileServiceSyncSettingsManager(store);
            return settings;
        }