Use Windows azure Mobile Service to develop Windows Phone 8 app

Source: Internet
Author: User

-How to Make a Windows Phone 8 app with Windows azure Mobile Service

Windows azure mobile service has been launched for some time. This may be one of the most popular feature in Windows azure since this time. I tried mobile service and thought it was good, share the trial process for your reference.

Create a mobile service

1. log on to the Windows azure portal and create a mobile service

2. create a mobile service: mytodos and create a database for it. Note that the region of the database server should be the same as that of the mobile service, this reduces network latency and traffic fees (you can also use existing database instances. Mobile Service will store the new data tables in the schema of mytodos, so you don't have to worry about duplicate names with the original table)

3. wait a few minutes. After the mobile service is created, click mytodos to configure it:

A) here we can see that Mobile Service supports Windows/WP8/Android/IOS/HTML5 applications. Here we choose windows phone8, install two sdks-Windows Phone 8 SDK and mobile service SDK;

B) Click "create todoitem table" to create a todoitem table in the database just now. You can also create a todoitem table in the database.

4. go to the configuration page and enable "Dynamic Architecture". In this way, in the development phase, the mobile service automatically creates the corresponding fields for the mobile service, however, in the release phase, it is best to disable the "Dynamic Architecture" for security considerations.

5. Go back to the mytodos homepage and download the automatically generated azure code.

6. Open the downloaded code. At this time, we have obtained a complete Windows Phone 8 Application to see what code is generated by mobile service.

A) mobileserviceclient: This is the client used to access the mobile service in the mobile service SDK.

B) todoitem and corresponding insert/update/refresh Methods: note that these methods use asynchronous programming of. Net 4.5, which is also the programming mode recommended by mobile service.

7. Run and test this small app, add some todoitem, and browse the database created earlier. You can see that a complete WP8 app has been obtained without writing a line of code.

Add User Verification

Next, add user verification. Mobile Service supports Microsoft account (liveid), Google, Facebook, and twritter. This article only uses Microsoft account.

1. To use microsofaccount, first go to live connect Developer Center (http://go.microsoft.com/fwlink/p? Linkid = 262039 & clcid = 0x409) register our app. Note that "yes" is selected for "mobile client application ".

2. Fill in the registered Client ID and client key to mobile service and save

3. Now set the data permission, set the todoitem table to read and write only authenticated users, and save

4. Run the app again. An unauthorized exception should be received this time because the current user has not logged on.

5. Add the logon code for the app.

A) add a login button for mainpage in mainpage. XAML.

B) comment out the code in onnavigatedto.

View code

protected override void OnNavigatedTo(NavigationEventArgs e){//RefreshTodoItems();}

 

C) modify the applicationkey in APP. XAML. CS.

View code

Public static mobileserviceclient mobileservice = new mobileserviceclient ("https://mytodos.azure-mobile.net/", "client key obtained upon app registration ");

 

D) Add the following code to mainpage class.

View code

private MobileServiceUser user;private async System.Threading.Tasks.Task Authenticate(){    if (user == null)    {    string message = "You must log in. Login Required";    try    {    user = await App.MobileService.LoginAsync    (MobileServiceAuthenticationProvider.MicrosoftAccount);    message = string.Format("You are now logged in - {0}", user.UserId);    }    catch (InvalidOperationException ex)    {        message = ex.Message;    }    MessageBox.Show(message);    }}private async void BtnLogin_Click(object sender, RoutedEventArgs e){    await Authenticate();    if (null != this.user)    {    RefreshTodoItems();    }}

 

Run and check the effect. Now you can refresh and add todoitem again.

6. If you need more user information, you need to download and install livesdk (http://msdn.microsoft.com/en-us/live/ff621310) and add references to mytodos to Microsoft. Live

A) Modify mainpage. Authenticate according to the following code.

View code

Private async system. threading. tasks. task authenticate () {If (user = NULL) {string message = "you must log in. login required "; try {string clientid =" client ID obtained when registering an app "; liveauthclient liveidclient = new liveauthclient (clientid); liveloginresult result = await liveidclient. loginasync (new [] {"WL. basic "," WL. photos "}); If (result. status = liveconnectsessionstatus. connected) {liveconnectclient client = new liveconnectclient (result. session); var me = await client. getasync ("me"); User = await app. mobileservice. loginasync (result. session. authenticationtoken); // (mobileserviceauthenticationprovider. microsoftaccount); this. titletextblock. TEXT = This. titletextblock. text + "-Welcome," + me. result ["first_name"]. tostring () + ". "+ me. result ["last_name"]. tostring (); message = string. format ("You are now logged in-{0}", user. userid);} else {message = string. format ("connect to Microsoft account failed. status: {0} ", result. status) ;}} catch (liveauthexception authex) {message = string. format ("{0 }:{ 1}", authex. getType (). name, httputility. urldecode (authex. message);} catch (liveconnectexception Connex) {message = string. format ("{0 }:{ 1}", CONNEX. getType (). name, httputility. urldecode (Connex. message);} catch (invalidoperationexception ex) {message = ex. message;} MessageBox. show (Message );}}

 

The running effect is as follows. You can see that the logon page is slightly different from the previous one, but this time you can get more user information.

Add push notification

1. Add the following code:

A) Add the following code to app. XAML. CS:

View code

public static HttpNotificationChannel CurrentChannel { get; private set; }private static readonly string ChannelName = "MyTodosPushChannel";private void AcquirePushChannel(){CurrentChannel = HttpNotificationChannel.Find(ChannelName);if (CurrentChannel == null){CurrentChannel = new HttpNotificationChannel(ChannelName);CurrentChannel.Open();CurrentChannel.BindToShellTile();CurrentChannel.BindToShellToast();}CurrentChannel.ShellToastNotificationReceived += CurrentChannel_ShellToastNotificationReceived;}void CurrentChannel_ShellToastNotificationReceived(object sender, NotificationEventArgs e){string msg = "";foreach (var kv in e.Collection){msg = msg + "\r\n" + kv.Key.ToString() + ": " + kv.Value;}Deployment.Current.Dispatcher.BeginInvoke(() => { MessageBox.Show(msg); });}

 

B) Call acquirepushchannel in application_launching

View code

private void Application_Launching(object sender, LaunchingEventArgs e){AcquirePushChannel();}

 

C) Add a property to todoitem class.

View code

[DataMember(Name = "channel")]public string Channel { get; set; }

 

D) modify the buttonsave_click of mainpage. XAML. cs. The Code is as follows. Because of the dynamic architecture we have enabled, mobile service will create a database field for the newly added channel attribute when saving.

View code

private void ButtonSave_Click(object sender, RoutedEventArgs e){var todoItem = new TodoItem{Text = TodoInput.Text,Channel = App.CurrentChannel.ChannelUri.ToString()};InsertTodoItem(todoItem);}

 

2. Enable push for the app

3. Return to the azure portal, modify the script of the mobile service server, and save the script. For detailed parameters, refer to here:

Http://msdn.microsoft.com/en-us/library/windowsazure/jj871025.aspx

The Code is as follows:

View code

function insert(item, user, request) {request.execute({success: function () {request.respond();// send flip tilepush.mpns.sendFlipTile(item.channel, {title: item.text}, {success: function (pushResponse) {console.log("Sent flip tile push:", pushResponse);}});// send toastpush.mpns.sendToast(item.channel, {text1: 'MyTodos',text2: item.text}, {success: function(pushResponse){console.log("Sent toast push:", pushResponse);}});}});}

 

4. Pin mytodos to the main interface, run the app, and observe the effect.

 

Summary

Azure mobile service greatly simplifies server-side code development, especially for small applications, so that app developers can focus on front-end code.

 

Appendix:

The client source code is here

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.