Server Side Validation & Modification in Microsoft Azure Mobile Services


Server Side Validation & Modification

In this article, i'll tell you how to modify and validate data in Microsoft Azure Mobile Service using Server Side Script.
Essentially, server side scripts provide a place for you to execute your custom business logic that you want to perform on "Server-Side" during operations. We've get a basic touch of SCRIPT tab of Azure Mobile Services in the previous article.

So let's start with the TodoList application which we've created in the previous article. You can grab the sample app from here.
This is the basic application that provides a simple Task List functionality that persists data within Mobile Services. Here is the screenshot of the app.

Now, most of the developers needs some sort of validation. And those developers that are building applications that capture data in the client app that is persisted in a service will typically perform validation on both the server and client side. How these developers do this kind of validation on server side? This is what i have to show you today. :)

So, to do this, return to the Portal, open your Mobile Service, select DATA tab, and than TodoItem Table. You'll see this screen.

You can see there are 3 tasks that we've added from the client application.
Now, select SCRIPT tab and you'll see the following screen.

This is where I can implement my own custom business that will be executed on the server side.
This is executed PRIOR the operation being completed, so in this case, i'll write code on Line # 2 , in order to execute the code PRIOR the operation execution.

Unlike-wise you can write your own logic for other operations like Update, Delete, Read etc. to perform on server side.

So, in this scenario, i'm validating if the task is less than 7 characters long than it is an invalid task. And also i want to send back the message to the user that it is an invalid task. And if it is valid, i want to execute the operation.
So, first lets have a look on the parameters of the method. There are 3 parameters, "item", "user", "request".
Now here the "item" parameter represent the task that the user pushed up to be persisted. The other parameter is "user" which represent the user (Authenticated User).
While the third parameter is "request" that allows us to do some functions with the coming request. For example, to execute the request, to respond back the request etc.

You can see the Line # 3, where the request is executed. Means, insert the item that is passed.
Coming back to our logic that the task should not less than 7 characters long, the whole method will be like this.

function insert(item, user, request) {
     
    if(item.text.length < 7) {
        request.respond(statusCodes.BAD_REQUEST, 'text should be 7 or more characters long');
    } else {
        request.execute();
    }
 
}

You maybe wondering where the "text" come from in item.text.length statement. Please see the Line # 25 of MainPage.xaml.cs in the Source Code.
Here i copy paste that line.

[JsonProperty(PropertyName = "text")]

This is where that text property comes from.
Let's run the app and check whether our server side script works or not. Please have a look on the app image below.
As you see, when i tried to add "1234567" in the tasks. It added successfully, as it is 7 characters long. But when i tried to add "123456", the app crash and give the following exception.

This exception comes when i tried to add less than 7 characters long task. And you can see the "Additional Information" in the exception which is showing the message we've put in the server side script.
We can handle this Exception in our client application to show appropriate message to the user.
Now in order to put some kind of handling to this Exception, we use try---catch hierarchy.
As we see in the exception that it is MobileServiceInvalidOperationException, so we should handle this in Catch block.
Please see the code below. Now the whole InsertTodoItem() method will be modified like this.

private async void InsertTodoItem(TodoItem todoItem)
{
     MobileServiceInvalidOperationException exception = null;
     try
     {
          await todoTable.InsertAsync(todoItem);
          items.Add(todoItem);
     }
     catch(MobileServiceInvalidOperationException e)
     {
          exception = e;
     }
 
     if(exception != null)
     {
          MessageDialog msg = new  MessageDialog(exception.Message);
          await msg.ShowAsync();
     }
}

Now, what we do in the code, we put our previous code in "try" block. Firstly the try block is executed, if it gets the exception (i.e. above given exception). it is catched through the "catch" block and the message that we receive is shown via MessageDialog Command. Pretty simple and easy it is.
Let's have a look on the output now. When i tried to put less than 7 characters long task, it looks like this.

You can see that the app didn't crash now and it shows the proper message to the user. This message comes from the server side script which we implemented before.
So, this is one way how we can validate and modify server side scripts in Azure Mobile Services.

You may also perhaps want to send Push Notifications, or do number of things with server side scripting. Hope that useful.
One last thing that I'm going to tell you is the "Help" section in the Portal.
Open the SCRIPT tab and you can see the "?" sign at the bottom write of the screen.

If you click on that, it brings up the whole thing of help that basically tells you how to go and do things in scripts. So this will really be helpful for you to do server side scripting.

Source Code of Sample App

Click here to download the source code.

That's all for now.
Any query is welcome. Please don't forget to comment.
Thank you. :)