Pages

Men

rh

10/28/2014

Validate and modify data in Mobile Services by using server scripts

This topic shows you how to leverage server scripts in Azure Mobile Services. Server scripts are registered in a mobile service and can be used to perform a wide range of operations on data being inserted and updated, including validation and data modification. In this tutorial, you will define and register server scripts that validate and modify data. Because the behavior of server side scripts often affects the client, you will also update your Windows Store app to take advantage of these new behaviors.
This tutorial walks you through these basic steps:
  1. Add string length validation
  2. Update the client to support validation
  3. Add a timestamp on insert
  4. Update the client to display the timestamp
This tutorial builds on the steps and the sample app from the previous tutorial Get started with data. Before you begin this tutorial, you must first complete Get started with data.

Add validation

It is always a good practice to validate the length of data that is submitted by users. First, you register a script that validates the length of string data sent to the mobile service and rejects strings that are too long, in this case longer than 10 characters.
  1. Log into the Azure Management Portal, click Mobile Services, and then click your app.
  2. Click the Data tab, then click the TodoItem table.
  3. Click Script, then select the Insert operation.
  4. Replace the existing script with the following function, and then click Save.
    function insert(item, user, request) {
        if (item.text.length > 10) {
            request.respond(statusCodes.BAD_REQUEST, 'Text length must be under 10');
        } else {
            request.execute();
        }
    }
    This script checks the length of the TodoItem.text property and sends an error response when the length exceeds 10 characters. Otherwise, the execute method is called to complete the insert.
    NOTE
    You can remove a registered script on the Script tab by clicking Clear and then Save.

Update the client

Now that the mobile service is validating data and sending error responses, you need to update your app to be able to handle error responses from validation.
  1. In Visual Studio 2012 Express for Windows 8, open the project that you modified when you completed the tutorial Get started with data.
  2. Press the F5 key to run the app, then type text longer than 10 characters in Insert a TodoItem and click Save.
    Notice that the app raises an unhandled MobileServiceInvalidOperationException as a result of the 400 response (Bad Request) returned by the mobile service.
  3. Open the file MainPage.xaml.cs, then add the following using statement:
    using Windows.UI.Popups;
  4. Replace the existing InsertTodoItem method with the following:
    private async void InsertTodoItem(TodoItem todoItem)
    {
        // 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 collection.
        try
        {
            await todoTable.InsertAsync(todoItem);
            items.Add(todoItem);
        }
        catch (MobileServiceInvalidOperationException e)
        {
            MessageDialog errormsg = new MessageDialog(e.Message, 
                string.Format("{0} (HTTP {1})",                     
                e.Response.ReasonPhrase,
                (int)e.Response.StatusCode));
            var ignoreAsyncOpResult = errormsg.ShowAsync();
        }
    }
    This version of the method includes error handling for the MobileServiceInvalidOperationException that displays the error response in a popup.

Add a timestamp

The previous tasks validated an insert and either accepted or rejected it. Now, you will update inserted data by using a server script that adds a timestamp property to the object before it gets inserted.
NOTE
The createdAt timestamp property demonstrated here is now redundant. Mobile Services automatically creates a__createdAt system property for each table. You could use this system property in your application by simply adding the following member to the TodoItem class
[JsonProperty(PropertyName = "__createdAt")]
public DateTime createdAt { set; get; }
  1. In the Scripts tab in the Management Portal, replace the current Insert script with the following function, and then clickSave.
    function insert(item, user, request) {
        if (item.text.length > 10) {
            request.respond(statusCodes.BAD_REQUEST, 'Text length must be under 10');
        } else {
            item.createdAt = new Date();
            request.execute();
        }
    }
    This function augments the previous insert script by adding a new createdAt timestamp property to the object before it gets inserted by the call to request.execute.
    NOTE
    Dynamic schema must be enabled the first time that this insert script runs. With dynamic schema enabled, Mobile Services automatically adds the createdAt column to the TodoItem table on the first execution. Dynamic schema is enabled by default for a new mobile service, and it should be disabled before the app is published to the Windows Store.
  2. In Visual Studio, press the F5 key to run the app, then type text (shorter than 10 characters) in Insert a TodoItem and clickSave.
    Notice that the new timestamp does not appear in the app UI.
  3. Back in the Management Portal, click the Browse tab in the todoitem table.
    Notice that there is now a createdAt column, and the new inserted item has a timestamp value.
Next, you need to update the Windows Store app to display this new column.

Update the client again

The Mobile Service client will ignore any data in a response that it cannot serialize into properties on the defined type. The final step is to update the client to display this new data.
  1. In Visual Studio, open the file MainPage.xaml.cs, then replace the existing TodoItem class with the following definition:
    public class TodoItem
    {
        public string Id { get; set; }
    
        [JsonProperty(PropertyName = "text")]
        public string Text { get; set; }
    
        [JsonProperty(PropertyName = "complete")]
        public bool Complete { get; set; }
    
        [JsonProperty(PropertyName = "createdAt")]
        public DateTime? CreatedAt { get; set; }
    }
    This new class definition includes the new timestamp property, as a nullable DateTime type.
    NOTE
    The DataMemberAttribute tells the client to map the new CreatedAt property in the app to the createdAtcolumn defined in the TodoItem table, which has a different casing. By using this attribute, your app can have property names on objects that differ from column names in the SQL Database. Without this attribute, an error occurs because of the casing differences.
  2. Add the following XAML element just below the CheckBoxComplete element in the MainPage.xaml file:
    <TextBlock Name="WhenCreated" Text="{Binding CreatedAt}" VerticalAlignment="Center"/>
    This displays the new CreatedAt property in a text box.
  3. Press the F5 key to run the app.
    Notice that the timestamp is only displayed for items inserted after you updated the insert script.
  4. Replace the existing RefreshTodoItems method with the following code:
    private async void RefreshTodoItems()
    {
        // This query filters out completed TodoItems and 
        // items without a timestamp. 
        items = await todoTable
           .Where(todoItem => todoItem.Complete == false
               && todoItem.CreatedAt != null)
           .ToCollectionAsync();
    
        ListItems.ItemsSource = items;
    }
    This method updates the query to also filter out items that do not have a timestamp value.
  5. Press the F5 key to run the app.
    Notice that all items created without timestamp value disappear from the UI.
You have completed this working with data tutorial.
Source from
http://azure.microsoft.com/en-us/documentation/articles/mobile-services-windows-store-dotnet-validate-modify-data-server-scripts/

No comments :

Post a Comment