How to use local database in Xamarin.form? - c#

I'm following a tutorial step by step to create a local database by using SQLite.net-PCL. However, when running the app, I tried to insert a data into the database, but it threw me a 'System.NullReferenceException'.
What I have done:
I'm only using SQLite.Net-TCL (1.2.1) package, and also added it into Android and iOS.
I noticed some tutorials saying that I should implement sqlite database on android and iOS, but I didn't find the tutorial is using this way, or maybe the IFileHelper interface has the same function?
I keep FileHelper interface in my Android folder
After debug, the database code passed. So the problem should happen when inserting data.
The exception happened at this line: if (person.ID != 0), and this line : await App.DB.SaveItemAsync(person);
Tutorial: https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/databases/
This is my database code:
using System.Threading.Tasks;
using System.Collections.Generic;
using System;
using SQLite;
namespace DatabaseDemo
{
public class Database
{
readonly SQLiteAsyncConnection _database;
public Database(string path)
{
_database = new SQLiteAsyncConnection(path);
_database.CreateTableAsync<Model>().Wait();
}
public Task<List<Model>> GetItemsAsync()
{
return _database.Table<Model>().ToListAsync();
}
public Task<int> SaveItemAsync(Model person)
{
if (person.ID != 0)
{
return _database.UpdateAsync(person);
}
else
{
return _database.InsertAsync(person);
}
}
}
}
This is my interface:
<StackLayout Margin="20" VerticalOptions="StartAndExpand">
<Label Text = "Name"/>
<Entry Text = "{Binding Name}" />
<Button Text = "Save" Clicked="OnSaveClicked" />
</StackLayout>
using Xamarin.Forms;
using System;
namespace DatabaseDemo
{
public partial class DatabaseDemoPage : ContentPage
{
public DatabaseDemoPage()
{
InitializeComponent();
}
async void OnSaveClicked(object sender, EventArgs e)
{
var person = (Model)BindingContext;
await App.DB.SaveItemAsync(person);
}
}
}
App.cs
using Xamarin.Forms;
namespace DatabaseDemo
{
public partial class App : Application
{
static Database database;
public static Database DB
{
get
{
if (database == null)
{
database = new Database(DependencyService.Get<IFileHelper>().GetLocalFilePath("db.db3"));
}
return database;
}
}
public App()
{
InitializeComponent();
MainPage = new DatabaseDemoPage();
}
}
}
I also created a public interface, and also created for Andriod and iOS.
using System;
namespace DatabaseDemo
{
public interface IFileHelper
{
string GetLocalFilePath(string filename);
}
}

You have to create Android side...
[assembly: Dependency(typeof(FileHelper))]
namespace Todo.Droid
{
public class FileHelper : IFileHelper
{
public string GetLocalFilePath(string filename)
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
return Path.Combine(path, filename);
}
}
}
Here all info
Once the interface has been defined, use the DependencyService to obtain an implementation and get a local file path (note that this interface has not been implemented yet). The following code gets an implementation in the App.Database property:
static TodoItemDatabase database;
public static TodoItemDatabase Database
{
get
{
if (database == null)
{
database = new TodoItemDatabase(DependencyService.Get<IFileHelper>().GetLocalFilePath("TodoSQLite.db3"));
}
return database;
}
}
The TodoItemDatabase constructor is shown below:
public TodoItemDatabase(string dbPath)
{
database = new SQLiteAsyncConnection(dbPath);
database.CreateTableAsync<TodoItem>().Wait();
}
This approach creates a single database connection that is kept open while the application runs, therefore avoiding the expense of opening and closing the database file each time a database operation is performed.

Solved by the following code:
public DatabaseDemoPage()
{
InitializeComponent();
this.BindingContext = new Model();
}

Related

How to use MongoDB connection globally

My API is on .net mvc c# platform. I am using mongo DB to drop and store data the following way. It is not working properly when I try to drop and insert data concurrently. The connections are multiplying and the requests are not executed in the same order. How can I use the MongoDB in a global class with only one connection open? do give some reference to look into.
public static string DB= DBConnection.MongoDB;
public bool Insert(Data data)
{
try
{
var con = new MongoClient(DBConnection.ConnectionString);
var db = con.GetDatabase(DB);
db.InsertOne(data);
return true;
}
catch (Exception exception)
{
}
}
using System.Configuration;
namespace DataAccess.Implementations
{
internal class DBConnection
{
#region ConnectionString
public static string ConnectionString { get { return ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString; } }
#endregion
#region Database
public static string MongoDB{ get { return ConfigurationManager.AppSettings["MongoDB"].ToString(); } }
#endregion
}
}
Try using a Singleton pattern:
https://social.msdn.microsoft.com/Forums/en-US/9e152212-2109-4d07-adbf-4ff0326c077b/how-to-establish-db-connection-using-singleton-pattern?forum=csharpgeneral
Singleton design pattern is preferred to get a DB Connection

Why is my Azure mobile app not returning any data?

I have been following a tutorial about Azure Mobile Apps'Easy Tables (https://blog.xamarin.com/getting-started-azure-mobile-apps-easy-tables/). Everything has been going quite well and I managed to get to the point of testing my app which doesn't seem to return any data and I don't know why, I don't recieve any errors either which is making the tracing of this problem more difficult.
Ok to start with I have my Azure database (configured to allow access to Azure Services) and I have my table created and working using EasyTables. I used the Postman (https://www.getpostman.com/) application to test my API and to ensure data was returned from my database using https://myproject.azurewebsites.net/tables/users which returned my data as json.
My database table is called users and it's structure is quite basic (for testing) with two columns id and FirstName. I have populated my table with dummy data which I have proven can be returned from my azure uri using Postman.
That's the ground work to get running, here is a snapshot of my project hierarchy.
MyProject/Model/users.cs
This is the entity data which is named to match the table in the database.
using System;
using Microsoft.WindowsAzure.MobileServices;
using Newtonsoft.Json;
namespace MyProject
{
public class users
{
[JsonProperty(PropertyName = "Id")]
public string id { get; set; }
public string FirstName {get; set; }
}
}
MyProject/Services/AzureService.cs
Crucially we have public async Task<IEnumerable<users>> GetUsers() task here which is and triggers Inialization task (which is where the app url is defined).
using System;
using Microsoft.WindowsAzure.MobileServices;
using Microsoft.WindowsAzure.MobileServices.Sync;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.WindowsAzure.MobileServices.SQLiteStore;
using System.Diagnostics;
using Xamarin.Forms;
using MyProject;
using System.IO;
using Plugin.Connectivity;
[assembly: Dependency(typeof(AzureService))]
namespace MyProject
{
public class AzureService
{
public MobileServiceClient Client { get; set; } = null;
IMobileServiceSyncTable<users> userTable;
public async Task Initialize()
{
if (Client?.SyncContext?.IsInitialized ?? false)
return;
var appUrl = "https://myproject.azurewebsites.net";
//Create our client
Client = new MobileServiceClient(appUrl);
//InitialzeDatabase 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<users>();
//Initialize SyncContext
await Client.SyncContext.InitializeAsync(store);
//Get our sync table that will call out to azure
userTable = Client.GetSyncTable<users>();
}
public async Task SyncUsers()
{
try
{
await userTable.PullAsync("allUsers", userTable.CreateQuery());
await Client.SyncContext.PushAsync();
}
catch (Exception ex)
{
Debug.WriteLine("Unable to sync users, that is alright as we have offline capabilities: " + ex);
}
}
//
//Get Users
public async Task<IEnumerable<users>> GetUsers()
{
await Initialize();
await SyncUsers();
return await userTable.ToEnumerableAsync(); ;
}
}
}
MyProject/View/UserList.xaml
I kept this short and minimalistic for the purposes of testing. A simple list with it's source set to UsersList (which is an Observable collection within the ViewModel). Each item in the list is bound to FirstName.
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:MyProject;assembly=MyProject"
x:Class="MyProject.UserList"
Title="UserList">
<ListView x:Name="userList"
ItemsSource="{Binding UsersList}"
IsRefreshing="{Binding IsBusy, Mode=OneWay}"
RefreshCommand="{Binding LoadUsersCommand}"
Grid.Row="1">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout HorizontalOptions="StartAndExpand" Orientation="Horizontal" Padding="15,5,0,0">
<StackLayout Padding="5,0,0,0" VerticalOptions="StartAndExpand" Orientation="Vertical">
<Label Text="{Binding FirstName}" />
</StackLayout>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentPage>
MyProject/View/UserList.xaml.cs
This simply states that UserList is bound to the viewmodel and when the list appears trigger the load users command from within the viewmodel.
using System;
using System.Collections.Generic;
using Plugin.Connectivity;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace MyProject
{
public partial class UserList : ContentPage
{
UsersViewModel vm;
public UserList()
{
InitializeComponent();
BindingContext = vm = new UsersViewModel();
}
protected override async void OnAppearing()
{
base.OnAppearing();
vm.LoadUsersCommand.Execute(null);
}
}
}
MyProject/ViewModel/UsersViewModel.cs
This file does the most work, the view model has the observable defined and the Load Users command too.
using System;
using MvvmHelpers;
using System.Windows.Input;
using System.Threading.Tasks;
using System.Diagnostics;
using Xamarin.Forms;
using System.Linq;
using Microsoft.WindowsAzure.MobileServices;
namespace MyProject
{
public class UsersViewModel : BaseViewModel
{
AzureService azureService;
public UsersViewModel()
{
azureService = DependencyService.Get<AzureService>();
}
public ObservableRangeCollection<users> UserList { get; } = new ObservableRangeCollection<users>();
string loadingMessage;
public string LoadingMessage
{
get { return loadingMessage; }
set { SetProperty(ref loadingMessage, value); }
}
ICommand loadUsersCommand;
public ICommand LoadUsersCommand =>
loadUsersCommand ?? (loadUsersCommand = new Command(async () => await ExecuteLoadUsersCommandAsync()));
async Task ExecuteLoadUsersCommandAsync()
{
try
{
LoadingMessage = "Loading Users...";
IsBusy = true;
var users = await azureService.GetUsers();
UserList.ReplaceRange(users);
}
catch (Exception ex)
{
Debug.WriteLine("OH NO!" + ex);
await Application.Current.MainPage.DisplayAlert("Sync Error", "Unable to sync users, you may be offline", "OK");
}
finally
{
IsBusy = false;
}
}
}
}
I popped a few break points in when I run the app to see if I can get to the bottom of the problem, the lack of error means I have no frame of reference to work from.
The current order in which events are triggering is as follows (based on breakpoints I put in):
public ObservableRangeCollection<users> UserList { get; } = new ObservableRangeCollection<users>(); - UserViewModel
azureService = DependencyService.Get<AzureService>(); - UserViewModel
var users = await azureService.GetUsers(); - UserViewModel
await Initialize(); - AzureService
public async Task Initialize() - AzureService
await SyncUsers(); - AzureServce
public async Task SyncUsers() - AzureService
return await userTable.ToEnumerableAsync(); ; - AzureService
UserList.ReplaceRange(users); - UserViewModel
The list is then loaded on my MacBook pro using the simulator but it's empty, no data at all. Can anyone help me understand why I can't get my data? Are their break points I should put in place and check if certain items exist?
Like I say without an actual error this is a tough one but it could also be something really simple, any help is appreciated.
Update
Further to my initial investigation I've added an if statement to my code, specifically within the OnAppearing method in UserList.xaml.cs. The code I added checks of the UserList collection in UserViewModel.cs is 0 or not.
protected override async void OnAppearing()
{
base.OnAppearing();
if (vm.UserList.Count == 0)
vm.LoadUsersCommand.Execute(null);
else
{
...
}
vm.LoadUsersCommand.Execute(null);
}
What is interesting about this is that the UserList is always coming back with 0. So the problem looks like it's in this line of code which sits in UsersViewModel.cs
public ObservableRangeCollection<users> UserList { get; } = new ObservableRangeCollection<users>();
What could be causing this?
The only thing I can see is that you have the id column renamed to Id - on the client, it needs to be id (lower-case).
There are a couple of other mistakes in there, but they should be readily found with a debugger. I see one of them has already been pointed out.

Convert windows form application to Asp lr console application

I am using vs 2017rc and I have compatibility issues. I can't add windows form doll to my project and when I try to convert the code from win forms to Asp k get issues. Maybe I am doing it wrong but it seem to work on vs2015.
Please I need help to solve this. Maybe I am doing it wrong. See the code below.
using DotNetBrowser;
using DotNetBrowser.WinForms;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Windows.Forms;
namespace GetAjaxResponseBodySample
{
public partial class Form1 : Form
{
private static List<string> ajaxUrls = new List<string>();
private WinFormsBrowserView browserView;
public Form1()
{
InitializeComponent();
browserView = new WinFormsBrowserView();
browserView.Browser.Context.NetworkService.ResourceHandler = new AjaxResourceHandler();
browserView.Browser.Context.NetworkService.NetworkDelegate = new AjaxNetworkDelegate();
Controls.Add(browserView);
browserView.Browser.LoadURL("http://www.w3schools.com/xml/ajax_examples.asp");
}
private class AjaxResourceHandler : ResourceHandler
{
public bool CanLoadResource(ResourceParams parameters)
{
if (parameters.ResourceType == ResourceType.XHR)
{
Debug.WriteLine("Intercepted AJAX request: " + parameters.URL);
ajaxUrls.Add(parameters.URL);
}
return true;
}
}
private class AjaxNetworkDelegate : DefaultNetworkDelegate
{
public override void OnDataReceived(DataReceivedParams parameters)
{
if (ajaxUrls.Contains(parameters.Url))
{
Debug.WriteLine("Captured response for: " + parameters.Url);
Debug.WriteLine("MimeType = " + parameters.MimeType);
Debug.WriteLine("Charset = " + parameters.Charset);
PrintResponseData(parameters.Data);
}
}
private void PrintResponseData(byte[] data) {
Debug.WriteLine("Data = ");
var str = Encoding.Default.GetString(data);
Debug.WriteLine(str);
}
}
}
Am not concerned with the browser view... I already get the Jason I need from the Ajax response body.
It is possible to use Browser in a headless mode without creating BrowserView at all.
The following sample code works in the web application on VS2017rc with ASP.NET Core Web Application (.NET Framework) or ASP.NET Web Application (.NET Framework).
Please take into account that it is necessary to Dispose browser after the response body has been captured.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using DotNetBrowser;
using System.Diagnostics;
using System.Text;
namespace WebApplication7.Controllers
{
public class HomeController : Controller
{
private static List<string> ajaxUrls = new List<string>();
Browser browser;
public string Index()
{
Init();
return "Test page";
}
private void Init()
{
browser = BrowserFactory.Create();
browser.Context.NetworkService.ResourceHandler = new AjaxResourceHandler();
browser.Context.NetworkService.NetworkDelegate = new AjaxNetworkDelegate();
browser.LoadURL("https://www.w3schools.com/xml/ajax_examples.asp");
}
private class AjaxResourceHandler : ResourceHandler
{
public bool CanLoadResource(ResourceParams parameters)
{
if (parameters.ResourceType == ResourceType.XHR)
{
Debug.WriteLine("Intercepted AJAX request: " + parameters.URL);
ajaxUrls.Add(parameters.URL);
}
return true;
}
}
private class AjaxNetworkDelegate : DefaultNetworkDelegate
{
public override void OnDataReceived(DataReceivedParams parameters)
{
if (ajaxUrls.Contains(parameters.Url))
{
Debug.WriteLine("Captured response for: " + parameters.Url);
Debug.WriteLine("MimeType = " + parameters.MimeType);
Debug.WriteLine("Charset = " + parameters.Charset);
PrintResponseData(parameters.Data);
}
}
private void PrintResponseData(byte[] data)
{
Debug.WriteLine("Data = ");
var str = Encoding.UTF8.GetString(data);
Debug.WriteLine(str);
}
}
}
}

Xamarin.Forms Connecting to Web Services

Good Day Everyone. I'm creating a simple Xamarin.Forms Portable Application in my Visual Studio 2015.
I want my Mobile Application to connect to the SQL Database I have in my VS2015 and return a LIST OF CUSTOMERS which should be display to my mobile phone.
I have created a Xamarin Portable project and a WebForms project that will handle my Web Services and Database.
In my WebForms project, I created a Controller that should return the List of Customers. This has a web service URL api/Customer that I used to connect to the RestClient in my Xamarin Portable. I also have CustomerViewModel that should represent the data in my application.
In my Xamarin Portable project, I have a ClientList.xaml that should display the List that comes from my database. I also have a CustomerVM that is connected to Services and my RestClient. My RestClient used the WEB SERVICE URL to get the List of Customer from my WebForms project.
Based on the given steps above, I still wasn't able to display the Data in my mobile phone. What do you think is the reason behind this? Thanks for your help.
Here are some of my codes:
RestClient.cs
public class RestClient_Customer<T>
{
private const string WebServiceUrl = "http://localhost:50857/api/Customer/";
public async Task<List<T>> GetCustomerAsync()
{
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var json = await httpClient.GetStringAsync(WebServiceUrl);
var taskModels = JsonConvert.DeserializeObject<List<T>>(json);
return taskModels;
}
}
CustomerServices.cs
using Plugin.RestClient;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using XamarinFormsDemo.Models;
namespace XamarinFormsDemo.Services
{
public class CustomerServices
{
public async Task<List<Customer>> GetCustomerAsync()
{
RestClient_Customer<Customer> restClient = new RestClient_Customer<Customer>();
var customerList = await restClient.GetCustomerAsync(); //yung getasync ay pantawag as restclient
return customerList;
}
}
}
CustomerVM.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;
using XamarinFormsDemo.Models;
using XamarinFormsDemo.Services;
using XamarinFormsDemo.Views;
namespace XamarinFormsDemo.ViewModels
{
public class CustomerVM : INotifyPropertyChanged
{
private List<Customer> _customerList; // keep all customers
private List<Customer> _searchedCustomerList; // keep a copy for searching
private Customer _selectedCustomer = new Customer();
private string _keyword = "";
public string Keyword
{
get
{
return _keyword;
}
set
{
this._keyword = value;
// while keyword changed we filter Employees
//Filter();
}
}
private void Filter()
{
if (string.IsNullOrWhiteSpace(_keyword))
{
CustomerList = _searchedCustomerList;
}
else
{
// var lowerKeyword = _keyword.ToLower();
CustomerList = _searchedCustomerList.Where(r => r.CUSTOMER_NAME.ToLower().Contains(_keyword.ToLower())).ToList();
// EmployeesList = _searchedEmployeesList.Where(r => r.EMPLOYEE_NAME.Contains(_keyword)).ToList();
}
}
public List<Customer> CustomerList
{
get
{
return _customerList;
}
set
{
_customerList = value;
OnPropertyChanged();
}
}
public CustomerVM()
{
InitializeDataAsync();
}
private async Task InitializeDataAsync()
{
var customerServices = new CustomerServices();
_searchedCustomerList = await customerServices.GetCustomerAsync();
CustomerList = await customerServices.GetCustomerAsync();
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
I think the problem is in your services hope this will help you,
public interface ICustomer
{
Task<string> GetCustomers();
}
public class CustomerService : ICustomer
{
public async Task<string> GetCustomers()
{
var client = new HttpClient();
var response = await client.GetAsync(string.Format("http://mysite/api/Customer"));
var responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
}
Call it anywhere you like
var _custList = new GetCustomers();
var returnJson = await _custList.GetCustomers();
Note the return is json string format or xml format depending on your REST API so you need to parse this first before you can get the value and display it to ListView
Try running it in UWP. If it works in UWP then you have to take a look at
Xamarin HttpClient.GetStringAsync not working on Xamarin.Droid
I had the same issue but when I tried it in UWP it worked fine. I am still seeking for the solution to run xamarin.android using device.

Azure mobile service - accessing a table controller from another custom controller

I am trying to access a table using its controller from another controller method.
But when the method tries to call the table controller method I get an exception:
Exception=System.NullReferenceException: Object reference not set to an instance of an object. at Microsoft.WindowsAzure.Mobile.Service.TableController.....
I manage to access the table controller method from the web API and execute it successfully.
I tried the same thing with TodoItem given as an example by the initial mobile service.
After several publishes to the server trying to fix the issue the web API stopped working and I get this exception : An exception of type 'Microsoft.WindowsAzure.MobileServices.MobileServiceInvalidOperationException' occurred in mscorlib.dll but was not handled in user code
Additional information: The request could not be completed. (Internal Server Error) I managed to solve it when I reopened a mobile service and database with the exact same code that didn't work.
Any tips ?
Here is my table controller created by the controller wizard:
using System.Linq;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.OData;
using Microsoft.WindowsAzure.Mobile.Service;
using FringProjectMobileService.DataObjects;
using FringProjectMobileService.Models;
namespace FringProjectMobileService.Controllers
{
public class StorageItemController : TableController<StorageItem>
{
protected override void Initialize(HttpControllerContext controllerContext)
{
base.Initialize(controllerContext);
FringProjectMobileServiceContext context = new FringProjectMobileServiceContext();
DomainManager = new EntityDomainManager<StorageItem>(context, Request, Services);
}
// GET tables/StorageItem
public IQueryable<StorageItem> GetAllStorageItem()
{
return Query();
}
// GET tables/StorageItem/xxxxxxxxxx
public SingleResult<StorageItem> GetStorageItem(string id)
{
return Lookup(id);
}
// PATCH tables/StorageItem/xxxxxxxx
public Task<StorageItem> PatchStorageItem(string id, Delta<StorageItem> patch)
{
return UpdateAsync(id, patch);
}
// POST tables/StorageItem
public async Task<IHttpActionResult> PostStorageItem(StorageItem item)
{
StorageItem current = await InsertAsync(item);
return CreatedAtRoute("Tables", new { id = current.Id }, current);
}
// DELETE tables/StorageItem/xxxxxxxxxx
public Task DeleteStorageItem(string id)
{
return DeleteAsync(id);
}
}
}
Below the other controller code trying to access the method:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Microsoft.WindowsAzure.Mobile.Service;
namespace FringProjectMobileService.Controllers
{
public class ArduinoController : ApiController
{
public ApiServices Services { get; set; }
// GET api/Arduino
public string Get()
{
Services.Log.Info("Hello from custom controller!");
return "Hello";
}
public async void PostProcessTag(String id)
{
Microsoft.WindowsAzure.MobileServices.MobileServiceClient client = new Microsoft.WindowsAzure.MobileServices.MobileServiceClient("http://some-service.azure-mobile.net", "XXXXXXXXXXXXXXX");
Microsoft.WindowsAzure.MobileServices.IMobileServiceTable<DataObjects.StorageItem> storage_item_table = client.GetTable<DataObjects.StorageItem>();
await storage_item_table.ToEnumerableAsync();
}
}
}
I also tried a different implementation for the method :
public void PostProcessTag(String id)
{
StorageItemController table_controller = new StorageItemController();
IQueryable<DataObjects.StorageItem> item = table_controller.GetAllStorageItem();
}
The service context:
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using Microsoft.WindowsAzure.Mobile.Service;
using Microsoft.WindowsAzure.Mobile.Service.Tables;
namespace FringProjectMobileService.Models
{
public class FringProjectMobileServiceContext : DbContext
{
// You can add custom code to this file. Changes will not be overwritten.
//
// If you want Entity Framework to alter your database
// automatically whenever you change your model schema, please use data migrations.
// For more information refer to the documentation:
// http://msdn.microsoft.com/en-us/data/jj591621.aspx
//
// To enable Entity Framework migrations in the cloud, please ensure that the
// service name, set by the 'MS_MobileServiceName' AppSettings in the local
// Web.config, is the same as the service name when hosted in Azure.
private const string connectionStringName = "Name=MS_TableConnectionString";
public FringProjectMobileServiceContext() : base(connectionStringName)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
string schema = ServiceSettingsDictionary.GetSchemaName();
if (!string.IsNullOrEmpty(schema))
{
modelBuilder.HasDefaultSchema(schema);
}
modelBuilder.Conventions.Add(
new AttributeToColumnAnnotationConvention<TableColumnAttribute, string>(
"ServiceTableColumn", (property, attributes) => attributes.Single().ColumnType.ToString()));
}
public System.Data.Entity.DbSet<FringProjectMobileService.DataObjects.StorageItem> StorageItems { get; set; }
}
}

Categories