如何解决移动应用程序如何与Azure后端Web应用程序“对话”
我是一名初学者的移动应用程序开发人员,我不了解移动应用程序如何确切地通过azure后端Web应用程序请求某些SQL查询。
我在XamarinForms中有一个示例TodoItem移动应用程序,
与Azure SQL数据库连接的后端Web应用。
一个人如何与另一个人交谈以接收自定义查询或存储过程? 2已经“连接”了,但是我不知道如何更改代码(c#)以运行不同的查询/存储过程。
后端Web应用代码:
using System.Linq;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.OData;
using Microsoft.Azure.Mobile.Server;
using ZUMOAPPNAMEService.DataObjects;
using ZUMOAPPNAMEService.Models;
namespace ZUMOAPPNAMEService.Controllers
{
public class TodoItemController : TableController<TodoItem>
{
protected override void Initialize(HttpControllerContext controllerContext)
{
base.Initialize(controllerContext);
ZUMOAPPNAMEContext context = new ZUMOAPPNAMEContext();
DomainManager = new EntityDomainManager<TodoItem>(context,Request);
}
// GET tables/TodoItem
public IQueryable<TodoItem> GetAllTodoItems()
{
return Query();
}
// GET tables/TodoItem
public SingleResult<TodoItem> GetTodoItem(string id)
{
return Lookup(id);
}
// PATCH tables/TodoItem
public Task<TodoItem> PatchTodoItem(string id,Delta<TodoItem> patch)
{
return UpdateAsync(id,patch);
}
// POST tables/TodoItem
public async Task<IHttpActionResult> PostTodoItem(TodoItem item)
{
TodoItem current = await InsertAsync(item);
return CreatedAtRoute("Tables",new { id = current.Id },current);
}
// DELETE tables/TodoItem
public Task DeleteTodoItem(string id)
{
return DeleteAsync(id);
}
}
}
移动应用代码:
TodoList.xaml
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="ZUMOAPPNAME.TodoList"
Title="Azure Todo">
<Grid RowSpacing="0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<ActivityIndicator Grid.RowSpan="2"
HorizontalOptions="Center"
VerticalOptions="Center"
IsVisible="False"
IsEnabled="True"
x:Name="syncIndicator"/>
<StackLayout Grid.Row="0" BackgroundColor="Blue" Padding="10,30,10,5">
<Label TextColor="#555555" Text="Azure App Service" />
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Entry x:Name="newItemName"
Placeholder="Item name" />
<StackLayout x:Name="buttonsPanel" Grid.Column="1" Orientation="Horizontal" HorizontalOptions="StartAndExpand">
<Button Text="+"
MinimumHeightRequest="30"
Clicked="OnAdd" />
</StackLayout>
</Grid>
</StackLayout>
<ListView x:Name="todoList"
ItemSelected="OnSelected"
IsPullToRefreshEnabled="true" Refreshing="OnRefresh"
Grid.Row="1">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.ContextActions>
<MenuItem Clicked="OnComplete" Text="Complete" CommandParameter="{Binding .}"/>
</ViewCell.ContextActions>
<StackLayout HorizontalOptions="StartAndExpand" Orientation="Horizontal" Padding="15,5,0">
<StackLayout Padding="5,0" VerticalOptions="StartAndExpand" Orientation="Vertical">
<Label Text="{Binding Name}" />
</StackLayout>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</ContentPage>
TodoList.xaml.cs
using System;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace ZUMOAPPNAME
{
public partial class TodoList : ContentPage
{
TodoItemManager manager;
public TodoList()
{
InitializeComponent();
manager = TodoItemManager.DefaultManager;
}
protected override async void OnAppearing()
{
base.OnAppearing();
// Set syncItems to true in order to synchronize the data on startup when running in offline mode
await RefreshItems(true,syncItems: true);
}
// Data methods
async Task AddItem(TodoItem item)
{
await manager.SaveTaskAsync(item); //ADD ITEM
todoList.ItemsSource = await manager.GetTodoItemsAsync(); // REFRESH
}
async Task CompleteItem(TodoItem item)
{
item.Done = true;
await manager.SaveTaskAsync(item);
todoList.ItemsSource = await manager.GetTodoItemsAsync();
}
public async void OnAdd(object sender,EventArgs e)
{
var todo = new TodoItem { Name = newItemName.Text };
await AddItem(todo);
newItemName.Text = string.Empty;
newItemName.Unfocus();
}
// Event handlers
public async void OnSelected(object sender,SelectedItemChangedEventArgs e)
{
var todo = e.SelectedItem as TodoItem;
if (Device.RuntimePlatform != Device.iOS && todo != null)
{
// Not iOS - the swipe-to-delete is discoverable there
if (Device.RuntimePlatform == Device.Android)
{
await DisplayAlert(todo.Name,"Press-and-hold to complete task " + todo.Name,"Got it!");
}
else
{
// Windows,not all platforms support the Context Actions yet
if (await DisplayAlert("Mark completed?","Do you wish to complete " + todo.Name + "?","Complete","Cancel"))
{
await CompleteItem(todo);
}
}
}
// prevents background getting highlighted
todoList.SelectedItem = null;
}
// http://developer.xamarin.com/guides/cross-platform/xamarin-forms/working-with/listview/#context
public async void OnComplete(object sender,EventArgs e)
{
var mi = ((MenuItem)sender);
var todo = mi.CommandParameter as TodoItem;
await CompleteItem(todo);
}
// http://developer.xamarin.com/guides/cross-platform/xamarin-forms/working-with/listview/#pulltorefresh
//PULL TO REFRESH
public async void OnRefresh(object sender,EventArgs e)
{
var list = (ListView)sender;
Exception error = null;
try
{
await RefreshItems(false,true);
}
catch (Exception ex)
{
error = ex;
}
finally
{
list.EndRefresh();
}
if (error != null)
{
await DisplayAlert("Refresh Error","Couldn't refresh data (" + error.Message + ")","OK");
}
}
//REFRESH ITEMS
private async Task RefreshItems(bool showActivityIndicator,bool syncItems)
{
using (var scope = new ActivityIndicatorScope(syncIndicator,showActivityIndicator))
{
todoList.ItemsSource = await manager.GetTodoItemsAsync(syncItems);
}
}
//ACTIVITY INDICATOR
private class ActivityIndicatorScope : IDisposable
{
private bool showIndicator;
private ActivityIndicator indicator;
private Task indicatorDelay;
public ActivityIndicatorScope(ActivityIndicator indicator,bool showIndicator)
{
this.indicator = indicator;
this.showIndicator = showIndicator;
if (showIndicator)
{
indicatorDelay = Task.Delay(2000);
SetIndicatorActivity(true);
}
else
{
indicatorDelay = Task.FromResult(0);
}
}
private void SetIndicatorActivity(bool isActive)
{
this.indicator.IsVisible = isActive;
this.indicator.IsRunning = isActive;
}
public void Dispose()
{
if (showIndicator)
{
indicatorDelay.ContinueWith(t => SetIndicatorActivity(false),TaskScheduler.FromCurrentSynchronizationContext());
}
}
}
}
}
TodoItemManager.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.MobileServices;
using Microsoft.WindowsAzure.MobileServices.Sync;
namespace ZUMOAPPNAME
{
public partial class TodoItemManager
{
static TodoItemManager defaultInstance = new TodoItemManager();
MobileServiceClient client;
private IMobileServiceSyncTable<TodoItem> todoTable;
private TodoItemManager()
{
this.client = new MobileServiceClient(Constants.ApplicationURL);
}
public static TodoItemManager DefaultManager
{
get
{
return defaultInstance;
}
private set
{
defaultInstance = value;
}
}
public MobileServiceClient CurrentClient
{
get { return client; }
}
//Refresh Table list
public async Task<ObservableCollection<TodoItem>> GetTodoItemsAsync(bool syncItems = false)
{
try
{
IEnumerable<TodoItem> items = await todoTable
.Where(todoItem => !todoItem.Done)
.ToEnumerableAsync();
return new ObservableCollection<TodoItem>(items);
}
catch (MobileServiceInvalidOperationException msioe)
{
Debug.WriteLine("Invalid sync operation: {0}",new[] { msioe.Message });
}
catch (Exception e)
{
Debug.WriteLine("Sync error: {0}",new[] { e.Message });
}
return null;
}
//Add or Update if ID exists or not
public async Task SaveTaskAsync(TodoItem item)
{
try
{
if (item.Id == null)
{
await todoTable.InsertAsync(item);
}
else
{
await todoTable.UpdateAsync(item);
}
}
catch (Exception e)
{
Debug.WriteLine("Save error: {0}",new[] { e.Message });
}
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。