Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// This file has been autogenerated from parsing an Objective-C header file added in Xcode.
using System;
using MonoTouch.UIKit;
using MonoTouch.Foundation;
using System.Threading.Tasks;
namespace amay077_baas_test
{
public partial class QSTodoListViewController : UITableViewController
{
QSTodoService todoService;
bool useRefreshControl = false;
public QSTodoListViewController (IntPtr handle) : base (handle)
{
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
todoService = QSTodoService.DefaultService;
todoService.BusyUpdate += (bool busy) => {
if (busy)
activityIndicator.StartAnimating ();
else
activityIndicator.StopAnimating ();
};
AddRefreshControl ();
}
public override async void ViewDidAppear(bool animated)
{
base.ViewDidAppear(animated);
if (QSTodoService.DefaultService.User == null)
{
await QSTodoService.DefaultService.LoginAndGetData(this);
}
if (QSTodoService.DefaultService.User == null)
{
// TODO:: show error
return;
}
RefreshAsync();
}
async Task RefreshAsync ()
{
// only activate the refresh control if the feature is available
if (useRefreshControl)
RefreshControl.BeginRefreshing ();
await todoService.RefreshDataAsync ();
if (useRefreshControl)
RefreshControl.EndRefreshing ();
TableView.ReloadData ();
}
#region UITableView methods
public override int RowsInSection (UITableView tableview, int section)
{
if (todoService == null || todoService.Items == null)
return 0;
return todoService.Items.Count;
}
public override int NumberOfSections (UITableView tableView)
{
return 1;
}
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
const string CellIdentifier = @"Cell";
var cell = tableView.DequeueReusableCell (CellIdentifier);
if (cell == null) {
cell = new UITableViewCell (UITableViewCellStyle.Default, CellIdentifier);
}
// Set the label on the cell and make sure the label color is black (in case this cell
// has been reused and was previously greyed out
var label = (UILabel)cell.ViewWithTag (1);
label.TextColor = UIColor.Black;
label.Text = todoService.Items [indexPath.Row].Text;
return cell;
}
public override string TitleForDeleteConfirmation (UITableView tableView, NSIndexPath indexPath)
{
// Customize the Delete button to say "complete"
return @"complete";
}
public override UITableViewCellEditingStyle EditingStyleForRow (UITableView tableView, NSIndexPath indexPath)
{
// Find the item that is about to be edited
var item = todoService.Items [indexPath.Row];
// If the item is complete, then this is just pending upload. Editing is not allowed
if (item.Complete)
return UITableViewCellEditingStyle.None;
// Otherwise, allow the delete button to appear
return UITableViewCellEditingStyle.Delete;
}
async public override void CommitEditingStyle (UITableView tableView, UITableViewCellEditingStyle editingStyle, NSIndexPath indexPath)
{
// Find item that was commited for editing (completed)
var item = todoService.Items [indexPath.Row];
// Change the appearance to look greyed out until we remove the item
var label = (UILabel)TableView.CellAt (indexPath).ViewWithTag (1);
label.TextColor = UIColor.Gray;
// Ask the todoService to set the item's complete value to YES, and remove the row if successful
await todoService.CompleteItemAsync (item);
// Remove the row from the UITableView
tableView.DeleteRows (new [] { indexPath }, UITableViewRowAnimation.Top);
}
#endregion
#region UI Actions
async partial void OnAdd (NSObject sender)
{
if (string.IsNullOrWhiteSpace (itemText.Text))
return;
var newItem = new ToDoItem {
Text = itemText.Text,
Complete = false
};
await todoService.InsertTodoItemAsync (newItem);
var index = todoService.Items.FindIndex (item => item.Id == newItem.Id);
TableView.InsertRows (new [] { NSIndexPath.FromItemSection (index, 0) },
UITableViewRowAnimation.Top);
itemText.Text = "";
}
#endregion
#region UITextFieldDelegate methods
[Export ("textFieldShouldReturn:")]
public virtual bool ShouldReturn (UITextField textField)
{
textField.ResignFirstResponder ();
return true;
}
#endregion
#region * iOS Specific Code
// This method will add the UIRefreshControl to the table view if
// it is available, ie, we are running on iOS 6+
void AddRefreshControl ()
{
if (UIDevice.CurrentDevice.CheckSystemVersion (6, 0)) {
// the refresh control is available, let's add it
RefreshControl = new UIRefreshControl ();
RefreshControl.ValueChanged += async (sender, e) => {
await RefreshAsync ();
};
useRefreshControl = true;
}
}
#endregion
}
}
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.WindowsAzure.MobileServices;
using MonoTouch.UIKit;
namespace amay077_baas_test
{
public class QSTodoService : DelegatingHandler
{
static QSTodoService instance = new QSTodoService ();
const string applicationURL = @"https://amay077-baas-test.azure-mobile.net/";
const string applicationKey = @"ECQOoXDqFtFZCeEaXBaEpBbOcTqvyx28";
MobileServiceClient client;
IMobileServiceTable<ToDoItem> todoTable;
int busyCount = 0;
public event Action<bool> BusyUpdate;
// Mobile Service logged in user
private MobileServiceUser user;
public MobileServiceUser User { get { return user; } }
QSTodoService ()
{
CurrentPlatform.Init ();
// Initialize the Mobile Service client with your URL and key
client = new MobileServiceClient (applicationURL, applicationKey, this);
}
private async Task Authenticate(UIViewController view)
{
try
{
user = await client.LoginAsync(view, MobileServiceAuthenticationProvider.Twitter);
}
catch (Exception ex)
{
Console.Error.WriteLine (@"ERROR - AUTHENTICATION FAILED {0}", ex.Message);
}
}
private async Task CreateTable()
{
// Create an MSTable instance to allow us to work with the TodoItem table
todoTable = client.GetTable<ToDoItem>();
}
public async Task LoginAndGetData(UIViewController view)
{
await Authenticate(view);
await CreateTable();
}
public static QSTodoService DefaultService {
get {
return instance;
}
}
public List<ToDoItem> Items { get; private set;}
async public Task<List<ToDoItem>> RefreshDataAsync ()
{
try {
// This code refreshes the entries in the list view by querying the TodoItems table.
// The query excludes completed TodoItems
Items = await todoTable
.Where (todoItem => todoItem.Complete == false).ToListAsync ();
} catch (MobileServiceInvalidOperationException e) {
Console.Error.WriteLine (@"ERROR {0}", e.Message);
return null;
}
return Items;
}
public async Task InsertTodoItemAsync (ToDoItem todoItem)
{
try {
// This code inserts a new TodoItem into the database. When the operation completes
// and Mobile Services has assigned an Id, the item is added to the CollectionView
await todoTable.InsertAsync (todoItem);
Items.Add (todoItem);
} catch (MobileServiceInvalidOperationException e) {
Console.Error.WriteLine (@"ERROR {0}", e.Message);
}
}
public async Task CompleteItemAsync (ToDoItem item)
{
try {
// This code takes a freshly completed TodoItem and updates the database. When the MobileService
// responds, the item is removed from the list
item.Complete = true;
await todoTable.UpdateAsync (item);
Items.Remove (item);
} catch (MobileServiceInvalidOperationException e) {
Console.Error.WriteLine (@"ERROR {0}", e.Message);
}
}
void Busy (bool busy)
{
// assumes always executes on UI thread
if (busy) {
if (busyCount++ == 0 && BusyUpdate != null)
BusyUpdate (true);
} else {
if (--busyCount == 0 && BusyUpdate != null)
BusyUpdate (false);
}
}
#region implemented abstract members of HttpMessageHandler
protected override async Task<System.Net.Http.HttpResponseMessage> SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
Busy (true);
var response = await base.SendAsync (request, cancellationToken);
Busy (false);
return response;
}
#endregion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.