1.31k likes | 1.5k Views
Mobile Services. Paolo Salvatori Microsoft. Paolo Salvatori. Senior Program Manager Microsoft. Agenda. 1 st Hour: Introduction to Mobile Services (45 minutes ) General Architecture Management Portal REST API Break (15 minutes). why is mobile so important?.
E N D
Mobile Services Paolo Salvatori Microsoft
Paolo Salvatori Senior Program Manager Microsoft
Agenda • 1st Hour: Introduction to Mobile Services (45 minutes) • General Architecture • Management Portal • REST API • Break (15 minutes)
App DevelopmentChallenges Enterprises want to manage internal mobile apps and consumer facing event- or product-specific mobile apps from the same portal as core LOB apps Small Businesses require solutions that accelerate development time and decrease development costs. Developers shouldn’t have to constantly reinvent the wheel and reproduce common backend functionality Consumers expect a continuous experience across all devices
Windows Azure Mobile Servicesaddresses each of those challenges.
Windows Azure Mobile Services accelerates connected client application development by streamlining common backend tasks like structuring storage, authenticating users, and sending push notifications.
Key Scenarios Rapid Development Time is money. Get your app up and running sooner when you use Mobile Services to configure a secure backend in less than five minutes. Make your app social Whether your customers use Google, Facebook, Twitter, or Microsoft Account, no matter what devices they run your app on, with Mobile Services you can makes your app social and personable fast. Make your app engaging and dynamic Push notifications and Live Tiles is the premier way to engage your customers. Make your app engaging and dynamic using Mobile Services Push.
Basic Features Data in the Cloud SQL Table Blob Connected Apps Windows Store iOS Android Windows Phone 8 iOS Android HTML 5/JS Server-Side Scripts & Scheduler User Authentication Facebook Twitter Microsoft Google Push Notifications WNS & APNS GCM MPNS SDKs
Supported Platforms Windows 8 iOS Windows Phone 8 Android HTML5 & Javascript
Architecture Zumo Resource Provider Portal RDFE SQL N SQL 1 SQL 2 Zumo Mgmt DB Site 2 Site N Site 1 Azure LB\ARR Scheduler Zumo Runtime App Scripts Zumo Antares Stamp Win8 Device Azure SDK 3rd party SDKS iPhone
Dashboard • Quick glance • Displays relevant mobile service information, including the service URL, status, location, database and subscription • Usage Timeline: • Displays a scalable chart of CPU time, API calls and data reads over a specific period of time. • Usage Overview: • Displays an overview of the total compute time and storage used by this mobile service • Manage Keys • Manage Keys • Delete • Delete the Mobile Service
Data • In Windows Azure Mobile Services, data is stored in tables, which are maintained in the Windows Azure SQL Database that is associated with your mobile service. • Click the Create button to add a new table to your mobile service. • By default, you don’t need to predefine the schema of tables in your database. • Mobile Services automatically add columns to a table based on the data you insert. To change this dynamic schema behavior, use the Dynamic Schema setting on the Configure tab. • To browse data, manage permissions and indexes on tables, or add server scripts, click on a table in the list. • To delete a table, click to select a table row, and then click Delete.
Browse • The Browse tab lets you browse data rows in a selected table. • Click the forward and back arrows to navigate through multiple pages of data. • Click on table names in the left navigation bar to switch between tables. • Click on the large left arrow to go back to the Data tab.
Script • Mobile Services enables you to register JavaScript code to be executed by the service when an insert, update, delete, or read operation occurs against a specific table. • For each table there are 4 CRUD operations (insert, read, update, del) • These scripts provide the ability to inject business logic into table operation, stop an operation from taking place, change or enrich values supplied to the operation or change the results. • For authenticated clients, you can also perform user-specific authorizations based on the userId value of the supplied userobject.
Columns • To delete columns, click the column and then click Delete. • To add additional columns to the table, simply send an insert request including the new properties from your app with dynamic schema enabled. • Once a column is created, its data type cannot be changed by Mobile Services. • Insert or update operations fail when the type of a property in the JSON object cannot be converted to the type of the equivalent column in the table. • You can improve the performance of queries by defining an index on the table. • To add a column to the index, select the column and click Set as Index.
Permissions • Mobile Services enables you to set the following permissions on table operations: • Everyone: request for the operation against the table is accepted. This option leaves your data wide-open for everyone to access. • Anybody with the Application Key: The application key is required to perform the operation. The application key is distributed with the application. Note: Because this key is not securely distributed, it cannot be considered a security token. To secure access to your mobile service data, you must instead authenticate users before accessing. • Only Authenticated Users: Only authenticated users are permitted to perform the operation. Scripts can be used to further restrict access to tables based on an authenticated user. • Only Scripts and Admins: The operation requires the service master key, which limits the operation only to registered scripts or to administrator accounts
Scheduler • Mobile Services enables you to register JavaScript code to be executed by the service either on a schedule that you define or on-demand from the Management Portal. • Removing duplicate records from a table. • Backing up a database. • Send a report via email. • When your mobile service runs in free mode, you can create only one scheduled job at a time; in reserved mode, you can create up to ten scheduled jobs at the same time.
Push • Mobile Services can send push notifications to your apps. • The way that you configure and send push notifications depends on your app. • You can send push notifications to the following applications: • Windows Store app by using the Windows Push Notification Service (WNS). To send push notifications to your app, you must configure your mobile service to work with WNS. • iPhone and iPad apps by using the Apple Push Notification Service (APNS). To send push notifications to your app, you must configure your mobile service to work with APNS. Do this by generating a special push notification certificate at the iOS Provisioning Portal • Android: You can send push notifications to Android apps by using the Google Cloud Messaging (GCM) service. To send push notifications to your app, you must configure your mobile service to work with GCM. • Windows Phone 8 app by using the Microsoft Push Notification Service (MPNS). Mobile Services does not require you to register your Windows Phone 8 app to send push notifications.
Identity • Mobile Services integrates with the following identity providers to make it easy to authenticate users from your app: • Microsoft Account • Facebook login • Twitter login • Google login • To enable authentication, you must first register your app with one or more of these identity providers and then configure your mobile service. • You must also add authentication code to your app. • When a user login is authenticated by Mobile Services, the value of the userId property on the userobject passed to server scripts is set to a value that uniquely identifies a user. This value can then be used to authorize access to data.
Configure • You can directly access to the database used by your mobile service just clicking the link. • You can change the database used by your mobile service to store data with a new or existing DB by clicking Change DB and select one of the following options. • Enable/disable dynamic schema. • In reserved mode, you can configure endpoint monitoring.
Scale • On the Scale tab, you can scale your mobile service by switching to reserved mode and adding role instances. • You can also scale the Windows Azure SQL Database instance used by the service. • Note: When you set the Mobile service mode to Reserved, all of your mobile services in the same region run in Reserved mode. • To estimate the cost required to scale your mobile service, see the Mobile Services Pricing Calculator.
Log • Mobile Services writes system and script errors to the log. • Click on a log entry to view details and copy to the clipboard. • Click the link in the Source column to directly jump to the script that generated the error. • Note: Existing log entries can be viewed in the Management Portal for 7 days. • Your registered server scripts can also write information directly to the log by using the consoleobject.
Login • Verb: POST • URL: https://<service-name>.azure-mobile.net/login?mode=authenticationToken • UriParameter: mode • Request Headers: • Body: JSON object{"authenticationToken":“<authentication-provider-token>"} for Microsoft{“access_token":“<authentication-provider-token>"} for Facebook and Google • Response: JSON object{"user":{"userId":"<authentication-provider>:cb392ceae24a44408ed863482b20f274"},"authenticationToken":"<mobile-service-authentication-token>"}
Query Records • Verb: GET • URL: https://<service_name>.azure-mobile.net/tables/<table_name> • URI Parameters: $filter, $inlinecount, $orderby, $select, $skip, $top • Request Headers: • Response: data in JSON format • Samples: • GET https://plunko.azure-mobile.net/tables/todoitem • GET https://plunko.azure-mobile.net/tables/todoitem/1 • GET https://plunko.azure-mobile.net/tables/todoitem?$filter=(complete%20eq%20false) • GET https://plunko.azure-mobile.net/tables/todoitem?$filter=(complete%20eq%20false)&$orderby=text%20asc
Insert Record • Verb: POST • URL: https://<service_name>.azure-mobile.net/tables/<table_name> • Request Headers: • Body: new record in JSON format • Response: The JSON representation of the inserted item, which includes the ID for the item generated by the mobile service. • Sample: • POST https://plunko.azure-mobile.net/tables/todoitem • Body: {"text" : "Go to Las Vegas", "complete": false, "when" : "don't know"}
Update Record • Verb: PATCH • URL: https://<service_name>.azure-mobile.net/tables/<table_name>/<item_id> • Request Headers: • Body: The updated values encoded in JSON format, along with the optional id value of the object. • Response: The JSON representation of the updated item • Sample: • PATCH https://plunko.azure-mobile.net/tables/todoitem/1 • Body: {"text" : "Go to Barcelona", "complete": false, "when" : "don't know"}
Delete Record • Verb: DELETE • URL: https://<service_name>.azure-mobile.net/tables/<table_name>/<item_id> • Request Headers: • Body: none • Response: none • Sample: • DELETE https://plunko.azure-mobile.net/tables/todoitem/6
HttpClient and Mobile Services privateasyncvoidbtnSend_Click(object sender, EventArgs e) { try { varhttpClient = newHttpClient(); var uri = newUri("https://<your-mobile-service>.azure-mobile.net/tables/TodoItem"); httpClient.DefaultRequestHeaders.Accept.Add(newMediaTypeWithQualityHeaderValue("application/json")); httpClient.DefaultRequestHeaders.Add("x-zumo-application", “<application-key>"); httpClient.DefaultRequestHeaders.Host = uri.Host; vartodoItem = newTodoItem {Text = txtText.Text, Complete = false}; varserializer = newDataContractJsonSerializer(typeof (TodoItem)); using (var stream = newMemoryStream()) { serializer.WriteObject(stream, todoItem); stream.Seek(0, SeekOrigin.Begin); //use a Stream reader to construct the StringContent (Json) using (var reader = newStreamReader(stream)) { var response = awaithttpClient.PostAsync(uri, newStringContent(reader.ReadToEnd(), Encoding.UTF8, "application/json")); WriteToLog(response.IsSuccessStatusCode ? string.Format("Message <{0}> successfully inserted!", txtText.Text) : string.Format("HTTP Status: <{0}> Reason: <{1}>", response.StatusCode, response.ReasonPhrase)); } } } catch (Exception ex) { WriteToLog(ex.Message); } }
Agenda • 2nd Hour: Server Scripts (45 minutes) • Server script objects • Server script modules • Configure user authentication: • Windows Live • Facebook • Twitter • Google • User object and integration with identity providers • Data validation and duplicate detection • Administer Mobile Services using Windows Azure Cross-Platform Command Line tool • Break (15 minutes)
Samples console object console.log("Inserting item '%j'.", item); // %j for 'JSON' console.error("Operation failed: ", error); mssql object mssql.query('select * from orders where country = "Russia"', {success: function (results) {console.log(results); }});
Samples Query object: is passed to read scripts function read(query, user, request) { query.where({ userId: user.userId }); request.execute(); } Requestobject: is passed to all scripts request.execute(); //Executes the default behavior for the operation request.respond(); //Writes the default response request.respond(error); //Writes a response with the specified error
Samples Tables and Table objects function insert(item, user, request) { varaddressTable= tables.getTable('address'); addressTable.where({userId: user.userId}) .read({success: function (results) { item.address = results.length > 0 ? results[0] : 'unknown'; request.execute(); } }); }
Samples Request varrequest = require('request'); varurl = 'https://api.twitter.com/1/users/show.json?screen_name=babosbird'; request(url, function(error, response, body) { if (error) { console.error(error); } else { var data = JSON.parse(body); console.log(data); } });
Samples SendGrid functionsendEmail(text) { varsendgrid = newSendGrid('<user-name>', ('<password>'); sendgrid.send({ to: 'paolos@microsoft.com', from: ‘info@acme.com', subject: ‘ACME Newsletter', text: text }, function (success, message) { // If the email failed to send, log it as an error so we can investigate if (!success) { console.error(message); } }); }
Portable Class Library • The Portable Class Library project supports a subset of assemblies from the .NET Framework, Silverlight, .NET for Windows Store apps, Windows Phone, and Xbox 360, and provides a Visual Studio template that you can use to build assemblies that run without modification on these platforms. • Mobile Services support the Portable Class Library model and this offers several advantages for developers, since they can now share the codebase of client applications between the different platforms. • The Portable Class Library needs a platform extension assembly (.Ext.dll) to work correctly. • We provide platform extension assemblies for: • Windows Phone 7.5 • Windows Phone 8 • Windows Store apps.
Portable Class Library • The Portable Class Librarycannot contain all the classesof the managed clients for all the platforms. • Some functionality is only available on one platform, while other functionality differs between platforms. • Therefore, to be able to use the new Managed Client you also need a platform specific assembly, which contains code to be able to use features available on that specific platform. • UI authentication is an example of a feature that works different on different platforms and is not portable. • For you as a developer this means you need two assemblies for your Windows Store App to use Mobile Services. • For Windows Phone there is an additional assembly which contains functionality which is not allowed in background agents (e.g. login)
Windows Store App App.xaml.cs usingMicrosoft.WindowsAzure.MobileServices; sealedpartialclassApp : Application { // This MobileServiceClient must be configured to communicate with // your Mobile Service's url and application key. // The MobileServiceClientclass provides basic access to Mobile Services. publicstaticreadonlyMobileServiceClientMobileService = newMobileServiceClient("https://<your-mobile-service>.azure-mobile.net/", “XXXXXXXXXXXXXXXXXXXX"); }
Windows Store App MainPage.xaml.cs usingMicrosoft.WindowsAzure.MobileServices; usingNewtonsoft.Json; publicclassTodoItem { publicint Id { get; set; } [JsonProperty(PropertyName = "text")] publicstring Text { get; set; } [JsonProperty(PropertyName = "complete")] publicbool Complete { get; set; } } publicsealedpartialclassMainPage : Page { privateMobileServiceCollection<TodoItem, TodoItem> items; // the IMobileServiceTable interface Provides operations on a table for a Mobile Service. privateIMobileServiceTable<TodoItem> todoTable = App.MobileService.GetTable<TodoItem>(); privateasyncvoidRefreshTodoItems() { // This code refreshes the entries in the list view by querying the TodoItems table. items = awaittodoTable .Where(todoItem => todoItem.Complete == false) .ToCollectionAsync(); } }