Sie sind auf Seite 1von 203

Backendless API for .

NET
2015 Backendless Corp.
Backendless API for .NET

2015 Backendless Corp.

All rights reserved. No parts of this work may be reproduced in any form or by any means - graphic, electronic, or
mechanical, including photocopying, recording, taping, or information storage and retrieval systems - without the
written permission of the publisher.

Products that are referred to in this document may be either trademarks and/or registered trademarks of the
respective owners. The publisher and the author make no claim to these trademarks.

While every precaution has been taken in the preparation of this document, the publisher and the author assume no
responsibility for errors or omissions, or for damages resulting from the use of information contained in this
document or from the use of programs and source code that may accompany it. In no event shall the publisher and
the author be liable for any loss of profit or any other commercial damage caused or alleged to have been caused
directly or indirectly by this document.

Generated on: December 2015

Special thanks to:


All the people who contributed to this document, to everyone who
has helped us out with the vision for the product, feature
suggestions and ideas for improvements. Special thank s to our
families for your support, encouragement and patience.
Contents 3
Table of Contents

User Service 6
1 Overview
................................................................................................................................... 6
2 Setup ................................................................................................................................... 6
3 Core Classes
................................................................................................................................... 7
4 Error Handling
................................................................................................................................... 9
5 User Properties
................................................................................................................................... 10
6 Retrieve
...................................................................................................................................
User Entity Properties 11
7 User Registration
................................................................................................................................... 13
8 Login................................................................................................................................... 16
9 Update
...................................................................................................................................
User Properties 19
10 Get Current
...................................................................................................................................
User 21
11 Logout
................................................................................................................................... 22
12 Password
...................................................................................................................................
Recovery 23
13 Security
................................................................................................................................... 25
14 User to
...................................................................................................................................
Role Mapping 29

Data Service 30
1 Overview
................................................................................................................................... 30
2 Setup................................................................................................................................... 30
3 Error ...................................................................................................................................
Handling 31
4 Native...................................................................................................................................
vs External Databases 32
5 Using...................................................................................................................................
External Databases 33
6 Saving
...................................................................................................................................
Data Objects 37
7 Updating
...................................................................................................................................
Data Objects 37
8 Deleting
...................................................................................................................................
Data Objects 41
9 Retrieving
...................................................................................................................................
Schema Definition 44
10 Basic...................................................................................................................................
Search 45
11 Advanced
...................................................................................................................................
Search 45
12 Using...................................................................................................................................
Dates in Search 48
13 Relations
...................................................................................................................................
Overview 49
14 Relations
...................................................................................................................................
(Save/Update) 55
15 Relations
...................................................................................................................................
(Delete) 58
16 Relations
...................................................................................................................................
(Retrieve) 60
17 Relations
...................................................................................................................................
with Geo Points 63
18 Security
................................................................................................................................... 69

2015 Backendless Corp.

3
4 Backendless API for .NET

19 Permissions
...................................................................................................................................
API 75

Messaging Service 78
1 Overview
................................................................................................................................... 78
2 Setup................................................................................................................................... 79
3 Core ...................................................................................................................................
Classes 80
4 Error ...................................................................................................................................
Handling 84
5 Push ...................................................................................................................................
Notification Setup (Android) 85
6 Push ...................................................................................................................................
Notification Setup (iOS) 88
7 Message
...................................................................................................................................
Publishing 98
8 Publish
...................................................................................................................................
Push Notifications 110
9 Cancel
...................................................................................................................................
Scheduled Message 111
10 Message
...................................................................................................................................
Subscription 113
11 Cancel
...................................................................................................................................
Subscription 119
12 Sending
...................................................................................................................................
Email 120

File Service 121


1 Overview
................................................................................................................................... 121
2 Setup
................................................................................................................................... 122
3 Error...................................................................................................................................
Handling 123
4 Handling
...................................................................................................................................
Files via Console 124
5 File ...................................................................................................................................
Upload 128
6 Save...................................................................................................................................
Files From Byte Arrays 131
7 File ...................................................................................................................................
Download 133
8 File ...................................................................................................................................
Deletion 134
9 Directory
...................................................................................................................................
Deletion 135
10 Git Integration
................................................................................................................................... 136
11 Web...................................................................................................................................
Hosting 137
12 Custom
...................................................................................................................................
Domain Name 138
13 Custom
...................................................................................................................................
Web Template Hosting 139
14 Files...................................................................................................................................
Security 142

Geo Service 143


1 Overview
................................................................................................................................... 143
2 Setup
................................................................................................................................... 145
3 Error...................................................................................................................................
Handling 146
4 Adding
...................................................................................................................................
a Geo Category 147
5 Deleting
...................................................................................................................................
a Geo Category 150
6 Retrieving
...................................................................................................................................
Geo Categories 152
7 Adding
...................................................................................................................................
a GeoPoint 153

2015 Backendless Corp.


Contents 5
8 Updating
...................................................................................................................................
a GeoPoint 155
9 Deleting
...................................................................................................................................
a GeoPoint 155
10 Importing
...................................................................................................................................
Geo Data 157
11 Search
...................................................................................................................................
in Category 158
12 Search
...................................................................................................................................
in Radius 163
13 Search
...................................................................................................................................
in Rectangular Area 169
14 Geo...................................................................................................................................
Point Clustering 174
15 Relations
...................................................................................................................................
with Data Objects 180
16 Geofence
...................................................................................................................................
Designer 184
17 Geofence
...................................................................................................................................
API 195

Index 201

2015 Backendless Corp.

5
6 Backendless API for .NET

1 User Service

1.1 Overview
The Backendless User Service empowers applications with the functionality related to the user accounts
such as user registrations, logins, password recovery and logouts. The core concept which the User
Service relies on is the User entity. The structure of the entity is configurable, that is a developer can
decide which properties "describe" a user in the context of a given version of the application. Typically,
properties describing a user are the ones collected during the user registration process. The User
Service provides the API enabling the following functionality for the applications built on top of
Backendless:

User Registration - Applications use the Backendless' registration API to let the users register
and create accounts for subsequent logins. Application developers can restrict access to the
server-side resources for specific user accounts or based on roles.
User Login - the API lets the registered users login to establish their identity within the
application.
Password Recovery - Backendless supports a complete workflow allowing users to recover lost or
forgotten passwords.
User Logout - the API lets the logged in users terminate their session and disassociate their
identity from the application.
Updating User Registration - the API supports the operation of updating user information.

1.2 Setup
To get access to the Backendless services, .NET and Windows Phone applications must reference the
backendless.dll assembly available in the Backendless SDK for .NET. All the Backendless SDK for .
NET classes are available in the BackendlessAPI namespace. Before the .NET/Windows Phone client
uses any of the APIs, the code must initialize the Backendless Application using the following call:
Backendless.InitApp( application-Id, secret-key, version )

Application ID and Secret Key


Values for the application-id and secret-key headers must be obtained through the Backendless
Console:

1. Login to your account and select the application.


2. Click the Manage icon from the vertical icon-menu on the left.
3. The "App Settings" section is selected by default. The interface contains the text fields for
"Application ID" and secret keys for each supported client-side environment.
4. Use the "Copy" button to copy the value into the system clipboard.

2015 Backendless Corp.


User Service 7

The version argument must contain the name of the targeted version. When a new application is
created, the default version name is "v1" . To manage versions, login to the console, select the
"Manage" icon and click "Versioning".

1.3 Core Classes


The Backendless User Service uses the following core classes:

Backendless.UserService - provides access to the user service API. All operations user-related
operations, such as user registration, user update, login, logout and password recovery are available
through this class.

Backendless.BackendlessUser - represents a user registered with the application. The class is


used in:
User Registration - an instance of the class contains a list of user properties
User Registration/Properties Update - an instance of the class contains a list of properties to be
updated
The Login method returns an instance of the class upon successful login.
BackendlessUser Class Definition
The Backendless.BackendlessUser class is defined as:
namespace Backendless
{
public class BackendlessUser
{

2015 Backendless Corp.


8 Backendless API for .NET

public BackendlessUser()

// initialize the user object with the given properties


public BackendlessUser( Dictionary<string, object>
properties )

// returns all properties of the user object


public Dictionary<string, object> Properties { get; set; }

// returns property value for the given key


public object GetProperty( string key )

// sets property value for the key


public void SetProperty( string key, object value )

// for each property in the collection: overrides the


value the user object
// already contains a property for the key, otherwise,
adds the property
public void PutProperties( Dictionary<string, object>
properties )

// returns or sets the value for the 'password' property


public string Password { get; set; }

// returns the Id assigned by the Backendless servers


public string Id { get; }
}
}

Backendless.AsyncCallBack<T> - a class used in the asynchronous API calls. An instance of the


class must reference two delegate methods. One accepting a result from the server (with the generic
type T as the argument) and the other for handling errors reported by the server.
Backendless.AsyncCallback Class Definition
The Backendless. AsyncCallback<T> interface is defined as:
namespace Backendless
{
public delegate void ErrorHandler( Fault fault );
public delegate void ResponseHandler<T>( T response );

public class AsyncCallback<T>


{
public AsyncCallback( ResponseHandler<T> responseHandler,
ErrorHandler errorHandler );
}
}

Backendless.Fault and Backendless.BackendlessException - Used in error handling,


asynchronous and synchronous respectfully.

2015 Backendless Corp.


User Service 9
1.4 Error Handling
When the server reports an error, it is delivered to the client through an instance of the
BackendlessFault class. A BackendlessFault object provides access to an error code which uniquely
identifies the root cause of the error. In addition to the error code, the fault object may include an error
message which provides additional information about the error:
using System;
using Weborb.Client;

namespace BackendlessAPI.Exception
{
public class BackendlessFault
{
private readonly string _faultCode;
private readonly string _message;
private readonly string _detail;

public string Detail


{
get { return _detail; }
}

public string FaultCode


{
get { return _faultCode; }
}

public string Message


{
get { return _message; }
}

public override string ToString()


{
return String.Format( "Backendless BackendlessFault. Code: {0},
Message: {1}", FaultCode ?? "N/A", Message ?? "N/A" );
}
}
}

The asynchronous API calls accept the AsyncCallback argument which receives the fault object
through the following delegate:
public delegate void ErrorHandler( Fault fault );

The synchronous API calls declare a checked exception - BackendlessException. The fault object can
be obtained from the exception:
namespace BackendlessAPI
{
public class BackendlessException : Exception
{
public Fault Fault { get; }
public string Code { get; }

2015 Backendless Corp.


10 Backendless API for .NET

public override string Message { get; }


public override string ToString();
}
}

1.5 User Properties


When a user registers with an application, he provides information which establishes the person's
identity. For one application these properties may include name, phone number and email address, for
another it could be user id, age and gender. Backendless User Service allows each application to have a
custom set of properties associated with the user entity. There are two ways to define what properties
the User entity should have in a Backendless application:

Defining properties with Console


User property management is available on the User Properties screen of the console. To get to the
screen:
1. Login to the console
2. Select the desired application and version
3. Click the Users icon on the left side of the interface. The "User Properties" panel is selected by
default.

The interface consists of two lists: Available Properties and Selected Properties. The Selected
Properties list contains the properties assigned to the User entity - these are the effective properties for
the selected version of the application. The Available Properties list is simply a storage for the non-
effective properties which can be moved to the Selected list if needed. A property can be moved between
the lists by clicking its name.

Identity Property
Among the Selected Properties, one must be marked as identity. This is the property Backendless
uses for the Login and Restore Password operations.. As users register, Backendless ensures the
provided value for the property selected as identity is unique in the context of a specific version for
an application.

Password Property
"password" is a special property. Backendless automatically adds the property when an application
is created. The following rules apply to the password property:
Password cannot be moved out of the Available Properties list.
Password cannot be marked as Identity.
Password is always a required property

2015 Backendless Corp.


User Service 11

To add a property, click the "Add Custom Property" button. New properties automatically added to the
Selected Properties list. To move a property to the other list, simply click its name.

Defining properties with API


User properties can be defined with the user registration API call. For any property specified in the
object with the user registration information Backendless creates a user property. This behavior can be
turned off/on using the Dynamic User Definition configuration setting in the console (select the Users >>
User Properties). The setting is turned on by default:

1.6 Retrieve User Entity Properties


Application developers can get a list of the properties associated with the user entity using the following
API:

Asynchronous Call Method Signature:


The method call does not block - it returns immediately. The AsyncCallback argument receives either
the response or the fault returned by the Backendless servers.
public void Backendless.UserService.DescribeUserClass
( AsyncCallback<List<UserProperty>> callback );

where:
callback - an object which receives either a return value or an error from the server. The return
value from the server is a collection of the UserProperty objects. The callback object
must be an instance of the AsyncCallback<List<UserProperty>> class .
The UserProperty class is defined as:

2015 Backendless Corp.


12 Backendless API for .NET

namespace Backendless.Property
{
public class UserProperty
{
public bool IsIdentity { get; set; }
public string Name { get; set; }
public bool IsRequired { get; set; }
public bool IsSelected { get; set; }
public DateTypeEnum Type { get; set; }
public object DefaultValue { get; set; }
}
}

Synchronous Call Method Signature:


public List<UserProperty> Backendless.UserService.DescribeUserClass
();

Asynchronous Call Example:


Backendless.App.Init( appId, secretKet, version ); // where to get
the argument values for this call
Backendless.AsyncCallback<List<UserProperty>> callback;

callback = new Backendless.AsyncCallback<List<UserProperty>>(


props =>
{
foreach( Backendless.Property.UserProperty p in props )
{
System.Console.WriteLine( "prop name " + p.Name );
System.Console.WriteLine( "\tis identity " + p.
IsIdentity );
System.Console.WriteLine( "\tis required " + p.
IsRequired );
System.Console.WriteLine( "\tprop type " + p.Type );
System.Console.WriteLine( "\tdefault value " + p.
DefaultValue );
}
},
fault =>
{
System.Console.WriteLine( fault.ToString() );
} );

Backendless.UserService.DescribeUserClass( callback );

Synchronous Call Example:


Backendless.App.Init( appId, secretKet, version ); // where to get
the argument values for this call
List<UserProperty> properties = Backendless.UserService.
DescribeUserClass();

2015 Backendless Corp.


User Service 13
foreach( Backendless.Property.UserProperty p in properties )
{
System.Console.WriteLine( "prop name " + p.Name );
System.Console.WriteLine( "\tis identity " + p.IsIdentity );
System.Console.WriteLine( "\tis required " + p.IsRequired );
System.Console.WriteLine( "\tprop type " + p.Type );
System.Console.WriteLine( "\tdefault value " + p.DefaultValue );
}

1.7 User Registration


The user registration API can be used to create user accounts in the application. The registration
request must provide a user object as a collection of key/value properties. The collection must contain
all the required properties which must include a property marked as identity as well as the "password"
property. Unless the properties are modified in the console, the default property marked as identity is
"email" . Additionally, the "email" property is required if the application is configured to confirm email
addresses for the registered users.

Asynchronous Call Method Signature:


The method call does not block - it returns immediately. The AsyncCallback argument receives either
the response or the fault returned by the Backendless servers.
Backendless.UserService.Register( BackendlessUser user,
AsyncCallback<BackendlessUser>()
callback );

where:
user - an instance of the BackendlessUser class which contains property values for the
account registration.
callback - an object which receives either a return value or an error from the server. The return
value from the server is an instance of the BackendlessUser class with the ID assigned
by the server-side. The callback object must be an instance of the
AsyncCallback<BackendlessUser> class .

Synchronous Call Method Signature:


public BackendlessUser Backendless.UserService.Register
( BackendlessUser userObj );

Error Codes:
The following errors may occur during User Registration API calls. See the Error Handling section for
details on how to retrieve the error code when the server returns an error.
Error Description
Code
2002 Version is disabled or provided wrong application info (application id or
secret key)
3009 User registration is disabled for the version of the application
3010 User registration has an unknown property and dynamic properties are
disabled for this version of the application

2015 Backendless Corp.


14 Backendless API for .NET

3011 Missing "password" property


3012 Required property is missing
3013 Missing value for the identity property
3014 External registration failed with an error.
3021 General user registration error. Details included with the error message.
3033 User with the same identity already exists
3038 Missing application-id, version name or collection of properties for the
registering user
3039 Property "id" cannot be used in the registration call
3040 Email address is in the wrong format
3041 A value for a required property is missing
3043 Duplicate properties in the registration request
8000 Property value exceeds the length limit

Asynchronous Call Example:


Backendless.App.Init( appId, secretKet, version ); // where to get
the argument values for this call
Backendless.AsyncCallback<BackendlessUser> callback = new
AsyncCallback<BackendlessUser>(
user =>
{
System.Console.WriteLine( "User registered. Assigned ID -
" + user.Id );
Dictionary<string, object> props = user.Properties;

foreach( KeyValuePair<string, object> pair in props )


System.Console.WriteLine( String.Format( "Property: {0}
- {1}", pair.Key, pair.Value ) );
},
fault =>
{
System.Console.WriteLine( fault.ToString() );
} );

BackendlessUser newUser = new BackendlessUser();


newUser.SetProperty( "login", "james.bond" );
newUser.SetProperty( "email", "jb@mi6.co.uk" );
newUser.Password = "hard2guess";
Backendless.UserService.Register( newUser, callback );

Synchronous Call Example:


Backendless.App.Init( appId, secretKet, version ); // where to get
the argument values for this call

BackendlessUser newUser = new BackendlessUser();


newUser.SetProperty( "login", "james.bond" );
newUser.SetProperty( "email", "jb@mi6.co.uk" );

2015 Backendless Corp.


User Service 15
newUser.Password = "hard2guess";
newUser = Backendless.UserService.Register( newUser );

System.Console.WriteLine( "User registered. Assigned ID - " + user.


Id );
Dictionary<string, object> props = user.Properties;

foreach( KeyValuePair<string, object> pair in props )


System.Console.WriteLine( String.Format( "Property: {0} - {1}",
pair.Key, pair.Value ) );

Turning Registration Off


User registration can be disabled for a particular version of the application using the Backendless
Console:
1. Login to the console and select the application.
2. Click the "Users" icon in the vertical icon menu on the left.
3. Click "Registration".

The "Registration" toggle turns the registration API on or off. When the registration is turned off and a
user attempts to register, the system returns error 3009 .

Email Confirmations
Backendless can send out an email requesting new registered users to confirm their email address. This
feature can be configured in the Backendless Console:
1. Log into the console and select the application.
2. Click the "Users" icon in the vertical icon menu on the left.
3. Click "Registration".

When email confirmations are required (the feature is enabled by default), the "email" user property is
required and must contain a value formatted as an email address. To configure the text of the email
message, select "Communication & Email Templates" from the Users menu in the console and select
the "User registers" event.

External Registration
User registrations can be duplicated in an external system through the External Registration Callback.
Developer can specify a URL where Backendless sends a POST request to with the user registration
data as a JSON object. The external registration callback is synchronous and takes place in the same
transaction as the Backendless registration call. As a result, the external system must return result as
fast as possible. The format of the request and response for the external registration is the same as the
request/response body of the Backendless registration API.
To configure the callback:
1. Login to the console and select the application.

2015 Backendless Corp.


16 Backendless API for .NET

2. Click the "Users" icon in the vertical icon menu on the left.
3. Click "Registration".
4. Turn on the "Execute registration callback" toggle.
5. Enter the URL of the script into the "Callback URL" text field.

1.8 Login
Registered users can login to establish their identity with the application using the API below. The login
operation requires two properties: one marked as user identity and the second is password .
Backendless automatically assigns the "AuthenticatedUser" role to all successfully logged in users.
The role can be used to differentiate access to various resources (persistent objects, messaging
channels, media streams) between authenticated users and guests.

Asynchronous Call Method Signature:


The method call does not block - it returns immediately. The AsyncCallback argument receives either
the response or the fault returned by the Backendless servers.
public void Backendless.UserService.Login( String login,
String password,
AsyncCallback<Backendle
ssUser> callback );

where:
login - a value for the property marked as identity.
password - user's password
callback - an object which receives either a return value or an error from the server. The class
must be an instance of the AsyncCallback<BackendlessUser> class .

Synchronous Call Method Signature:


public BackendlessUser Backendless.UserService.login( String login,
String password );

where:
login - a value for the property marked as identity.
password - user's password

Error Codes:
The following errors may occur during the Login API call. See the Error Handling section for details on
how to retrieve the error code when the server returns an error.
Error Description
Code
2002 Version is disabled or provided wrong application info (application id
or secret key)
3000 Login has been disabled for the user account.
3001 Missing login settings, possibly invalid application id or version.
3002 User cannot login because Multiple Logins disabled and there is a

2015 Backendless Corp.


User Service 17
logged in user for the account.
3003 Invalid login or password.
3006 Either login or password is an empty string value.
3034 User logins are disabled for the version of the application.
3036 Account locked out due to too many failed logins.
3038 One of the required parameters (application id, version, login or
password) is null
3044 Multiple login limit for the same user account has been reached.
8000 Property value exceeds the length limit

Asynchronous Call Example:


Backendless.App.Init( appId, secretKet, version ); // where to get
the argument values for this call
Backendless.AsyncCallback<BackendlessUser> callback = new
AsyncCallback<BackendlessUser>(
user =>
{
System.Console.WriteLine( "User logged in. Assigned ID -
" + user.Id );
Dictionary<string, object> props = user.Properties;
foreach( KeyValuePair<string, object> pair in props )
System.Console.WriteLine( String.Format( "Property: {0}
- {1}", pair.Key, pair.Value ) );
},
fault =>
{
System.Console.WriteLine( fault.ToString() );
} );

String login = "james.bond123";


String password = "guessIt";
Backendless.UserService.Login( login, password, callback );

Synchronous Call Example:


Backendless.App.Init( appId, secretKet, version ); // where to get
the argument values for this call
BackendlessUser user;

try
{
String login = "james.bond123";
String password = "guessIt";
user = Backendless.UserService.Login( login, password );
}
catch( BackendlessException exception )
{
// login failed, to get the error code, call exception.Fault.
FaultCode

2015 Backendless Corp.


18 Backendless API for .NET

External Authentication
Similar to external registration, Backendless supports external authentication. When configured,
Backendless delegates the authentication process to an external system by sending the provided user
credentials to a URL. The URL of the external authentication system can be configured in Backendless
Console:
1. Log into the console and select the application.
2. Click the "Users" icon in the vertical icon menu on the left.
3. Click "Login".
4. The "External authentication" section contains the configuration settings.

When the external authentication is enabled and user attempts to login, Backendless sends the
following request to the specified URL:
POST http://external-authentication-url
Authorization: Basic base64-encoded-login:password

Where base64-encoded-login:password is constructed as follows:


1. login and password are combined into a string "login:password"
2. The resulting string literal is then encoded using Base64

Multiple Logins
The Multiple Logins feature enables login using the same account from different computers or devices.
Multiple logins can be configured in the Backendless Console:
1. Log into the console and select the application.
2. Click the "Users" icon in the vertical icon menu on the left.
3. Click "Login".
4. The "Multiple Logins" section contains the configuration settings.
When the feature is turned on (multiple logins allowed), the configuration setting may include the
maximum number of simultaneous logins for the selected version of the application. When the feature is
disabled (multiple logins are not allowed), the configuration must indicate whether which login should be
invalidated (first or second for the account):

2015 Backendless Corp.


User Service 19

Session Timeout
Backendless supports session expiration which can be configured in console. Along with the session
timeout interval, the configuration can also include a forwarding URL which is used to redirect requests
to for the expired sessions.

Account Lockout
An application powered by Backendless can be configured to lock out accounts with failed logins. The
console has two configuration options: number of failed logins before the account is locked and a time
interval to wait before the account is available for logins again.

1.9 Update User Properties


Backendless supports the operation of user properties update for the logged in users. This operation is
useful if an application needs to provide to the users the functionality for updating user profiles and
registration properties. User must be logged in in order to update his registration properties.

Asynchronous Call Method Signature:


The method call does not block - it returns immediately. The AsyncCallback argument receives either
the response or the fault returned by the Backendless servers.
public void Backendless.UserService.Update( BackendlessUser user,
AsyncCallback<Backendle
ssUser> callback );

2015 Backendless Corp.


20 Backendless API for .NET

where:
user - an instance of the BackendlessUser class which contains property values to update
the user account with.
callback - an object which receives either a return value or an error from the server. The return
value from the server is an updated instance of the BackendlessUser class. The class
of the callback object must be an instance of the AsyncCallback<BackendlessUser>
class .

Synchronous Call Method Signature:


public BackendlessUser Backendless.UserService.Update
( BackendlessUser user );

where:
user - an instance of the BackendlessUser class which contains property values to update
the user account with.

Error Codes:
The following errors may occur during the Update User Properties API call. See the Error Handling
section for details on how to retrieve the error code when the server returns an error.
Error Description
Code
2002 Version is disabled or provided wrong application info (application id or
secret key)
3018 The property marked as "identity" is being updated and another user
already has the specified value which must be unique.
3024 General "update registration" error. Error message should contain
additional details.
3028 User is not logged in.
3029 Cannot modify properties of another user. Returned when one user is
logged and the call attempts to modify properties of another user.
3030 Unable to locate user account - invalid user id.
3031 A new "dynamic" property is being added, but dynamic property
definition is disabled.
3045 Required properties in the provided object do not contain values.

Asynchronous Call Example:


Backendless.initApp( appId, secretKet, version ); // where to get
the argument values for this call
Backendless.AsyncCallback<BackendlessUser> updateCallback = new
AsyncCallback<BackendlessUser>(
user =>
{
System.Console.WriteLine( "User account has been updated"
);
Dictionary<string, object> props = user.Properties;
foreach( KeyValuePair<string, object> pair in props )
System.Console.WriteLine( String.Format( "Property: {0}
- {1}", pair.Key, pair.Value ) );
},

2015 Backendless Corp.


User Service 21
fault =>
{
System.Console.WriteLine( fault.ToString() );
} );

Backendless.AsyncCallback<BackendlessUser> loginCallback = new


AsyncCallback<BackendlessUser>(
user =>
{
user.SetProperty( "phoneNumber", "5551212" );
Backendless.UserService.Update( user, updateCallback );
},
fault =>
{
System.Console.WriteLine( fault.ToString() );
} );

Backendless.UserService.Login( login, password, loginCallback );

Synchronous Call Example:


Backendless.initApp( appId, secretKet, version ); // where to get
the argument values for this call
BackendlessUser user;

try
{
user = Backendless.UserService.Login( username, password );
}
catch( BackendlessException exception )
{
// login failed, to get the error code, call exception.Fault.
FaultCode
}

try
{
user.setProperty( "phoneNumber", "5551212" );
user = Backendless.UserService.Update( user );
}
catch( BackendlessException exception )
{
// update failed, to get the error code, call exception.Fault.
FaultCode
}

1.10 Get Current User


A .NET application can retrieve an instance of BackendlessUser representing the currently logged in
user using the following API call:
public BackendlessUser Backendless.UserService.CurrentUser

2015 Backendless Corp.


22 Backendless API for .NET

{
get;
}

If a user is not logged in, the method returns null .

1.11 Logout
The Logout operation terminates user session and disassociates the AuthenticatedUser role from the
subsequent requests made by the client application.

Asynchronous Call Method Signature:


The method call does not block - it returns immediately. The AsyncCallback argument receives either
the response or the fault returned by the Backendless servers.
public void Backendless.UserService.Logout( AsyncCallback<Object>
callback )

where:
callback - an object which is notified when the server completes the logout operation or returns
an error. The class must be an instance of the AsyncCallback<BackendlessUser> class .

Synchronous Call Method Signature:


public void Backendless.UserService.Logout();

Error Codes:
The following errors may occur during the Logout API call. See the Error Handling section for details on
how to retrieve the error code when the server returns an error.
Error Description
Code
2002 Version is disabled or provided wrong application info (application id or
secret key)
3007 Invalid application-id or version.
3023 General error while executing logout. Error details should be available in
the message property.

Asynchronous Call Example:


Backendless.App.Init( appId, secretKet, version ); // where to get
the argument values for this call
Backendless.AsyncCallback<Object> logoutCallback = new
AsyncCallback<Object>(
user =>
{
System.Console.WriteLine( "User has been logged out" );
},
fault =>
{
System.Console.WriteLine( fault.ToString() );
} );

Backendless.AsyncCallback<BackendlessUser> loginCallback = new

2015 Backendless Corp.


User Service 23
AsyncCallback<BackendlessUser>(
user =>
{
UserService.Logout( logoutCallback );
},
fault =>
{
System.Console.WriteLine( fault.ToString() );
} );

UserService.Login( login, password, loginCallback );

Synchronous Call Example:


Backendless.App.Init( appId, secretKet, version ); // where to get
the argument values for this call
BackendlessUser user;

try
{
user = Backendless.UserService.Login( username, password );
}
catch( BackendlessException exception )
{
// login failed, to get the error code, call exception.Fault.
FaultCode
}

try
{
// now log out:
Backendless.UserService.Logout();
}
catch( BackendlessException exception )
{
// logout failed, to get the error code, call exception.Fault.
FaultCode
}

1.12 Password Recovery


Password recovery sends an email to the user's email address with a link where the user can change
the password.

Asynchronous Call Method Signature:


The method call does not block - it returns immediately. The AsyncCallback argument receives either
the response or the fault returned by the Backendless servers.
public void Backendless.UserService.restorePassword( String
identityValue, AsyncCallback<Object> callback )

where:
identityValue - a value for the property marked as identity which uniquely identifies the user
within the application.

2015 Backendless Corp.


24 Backendless API for .NET

callback - an object which is notified when the server completes the logout operation or
returns an error. The class must be an instance of the
AsyncCallback<BackendlessUser> class .

Synchronous Call Method Signature:


public void Backendless.UserService.restorePassword( String
identityValue );

where:
identityValue - a value for the property marked as identity which uniquely identifies the user
within the application.

Error Codes:
The following errors may occur during the Password Recovery API call. See the Error Handling section
for details on how to retrieve the error code when the server returns an error.
Error Description
Code
2002 Version is disabled or provided wrong application info (application id or
secret key)
3020 Unable to find user with the specified login (invalid user identity).
3025 General password recovery error. Additional details should be available
in the "message" property of the response.
3038 One of the requirement arguments (application id, version or user
identity) is missing.

Asynchronous Call Example:


Backendless.App.Init( appId, secretKet, version ); // where to get
the argument values for this call
Backendless.AsyncCallback<Object> pwRecoveryCallback = new
AsyncCallback<Object>(
user =>
{
System.Console.WriteLine( "Password recovery email has
been sent" );
},
fault =>
{
System.Console.WriteLine( fault.ToString() );
} );

UserService.RestorePassword( identityPropValue,
pwRecoveryCallback );

Synchronous Call Example:


Backendless.App.Init( appId, secretKet, version ); // where to get
the argument values for this call

try
{
UserService.RestorePassword( identityPropValue );

2015 Backendless Corp.


User Service 25
System.Console.WriteLine( "Password recovery email has been sent"
);
}
catch( BackendlessException exception )
{
// password recovery failed, to get the error code, call
exception.Fault.FaultCode
}

1.13 Security
All Backendless API operations can be restricted either for specific user accounts or for roles. A user
account may be associated with one or more roles. Backendless supports several built-in system roles
as well as developer-defined roles. The system roles include:
NotAuthenticatedUser - any user who has not authenticated to a Backendless application.
AuthenticatedUser - any user who has successfully logged in.
SocialUser - any user who has logged in through a social network.
FacebookUser - any user who has logged in with a Facebook account.
TwitterUser - any user who has logged in with a Twitter account.

Developer-defined roles can be added using the Backendless Console. Roles are defined at the
application version level, that is a particular version of an application may have its own set of developer-
defined roles.

Backendless manages permissions as tuples consisting of:


Operation - Users interact with Backendless either via console or the API. Any request to
Backendless is an operation which may have a permission associated with it.
Resource - Some operations target specific resources. These can be data tables, messaging
channels or media tubes.
Principal - Either a specific user identity or a role associated with the user initiating the operation.

There are two levels of permissions for the API operations - global and resource-specific. The resource-
specific permissions guard access to the specific resources (data tables, messaging channels, etc).
They have higher priority and are checked first. When Backendless receives an API call from a client, it
determines the user associated with the request and obtains a list of roles associated with the user
account (for the users who have not authenticated, the NotAuthenticatedUser role is used). The
resource-specific permissions can be set to either inherit the permission from the global matrix or
explicitly grant or deny access to the resource for the given user or role. The diagram below illustrates
the process when the resource-specific permission is set to inherit:

2015 Backendless Corp.


26 Backendless API for .NET

When the resource-specific permission is explicitly set to either grant or deny access, the global
permissions are bypassed:

Global Permissions
The global service permissions apply to all resources managed by a particular service. For example,
global Data Service permissions for a particular role apply to all data tables. These permissions can be
viewed and modified by clicking a role on the Users > Security and Restrictions screen in Backendless
Console:

2015 Backendless Corp.


User Service 27

The table below shows a global permissions matrix for a role:

2015 Backendless Corp.


28 Backendless API for .NET

Each global permission has two states:


Grant - represented by a green check mark - grants the rights to execute an operation
Deny - represented by a red X - denies the rights to execute an operation.
To change a permission click the icon of the current state. The change will be effective immediately.

To register a new role use the "Add Role" button on the "Security and Restrictions" screen. Once a role
is added, you can configure it's global permission matrix as well as resource-specific permissions.

Resource-Specific Permissions
To view, assign or modify resource-specific permissions, use a corresponding screen in the
Backendless Console. For example, to restrict access to a data table, switch to the Data view, select a
table and click the "Schema and Permissions" button. The user interface has two views - one is for
managing permissions for user accounts and the other for roles. To modify permissions for a user
account:
1. Click the "User Permissions" list item.
2. Enter the user name in the search field.
3. Select the user and click the "Add" button.
4. The table displays the permissions for various operations for the selected user and the resource.
5. Click an icon representing the permission state to modify the permission.

2015 Backendless Corp.


User Service 29

Similarly permissions can be assigned or modified for specific roles - use the "Role Permissions" list
item.
To modify the permissions for Messaging channels, click the "Messaging" icon, select a channel and
switch to the "Permissions" view.

1.14 User to Role Mapping


User accounts can be mapped to roles in Custom Business Logic (available for Android and REST).
Once a role is assigned to a user account, any permissions assigned to the role (both grant and deny)
automatically apply to all API operations executed by the application on behalf of the user.

Retrieving Available User Roles


Before you assign a user to a role, you might need to figure out what roles are available in the system.
Please note that the system will return the list of the roles associated with your user account in
Backendless. If you send the request without logging in, the system will return only one role -
NotAuthenticatedUser.

To get the list of the available user roles:


Method
List<String> userRoles = Backendless.UserService.GetUserRoles();

Example:
To retrieve the list of the available user roles, you need to log in first:
static void LoginUser ()
{
Backendless.UserService.Login( "joe@developer.com", "password" );
}

Then, retrieve the list of the available roles:


static void GetUserRoles()
{
IList<String> userRoles = Backendless.UserService.GetUserRoles();

foreach( String roleName in userRoles )


System.Console.WriteLine( roleName );
}

If you try to retrieve the available roles without logging in:


static void GetUserRoles()
{
IList<String> userRoles = Backendless.UserService.GetUserRoles();

2015 Backendless Corp.


30 Backendless API for .NET

foreach( String roleName in userRoles )


System.Console.WriteLine( roleName );
}

the system will return only one role - NotAuthenticatedUser.

2 Data Service

2.1 Overview
The Backendless Data Service is a highly scalable, object storage system. It is available via intuitive API
which supports all basic data persistence operations - Create, Retrieve, Update and Delete (CRUD). The
Data Service operates with persistent data at the object level, that means applications use the APIs to
save, update, delete or search for objects, rather than traditional database records. Developers using the
Data Service API do not need to know or understand the databases, schema creation rules, stored
procedures or SQL syntax.

The Data Service follows the following rules when working with user objects:
1. Objects persisted by the Data Service must specify the "type" or be an instance of a class (for
client applications written in strongly-typed languages).
2. Backendless automatically creates tables for each persisted type it has not seen before and
saves objects in the corresponding tables. Each table has columns corresponding to the
properties of the persisted objects.
3. Backendless creates three additional system-level columns for each new table:
objectId - contains a unique object ID assigned by Backendless to each object.
created - contains a timestamp when the object was first saved by Data Service
updated - contains a timestamp when the object was most recently updated. The value is
null for newly created objects.
4. When an object of a known type/class introduces any new properties throughout the lifetime of
the application, the persistence structure will be modified accordingly. When such an object is
persisted, Backendless analyzes the object's properties and automatically alters the structure of
the corresponding table if any new properties are added.
5. When an object is saved or updated, it may reference another related object (a one-to-one
relationship) or objects (one-to-many). Backendless creates the underlying tables for the main
and the referenced types and persists the hierarchy accordingly.

2.2 Setup
To get access to the Backendless services, .NET and Windows Phone applications must reference the
backendless.dll assembly available in the Backendless SDK for .NET. All the Backendless SDK for .
NET classes are available in the BackendlessAPI namespace. Before the .NET/Windows Phone client
uses any of the APIs, the code must initialize the Backendless Application using the following call:
Backendless.InitApp( application-Id, secret-key, version )

Application ID and Secret Key


Values for the application-id and secret-key headers must be obtained through the Backendless
Console:

1. Login to your account and select the application.

2015 Backendless Corp.


Data Service 31
2. Click the Manage icon from the vertical icon-menu on the left.
3. The "App Settings" section is selected by default. The interface contains the text fields for
"Application ID" and secret keys for each supported client-side environment.
4. Use the "Copy" button to copy the value into the system clipboard.

The version argument must contain the name of the targeted version. When a new application is
created, the default version name is "v1" . To manage versions, login to the console, select the
"Manage" icon and click "Versioning".

2.3 Error Handling


When the server reports an error, it is delivered to the client through an instance of the
BackendlessFault class. A BackendlessFault object provides access to an error code which uniquely
identifies the root cause of the error. In addition to the error code, the fault object may include an error
message which provides additional information about the error:
using System;
using Weborb.Client;

namespace BackendlessAPI.Exception
{
public class BackendlessFault
{
private readonly string _faultCode;
private readonly string _message;
private readonly string _detail;

2015 Backendless Corp.


32 Backendless API for .NET

public string Detail


{
get { return _detail; }
}

public string FaultCode


{
get { return _faultCode; }
}

public string Message


{
get { return _message; }
}

public override string ToString()


{
return String.Format( "Backendless BackendlessFault. Code: {0},
Message: {1}", FaultCode ?? "N/A", Message ?? "N/A" );
}
}
}

The asynchronous API calls accept the AsyncCallback argument which receives the fault object
through the following delegate:
public delegate void ErrorHandler( Fault fault );

The synchronous API calls declare a checked exception - BackendlessException. The fault object can
be obtained from the exception:
namespace BackendlessAPI
{
public class BackendlessException : Exception
{
public Fault Fault { get; }
public string Code { get; }
public override string Message { get; }
public override string ToString();
}
}

2.4 Native vs External Databases


A Backendless backend supports two alternative mechanisms of data persistence. There is a built-in
storage, referred to as native and an external storage. The native mechanism is enabled by default and a
developer working with a Backendless backend does not need to do anything special to configure it. All
the data persisted through the Data Service API and Backendless console is stored internally, in the
database maintained by the Backendless service.

The external storage can be any database located elsewhere which the Backendless service connects
to with the connection parameters provided by the developer. Currently MySQL/MariaDB databases is
the only type of the supported external storage.

2015 Backendless Corp.


Data Service 33
An application must be configured to use either the native or an external storage mechanism, they
cannot be combined into the hybrid mode. However, regardless of which mechanism is enabled, the
Data Service API can be used to work with the data. Additionally, if the application is configured to use
an external database, Backendless console can be used the manage the external data the same way it
does so with native. The only exception is the management of an external schema - Backendless
Console displays it in the view only mode.

To learn more about external data storage, see the Using External Databases chapter.

2.5 Using External Databases


Backendless data storage is an ultra-scalable system for storing objects hierarchies ranging from simple
to very deep and possibly recursive in nature. The default implementation uses an internal persistent
system which functions as a black box from the client-side developer's perspective. The internal
implementation is referred to as native. There are use-cases when the native storage system cannot be
used in an application built with Backendless. For instance, a new mobile application must built on top
of an existing MySQL database which is used by an existing desktop application. To support this
scenario, Backendless provides integration with External Databases. The integration enables a client
application to use the Data Service API as it would with the native storage, however the backend
operates on the data stored externally.

Adding an External Database in Backendless


Console
To link the external database to your Backendless backend:
1. Log in to the Backendless Console, select your app and click the Data icon.
2. Click the External radio-button as shown in the image below:

3. In the Database Connection pop-up window, specify the connection details. To test the
connection, click the Test link. To proceed with the connection, click the Next button.

2015 Backendless Corp.


34 Backendless API for .NET

4. Once a connection is established (it may take several minutes), console displays a list of the
databases in the Database drop-down menu. Select a database and click the Ok button to
confirm your choice.

5. Backendless will inspect the selected database and an email is delivered to the application
developer email address with the status of the inspection.
6. Upon successful database inspection the Data Management screen displays a list of the
tables from the external database.

The user interfaces is updated to reflect the new available functions:


Re-inspect the external database by clicking the Refresh icon:

2015 Backendless Corp.


Data Service 35

Connect to another external database by clicking the add button:

Re-connect (or edit the connection details) to current external database by clicking the
connect button:

2015 Backendless Corp.


36 Backendless API for .NET

Handling Data Objects in an External Database


All of the Data Service APIs can be used with external databases. The only caveat is with the data
tables which have composite primary keys (a PK consisting of more than one column). In this case, the
Data Service API provides special methods where object identity is established by sending in entire
object rather than a specific identity value.
saving an object
updating an object
deleting an object
basic search
advanced search
saving and updating relations
retrieving relations

Supported Data Types


Currently Backendless supports only MySQL and MariaDB as external databases. The table below
provides a mapping between the MySQL data types and the corresponding types in Backendless:
MySQL Data Type Backendless Data Type
varchar( x ) String value with maxLength = x
int Integer
long Long integer
Double
double, float, decimal
tinyint( 1 ) Boolean
datetime Datetime
text Text
other types String

Limitations
2015 Backendless Corp.
Data Service 37
There are several limitations for working with external databases:
1. The number of tables allowed in a database is limited by your billing plan
(which is the same as for the native Backendless storage).
2. There must be a permission for the MySQL information_schema table used
to inspect the external database.
3. Some of the system-level columns (and thus data object properties) will not
be available with the external databases, specifically: updated, created, ownerId
, objectId .
4. You can not use the native and external databases simultaneously; once you establish a
connection with an external database, a native one will not be available any longer and vice
versa.
5. Only one external database can be used in an application (cannot connect to two different
external databases).
6. The schema of an external database cannot be edited in Backendless Console.
7. You can not import data to or export data from an external database using Backendless
Console.
8. If the database schema changes, it is important to re-inspect the database to avoid errors.

2.6 Saving Data Objects


The API to save an object can be used for two separate scenarios: if an object has been previously
saved, it is updated in the data store, otherwise it is saved (created). The save operation checks if the
object has objectId assigned by the server. in that case, the object is updated, otherwise it is created
in the Backendless data store. In case when there is no table for the persisted object, Backendless
creates one and maps table's columns to the object's properties.
The objectId property is automatically assigned to all persisted objects when they are initially saved.
See the Data Object section for details on objectId .

Saving a Data Object in an External Database


When saving a new data object to an external database, you need to take into consideration that such
object does not have some properties characteristic for the native data objects. Thus, these properties
will be omitted in the queries when saving a data object to an external database.

2.7 Updating Data Objects


Updating a data object which has been previously stored in the Backendless data store can be done
using the same API as for saving the initial object version. Once an object has objectId assigned, the
call updates the persisted copy of the object:
Please note: updating an object in a native database differs from updating an object in an external

2015 Backendless Corp.


38 Backendless API for .NET

database.

Updating an Object Individually in a Native Database


Method:
PUT

URL:
https://api.backendless.com/<version>/data/<table-name>/<object-id>

where:
<version> - name of the application's version. Application versions can be
managed using Backendless Console. Login to the console,
select an application, click Manage, then Versioning.
Backendless automatically creates version "v1" for any new
application.
<table-name> - name of the table where the object needs to be updated.
<object-id> - ID of the object to update assigned by Backendless in the
create object operation.

Request Headers:
application-id: app-id-value
secret-key: secret-key-value
Content-Type:application/json
application-type: REST

where:
application-id - the ID of your application generated upon its creation. You can
find this header in the Manage > App Settings section of the
Backendless Console. This header is mandatory. Please refer to
the Setup section for information on how to obtain the values for
the header.
secret-key - the key of your application generated upon its creation. You
can find this header in the Manage > App Settings section of
the Backendless Console. This header is mandatory. Please
refer to the Setup section for information on how to obtain the
values for the header.
Content-Type - the static value, should be set to application/json. This header
is mandatory.
application-type - the static value, should be set to REST. This header is
mandatory.

Sample Request Body:


{
"objectId" : "28325E9F-2DED-D3CA-FFC6-C76911AFBB00"
"name" : "James Bond",
"age" : 33,
"phoneNumber" : "+44123456789",
}

Sample Response Body:

2015 Backendless Corp.


Data Service 39
{
"name" : "James Bond",
"age" : 33,
"phoneNumber" : "+44123456789",
"updated" : "02/05/2014 12:47:10 GMT+0000",
"created" : "02/04/2014 19:40:10 GMT+0000",
"ownerId" : null | <user-id>,
"objectId" : "28325E9F-2DED-D3CA-FFC6-C76911AFBB00",
"___class" : "Person"
}

where:
updated - special property generated by Backendless which contains the
timestamp when the object was last updated.
created - similar to 'updated', but contains the timestamp showing when
the object was initially created.
ownerId - when the object is created by an authenticated user, this
property contains the id of the currently logged in user object.
objectId - unique id (GUID) assigned to the object.
___class - contains the name of the table where the object is stored. This
is the same value as the <table-name> in the URL.

Example:
curl
-H application-id:application-id-value-from-console
-H secret-key:secret-key-value-from-console
-H Content-Type:application/json
-X PUT
-d "{\"name\":\"Bob\", \"age\":20 }"
-v https://api.backendless.com/v1/data/Person/6C77C11B-E9B3-EB14-
FFA2-69F38CF48800

Notice the objectId value is put directly into the URL. The same value is optional in the JSON
body of the request.

Updating Several Objects at a Time (Bulk Update) in


a Native Database
Method:
PUT

URL:
https://api.backendless.com/<app version>/data/bulk/<table-name>?
where=<where clause>

where:
<app version> - name of the application's version. Application versions can be
managed using Backendless Console. Login to the console,
select an application, click Manage, then Versioning.
Backendless automatically creates version "v1" for any new
application.
<table-name> - name of the table where the objects need to be updated.
<where clause> - condition for selecting the objects for the bulk update (please

2015 Backendless Corp.


40 Backendless API for .NET

refer to the examples below in this section). Should be URL


encoded.

Request Headers:
application-id: app-id-value
secret-key: secret-key-value
Content-Type:application/json
application-type: REST

where:
application-id - the ID of your application generated upon its creation. You can
find this header in the Manage > App Settings section of the
Backendless Console. This header is mandatory. Please refer to
the Setup section for information on how to obtain the values for
the header.
secret-key - the key of your application generated upon its creation. You
can find this header in the Manage > App Settings section of
the Backendless Console. This header is mandatory. Please
refer to the Setup section for information on how to obtain the
values for the header.
Content-Type - the static value, should be set to application/json. This header
is mandatory.
application-type - the static value, should be set to REST. This header is
mandatory.

Sample Request:
Bulk update allows changing several data objects selected by the specified criteria. For
instance, if you have the list of employees and need to update their salary info depending on
their time of employment, you can do it by using the bulk update feature.
To test the feature:
1. Create two persons/employees: one employed for 15 days curl -H application-id:
application-id-value-from-console-H secret-key:secret-key-value-
from-console -H Content-Type:application/json -X POST -d
"{\"name\":\"Tom\", \"age\":35, \"salary\":0, \"workDays\":\"15\"}"
-v https://api.backendless.com/v1/data/Person , another one employed for
20 days curl -H application-id:application-id-value-from-console-H
secret-key:secret-key-value-from-console -H Content-Type:
application/json -X POST -d "{\"name\":\"Bob\", \"age\":20,
\"salary\":0, \"workDays\":\"20\"}" -v https://api.backendless.com/
v1/data/Person.
Please note: salaries of both employees are zero.
2. To set new salary (1000) to all staff members that are employed for more than 10 days:
specify the new salary in the -d argument as follows: -d "{\"salary\":1000}"
set the value of <where clause> argument in URL to workDays>10 , that is:
where=workDays>10 . The URL encoded query will look as follows:
curl
-H application-id:application-id-value-from-console
-H secret-key:secret-key-value-from-console
-H Content-Type:application/json
-X PUT
-d "{\"salary\":1000}"
-v https://api.backendless.com/v1/data/bulk/Person?where=workDays%

2015 Backendless Corp.


Data Service 41
3E10

As a result you will receive the response displaying the number of data object updated (2
objects). The salary of both employees will be changed to 1000.

Sample Response:
Server will return the number of the updated objects.

Updating a Data Object in an External Database


When updating a data object in an external database, you need to take into consideration that such
object does not have some properties characteristic for the native data objects. Thus, these properties
will be omitted in the queries when saving a data object to an external database.

2.8 Deleting Data Objects


The API completely removes an object from the persistent store. If the object is successfully delete, the
API returns the timestamp of the exact deletion time in milliseconds.

Please note: deleting an object from a native database differs from deleting an object from an external
database.

Deleting an Object Individually from a Native


Database
Method:
DELETE

URL:
https://api.backendless.com/<version>/data/<table-name>/<object-id>

where:
<version> - name of the application's version. Application versions can be
managed using Backendless Console. Login to the console,
select an application, click Manage, then Versioning.
Backendless automatically creates version "v1" for any new
application.
<table-name> - name of the table where the object needs to be deleted.
<object-id> - ID of the object to delete. The ID assigned by Backendless in
the create object operation.

Request Headers:
application-id: app-id-value
secret-key: secret-key-value
application-type: REST

where:
application-id - the ID of your application generated upon its creation. You can

2015 Backendless Corp.


42 Backendless API for .NET

find this header in the Manage > App Settings section of the
Backendless Console. This header is mandatory. Please refer to
the Setup section for information on how to obtain the values for
the header.
secret-key - the key of your application generated upon its creation. You
can find this header in the Manage > App Settings section of
the Backendless Console. This header is mandatory. Please
refer to the Setup section for information on how to obtain the
values for the header.
application-type - the static value, should be set to REST. This header is
mandatory.

Request Body:
None

Sample Response Body:


{
"deletionTime" : timestamp in milliseconds
}

Example:
curl
-H application-id:application-id-value-from-console
-H secret-key:secret-key-value-from-console
-X DELETE
-v https://api.backendless.com/v1/data/Orders/6C77C11B-E9B3-EB14-
FFA2-69F38CF48800

Deleting Several Objects at a Time (Bulk Delete)


from a Native Database
Method:
DELETE

URL:
https://api.backendless.com/<app version>/data/bulk/<table-name>?
where=<where clause>

where:
<app version> - name of the application's version. Application versions can be
managed using Backendless Console. Login to the console,
select an application, click Manage, then Versioning.
Backendless automatically creates version "v1" for any new
application.
<table-name> - name of the table where the objects need to be deleted.
<where clause> - condition for selecting the objects for the bulk delete (please
refer to the examples below in this section). Should be URL
encoded.

Request Headers:

2015 Backendless Corp.


Data Service 43
application-id: app-id-value
secret-key: secret-key-value
application-type: REST

where:
application-id - the ID of your application generated upon its creation. You can
find this header in the Manage > App Settings section of the
Backendless Console. This header is mandatory. Please refer to
the Setup section for information on how to obtain the values for
the header.
secret-key - the key of your application generated upon its creation. You
can find this header in the Manage > App Settings section of
the Backendless Console. This header is mandatory. Please
refer to the Setup section for information on how to obtain the
values for the header.
application-type - the static value, should be set to REST . This header is
mandatory.
Sample Request:
Bulk delete allows removing several data objects selected by the specified criteria. For instance,
if you have the list of employees and need to delete some of them depending on their time of
employment, you can do it by using the bulk delete feature.
To test the feature:
1. Create three persons/employees:
employed for 15 days curl -H application-id:application-id-value-from-
console-H secret-key:secret-key-value-from-console -H Content-
Type:application/json -X POST -d "{\"name\":\"Tom\", \"age\":35,
\"salary\":0, \"workDays\":\"15\"}" -v https://api.backendless.
com/v1/data/Person
employed for 0 days curl -H application-id:application-id-value-from-
console-H secret-key:secret-key-value-from-console -H Content-
Type:application/json -X POST -d "{\"name\":\"Bob\", \"age\":20,
\"salary\":0, \"workDays\":\"0\"}" -v https://api.backendless.
com/v1/data/Person
employed for 0 days curl -H application-id:application-id-value-from-
console-H secret-key:secret-key-value-from-console -H Content-
Type:application/json -X POST -d "{\"name\":\"Brad\", \"age\":22,
\"salary\":10, \"workDays\":\"0\"}" -v https://api.backendless.
com/v1/data/Person
2. To delete all staff members that are employed for 0 days, set the value of <where clause>
argument in URL to workDays=0 , that is: where=workDays=0 . The URL encoded query will
look as follows:
curl
-H application-id:application-id-value-from-console
-H secret-key:secret-key-value-from-console
-X DELETE
-v https://api.backendless.com/v1/data/bulk/Person?where=workDays%
3D0

As a result you will receive the response displaying the number of data object deleted (2
objects). The second and third employees (Bob and Brad) will be deleted from the database.

2015 Backendless Corp.


44 Backendless API for .NET

Sample Response:
Server will return the number of the deleted objects.

Deleting a Data Object from an External Database


When deleting a data object from an external database, you need to take into consideration that such
object does not have some properties characteristic for the native data objects. Thus, these properties
will be omitted in the queries when deleting a data object from an external database.

2.9 Retrieving Schema Definition


Backendless supports API for data table schema introspection. The API provides information about
table's columns and their data types, whether a value for a column is required or if there is a default
value.
Asynchronous Method:
public void Describe( string className, AsyncCallback<List<ObjectProperty>>
callback )
Synchronous Method:
public List<ObjectProperty> Describe( string className )
where:
className - name of a class corresponding to a data table.

Return value:
Method returns a collection of the ObjectProperty objects. The ObjectProperty class includes
the following properties:
autoLoad:boolean - applies only to relations. If true, the property is set to auto-
load related data for the data retrieval queries.
CustomRegex:String - a regular expression assigned to the column as a validator.
The validator applies when a new object is saved in the table
or an existing one is updated.
DefaultValue:Object - a default value assigned to any object saved/updated in the
table where the column does not have a value.
PrimaryKey:bool - true if the column is or is a part of a primary key.
Name:String - contains the name of a property.
RelatedTable:String - contains the name of the related table(s).
IsRequired:boolean - defines whether a property is optional or required for the
requests which save the initial object or update an existing
one.
Type:DateTypeEnum - defines the column type.

Example:
The example below describes how to retrieve schema for a data table. Consider the following
class:
class Person
{
public String name { get; set; }
public int age { get; set; }
}

Save an instance of the Person class in the persistent storage (this will force Backendless to

2015 Backendless Corp.


Data Service 45
create the Person table):
Person person = new Person();
person.name = "James Bond";
person.age = 42;
Backendless.Persistence.Of<Person>().Save( person );

Run the following request to retrieve table schema:


List<ObjectProperty> properties = Backendless.Persistence.Describe( "Person"
);

foreach( ObjectProperty property in properties )


{
System.Console.WriteLine( "Property name - " + property.Name );
System.Console.WriteLine( "Required property? - " + property.IsRequired );
System.Console.WriteLine( "Type - " + property.Type );
System.Console.WriteLine( "Is the property the primary key? - " + property.
PrimaryKey );
System.Console.WriteLine( "Default value - " + property.DefaultValue );
System.Console.WriteLine( "Custom validator - " + property.CustomRegex );
System.Console.WriteLine( "Is it a relation? (related table name) - " +
property.RelatedTable );
System.Console.WriteLine( "=====================================" );
}

2.10 Basic Search


Backendless supports multiple basic search operations. These include finding an object by ID, finding
first or last object in the collection or retrieving the entire persisted collection. Each method is available
in both synchronous and asynchronous versions:

Please note: searching for an object in a native database differs from searching for an object in an
external database.

Searching for a Data Object in a Native Database

Searching for a Data Object in an External Database


When searching for a data object in an external database, it is important to keep in mind that external
objects do not have all the same properties as the native data objects. See the complete list of
differences for more details.

2.11 Advanced Search


Advanced search use-cases supported by Backendless include:
Search with query - a query is an SQL-92 expression (the where clause) referencing data object
properties.
Paged search - sets the page size and index (offset) to search from.
Sorted search - lists the data object properties to sort the result collection by.

2015 Backendless Corp.


46 Backendless API for .NET

Additionally, search requests may include special modifiers:


Request for specific properties of the data objects returned in the result collection.
Request to return related data objects attached to the 'parent' objects in the result collection.

Please note: searching for an object in a native database differs from searching for an object in an
external database.

Searching for a Data Object in a Native Database

Find objects within certain distance from a geo point


With the ability to link data objects with geo points, you can search for data
objects by distance. This type of search returns all data objects located within
the specified distance. Distance-based search uses a special function in
whereClause of the search request. The syntax of the function is:
distance(
center point latitude,
center point longitude,
columnname which contains geo point.latitude,
columnname which contains geo point.longitude ) <operator>
units-function(value)

where:
<operator> - Possible values are <, >, =, >=, <=
units-function - Defines the units of measure for the distance. Possible values
are:
ft( X ) - the distance value X is expressed in feet
km( X ) - the distance value X is expressed in kilometers
mi( X ) - the distance value X is expressed in miles
yd( X ) - the distance value X is expressed in yards

For example, the following expression searches for data objects located within 200 miles from
the point at 30.26715, -97.74306. Each data object must have the "coordinates" property
of type GeoPoint.
distance( 30.26715, -97.74306, coordinates.latitude, coordinates.longitude )
< mi(200)

The following example demonstrates a search-by-distance query. The example


uses three data objects stored in the Friend table: Bob, Jane, and Fred who
respectively live in Austin, Houston, San Antonio. The search query in the
example finds all friends who love within the specified distance. Before running
the search query, create the objects in the data storage with the corresponding
geo points.
The Friend class definition:
class Friend
{

2015 Backendless Corp.


Data Service 47
public string Name { get; set; }
public String PhoneNumber { get; set; }
public GeoPoint Coordinates { get; set; }
}

Run the following query/code to store a data object representing Bob with a link to his home in
Austin, TX:

Friend bob = new Friend();


bob.Name = "Bob";
bob.PhoneNumber = "512-555-1212";
bob.Coordinates = new GeoPoint( 30.26715, -97.74306 );
bob.Coordinates.Categories.Add( "Home" );
bob.Coordinates.Metadata.Add( "description", "Bob's home" );
Backendless.Data.Of<Friend>().Save( bob );

Run the following query/code to store a data object representing Jane with a link to his home in
Houston, TX:
Friend jane = new Friend();
jane.Name = "Jane";
jane.PhoneNumber = "281-555-1212";
jane.Coordinates = new GeoPoint( 29.76328, -95.36327 );
jane.Coordinates.Categories.Add( "Home" );
jane.Coordinates.Metadata.Add( "description", "Jane's home" );
Backendless.Data.Of<Friend>().Save( jane );

Run the following query/code to store a data object representing Fred with a link to his home in
San Antonio, TX:
Friend fred = new Friend();
fred.Name = "Jane";
fred.PhoneNumber = "210-555-1212";
fred.Coordinates = new GeoPoint( 29.42412, -98.49363 );
fred.Coordinates.Categories.Add( "Home" );
fred.Coordinates.Metadata.Add( "description", "Fred's home" );
Backendless.Data.Of<Friend>().Save( fred );

Once the data is in the persistent object and geo location storage, run the following code/query
to perform a distance-based search:
String whereClause = "distance( 30.26715, -97.74306, Coordinates.latitude,
Coordinates.longitude ) < mi(200)";
BackendlessDataQuery dataQuery = new BackendlessDataQuery( whereClause );
dataQuery.QueryOptions = new QueryOptions()
{
RelationsDepth = 1
};

BackendlessCollection<Friend> friends = Backendless.Data.Of<Friend>().Find


( dataQuery );

foreach( Friend friend in friends.Data )


System.Console.WriteLine( String.Format( "{0} lives at {1}, {2} tagged as
'{3}'", friend.Name, friend.Coordinates.Latitude, friend.Coordinates.
Longitude, friend.Coordinates.Metadata[ "description" ] ) );

2015 Backendless Corp.


48 Backendless API for .NET

The search returns all data objects within the specified distance. Each data object has the
coordinates property containing the coordinates of a geo point associated with this data
object.

Searching for a Data Object in an External Database


When searching for a data object in an external database, you need to take into consideration that such
object does not have some properties characteristic for the native data objects. Thus, these properties
will be omitted in the queries when searching for a data object in an external database.

2.12 Using Dates in Search


There is a special consideration for the whereClause-based queries which reference a column of the
DATETIME data type. Typically a DATETIME column is referenced in a comparison against a scalar value
describing a specific date or a timestamp. The scalar value can be a number of milliseconds since the
epoch (UNIX timestamp as milliseconds) or a string. Backendless supports a variety of date formats for
the latter. For example, the queries below will find all the objects which were updated after March 23rd,
2015:
updated > '23-Mar-2015'

updated > '03/23/2015'

updated > 1427068800000

Comparison Operators
Backendless supports the following date comparison operators:
Column's value is after the specified date/time: use either > or the after keyword:
birthDate > '22-Dec-1980'

birthDate after 1427068800000

Column's value is before the specified date/time: use either < or the before keyword:
birthDate < '22-Dec-1980'

birthDate before 1427068800000

Column's value is either at or after the specified date/time: use either => or the at or after
keyword:
birthDate >= '28-10-1988'

birthDate at or after '10/28/1988 00:00:00 GMT-0200'

Column's value is either at or before the specified date/time: use either <= or the at or
before keyword:
birthDate >= '28-10-1988'

2015 Backendless Corp.


Data Service 49
birthDate at or after '10/28/1988 00:00:00 GMT-0200'

Note: the whereClause-based queries can be tested in the Backendless Console with the SQL Search
turned on.

Supported Date Formats


Date/time string values may be in any of the following formats. The pattern letters have the same
definition as in Java's SimpleDateFormat:
EEE MMM dd HH:mm:ss zzz yyyy
MM/dd/yyyy HH:mm:ss 'GMT'z
MM.dd.yyyy HH:mm:ss 'GMT'z
MM-dd-yyyy HH:mm:ss 'GMT'z
MM.dd.yyyy HH:mm:ss
MM-dd-yyyy HH:mm:ss
MM/dd/yyyy HH:mm:ss
MM.dd.yyyy
MM-dd-yyyy
MM/dd/yyyy HH:mm:ss z
MM/dd/yyyy HH:mm:ss 'GMT'Z
MM.dd.yyyy HH:mm:ss z
MM/dd/yyyy HH:mm
MM/dd/yyyy
dd/MMM/yyyy
dd-MMM-yyyy
EEEEE, d MMMMM yyyy
ddMyy
d MMMMM yyyy, HH'h' mm'm' ss's'
yyyy/MM/d/hh:mm:ss
yyyy-MM-dd'T'hh:mm:ss
EEEEE, MMMMM d, yyyy
MMMMM d, yyyy
yyyy-MM-dd
yyyy M d
yyyyMMMd
yyyy-MMM-d
yyyy-M-d, E
yyyyMMdd
'Date' yyyy-MM-dd
yyyy-MM-dd'T'hh:mm:ssZ
yyyy-MM-dd'T'hh:mmZ
yyyy-'W'w-d
yyyy-DDD

Example

2.13 Relations Overview


A data object stored in a Backendless backend may reference other objects. These references are
called relations. There are two types of relations: one-to-one and one-to-many. Relations may be
declared manually in a table schema using the Backendless Console or derived (and added to schema)

2015 Backendless Corp.


50 Backendless API for .NET

from the objects which are being saved. Additionally, Backendless supports bidirectional relations
between the objects stored in the Data Service and other entities in a Backendless backend. For
example, a data object may have a relation with a User object and/or Geo Point objects.

Creating Relations
Relations can be declared manually by using the Backendless Console. Creating a relation between
objects involves two main steps:
1. Declaring a relationship between the tables where the objects are stored.
2. Establishing relations between the objects from the related tables.

Declaring a Relation Between Tables


The instructions below describe how to declare a relation between two tables:
1. Select a table where a relation should be declared.
2. Click the Table Schema and Permissions button in the top right corner of the user
interface.
3. Click the Add Column button. The pop-up window will display as shown below:

4. Enter column name that will represent the relation.


5. Click the Type drop-down list and select the Data Object Relationship option.

2015 Backendless Corp.


Data Service 51

6. The pop-up window will display new menu options. Select a related table and the cardinality
of the relations from the corresponding drop-down menus. The one-to-one relation means that
a table's object can be linked with only one object from the related table. While the one-to-
many relation means that a table's object can be linked with several objects from the related
table.

7. Click Save to save the changes.

Once a relationship column is declared, it will appear along other columns in the Data Browser view of
the Backendless Console.

Creating Relations Between Objects in Related Tables


Once you have declared a relation between table schemas, you can establish a relation between objects

2015 Backendless Corp.


52 Backendless API for .NET

in these tables. Follow the instructions below to establish a relationship:

1. Click the table name where you declared a relation. Console displays the columns
representing relations slightly different than the other ones. The header for these columns
includes:
- name of the related table;
- relation type (cardinality) visualized as either a single line for one-to-one relations or three
lines for one-to-many relations;
- the "auto-load" checkbox.

2. Click the plus icon next to the object, for which you want to create a relation. The Set
Related Object pop-up window will display the list of objects from the related table.

3. Each object in the displayed popup has either a radio button or a checkbox next to the

2015 Backendless Corp.


Data Service 53
object's data. Radio buttons are used for one-to-one relations, while checkboxes apply for the
one-to-many relations. Select the object(s) which will be linked to the parent object.
4. Click the Set Related Object button to save the changes.

The Data Service API can be used to link objects from different tables to form a relation. For more
information see the Relations (Save/Update) section of the guide.

Editing Relations
You can edit the relations between the data objects via the Backendless Console:
1. Click the name of the table containing the object with relations. Click the plus icon next to
the relation you want to edit:

2. The Set Related Object pop-up window will display. If you want to link a data object with
different object(s), click the radio-button or check-box(s) next to the necessary object(s).
3. Click the Set Related Object button to save the changes.

Refer to the Relations (Save/Update) section to learn how to update relations by using the API.

Deleting Relations
You can delete both relations between the objects and between the tables if necessary. Relations
between the tables can be deleted only by using the Backendless Console. While relations between the
objects can be deleted either via the Backendless Console or API.

To delete relations between the tables by using the Backendless Console:


1. Click the name of the table that you want to unlink from another table.
2. Click the Table Schema and Permissions button at the top right. The Table Schema and
Permissions page will display.
3. Click the check-box(s) next to the column associated with the relation(s) between the
tables.

2015 Backendless Corp.


54 Backendless API for .NET

4. Click the Delete Selected button.

To delete relations between the data objects via the Backendless Console:
1. Click the name of the table, where you want to delete a relation. Click the plus icon next to
the relation you want to delete.

2. The Set Related Object pop-up window will display. Click the Unlink Related Object
button to delete the relation.

Additionally, a relation between two objects (not tables) can be deleted by using the API. For more
information see the Relations (Delete) section.

2015 Backendless Corp.


Data Service 55
2.14 Relations (Save/Update)
Backendless Data Service supports a complete set of CRUD (create, retrieve, update, delete) operations
for related objects.
Please note: handling relations in a native database differs from handling relations in an external
database.

Handling Relations in a Native Database


Consider the following class diagram:

Notice the PhoneBook entity references Contact through two properties - "owner" (the one to one
relationship) and "contacts" (the one to many relationship). Each contact entity also references
Address. These entities will be used to demonstrate how Backendless handles related entities in all
basic data persistence operations. Consider the following class definitions for these entities:
Consider the following examples of saving objects with related data:

Constructing PhoneBook with the Owner and no Contacts:

Constructing PhoneBook with the Owner and two Contacts:

2015 Backendless Corp.


56 Backendless API for .NET

Add Contact to an existing PhoneBook (uses the "savedPhoneBook" object created at the
end of the example above):

Update a property in the aggregated object (update the phone number in the "owner" of
PhoneBook) and save PhoneBook:

2015 Backendless Corp.


Data Service 57

Removing one contact from PhoneBook, adding another and re-saving PhoneBook:

Handling Relations in an External Database


Saving and updating the relations between the data objects in an external database works generally the
same way as in the native database. Except

2015 Backendless Corp.


58 Backendless API for .NET

the class diagram will include the Contact and Address entities only
when saving/updating relations in an external database, contactId and addressId argument
will be used instead of objectId argument used in the native database.

2.15 Relations (Delete)


Backendless Data Service supports a complete set of CRUD (create, retrieve, update, delete) operations
for related objects.
Please note: handling relations in a native database differs from handling relations in an external
database.

Handling Relations in a Native Database


Consider the following class diagram:

Notice the PhoneBook entity references Contact through two properties - "owner" (the one to one
relationship) and "contacts" (the one to many relationship). Each contact entity also references
Address. These entities will be used to demonstrate how Backendless handles related entities in all
basic data persistence operations. Consider the following class definitions for these entities:
Consider the following examples of saving objects with related data:

2015 Backendless Corp.


Data Service 59
Delete parent object (deleting a PhoneBook):

Remove a contact from PhoneBook and save the change:

Deleting Relations in an External Database

2015 Backendless Corp.


60 Backendless API for .NET

2.16 Relations (Retrieve)


When a data object or a collection of objects is retrieved using the client API, Backendless does not
automatically include related objects into the returned object hierarchy. The reason for this is it would
make it very easy to load a lot of unnecessary data which could impact application's performance. There
are multiple ways to retrieve related data:

Relations auto-load - a mechanism built-into Backendless Console for configuring specific


relations to be included into responses with the parent objects.
Single-step relations retrieval - initializing and including related objects into the response
when running a find query for parent objects.
Two-step relations retrieval - a process of retrieving relations where the first step is to load the
parent object and the second step is to load specific relations for the given parent.
Loading with relations depth - retrieving related objects by specifying the depth of the object
hierarchy
Loading related child objects by condition applied to parent - load related objects using a
search query where the condition applies to the parent object properties.

Please note: retrieving relations in a native database differs from retrieving relations in an external
database.

Relations Auto Load


By default when an object is retrieved from Backendless using any of the find APIs (basic or advanced),
its related objects are not included into the response, unless explicitly referenced in the request. This
behavior can be easily modified using Backendless Console:

For any two tables A and B where A has a relationship column linking it to B, the console includes the
"auto load" checkbox for the relationship column. Selecting the checkbox instructs Backendless to
return all related B objects when the parent instance of A is retrieved through an API call. For example,
in the image above, the Order table has the one-to-many "items" relationship with the OrderItem table.
When the "auto load" checkbox in the "items" column is selected, all related OrderItem objects will be
included into the response for a find query for the Order table.

Single Step Retrieval


This approach allows to retrieve related objects along with the parent object in a single find request.
Each relationship property (column) must be uniquely identified by name using the following API:

BackendlessDataQuery query = new BackendlessDataQuery();


QueryOptions queryOptions = new QueryOptions();
queryOptions.Related = new List<String>();
queryOptions.Related.Add( "RELATED-PROPERTY-NAME" );

2015 Backendless Corp.


Data Service 61
queryOptions.Related.Add( "RELATED-PROPERTY-NAME.RELATION-OF-RELATION" );
query.QueryOptions = queryOptions;
BackendlessCollection<Foo> invoices = Backendless.Persistence.Of<Foo>().Find
( query );
where
RELATED-PROPERTY-NAME - name of a related property to load. For example, if table
Person, has a relation "homeAddress" pointing to an object in
the Address table, the value would be "homeAddress". The
syntax allows to add relations of relations. For example, if the
same Address table has a relation "country" pointing to the
Country table, then "homeAddress.country" would instruct the
related Country object to be loaded as well.
Foo - reference to a class which identifies the table from which the
data is to be loaded.

Two Step Retrieval


With this approach a parent object is loaded first and then there is a separate API call to load specific
related objects into the given parent object. For example, suppose the Order table has a one-to-many
relationship column "items " pointing to the OrderItem table. The OrderItem table has a one-to-one
relationship to the Manufacturer table, the code below loads first Order object and then loads related
OrderItems and corresponding Manufacturers :

Order invoice = Backendless.Persistence.Of<Order>().FindFirst();


List<String> relations = new List<String>();
relations.Add( "items" );
relations.Add( "items.manufacturer" );
Backendless.Persistence.Of<Order>().LoadRelations( order, relations );

Loading with Relations Depth


The Data Service API supports a mechanism for loading related objects without identifying each by its
name. Instead, the API includes a parameter which specifies the "depth" of the relations to include into
the response. Consider the following diagram:

2015 Backendless Corp.


62 Backendless API for .NET

The diagram shows a hierarchy for class structure - the Order class has two relations: with OrderItem
and Customer classes. Each in turn has a relation to the Manufacturer and Address classes. When an
instance or a collection of Order objects is retrieved from Backendless, the API may include a parameter
specifying the depth of relations to include into the response. If the relation depth is 1, then all related
instances of OrderItem and Customer will be included into each Order object. If the relation depth is 2,
then not only OrderItem and Customer instances will be included, but the corresponding Manufacturer
and Address objects as well.

API methods supporting relations depth


All methods are available via Backendless.Persistence accessor, for example Backendless.
Persistence.FindFirst( 2 ):

Synchronous methods:
public T FindFirst( int relationsDepth );
public T FindLast( int relationsDepth );
public T FindById( string id, int relationsDepth );
public BackendlessCollection<T> Find( BackendlessDataQuery
dataQueryOptions );

Asynchronous methods:
public void FindFirst( int relationsDepth, AsyncCallback<T> responder );
public void FindLast( int relationsDepth, AsyncCallback<T> responder );
public void FindById( string id, int relationsDepth, AsyncCallback<T>
responder );
public void Find( BackendlessDataQuery dataQueryOptions, AsyncCallback<
BackendlessCollection<T>> responder );

Example:
BackendlessDataQuery query = new BackendlessDataQuery();
QueryOptions queryOptions = new QueryOptions();
queryOptions.RelationsDepth = 2;
query.QueryOptions = queryOptions;
BackendlessCollection<Foo> invoices = Backendless.Persistence.Of<Foo>().Find
( query );
where
Foo - reference to a class which identifies the table from which the
data is to be loaded.

Loading a Subset of Related Child Objects


Backendless supports a special query syntax for loading a subset of child objects for a specific parent.
Consider the following class diagram:

2015 Backendless Corp.


Data Service 63

Notice the PhoneBook entity references Contact through two properties - "owner" (the one to one
relationship) and "contacts" (the one to many relationship). Each contact entity also references
Address. These entities will be used to demonstrate how Backendless handles related entities in all
basic data persistence operations. Consider the following class definitions for these entities:

The general structure of the query to load a collection of child objects for a specific parent object is:
ParentTableName[ relatedPropertyForChildrenCollection ].
parentColumnName COLUMN-VALUE-CONDITION

When a query in this format is used to fetch a collection of child object, the table addresses in the
request must be one which the "relatedPropertyForChildrenCollection" points to.

2.17 Relations with Geo Points


Backendless Geo Service manages application's geo location data and provides APIs to
work with Geo points. Backendless supports integration between data objects
managed by Data Service and geo points for the scenarios when a logical connection
between the two entity types must exist in an application. For instance, in a taxi
ordering application a data object may represent a taxi car, while a geo point
represents its location on the map. Link the two together provides great benefits such
as retrieving both objects at once and managing as a consistent, cohesive object
hierarchy.

The Data-to-Geo integration is implemented through object relations. A data table


schema may declare a table column with a special data type - "GeoPoint Relationship".
As a result, the data objects in the table may contain a reference to one or more
GeoPoints. When a data object with a related GeoPoint is saved, Backendless persists
information about both the data object and the geo point in the corresponding
persistent systems and sets up the relationship. Likewise, when a data object is
retrieved by using the API, any related geo points can be retrieved using the same

2015 Backendless Corp.


64 Backendless API for .NET

principle for loading data relations. The data-to-geo relation is bidirectional, it means a
geo point may reference a data object in its metadata. You can learn more about it in
the Relations with Data Objects section of the Geolocation documentation.
The relationship between a data object and a geo point (or a collection of) can be established by using
either the "code first" or the "schema first" approaches. With the former, the relationship is determined
by the data structure persisted with the API. If a data object references a GeoPoint (or a collection of) in
one of its properties, Backendless interprets it as a relation and, as a result, will create a relation
column in the data table schema. With the latter ("schema first") approach, application developer can
declare a relationship in the data table schema first. In either one of these approaches, once a
relationship is declared, data objects and geo points may be linked together by using the Backendless
console as well.

Declaring a Data-to-Geo Relationship in Table Schema


To declare a relationship in a data table schema:
1. Select a table where a relation should be declared.
2. Click the Table Schema and Permissions button in the top right corner. The Table
Schema and Permissions page will display.
3. Click the Add Column button. The pop-up window will display:

4. Enter the name of the column in the Name field. This column will represent a data-to-geo
relationship.
5. Select the Geopoint Relationship option from the Type drop-down list.

2015 Backendless Corp.


Data Service 65

6. New menu options will become available. Select the cardinality of the relation from the
corresponding drop-down menu. The one-to-one relation means that a table's object can be
linked with only one geo point, while the one-to-many relation means that a table's object can
be linked with multiple geo points.

7. Click the Save button to save the changes.

Linking a Data Object with Geo Points


Once a data-to-geo relationship is declared (see the instructions above), data objects from the table can
be linked to geo point(s) as described below:
1. Click the name of the table containing an object that you want to link with a geo point.
2. Table columns representing the data-to-geo relationships are identified as "GEOPOINT
relationship" in the header row. The cardinality of the relation is visualized as one red line for
the one-to-one relations and three parallel lines for the one-to-many relations:

2015 Backendless Corp.


66 Backendless API for .NET

3. Click the plus icon next to the object, for which you want to create a data-to-geo relation.
The Set Related GeoPoint pop-up window will display the list of the geo points.

4. Use the Geo Category drop-down list to select a geo category from which the points should
be displayed.
5. If you declared a one-to-one relation for a table the object belongs to, you will be able to link
this object with only one geo point (by the means of a radio button). If it is a one-to-many
relationship, the interface uses check boxes, which allow for multiple selection. Click a radio-
button or select check-boxes next to the geo points which you want to link with the data
object.
6. Click the Set Related GeoPoint button to save the changes.

Once a relation is established, it is shown in the data browser as a hyperlink. The hyperlink for the one-
to-one relations displays the coordinates of the related geo point. For the one-to-many relations the link
says "multiple Geopoints". In both cases, the link opens the Geolocation screen of the console which
displays the related geo point(s).

2015 Backendless Corp.


Data Service 67

Updating Relations
You can update a data-to-geo relation by following the steps shown below:
1. Click the name of the table containing an object that has a data-to-geo relation you want to
edit . Click the plus icon next to the relation:

2. The Set Related GeoPoint pop-up window will display. Use the radio-buttons (one-to-one
relations) or check-boxes (one-to-many relations) next to select/deselect the geo points.
3. Click the Set Related GeoPoint button to save the changes.

Deleting Relation Definition in Table Schema


A data-to-geo relationship can be removed at the schema level. Removing the relationship is done by
deleting the column which represents it. When a column is removed the relationships identified by the
column between the data objects and geo points are removed as well.

To delete a relationship definition between a data table and the geo points:
1. Click the name of the table which contains a "GeoPoint relationship" column you need to
remove.
2. Click the Table Schema and Permissions button in the top right corner. The Table
Schema and Permissions page will display.
3. Click the check-box next to the column you need to delete.

2015 Backendless Corp.


68 Backendless API for .NET

4. Click the Delete Selected button.

Deleting Relation between Data and Geo Point


Objects
To delete relations between a data object and geo point(s) via the Backendless Console:
1. Click the name of the table which contains a data-to-geo relationship you need to remove.
Click the plus icon next to the relation you want to delete.

2. The Set Related GeoPoint pop-up window will display. Click the Unlink Relation button to
delete the relation.

Establishing Relations with Geo Points via API

2015 Backendless Corp.


Data Service 69
Creating a relationship between a data object and a geo point (or a collection of) uses the same API as
saving a data object with a related entity. In the case of data-to-geo relations, the related entity is a geo
point or a collection of geo points. Consider the example that below saves a data object with a related
geo point. The geo point is also persisted in the Geo Service

The example below demonstrates how to link a taxi (a data object) with its location (geo point). First,
create TaxiCab class:
class TaxiCab
{
public String CarMake;
public String CarModel;
public GeoPoint Location { get; set; }
public List<GeoPoint> PreviousDropOffs { get; set; }
}

To set one-to-one or one-to-may relation:


TaxiCab taxi = new TaxiCab();
taxi.CarMake = "Toyota";
taxi.CarModel = "Prius";

// one-to-one relation between a data object and a geo point


taxi.Location = new GeoPoint( 40.7148, -74.0059 );
taxi.Location.Categories.Add( "taxi" );
taxi.Location.Metadata.Add( "service_area", "NYC" );

// one-to-many relation between a data object and geo points


List<GeoPoint> previousDropOffs = new List<GeoPoint>();

GeoPoint droppOff1 = new GeoPoint( 40.757977, -73.98557 );


droppOff1.Metadata.Add( "name", "Times Square" );
droppOff1.Categories.Add( "DropOffs" );
previousDropOffs.Add( droppOff1 );

GeoPoint droppOff2 = new GeoPoint( 40.748379, -73.985565 );


droppOff2.Metadata.Add( "name", "Empire State Building" );
droppOff2.Categories.Add( "DropOffs" );
previousDropOffs.Add( droppOff2 );

taxi.PreviousDropOffs = previousDropOffs;

Backendless.Data.Of<TaxiCab>().Save( taxi );

2.18 Security
Data Service supports a very flexible security mechanism for restricting access to objects stored in
Backendless. Security permissions apply to users and roles. A permission can either grant or reject an
operation for a particular asset. In the context of Data Service, the asset is an object which your app can
retrieve, update or delete. Permissions can be granted or rejected globally, where they apply to all tables
and all objects in the data store. Additionally, every table may have its own permission matrix and owner
policy a special instruction whether object owners can or cannot retrieve/update/delete the objects
they own. Finally, every object has its own Access Control List (ACL) which is a matrix of permissions
for the operations applicable specifically to the object:

2015 Backendless Corp.


70 Backendless API for .NET

The security system is multi-layered. For an API call to retrieve, update or delete object(s), the system
goes through several where each can trim the scope of the operations. The layered order of the decision
making is important and consists of the following:

1. ObjectACL for the user who makes the call


2. ObjectACL for user-defined roles assigned to the user who makes the call.
3. Table permissions for the User account
4. Table permissions for the user-defined roles
5. Owner Policy
6. ObjectACL for system roles
7. Table permissions for system-level roles
8. Global user-defined roles
9. Global system roles

Where:
User-defined roles roles created by the application developer
System roles roles built into Backendless (Authenticated User, NonAuthenticated User,
SocialUser, etc)

Consider the following guide which illustrates the decision making process:
1. Backend receives an API request to load data from a table (the Find operation). All objects
become candidates for the retrieval. Backendless goes through the security permissions chain
to determine which ones must be included.

2015 Backendless Corp.


Data Service 71

2. ObjectACL for the user who makes the call. Backendless checks if there are any
restrictions for the user account at the object level. Any object in the collection with ACL which
rejects access to the user is excluded from the result. To see or modify the permissions for a
particular object, click the key icon in the ACL column in the data browser in management
console.

2015 Backendless Corp.


72 Backendless API for .NET

3. ObjectACL for user-defined roles assigned to the user who makes the call. This is the
same check as the one above, except Backendless looks into the permissions for the roles
defined by the application developer. If the user belongs to any of the custom roles,
Backendless checks if these roles are allowed to perform the current operation. In the
screenshot below, only the MyRole role will be checked in this step, since this is the only
custom role in the application:

4. Table permissions for the User account. Every table in Backendless may have its own set of
permissions for users and roles. At this point Backendless checks if the currently logged in
user is allowed to run the current operation. For example, if the Find operation is denied for the
user, no objects would be returned.
5. Table permissions for the user-defined roles. This step is identical to the one described
above with the exception that is checks custom roles for the table. Since this guide reviews the
decision making process for the Find operation, Backendless checks the column for Find. If any
of the custom roles deny access, the operation is rejected and no data is returned.

2015 Backendless Corp.


Data Service 73

6. Owner Policy. When a new object is created in Backendless, the system automatically links
it with the account of the currently logged in user. You can see that information in the ownerId
column in any of your tables in the data browser. With the association between objects and
users, Backendless provides a way to control whether users can get access to the data they
created. This is done through a concept we call Owner Policy. The policy is available on the
Schema and Permissions screen. Select a table in the data browser and click the Table
Schema and Permissions button in the upper right corner. Select the Owner Policy menu
item. Owner policy can be global (select All Tables from the drop down in the upper right
corner) or it could apply to a specific table.
Granting a permission for an operation in Owner Policy, guarantees that the objects owned by
the current user will be included in the resulting collection. Denying a permission, takes out the
owned objects from the collection of candidate objects to return. Consider the following:

Granting Find permission in Owner Policy:

Results in the following. The objects with bold border are guaranteed to be returned. All other
objects will be subject to the subsequent permission checks.

2015 Backendless Corp.


74 Backendless API for .NET

However, if the Owner Policy rejects a permission:

The objects owned by the current user will be excluded from the resulting collection. All
remaining objects will be decided by the subsequent permission checks.

7. Object ACL for system roles. This check is identical to step 3 (Object ACL for custom roles).
The difference is the system roles cover larger groups of users. For example, this step would
make possible to restrict access to specific objects for all authenticated (or not authenticated)

2015 Backendless Corp.


Data Service 75
users, yet the object would be returned with a query made by the objects owner if the Owner
Policy (previous step) grants access.
8. Table permissions for system roles. Identical to step 5, this checks if any of the system
roles reject the operation at the table level.
9. Global custom roles. Global policy applies to all tables and objects. By default all table level
permissions inherit from the global policy. You can configure in the console at: Users >
Security and Permissions. Create a new role and click it to configure the permission matrix:

2.19 Permissions API


Every data object in Backendless has its own access control list (ACL) - a matrix of operations and
principals (application's users or roles). An intersection of an operation and a principal contains a
permission which determines whether the principal has the right to execute the operation. These
permission could be either grant or deny. Backendless console provides an easy to understand way to
see and manage these permissions. For example, the screenshot below demonstrates an ACL matrix
for an object. Notice the intersection of a column for the Update operation and the
NotAuthenticatedUser role. The cell contains a red X icon representing that the permission is denied:

2015 Backendless Corp.


76 Backendless API for .NET

In addition to managing the ACL permissions with Backendless Console there is also Permissions API:

Method Signatures
The following method signatures are used for granting or denying access to a data object for a
user, a role, all users, or all roles:
public void GrantForUser<T>( String userId, T dataObject )
public void GrantForUser<T>( String userId, T dataObject,
AsyncCallback<Object> responder )
public void DenyForUser<T>( String userId, T dataObject )
public void DenyForUser<T>( String userId, T dataObject,
AsyncCallback<Object> responder )
public void GrantForRole<T>( String roleName, T dataObject )
public void GrantForRole<T>( String roleName, T dataObject,
AsyncCallback<Object> responder )
public void DenyForRole<T>( String roleName, T dataObject )
public void DenyForRole<T>( String roleName, T dataObject,
AsyncCallback<Object> responder )
public void GrantForAllUsers<T>( T dataObject )
public void GrantForAllUsers<T>( T dataObject, AsyncCallback<Object>
responder )
public void DenyForAllUsers<T>( Object dataObject )
public void DenyForAllUsers<T>( T dataObject, AsyncCallback<Object> responder
)
public void GrantForAllRoles<T>( T dataObject )
public void GrantForAllRoles<T>( T dataObject, AsyncCallback<Object>
responder )
public void DenyForAllRoles<T>( T dataObject )
public void DenyForAllRoles<T>( T dataObject, AsyncCallback<Object> responder
)

Use these methods for the Data operations (that is, to find, update, and remove the data)
performed by DataPermission class, which is available in BackendlessAPI.Persistence
namespace.
DataPermission.FIND.<method> to set a permission to find/retrieve a data object
DataPermission.UPDATE.<method> to set a permission to update a data object
DataPermission.REMOVE.<method> to set a permission to remove a data object

To grant access for a user


DataPermission.FIND.GrantForUser( userId, dataObject );
DataPermission.UPDATE.GrantForUser( userId, dataObject );
DataPermission.REMOVE.GrantForUser( userId, dataObject );

where:
userId - ID of a user, for which you want to grant the find,
update, or remove permission.

2015 Backendless Corp.


Data Service 77
dataObject - an object for which you want to grant a permission.

To grant access for a user role


DataPermission.FIND.GrantForRole ( roleName, dataObject );
DataPermission.UPDATE.GrantForRole ( roleName, dataObject );
DataPermission.REMOVE.GrantForRole ( roleName, dataObject );

where:
roleName - name of a user role, for which you want to grant the
find, update, or remove permission.
dataObject - an object for which you want to grant a permission.

To grant access for all users


DataPermission.FIND.GrantForAllUsers ( dataObject );
DataPermission.UPDATE.GrantForAllUsers ( dataObject );
DataPermission.REMOVE.GrantForAllUsers ( dataObject );

where:
dataObject - an object for which you want to grant a permission.

To grant access for all user roles


DataPermission.FIND.GrantForAllRoles ( dataObject );
DataPermission.UPDATE.GrantForAllRoles ( dataObject );
DataPermission.REMOVE.GrantForAllRoles ( dataObject );

where:
dataObject - an object for which you want to grant a permission.

To deny access for a user


DataPermission.FIND.DenyForUser ( userId, dataObject );
DataPermission.UPDATE.DenyForUser ( userId, dataObject );
DataPermission.REMOVE.DenyForUser ( userId, dataObject );

where:
userId - ID of a user, for which you want to deny a
permission.
dataObject - an object for which you want to deny a permission.

To deny access for a user role


DataPermission.FIND.DenyForRole ( roleName, dataObject );
DataPermission.UPDATE.DenyForRole ( roleName, dataObject );
DataPermission.REMOVE.DenyForRole ( roleName, dataObject );

where:
roleName - name of a user role, for which you want to deny a
permission.
dataObject - an object for which you want to deny a permission.

2015 Backendless Corp.


78 Backendless API for .NET

To deny access for all users


DataPermission.FIND.DenyForAllUsers ( dataObject );
DataPermission.UPDATE.DenyForAllUsers ( dataObject );
DataPermission.REMOVE.DenyForAllUsers ( dataObject );

where:
dataObject - an object for which you want to deny a permission.
To deny access for all user roles
DataPermission.FIND.DenyForAllRoles ( dataObject );
DataPermission.UPDATE.DenyForAllRoles ( dataObject );
DataPermission.REMOVE.DenyForAllRoles ( dataObject );

where:
dataObject - an object for which you want to deny a permission.
Example:
The example below demonstrates how to deny retrieving an object for all roles. The code loads
an object from the Address table and then uses the object reference to deny any FIND-related
operation for all roles.
AsyncCallback<Object> denyCallback = new AsyncCallback<Object>(
result =>
{
System.Console.WriteLine( "Permission has been denied for all roles" );
},
fault =>
{
System.Console.WriteLine( "Error - " + fault );
} );

AsyncCallback<Address> searchCallback = new AsyncCallback<Address>(


result =>
{
DataPermission.FIND.DenyForAllRoles( result, denyCallback );
},
fault =>
{
System.Console.WriteLine( "Error - " + fault );
} )

Backendless.Data.Of<Address>().FindFirst( searchCallback );

3 Messaging Service

3.1 Overview
Data Messaging is an essential function of mobile and desktop applications. It can be used for a
multitude of functions including chat or private messaging, system update broadcast, maintaining game
scores, etc. The Backendless Messaging Service provides API and software infrastructure enabling
publish-subscribe message exchange pattern and mobile push notifications. The service consists of the
following core concepts: channels, publishers, subscribers and registered devices:
channel - a logical medium "carrying" the messages.

2015 Backendless Corp.


Messaging Service 79
publisher - a program using the Publishing API to send messages to a channel.
subscriber - a program using the Subscription API to receive messages from a channel.
registered device - a mobile device registered with a Backendless channel to receive
push notifications.

Publish-Subscribe Messaging
With the publish-subscribe pattern, one part of the code (or an entire application) can subscribe to
receive messages and another publishes messages. A message can be any data - Backendless
supports messages of primitive or complex data types. To enable publish-subscribe messaging,
Backendless supports the concept of a channel. Subscriptions are "attached" to a channel (or multiple
channels) and messages are published into a channel. By default Backendless sends all messages
published into a channel to all the channel's subscribers. However, a subscription can include message
filters, in this case Backendless delivers only the messages matching the filter.

Push Notifications
A message published to a channel can be tagged as a push notification, thus triggering the logic for
distributing it to the registered devices. Backendless supports push notifications for iOS, Android and
Windows Phone devices. Messages published as push notifications can target either a specific
subscriber (as a device) or a group of subscribers. Subscribers can be grouped by operating system (for
example, a message sent to all registered iOS devices) or as a collection of individual registrations. The
Backendless messaging API supports different types of push notifications - badge updates, alerts, etc.

3.2 Setup
To get access to the Backendless services, .NET and Windows Phone applications must reference the
backendless.dll assembly available in the Backendless SDK for .NET. All the Backendless SDK for .
NET classes are available in the BackendlessAPI namespace. Before the .NET/Windows Phone client
uses any of the APIs, the code must initialize the Backendless Application using the following call:
Backendless.InitApp( application-Id, secret-key, version )

Application ID and Secret Key


Values for the application-id and secret-key headers must be obtained through the Backendless
Console:

1. Login to your account and select the application.


2. Click the Manage icon from the vertical icon-menu on the left.
3. The "App Settings" section is selected by default. The interface contains the text fields for
"Application ID" and secret keys for each supported client-side environment.
4. Use the "Copy" button to copy the value into the system clipboard.

2015 Backendless Corp.


80 Backendless API for .NET

The version argument must contain the name of the targeted version. When a new application is
created, the default version name is "v1" . To manage versions, login to the console, select the
"Manage" icon and click "Versioning".

3.3 Core Classes


The Backendless Messaging Service uses the following core classes:

Backendless.Messaging - is the central point for all Backendless Messaging APIs. Provides
access to the device registration, subscription management and messaging publishing functionality

SubscriptionOptions - may be used in the subscription call to establish subscriber identity and set messaging filte
namespace BackendlessAPI.Messaging
{
public class SubscriptionOptions
{
public SubscriptionOptions()
{
}

public SubscriptionOptions(string subscriberId)


{
this.SubscriberId = subscriberId;
}

2015 Backendless Corp.


Messaging Service 81
public SubscriptionOptions(string subscriberId, string subtopic)
{
this.SubscriberId = subscriberId;
this.Subtopic = subtopic;
}

public SubscriptionOptions(string subscriberId, string subtopic, string


selector)
{
this.SubscriberId = subscriberId;
this.Subtopic = subtopic;
this.Selector = selector;
}

public string SubscriberId { get; set; }


public string Subtopic { get; set; }
public string Selector { get; set; }
}
}

PublishOptions - this class is the publishing counterpart for the SubscriptionOptions


shown above. Can be used in the publishing API to set the publisher's ID and/or to set properties for
message filtering, such as message headers and subtopic.
using System.Collections.Generic;

namespace BackendlessAPI.Messaging
{
public class PublishOptions
{
public const string MESSAGE_TAG = "message";

public const string IOS_ALERT_TAG = "ios-alert";


public const string IOS_BADGE_TAG = "ios-badge";
public const string IOS_SOUND_TAG = "ios-sound";

public const string ANDROID_TICKER_TEXT_TAG = "android-ticker-text";


public const string ANDROID_CONTENT_TITLE_TAG = "android-content-title";
public const string ANDROID_CONTENT_TEXT_TAG = "android-content-text";
public const string ANDROID_ACTION_TAG = "android-action";

public const string WP_TYPE_TAG = "wp-type";


public const string WP_TITLE_TAG = "wp-title";
public const string WP_TOAST_SUBTITLE_TAG = "wp-subtitle";
public const string WP_TOAST_PARAMETER_TAG = "wp-parameter";
public const string WP_TILE_BACKGROUND_IMAGE = "wp-backgroundImage";
public const string WP_TILE_COUNT = "wp-count";
public const string WP_TILE_BACK_TITLE = "wp-backTitle";
public const string WP_TILE_BACK_BACKGROUND_IMAGE = "wp-backImage";
public const string WP_TILE_BACK_CONTENT = "wp-backContent";
public const string WP_RAW_DATA = "wp-raw";

public PublishOptions()

2015 Backendless Corp.


82 Backendless API for .NET

{
}

public PublishOptions( string publisherId )


{
this.PublisherId = publisherId;
}

public PublishOptions( string publisherId, string subtopic )


{
this.PublisherId = publisherId;
this.Subtopic = subtopic;
}

public PublishOptions( string publisherId, Dictionary<string, string> headers,


string subtopic )
{
this.PublisherId = publisherId;
this.Headers = headers;
this.Subtopic = subtopic;
}

public string PublisherId { get; set; }


public Dictionary<string, string> Headers { get; set; }
public string Subtopic { get; set; }

public void AddHeader( string key, string value )


{
if( Headers == null )
Headers = new Dictionary<string, string>();

Headers[ key ] = value;


}
}
}

DeliveryOptions - used in the publishing API for targeted message delivery. Supported options
include: tagging a message as a push notification, scheduling message delivery in the future,
scheduling repeated message delivery and message expiration.
using System;
using System.Collections.Generic;

namespace BackendlessAPI.Messaging
{
public class DeliveryOptions
{
public const int IOS = 1;
public const int ANDROID = 1 << 1;
public const int WP = 1 << 2;
public const int ALL = IOS | ANDROID | WP;

private PushPolicyEnum _pushPolicy = PushPolicyEnum.ALSO;

// accepts a mask value used by Backendless to route the message

2015 Backendless Corp.


Messaging Service 83
// to the registered devices with the specified operating system.
// The mask value may consist of the following values:
// DeliveryOptions.IOS, DeliveryOptions.ANDROID, DeliveryOptions.WP and
PushBroadcast.ALL
public int PushBroadcast { get; set; }

// configures a list of registered device IDs to deliver the message to


public List<string> PushSinglecast { get; set; }

// sets the time when the message should be published


public DateTime? PublishAt { get; set; }

// sets the interval as the number of milliseconds repeated message


publications.
// When a value is set Backendless re-publishes the message with the
interval.
public long RepeatEvery { get; set; }

// sets the time when the message republishing configured with "repeatEvery"
should stop
public DateTime? RepeatExpiresAt { get; set; }

// Controls if the published messages are distributed as a push notification


ONLY or
// both push notification and ALSO as regular publish/subscribe messages.
// There are two values ONLY and ALSO which correspond to the described
scenarios.
public PushPolicyEnum PushPolicy
{
get { return _pushPolicy; }
set { _pushPolicy = value; }
}
}
}

Subscription - represents an established subscription between a client and a Backendless channel


using System;
using System.Threading;
using System.Collections.Generic;
using BackendlessAPI.Async;
using BackendlessAPI.Exception;

namespace BackendlessAPI.Messaging
{
public class Subscription
{
private int _pollingInterval = 1000;

public Subscription()
{
}

public Subscription( int pollingInterval )


{

2015 Backendless Corp.


84 Backendless API for .NET

this._pollingInterval = pollingInterval;
}

// returns a unique subscription identifier (assigned by Backendless)


public string SubscriptionId { get; set; }

// returns the name of the channel the subscription gets messages from
public string ChannelName { get; set; }

// controls how frequently the client polls for messages


public int PollingInterval
{
get { return this._pollingInterval; }
set { this._pollingInterval = value; }
}

// cancels the subscription


public bool CancelSubscription();

// suspends the subscription (the client stops receiving new messages)


public void PauseSubscription();

// resumes the subscription


public void ResumeSubscription();
}
}

3.4 Error Handling


When the server reports an error, it is delivered to the client through an instance of the
BackendlessFault class. A BackendlessFault object provides access to an error code which uniquely
identifies the root cause of the error. In addition to the error code, the fault object may include an error
message which provides additional information about the error:
using System;
using Weborb.Client;

namespace BackendlessAPI.Exception
{
public class BackendlessFault
{
private readonly string _faultCode;
private readonly string _message;
private readonly string _detail;

public string Detail


{
get { return _detail; }
}

public string FaultCode


{

2015 Backendless Corp.


Messaging Service 85
get { return _faultCode; }
}

public string Message


{
get { return _message; }
}

public override string ToString()


{
return String.Format( "Backendless BackendlessFault. Code: {0},
Message: {1}", FaultCode ?? "N/A", Message ?? "N/A" );
}
}
}

The asynchronous API calls accept the AsyncCallback argument which receives the fault object
through the following delegate:
public delegate void ErrorHandler( Fault fault );

The synchronous API calls declare a checked exception - BackendlessException. The fault object can
be obtained from the exception:
namespace BackendlessAPI
{
public class BackendlessException : Exception
{
public Fault Fault { get; }
public string Code { get; }
public override string Message { get; }
public override string ToString();
}
}

3.5 Push Notification Setup (Android)


Backendless can deliver published messages as push notifications to Android devices. Additionally,
Backendless Console can be used to publish push notifications. In order to deliver a push notification to
Android, the backend must be configured with Google API Key:
1. Login to Google Developers Console and select or create a project.
2. Click Credentials located under the APIS & AUTH menu.
3. If you dont have Key for server application, you create it:
Click Create new Key under the Public API access section;
Choose Server key;
Click Create;
4. Copy the API Key for server applications:

2015 Backendless Corp.


86 Backendless API for .NET

5. Open Backendless Console and select your application.


6. Click Manage and scroll down to Mobile Settings.
7. Paste the Google API Key into corresponding field located under the Android Push
Notifications label:

2015 Backendless Corp.


Messaging Service 87

8. Click Save. At this point the backend is configured and is ready to publish push notifications to
Android devices.

In your project you should register the device in order to receive or send push notifications. To
accomplish this, do the following:
1. Login to Google Developers Console and select your previously created project.
2. Copy the project number located at the top of the screen:

2015 Backendless Corp.


88 Backendless API for .NET

3. Use this project number in Backendless.Messaging.registerDevice(...) method as GCMSenderID


argument. For example:

3.6 Push Notification Setup (iOS)


Setting up your backend to support Push Notifications for iOS requires a few steps, most of which are in
Apple Developer Member Center and Keychain Access. The process consists of the following steps:

1. Creating App ID
2. Creating Certificate Request
3. Generating an SSL Certificate
4. Configuring Backendless App/Backend with the Certificate

Creating App ID
1. First we are going to create an App ID for the mobile application which will receive Push
Notifications. Login to Apple Developer Member Center. Click on App IDs in the Identifiers
section. Use the plus sign + button to create a new ID:

2015 Backendless Corp.


Messaging Service 89

2. When prompted enter App ID Prefix. Make sure it is descriptive enough so you recognize it
later when you return to the Member Center.
3. Select Explicit App ID in the App ID Suffix section and enter the same bundle ID which you
will be using in the application:

2015 Backendless Corp.


90 Backendless API for .NET

4. In App Services select the services which the application will use and click continue:

5. Make sure that Push Notifications are enabled and click submit. This will conclude the App ID
creation for the app:

2015 Backendless Corp.


Messaging Service 91

Creating Certificate Request


Push Notifications require a certificate which will be used on a device by the means of a provisioning
profile. Also the same certificate (transformed to the Personal Information Exchange .p12 format) will
be used by Backendless to publish Push Notifications. If this makes little sense, do not worry, you will
need to perform these steps only ones and then can move on to code and using the APIs.
1. In order to create a certificate a Certificate Signing Request (CSR) must be issued. To create
a CSR, open Keychain Access and select Keychain Access >> Certificate Assistant >>
Request a Certificate from the main menu:

2015 Backendless Corp.


92 Backendless API for .NET

2. Enter your email address and Common Name (leave the CA Email Address field empty),
select Saved to disk and click Continue:

3. Select a directory where to save the file and click Save.

Generating an SSL Certificate


The CSR file created in the section above will be used to create an SSL Certificate. That certificate will
then be used by Backendless to publish push notifications.
1. Return to Apple Developer Member Center and select All under Certificates. Click the plus
button + to add a new certificate:

2015 Backendless Corp.


Messaging Service 93

2. Select certificate type there are two options Development and Production. For now select
Apple Push Notification service SSL (Sandbox):

2015 Backendless Corp.


94 Backendless API for .NET

3. Select the App ID created earlier in these instructions:

4. Next you will see the instructions for generating a CSR which you have already created by
now. Click Continue to proceed to the next step.
5. Select the CSR file created and saved to the disk earlier and click Generate:

2015 Backendless Corp.


Messaging Service 95

6. The certificate is ready now, click Download to download it:

7. Add the certificate file to Keychain Access.


8. Open Keychain Access and locate the certificate in the My Certificates section:

2015 Backendless Corp.


96 Backendless API for .NET

9. Right click on the certificate and select the Export option:

10. Save the certificate in the p12 format:

11. Enter a password for the certificate. Make sure to make a record of the password you will
need to use it later in the instructions when you submit the certificate to Backendless:

2015 Backendless Corp.


Messaging Service 97

12. Enter your Mac OS X account password to confirm the action. At this point you have a
certificate for Push Notifications.

Configuring Backendless App/Backend with the


Certificate
Since Backendless provides the actual server-side integration for delivering Push Notifications for your
application, it needs to have access to the certificate you created above. The steps below provide the
instructions for uploading the certificate into Backendless:
1. Login to Backendless Console at: https://backendless.com/develop and create/select an
application which you will use on the server-side:

2. Click Manage > App Settings. Locate the Mobile Settings section and upload the .p12
certificate created earlier. Make sure to enter the same password you used when created the
certificate:

2015 Backendless Corp.


98 Backendless API for .NET

3. Now your Backendless server is ready to publish Push Notifications.

3.7 Message Publishing


Application can publish messages to Backendless for subsequent distribution to subscribers.
Backendless delivers published messages to subscribers as message objects and/or to devices as
push notifications. A message must be published to a channel (or a group of channels). Backendless
supports unlimited number of channels. Applications can use them as a filtering mechanism - channel
subscribers see messages published only to that channel. Similarly, devices can specify a channel (or a
group of them) when registering for push notifications. Message publishing supports the following
scenarios:

Publishing with message headers - headers is a collection of name = value pairs of arbitrary
data. Subscribers can set additional filters expressed as SQL queries which Backendless applies
to the headers. When the query matches the published data in headers, message is delivered to

2015 Backendless Corp.


Messaging Service 99
the corresponding subscriber. See example.

Publishing to a subtopic - Subtopics provide an additional level of message filtering.


Multiple subtopics can be defined within a channel. Both publishers and subscribers can
specify a subtopic within a channel. Subtopic names can be defined using a multi-tiered
format:
maintoken[.secondaryToken][.additionalToken]

To receive messages from more than one subtopic, subscribers can use the wildcard
character (*) in place of any tokens in the subtopic name. For instance, a subscriber
could subscribe to the following subtopic: "news..business.* ", and the publisher sends
messages to "news.business.newyork " and "news.business.tokyo ". In this case the
messages published to either subtopic will be delivered to the consumer.

The wildcard character in the last position will match any token in that position as well as
tokens after it. For instance, subtopic com.foo.* will match all of the following: com.foo.
bar, com.foo.abc.def , etc. However, the wildcard character in any position other than
the last will match only one token. For example, subtopic com.*.foo will match com.
abc.foo and com.123.foo , but will not match com.foo .
See example.

Publishing a message only/also as a push notification - By default Backendless delivers


published messages only to the "pub/sub subscribers", that is programs subscribed to receive
messages using the Subscription API. The publishing API provides a way to configure the
delivery mode for the following three modes:
API Subscribers (see example)
Only as Push Notifications (see example)
API Subscribers and Push Notifications (same example as above, see the comment in the
example's code)

Publishing a push notification to a group of devices - Backendless can deliver messages


published as a push notifications to devices grouped
by operating system. That is messages can be delivered only to Android devices, iOS or Windows
Phone or a any combination of these. See example.

Publishing a push notification and targeting specific devices - By default Backendless


delivers published messages to all matched subscribers. (Subscribers may be matched by the
topic name or a query). Alternatively, publishers can direct messages to specific subscribers by
specifying the subscriber or device ID in message meta-data. See example.

Delayed publishing - Backendless immediately processes any published messages and


delivers them to subscribers without any delay. However, publishers can specify the time when
the message should be processed. This is applicable to all the publishing options listed above.
Message processing can be canceled at any time using the message cancellation API. See
example.

Scheduled (repeated) publishing - Backendless supports repeated message processing - a


message is published once, but delivered to subscribers with the specified frequency. Repeated
delivery can stop either at the specified time or they can be canceled using the message
cancellation API. For instance, this could be used for reminders or scheduled tasks. See example
.

2015 Backendless Corp.


100 Backendless API for .NET

Method Signatures
Synchronous Methods (not available for Windows Phone):
Publishes message to "Default" channel. The message is not a push notification, it does not
have any headers and does not go into any subtopics.
public MessageStatus Backendless.Messaging.Publish( object message )

Same as above, but published into the specified channel.


public MessageStatus Backendless.Messaging.Publish( object message,
string channelName )

Publishes message to "Default" channel. The message is not a push notification, it may have
headers and/or subtopic defined in the publishOptions argument.
public MessageStatus Backendless.Messaging.Publish( object message,
PublishOptions
publishOptions )

Same as above, but published into the specified channel.


public MessageStatus Backendless.Messaging.Publish( object message,
string channelName,
PublishOptions
publishOptions )

Publishes message to "Default" channel. The message may be configured as a push


notification. It may have headers and/or subtopic defined in the publishOptions argument.
public MessageStatus Backendless.Messaging.Publish( object message,
PublishOptions
publishOptions,
DeliveryOptions
deliveryOptions )

Same as above, but published into the specified channel.


public MessageStatus Backendless.Messaging.Publish( object message,
string channelName,
PublishOptions
publishOptions,
DeliveryOptions
deliveryOptions )
Asynchronous Methods:
The same set of methods is available for the asynchronous invocation. The difference in the
method signatures is the AsyncCallback<MessageStatus> argument:
// Publishes message to "Default" channel. The message is not a push
notification,
// it does not have any headers and does not go into any subtopics.
public MessageStatus Backendless.Messaging.Publish( object message,
AsyncCallback<
MessageStatus> publishResponder )

// Same as above, but published into the specified channel.

2015 Backendless Corp.


Messaging Service 101
public MessageStatus Backendless.Messaging.Publish( object message,
string channelName,
AsyncCallback<
MessageStatus> publishResponder )

// Publishes message to "Default" channel. The message is not a push


notification,
// it may have headers and/or subtopic defined in the publishOptions
argument.
public MessageStatus Backendless.Messaging.Publish( object message,
PublishOptions
publishOptions,
AsyncCallback<
MessageStatus> publishResponder )

// Same as above, but published into the specified channel.


public MessageStatus Backendless.Messaging.Publish( object message,
string channelName,
PublishOptions
publishOptions,
AsyncCallback<
MessageStatus> publishResponder )

// Publishes message to "Default" channel. The message may be configured as a


push notification.
// It may have headers and/or subtopic defined in the publishOptions
argument.
public MessageStatus Backendless.Messaging.Publish( object message,
PublishOptions
publishOptions,
DeliveryOptions
deliveryOptions,
AsyncCallback<
MessageStatus> publishResponder )

// Same as above, but published into the specified channel.


public MessageStatus Backendless.Messaging.Publish( object message,
string channelName,
PublishOptions
publishOptions,
DeliveryOptions
deliveryOptions,
AsyncCallback<
MessageStatus> publishResponder )
where:
channelName - name of the channel to publish the message to. If the channel
does not exist, Backendless automatically creates it.
message - object to publish. The object can be of any data type - a
primitive value, String, Date, a user-defined complex type, a
collection or an array of these types.
publishOptions - an instance of PublishOptions . When provided may contain
publisher ID (an arbitrary, application-specific string value
identifying the publisher), subtopic value and/or a collection of
headers.
deliveryOptions - an instance of DeliveryOptions . When provides may specify

2015 Backendless Corp.


102 Backendless API for .NET

options for message delivery such as: deliver as a push


notification, deliver to specific devices (or a group of devices
grouped by the operating system), delayed delivery or repeated
delivery
Return value:
MessageStatus - A data structure which contains ID of the published message
and the status of the publish operation:
namespace BackendlessAPI.Messaging
{
public class MessageStatus
{
public PublishStatusEnum Status { get; }
public string MessageId { get; }
public string ErrorMessage { get; }
}
}
Supported message statuses are:
namespace BackendlessAPI.Messaging
{
public enum PublishStatusEnum
{
FAILED,
PUBLISHED,
SCHEDULED,
CANCELLED
}
}
When the message Status is returned as PublishStatusEnum.FAILED , the corresponding
error message is available through the ErrorMessage property.
Errors:
The following errors may occur during the message publishing API call. See the Error Handling
section for details on how to retrieve the error code when the server returns an error:

Error Description
Code
5003 Invalid repeatExpiresAt date in delivery options.
5007 User does not have the permission to publish messages
5030 Invalid publishAt date in the delivery options.
Examples:
Basic message publishing
Publishing with message headers
Publishing to a subtopic
Publishing a message only as a push notification
Publishing a message as a push notification and targeting specific group of devices (grouped by
OS)
Publishing a push notification and targeting specific devices
Delayed publishing
Repeated publishing

Basic message publishing

2015 Backendless Corp.


Messaging Service 103
Synchronous Publish
using BackendlessAPI;
using BackendlessAPI.Messaging;
Backendless.InitApp( appId, secretKey, version ); // where to get the values
for the InitApp call

MessageStatus status = Backendless.Messaging.Publish( "hello world" );


System.Console.WriteLine( "Message published. Message ID - " + status.
MessageId + ". Message Status - " + status.Status );

Asynchronous Publish
using BackendlessAPI;
using BackendlessAPI.Messaging;
Backendless.InitApp( appId, secretKey, version ); // where to get the values
for the InitApp call

AsyncCallback<MessageStatus> callback = new AsyncCallback<MessageStatus>(


result =>
{
System.Console.WriteLine( "Message published. Message ID - " +
result.MessageId + ". Message Status - " + result.Status );
},

fault =>
{
System.Console.WriteLine( "Error - " + fault );
} );

Backendless.Messaging.Publish( "Hello world", callback );

Publishing with message headers


Synchronous Publish
using BackendlessAPI;
using BackendlessAPI.Messaging;
Backendless.InitApp( appId, secretKey, version ); // where to get the values
for the InitApp call

PublishOptions publishOptions = new PublishOptions();


publishOptions.AddHeader( "city", "Tokyo" );

Weather weather = new Weather();


weather.Humidity = 80;
weather.Temperature = 78;

MessageStatus status = Backendless.Messaging.Publish( weather, publishOptions


);
System.Console.WriteLine( "Message published. Message ID - " + status.
MessageId + ". Message Status - " + status.Status );
Asynchronous Publish
using BackendlessAPI;
using BackendlessAPI.Messaging;

2015 Backendless Corp.


104 Backendless API for .NET

Backendless.InitApp( appId, secretKey, version ); // where to get the values


for the InitApp call

AsyncCallback<MessageStatus> callback = new AsyncCallback<MessageStatus>(


result =>
{
System.Console.WriteLine( "Message published. Message ID - " +
result.MessageId + ". Message Status - " + result.Status );
},
fault =>
{
System.Console.WriteLine( "Error - " + fault );
} );

PublishOptions publishOptions = new PublishOptions();


publishOptions.AddHeader( "city", "Tokyo" );

Weather weather = new Weather();


weather.Humidity = 80;
weather.Temperature = 78;
Backendless.Messaging.Publish( weather, publishOptions, callback );

Publishing to a subtopic
Synchronous Publish
using BackendlessAPI;
using BackendlessAPI.Messaging;
Backendless.InitApp( appId, secretKey, version ); // where to get the values
for the InitApp call

PublishOptions publishOptions = new PublishOptions();


publishOptions.Subtopic = "news.business.newyork";

MessageStatus status = Backendless.Messaging.Publish( "Get free coffee at


Moonbucks today", publishOptions );
System.Console.WriteLine( "Message published. Message ID - " + status.
MessageId + ". Message Status - " + status.Status );
Asynchronous Publish
using BackendlessAPI;
using BackendlessAPI.Messaging;
Backendless.InitApp( appId, secretKey, version ); // where to get the values
for the InitApp call

AsyncCallback<MessageStatus> callback = new AsyncCallback<MessageStatus>(


result =>
{
System.Console.WriteLine( "Message published. Message ID - " +
result.MessageId + ". Message Status - " + result.Status );
},
fault =>
{
System.Console.WriteLine( "Error - " + fault );
} );

2015 Backendless Corp.


Messaging Service 105
PublishOptions publishOptions = new PublishOptions();
publishOptions.Subtopic = "news.business.newyork";
Backendless.Messaging.Publish( "Get free coffee at Moonbucks today",
publishOptions, callback );

Publishing a message only as a push notification


Synchronous Publish
using BackendlessAPI;
using BackendlessAPI.Messaging;
Backendless.InitApp( appId, secretKey, version ); // where to get the values
for the InitApp call

DeliveryOptions deliveryOptions = new DeliveryOptions();


deliveryOptions.PushBroadcast = DeliveryOptions.ALL;
deliveryOptions.PushPolicy = PushPolicyEnum.ONLY;

MessageStatus status = Backendless.Messaging.Publish( "Hey Devices!",


deliveryOptions );
System.Console.WriteLine( "Message published. Message ID - " + status.
MessageId + ". Message Status - " + status.Status );

if( status.Status == PublishStatusEnum.FAILED )


System.Console.WriteLine( "Message publish failed with error " + status.
ErrorMessage );
Asynchronous Publish
using BackendlessAPI;
using BackendlessAPI.Messaging;
Backendless.InitApp( appId, secretKey, version ); // where to get the values
for the InitApp call

AsyncCallback<MessageStatus> callback = new AsyncCallback<MessageStatus>(


result =>
{
System.Console.WriteLine( "Message published. Message ID - " +
result.MessageId + ". Message Status - " + result.Status );

if( result.Status == PublishStatusEnum.FAILED )


System.Console.WriteLine( "Message publish failed with error " +
result.ErrorMessage );
},
fault =>
{
System.Console.WriteLine( "Error - " + fault );
} );

DeliveryOptions deliveryOptions = new DeliveryOptions();


deliveryOptions.PushBroadcast = DeliveryOptions.ALL;
deliveryOptions.PushPolicy = PushPolicyEnum.ONLY;

Backendless.Messaging.Publish( "Hey Devices!", deliveryOptions, callback );

2015 Backendless Corp.


106 Backendless API for .NET

Publishing a message as a push notification and targeting


specific group of devices
The only difference between this example and the one above is the value of the pushBroadcast
property in DeliveryOptions :
Synchronous Publish
using BackendlessAPI;
using BackendlessAPI.Messaging;
Backendless.InitApp( appId, secretKey, version ); // where to get the values
for the InitApp call

DeliveryOptions deliveryOptions = new DeliveryOptions();


deliveryOptions.PushBroadcast = DeliveryOptions.ANDROID;
deliveryOptions.PushPolicy = PushPolicyEnum.ONLY;

PublishOptions publishOptions = new PublishOptions();


publishOptions.AddHeader( "android-ticker-text", "You just got a push
notification!" );
publishOptions.AddHeader( "android-content-title", "This is a notification
title" );
publishOptions.AddHeader( "android-content-text", "Push Notifications are
cool" );

MessageStatus status = Backendless.Messaging.Publish( "Hi Android!",


publishOptions, deliveryOptions );
System.Console.WriteLine( "Message published. Message ID - " + status.
MessageId + ". Message Status - " + status.Status );

if( status.Status == PublishStatusEnum.FAILED )


System.Console.WriteLine( "Message publish failed with error " + status.
ErrorMessage );
Asynchronous Publish
using BackendlessAPI;
using BackendlessAPI.Messaging;
Backendless.InitApp( appId, secretKey, version ); // where to get the values
for the InitApp call

AsyncCallback<MessageStatus> callback = new AsyncCallback<MessageStatus>(


result =>
{
System.Console.WriteLine( "Message published. Message ID - " +
result.MessageId + ". Message Status - " + result.Status );

if( result.Status == PublishStatusEnum.FAILED )


System.Console.WriteLine( "Message publish failed with error " +
result.ErrorMessage );
},
fault =>
{
System.Console.WriteLine( "Error - " + fault );
} );

DeliveryOptions deliveryOptions = new DeliveryOptions();


deliveryOptions.PushBroadcast = DeliveryOptions.ANDROID;

2015 Backendless Corp.


Messaging Service 107
deliveryOptions.PushPolicy = PushPolicyEnum.ONLY;

PublishOptions publishOptions = new PublishOptions();


publishOptions.AddHeader( "android-ticker-text", "You just got a push
notification!" );
publishOptions.AddHeader( "android-content-title", "This is a notification
title" );
publishOptions.AddHeader( "android-content-text", "Push Notifications are
cool" );

Backendless.Messaging.Publish("Hi Android!", publishOptions, deliveryOptions,


callback );

Publishing a push notification and targeting specific


devices
Synchronous Publish
using BackendlessAPI;
using BackendlessAPI.Messaging;
Backendless.InitApp( appId, secretKey, version ); // where to get the values
for the InitApp call

DeliveryOptions deliveryOptions = new DeliveryOptions();


deliveryOptions.PushSinglecast.Add( TARGET_DEVICE_ID );
deliveryOptions.PushPolicy = PushPolicyEnum.ONLY;

PublishOptions publishOptions = new PublishOptions();


publishOptions.AddHeader( "android-ticker-text", "You just got a push
notification!" );
publishOptions.AddHeader( "android-content-title", "This is a notification
title" );
publishOptions.AddHeader( "android-content-text", "Push Notifications are
cool" );

MessageStatus status = Backendless.Messaging.Publish( "Hi Android!",


publishOptions, deliveryOptions );
System.Console.WriteLine( "Message published. Message ID - " + status.
MessageId + ". Message Status - " + status.Status );

if( status.Status == PublishStatusEnum.FAILED )


System.Console.WriteLine( "Message publish failed with error " + status.
ErrorMessage );
Asynchronous Publish
using BackendlessAPI;
using BackendlessAPI.Messaging;
Backendless.InitApp( appId, secretKey, version ); // where to get the values
for the InitApp call

AsyncCallback<MessageStatus> callback = new AsyncCallback<MessageStatus>(


result =>
{
System.Console.WriteLine( "Message published. Message ID - " +
result.MessageId + ". Message Status - " + result.Status );

2015 Backendless Corp.


108 Backendless API for .NET

if( result.Status == PublishStatusEnum.FAILED )


System.Console.WriteLine( "Message publish failed with error " +
result.ErrorMessage );
},
fault =>
{
System.Console.WriteLine( "Error - " + fault );
} );

DeliveryOptions deliveryOptions = new DeliveryOptions();


deliveryOptions.PushSinglecast.Add( TARGET_DEVICE_ID );
deliveryOptions.PushPolicy = PushPolicyEnum.ONLY;

PublishOptions publishOptions = new PublishOptions();


publishOptions.AddHeader( "android-ticker-text", "You just got a push
notification!" );
publishOptions.AddHeader( "android-content-title", "This is a notification
title" );
publishOptions.AddHeader( "android-content-text", "Push Notifications are
cool" );

Backendless.Messaging.Publish("Hi Android!", publishOptions, deliveryOptions,


callback );

Delayed publishing
Synchronous Publish
using BackendlessAPI;
using BackendlessAPI.Messaging;
Backendless.InitApp( appId, secretKey, version ); // where to get the values
for the InitApp call

DeliveryOptions deliveryOptions = new DeliveryOptions();


deliveryOptions.PublishAt = DateTime.Now.AddSeconds( 20 );

MessageStatus status = Backendless.Messaging.Publish( "This message was


scheduled 20 seconds ago", deliveryOptions );
System.Console.WriteLine( "Message scheduled. Message ID - " + status.
MessageId + ". Message Status - " + status.Status );

if( status.Status == PublishStatusEnum.FAILED )


System.Console.WriteLine( "Message publish failed with error " + status.
ErrorMessage );
Asynchronous Publish
using BackendlessAPI;
using BackendlessAPI.Messaging;
Backendless.InitApp( appId, secretKey, version ); // where to get the values
for the InitApp call

AsyncCallback<MessageStatus> callback = new AsyncCallback<MessageStatus>(


result =>
{
System.Console.WriteLine( "Message scheduled. Message ID - " +

2015 Backendless Corp.


Messaging Service 109
result.MessageId + ". Message Status - " + result.Status );

if( result.Status == PublishStatusEnum.FAILED )


System.Console.WriteLine( "Message publish failed with error " +
result.ErrorMessage );
},
fault =>
{
System.Console.WriteLine( "Error - " + fault );
} );

DeliveryOptions deliveryOptions = new DeliveryOptions();


deliveryOptions.PublishAt = DateTime.Now.AddSeconds( 20 );

Backendless.Messaging.Publish( "This message was scheduled 20 seconds ago",


deliveryOptions, callback );

Repeated publishing
Synchronous Publish
using BackendlessAPI;
using BackendlessAPI.Messaging;
Backendless.InitApp( appId, secretKey, version ); // where to get the values
for the InitApp call

DeliveryOptions deliveryOptions = new DeliveryOptions();


deliveryOptions.PublishAt = DateTime.Now.AddSeconds( 20 );
deliveryOptions.RepeatEvery = 20;
deliveryOptions.RepeatExpiresAt = DateTime.Now.AddHours( 1 );

MessageStatus status = Backendless.Messaging.Publish( "This message was


scheduled 20 seconds ago", deliveryOptions );
System.Console.WriteLine( "Message scheduled. Message ID - " + status.
MessageId + ". Message Status - " + status.Status );

if( status.Status == PublishStatusEnum.FAILED )


System.Console.WriteLine( "Message publish failed with error " + status.
ErrorMessage );
Asynchronous Publish
using BackendlessAPI;
using BackendlessAPI.Messaging;
Backendless.InitApp( appId, secretKey, version ); // where to get the values
for the InitApp call

AsyncCallback<MessageStatus> callback = new AsyncCallback<MessageStatus>(


result =>
{
System.Console.WriteLine( "Message scheduled. Message ID - " +
result.MessageId + ". Message Status - " + result.Status );

if( result.Status == PublishStatusEnum.FAILED )


System.Console.WriteLine( "Message publish failed with error " +
result.ErrorMessage );
},

2015 Backendless Corp.


110 Backendless API for .NET

fault =>
{
System.Console.WriteLine( "Error - " + fault );
} );

DeliveryOptions deliveryOptions = new DeliveryOptions();


deliveryOptions.PublishAt = DateTime.Now.AddSeconds( 20 );
deliveryOptions.RepeatEvery = 20;
deliveryOptions.RepeatExpiresAt = DateTime.Now.AddHours( 1 );

Backendless.Messaging.Publish( "This message was scheduled 20 seconds ago",


deliveryOptions, callback );

3.8 Publish Push Notifications


Publishing a push notification is a specialized usage of the Message Publishing API. Push notifications
have different graphical representation on different mobile operating systems. For instance, a push
notification on an iOS device may be either an alert or a badge update, however a notification on a
Windows Phone device may be either a toaster alert or a tile element update. Backendless supports
different formats of the push notification delivery to various operating systems via specialized message
headers. These headers must be added to the publish options object or in case of REST clients, they
are plain message headers:
Operating Headers Description
System
iOS "ios-alert":value Sets the text of
the alert
message. If the
header is not
present and the
published
notification
targets the iOS
devices,
Backendless
sets the header
to the value of
the "message"
argument. To
disable this
behavior, set
the ios-alert
header to null .
"ios-badge":value Sets the value
to update the
badge with
"ios-sound":URL string or array of bytes Sets either a
URL for the
sound
notification to
play on the

2015 Backendless Corp.


Messaging Service 111
device or an
array of bytes
for the sound to
play.
Android "android-ticker-text":value Sets the text of
the ticker
showing up at
the top of a
device's screen
when the device
receives the
notification.
"android-content-title":value Sets the title of
the notification
as it is visible in
the Android
Notification
Center
"android-content-text":value Sets the
message of the
notification
which appears
under android-
content-title
in the Android
Notification
Center.
Windows "wp-title":value, Sets the title
Phone "wp-content":value and the content
of a toast
notification.
"wp-type":"TILE": Sets the
"wp-title" : value, properties for a
"wp-backgroundImage" : URL string,
tile notification.
"wp-badge" : number value,
"wp-backTitle" : value,
"wp-backImage" : URL string,
"wp-backContent" : value
"wp-type":"RAW", Sets the
"wp-raw":XMLString properties for a
raw notification

Push notifications can be published directly from Backendless Console or using the API (see the
examples in the Message Publishing section).

3.9 Cancel Scheduled Message


Delayed or scheduled messages can be canceled using the API documented below. Backendless
processes delayed messages at the time specified by the publisher. Scheduled messages are
processed and delivered with a specified interval.

Method Signatures

2015 Backendless Corp.


112 Backendless API for .NET

Synchronous Method:
public bool Backendless.Messaging.Cancel( string messageId )

Asynchronous Method:
public MessageStatus Backendless.Messaging.Publish( string messageId,
AsyncCallback<bool> cancelResponder )
where:
messageId - ID of the message to cancel. Message ID must be obtained
from the MessageStatus object obtained as the result of the
Publish methods.
Return value:
bool -True is the scheduled message has been successfully
canceled, false otherwise.

Errors:
The following errors may occur during the message cancellation API call. See the Error
Handling section for details on how to retrieve the error code when the server returns an error:
Error Description
Code
5040 Message has already been canceled or does not exist.

Examples:
Synchronous Publish and Cancellation
using BackendlessAPI;
using BackendlessAPI.Messaging;
Backendless.InitApp( appId, secretKey, version ); // where to get the values
for the InitApp call

DeliveryOptions deliveryOptions = new DeliveryOptions();


deliveryOptions.PublishAt = DateTime.Now.AddSeconds( 200 );

MessageStatus status = Backendless.Messaging.Publish( "This message was


scheduled 20 seconds ago", deliveryOptions );
System.Console.WriteLine( "Message scheduled. Message ID - " + status.
MessageId + ". Message Status - " + status.Status );

Backendless.Messaging.Cancel( status.MessageId );
Asynchronous Publish and Cancellation
using BackendlessAPI;
using BackendlessAPI.Messaging;
Backendless.InitApp( appId, secretKey, version ); // where to get the values
for the InitApp call

AsyncCallback<MessageStatus> cancelCallback = new AsyncCallback<MessageStatus


>(
result =>
{
System.Console.WriteLine( "Message canceled - " + result );

},

2015 Backendless Corp.


Messaging Service 113
fault =>
{
System.Console.WriteLine( "Error - " + fault );
} );

AsyncCallback<MessageStatus> publishCallback = new AsyncCallback<


MessageStatus>(
result =>
{
System.Console.WriteLine( "Message scheduled. Message ID - " +
result.MessageId + ". Message Status - " + result.Status );
Backendless.Messaging.Cancel( result.MessageId, cancelCallback );
},
fault =>
{
System.Console.WriteLine( "Error - " + fault );
} );

DeliveryOptions deliveryOptions = new DeliveryOptions();


deliveryOptions.PublishAt = DateTime.Now.AddSeconds( 200 );

Backendless.Messaging.Publish( "This message was scheduled 20 seconds ago",


deliveryOptions, publishCallback );

3.10 Message Subscription


In order to receive published messages, application must subscribe to a channel using the API below.
Using the API, an application becomes an "API subscriber". Another form of subscription can be
accomplished by using the Device Registration API which provides a way to receive push notifications.
Note that the same mobile application can use both device registration and message subscription APIs.

Synchronous Methods (are not available for Windows Phone)


Subscribing to "Default" channel:
public Subscription Subscribe( AsyncCallback<List<Message>> callback )

public Subscription Subscribe( int pollingInterval,


AsyncCallback<List<Message>> callback )

public Subscription Subscribe( AsyncCallback<List<Message>>


subscriptionResponder,
SubscriptionOptions subscriptionOptions )

public Subscription Subscribe( int pollingInterval,


AsyncCallback<List<Message>>
subscriptionResponder,
SubscriptionOptions subscriptionOptions )
Subscribing to a specific channel:

2015 Backendless Corp.


114 Backendless API for .NET

public Subscription Subscribe( string channelName,


AsyncCallback<List<Message>>
subscriptionResponder )

public Subscription Subscribe( string channelName,


int pollingInterval,
AsyncCallback<List<Message>>
subscriptionResponder )

public Subscription Subscribe( string channelName,


AsyncCallback<List<Message>>
subscriptionResponder,
SubscriptionOptions subscriptionOptions )

public Subscription Subscribe( string channelName,


int pollingInterval,
AsyncCallback<List<Message>>
subscriptionResponder,
SubscriptionOptions subscriptionOptions )
where:
channelName - name of the channel to subscribe to.
subscriptionResponder - responder object where Backendless delivers messages for the
subscriber.
subscriptionOptions - contains settings for filtered message delivery. Available options
include subtopic and selector. See the Message Filtering section
below.
pollingInterval - the interval in milliseconds between subsequent polling
requests. Each polling request checks for messages for the
subscription.

Return value:
Subscription - An object representing the subscription. A Subscription
object provides access to a unique identifier which can be used
for subscription cancellation.

Asynchronous Methods:
All asynchronous methods have exactly the same signatures as the synchronous counterparts
except for the AsyncCallback argument which receives a notification about the successful or
failed completion of the method:
Subscribing to "Default" channel:
public void Subscribe( AsyncCallback<List<Message>> subscriptionResponder,
AsyncCallback<Subscription> methodCallback )

public void Subscribe( int pollingInterval,


AsyncCallback<List<Message>> subscriptionResponder,
AsyncCallback<Subscription> methodCallback )

public void Subscribe( AsyncCallback<List<Message>> subscriptionResponder,

2015 Backendless Corp.


Messaging Service 115
SubscriptionOptions subscriptionOptions,
AsyncCallback<Subscription> methodCallback )

public void Subscribe( int pollingInterval,


AsyncCallback<List<Message>> subscriptionResponder,
SubscriptionOptions subscriptionOptions,
AsyncCallback<Subscription> methodCallback )
Subscribing to a specific channel:
public void Subscribe( string channelName,
AsyncCallback<List<Message>> subscriptionResponder,
AsyncCallback<Subscription> methodCallback )

public void Subscribe( string channelName,


int pollingInterval,
AsyncCallback<List<Message>> subscriptionResponder,
AsyncCallback<Subscription> methodCallback )

public void Subscribe( string channelName,


AsyncCallback<List<Message>> subscriptionResponder,
SubscriptionOptions subscriptionOptions,
AsyncCallback<Subscription> methodCallback )

public void Subscribe( string channelName,


int pollingInterval,
AsyncCallback<List<Message>> subscriptionResponder,
SubscriptionOptions subscriptionOptions,
AsyncCallback<Subscription> methodCallback )
where:
channelName - name of the channel to subscribe to.
subscriptionResponder - responder object where Backendless delivers messages for the
subscriber.
subscriptionOptions - contains settings for filtered message delivery. Available options
include subtopic and selector. See the Message Filtering section
below.
pollingInterval - the interval in milliseconds between subsequent polling
requests. Each polling request checks for messages for the
subscription.
methodCallback - a callback object notified of the successful or failed completion
of the subscription operation. An invocation the
ResponseHandler delegate represents a successful message
subscription. The argument of the callback is an instance of the
Subscription class - an object representing the established
subscription. A Subscription object provides access to a
unique identifier which can be used for subscription cancellation.
Errors:
The following errors may occur during the message cancellation API call. See the Error
Handling section for details on how to retrieve the error code when the server returns an error:
Error Description

2015 Backendless Corp.


116 Backendless API for .NET

Code
5008 User does not have permission to create a subscription.
5009 General subscription error. See error message for additional
details.
5010 Unknown messaging channel.
Messages
The .NET/Windows Phone client retrieves messages using the AsyncCallback class. All Subscribe
methods described above receive the following argument:AsyncCallback<List<Message>>
subscriptionResponder . Backendless delivers new messages published to the subscribed channel
through the ReceivedResponse delegate of the subscriptionResponder object:
namespace BackendlessAPI
{
public delegate void ErrorHandler( BackendlessFault _backendlessFault );
public delegate void ResponseHandler<T>( T response );

public class AsyncCallback<T>


{
internal ErrorHandler ErrorHandler;
internal ResponseHandler<T> ResponseHandler;

public AsyncCallback( ResponseHandler<T> responseHandler, ErrorHandler


errorHandler )
{
this.ResponseHandler = responseHandler;
this.ErrorHandler = errorHandler;
}
}
}
The "T response" argument in the ResponseHandler delegate is a collection of the BackendlessAPI.
Messaging.Message objects:
namespace BackendlessAPI.Messaging
{
public class Message
{
public string MessageId { get; }
public object Data { get; }
public Dictionary<string, string> Headers { get; }
public string PublisherId { get; }
public long Timestamp { get; }
}
}
where:
messageId - unique message ID. The ID is assigned at the time of message
publishing.
headers - an associative array which is a collection of key/value pairs.
Includes all the headers included with the message publishing.
Additionally, Backendless adds the following headers:
BL_APPLICATION_ID - contains the ID of the application and
BL_VERSION_URL_PREFIX - contains the name of the version of
the application.
data - message payload. It is the object sent by a publisher.

2015 Backendless Corp.


Messaging Service 117
publisherID - the property contains sender (publisher) ID if it is provided by
the publisher.
timestamp - a timestamp indicating when the message was received by
Backendless from the publisher.

Examples:

Backendless.InitApp( appId, secretKey, versionName ); // where to get the


values for the InitApp method arguments
Backendless.Messaging.Subscribe( new AsyncCallback < List < Message > >
( response => Dispatcher.BeginInvoke( () =>
{
foreach( Message message in response )
{
// do something with the message
}
AsyncFinishedEvent.Invoke();
} ), HandleFault ),
new AsyncCallback<Subscription>( response =>
{
/*NO ACTION*/
}, HandleFault ) );

private void HandleFault( BackendlessFault fault )


{
Dispatcher.BeginInvoke( () =>
{
MessageBox.Show( fault.Message );
AsyncFinishedEvent.Invoke();
} );
}

Message Filtering
Backendless message filtering is a powerful mechanism enabling conditional message delivery, interest-
based subscriptions and private messaging. A subscription request may include filters in the form of
subtopics and selectors. Backendless applies subscriber's filters to every message published into the
channel and they match, the message is delivered to the subscriber.

Subtopics
Multiple subtopics can be defined within a channel. Both publishers and subscribers can specify
a subtopic within a channel. Subtopic names can be defined using a multi-tiered format:
maintoken[.secondaryToken][.additionalToken]

To receive messages from more than one subtopic, subscribers can use the wildcard character
(*) in place of any tokens in the subtopic name. For instance, a subscriber could subscribe to
the following subtopic: "news..business.* ", and the publisher sends messages to "news.
business.newyork " and " news.business.tokyo ". In this case the messages published to
either subtopic will be delivered to the consumer.

The wildcard character in the last position will match any token in that position as well as
tokens after it. For instance, subtopic com.foo.* will match all of the following: com.foo.bar,
com.foo.abc.def , etc. However, the wildcard character in any position other than the last will

2015 Backendless Corp.


118 Backendless API for .NET

match only one token. For example, subtopic com.*.foo will match com.abc.foo and
com.123.foo , but will not match com.foo .

Selectors
A selector is a query expressed using the SQL-92 syntax and formatted as the condition part of
the SQL's WHERE clause. A query condition must reference the headers of the published
messages. When a message is published and a subscriber has a selector query, Backendless
executes the query on the headers of the published message. If the result of the query is true,
the message is delivered to the subscriber. Consider the following example where the subscriber
will receive only messages containing the "city " header with the value of "Tokyo ":

Publisher:

using BackendlessAPI;
using BackendlessAPI.Messaging;
Backendless.InitApp( appId, secretKey, version ); // where to get the values
for the InitApp call

PublishOptions publishOptions = new PublishOptions();


publishOptions.AddHeader( "city", "Tokyo" );

Weather weather = new Weather();


weather.Humidity = 80;
weather.Temperature = 78;

MessageStatus status = Backendless.Messaging.Publish( weather, publishOptions


);
System.Console.WriteLine( "Message published. Message ID - " + status.
MessageId + ". Message Status - " + status.Status );
Subscriber:

Backendless.InitApp( appId, secretKey, versionName ); // where to get the


values for the InitApp method arguments

SubscriptionOptions subscriptionOptions = new SubscriptionOptions();


subscriptionOptions.Selector = "city='Tokyo'";

AsyncCallback<List<Message>> messageHandler = new AsyncCallback <List<Message


>>( response => Dispatcher.BeginInvoke( () =>
{
foreach( Message message in response )
// do something with the message
AsyncFinishedEvent.Invoke();
} ), HandleFault );

AsyncCallback<Subscription> subscriptionResponder = new AsyncCallback<


Subscription>( response =>
{
/*NO ACTION*/
}, HandleFault );

Backendless.Messaging.Subscribe( messageHandler,
subscriptionOptions,

2015 Backendless Corp.


Messaging Service 119
subscriptionResponder );

private void HandleFault( BackendlessFault fault )


{
Dispatcher.BeginInvoke( () =>
{
MessageBox.Show( fault.Message );
AsyncFinishedEvent.Invoke();
} );
}

3.11 Cancel Subscription


In order to stop a client from polling for messages, it must issue subscription cancellation request using
the API method described below:

Method Signatures:

public class Subscription


{
...
public bool CancelSubscription()
...
}
where:
Subscription - An instance of the Subscription class is obtained as the result
of the Message Subscription call.
Return value:
boolean - True if the scheduled message has been successfully
canceled, False otherwise.

Examples:

Backendless.InitApp( appId, secretKey, versionName ); // where to get the


values for the InitApp method arguments

AsyncCallback<List<Message>> messageHandler = new AsyncCallback<List<Message


>>(
response => {
foreach( Message message in response )
// do something with the message
},
fault => {
// do something with the fault
});

AsyncCallback<Subscription> subscriptionHandler = new AsyncCallback<


Subscription>(
response => {
// CANCEL SUBSCRIPTION
response.CancelSubscription();

2015 Backendless Corp.


120 Backendless API for .NET

},
fault => {
// do something with the fault
});

Backendless.Messaging.Subscribe( messageHandler, subscriptionHandler );

3.12 Sending Email


Backendless provides API for email delivery on behalf of your application. Before the API can be used,
the Backendless backend must be configured with your own SMTP server information. This is an
important requirement as the API will not work if the Manage > App Settings > Email Settings section
in Backendless Console contains default values.

Configuration
To configure a backend:

1. Login to Backendless Console.


2. Select an app.
3. Click Manage, then scroll down to Email Settings on the App Settings screen.
4. Fill out the form with the SMTP server information

2015 Backendless Corp.


Messaging Service 121
where:
SMTP Server - Hostname or public IP address of the server where the SMTP server is
running.
Port - The port number the SMTP server accepts requests on.
From - The Name which will appear in the From field of the sent out emails.
User ID - The user id or email address for the SMTP server connection
authentication
Password - The password for the SMTP server connection authentication.
Security - Choose between SSL or TLS connection.

Make sure to click Test before saving any configuration changes. The Discard button discards any
unsaved changes.

Sending Email API


Delivers an email message using current server-side email settings to the recipient specified in the API
call.

where:
subject - email message subject.
messageBody - plain text or HTML body of the email message.
bodyParts - an instance of com.backendless.messaging.BodyParts class
which contains either plain text and/or HTML version of the
message body.
recipient - email address to deliver the email message to.
recipients - a collection of email addressed to deliver the email message to.
attachments - an array of file paths for the file entries from the Backendless
File Service. Referenced files will be attached to the email
message. The path is calculated from the root of the file system
(as it is seen in File Service browser in Backendless console)
without the leading slash. For example, if file agreement.txt is
located at /documents/legal/, then the path in the API call must
be "documents/legal/agreement.txt".
responder - the callback used for asynchronous calls to indicate that the
operation has either successfully completed or resulted in error.

Example:

4 File Service

4.1 Overview
Every Backendless backend/app is allocated a dedicated file storage space. The file storage is located
remotely on the Backendless servers. The file storage can be used to store application's files and on-
demand video streams. Backendless File Service provides the API to work with the file storage. The API
supports the following operations:

File Upload - upload files to the applications's file storage. The operation creates directories up
the hierarchy if necessary. Returns file URL which can be used to download or share the file
with others.
File Download - download file using file's URL. The download operation is subject to the

2015 Backendless Corp.


122 Backendless API for .NET

permissions from the File access control list (ACL).


File Deletion - delete a file from the file storage. The delete operation is subject to the
permissions from the File access control list (ACL).
Directory Deletion - same as file deletion, but applies to the directories.
File/Directory Security (File ACL) - assign/unassign user and roles permissions to upload,
download and delete files and directories. This API is used to modify file or directory ACL.

In addition to the API implementation, the File Service enables the following capabilities:

Git Integration - application developers can interact with the file storage as with a git repository.
Web Hosting - file storage can be used to host static web content.
Custom Domain Name - a custom domain name can be mapped to the file storage in a
Backendless backend. This feature in combination with the Web Hosting provides a way to host
websites on Backendless.
Custom Web Templates Hosting - includes HTML files and JS scripts for special pages used in
various workflows such as user email confirmation, password change and session expiration.

4.2 Setup
To get access to the Backendless services, .NET and Windows Phone applications must reference the
backendless.dll assembly available in the Backendless SDK for .NET. All the Backendless SDK for .
NET classes are available in the BackendlessAPI namespace. Before the .NET/Windows Phone client
uses any of the APIs, the code must initialize the Backendless Application using the following call:
Backendless.InitApp( application-Id, secret-key, version )

Application ID and Secret Key


Values for the application-id and secret-key headers must be obtained through the Backendless
Console:

1. Login to your account and select the application.


2. Click the Manage icon from the vertical icon-menu on the left.
3. The "App Settings" section is selected by default. The interface contains the text fields for
"Application ID" and secret keys for each supported client-side environment.
4. Use the "Copy" button to copy the value into the system clipboard.

2015 Backendless Corp.


File Service 123

The version argument must contain the name of the targeted version. When a new application is
created, the default version name is "v1" . To manage versions, login to the console, select the
"Manage" icon and click "Versioning".

4.3 Error Handling


When the server reports an error, it is delivered to the client through an instance of the
BackendlessFault class. A BackendlessFault object provides access to an error code which uniquely
identifies the root cause of the error. In addition to the error code, the fault object may include an error
message which provides additional information about the error:
using System;
using Weborb.Client;

namespace BackendlessAPI.Exception
{
public class BackendlessFault
{
private readonly string _faultCode;
private readonly string _message;
private readonly string _detail;

public string Detail


{
get { return _detail; }
}

2015 Backendless Corp.


124 Backendless API for .NET

public string FaultCode


{
get { return _faultCode; }
}

public string Message


{
get { return _message; }
}

public override string ToString()


{
return String.Format( "Backendless BackendlessFault. Code: {0},
Message: {1}", FaultCode ?? "N/A", Message ?? "N/A" );
}
}
}

The asynchronous API calls accept the AsyncCallback argument which receives the fault object
through the following delegate:
public delegate void ErrorHandler( Fault fault );

The synchronous API calls declare a checked exception - BackendlessException. The fault object can
be obtained from the exception:
namespace BackendlessAPI
{
public class BackendlessException : Exception
{
public Fault Fault { get; }
public string Code { get; }
public override string Message { get; }
public override string ToString();
}
}

4.4 Handling Files via Console


Backendless Console includes a graphical file browser which supports the following operations:
Creating new file
Editing a file
Getting public URL for a file
Creating file archives

Creating a New File


You can create a file in Backendless Console with the following file extensions:
.conf, ,css, .csv, .htm, .html, .ini, .java, .js, .log, .php, .
properties, .py, .rb, .sh, .txt, .xml, .xsd

To create a file:
1. Log in to Backendless Console. Select an application. Click the Files icon:

2015 Backendless Corp.


File Service 125

2. Select a directory where a new file should created. Click the New File button at the top of
the file listing table.
3. Enter the name in the File name field and select a file extension from the Syntax
highlighter drop-down menu:

4. Enter the contents for the file as necessary. Click the Save button.

Editing a File
Backendless supports in-browser editing of the files with the following extensions:
.conf, ,css, .csv, .htm, .html, .ini, .java, .js, .log, .php, .
properties, .py, .rb, .sh, .txt, .xml, .xsd

To edit a file:

2015 Backendless Corp.


126 Backendless API for .NET

1. Select a directory containing the file on the Files screen of the console.
2. Click the Edit file icon next to the file to open it for editing:

3. Once the changes in the file are made click the Save button.

Getting Public URL for a File


A file in Backendless File Storage has two URLs:
a public URL which can be used to download the file outside of Backendless console. This URL
accounts for any permissions assigned to the file or the directory where it resides.
a private URL which makes the file accessible by the developer of the application.

In order to obtain the public URL:


1. Select a directory containing a file on the Files screen of Backendless console.
2. Click the Get Public URL icon next to the file. Backendless console copies the file's public
URL to the computer's clipboard:

2015 Backendless Corp.


File Service 127

Archiving Files
Backendless Console includes a feature enabling to compress directories into a single ZIP file. The
feature applies specifically to directories, meaning an individual file cannot be compressed - it must be
placed into a directory first.

Notice: archiving of directories with total content size greater than 100 Mb may take longer time;
Backendless sends an email to the application developer upon successful completion of the operation.

To archive a directory:
1. Log in to Backendless Console. Select an application and click the Files icon.
2. Navigate to a directory which should be compressed.
3. Click the ZIP Directory button:

4. Once the directory is compressed into an archive, it will appear in the parent directory:

2015 Backendless Corp.


128 Backendless API for .NET

4.5 File Upload


The file upload operation delivers and saves a local file in the remote Backendless file storage. The return
value of the operation is the file URL which has the following structure:

https://api.backendless.com/<application id>/<version name>/files/


<path>/<file name>

where:
<application id> - ID of the application which can be obtained from the Manage >
App Settings screen of the Backendless Console
<version name> - application's version name
<path> - directory path where the file is saved
<file name> - name of the file

The URL assigned to a file and returned as a result of the upload operation accounts for any security
permissions assigned to the file (or the folder it is located in).

Backendless Console includes a file browser with the management functions to upload files, create or
delete directories and files. The file browser is available in the Files section of the console:

2015 Backendless Corp.


File Service 129

File browser also provides a way to see the contents of the files. Every file is a link which opens the file.
The URL of files in file browser is not the same as the URL returned by the file upload operation. The
reason file browser uses a different URL is to let the application developer see the file contents without
any application security constraints. The only constraint applied to the URLs available in file browser is
the application developer must be logged to the console.

Methods:

Upload a file to a remote path in the Backendless storage.


public void BackendlessAPI.Backendless.FilesUpload( FileStream fileStream,
string remotePath,
AsyncCallback<
BackendlessFile> callback );
Upload a file to a remote path and receive updates for the status of the upload. Updates are
represented as percentages and are delivered via the uploadCallback argument.
public void BackendlessAPI.Backendless.FilesUpload( FileStream fileStream,
string remotePath,
UploadCallback
uploadCallback,
AsyncCallback<
BackendlessFile> callback )
where:
fileStream - stream for a local file to upload to Backendless file storage.
Remote file name is the same as the name of the local file.
remotePath - path (without file name) in the remote Backendless file storage
where the file should be saved.
uploadCallback - receives updates through the upload process. Updates
expressed as percentage of file uploaded to the server.
callback - a responder object which receives a callback when the method
successfully uploads the file or if an error occurs.

Return Value (delivered via AsyncCallback):


BackendlessFile - a wrapper around the URL assigned to the uploaded file.

2015 Backendless Corp.


130 Backendless API for .NET

Additional API Classes:


UploadCallback
namespace BackendlessAPI.Async
{
public delegate void ProgressHandler( int response );

public class UploadCallback


{

internal readonly ProgressHandler ProgressHandler;

public UploadCallback( ProgressHandler progressHandler )


{
ProgressHandler = progressHandler;
}
}
}
BackendlessFile
using BackendlessAPI.Async;

namespace BackendlessAPI.File
{
public class BackendlessFile
{
public BackendlessFile( string fileURL )
{
FileURL = fileURL;
}

public string FileURL { get; set; }

public void Remove()


{
Backendless.Files.Remove( FileURL );
}

public void Remove( AsyncCallback<object> callback )


{
Backendless.Files.Remove( FileURL, callback );
}
}
}

Example:

AsyncCallback<BackendlessAPI.File.BackendlessFile> callback = new


AsyncCallback<BackendlessAPI.File.BackendlessFile>(
result =>
{
System.Console.WriteLine( "File uploaded. URL - " + result.
FileURL );
},

2015 Backendless Corp.


File Service 131
fault =>
{
System.Console.WriteLine( "Error - " + fault );
} );

FileStream fs = new FileStream( "test.txt", FileMode.Open, FileAccess.Read );


BackendlessAPI.Backendless.Files.Upload( fs, "myfiles", callback );

4.6 Save Files From Byte Arrays


In addition to the traditional file upload, files can be saved by uploading a byte array which becomes the
content of the saved file.
Methods:
Synchronous methods:
public String SaveFile( String filePathName, byte[] fileContent )
public String SaveFile( String filePathName, byte[] fileContent, Boolean
overwrite )
public String SaveFile( String path, String fileName, byte[] fileContent )
public String SaveFile( String path, String fileName, byte[] fileContent,
Boolean overwrite )
Asynchronous methods:
public void SaveFile( String filePathName, byte[] fileContent, AsyncCallback<
String> responder )
public void SaveFile( String filePathName, byte[] fileContent, Boolean
overwrite, AsyncCallback<String> responder )
public void SaveFile( String path, String fileName, byte[] fileContent,
AsyncCallback<String> responder )
public void SaveFile( String path, String fileName, byte[] fileContent,
Boolean overwrite, AsyncCallback<String> responder )
where:
filePathName - Identifies both the directory where the file should be
saved and the file name. Must start with "/" which
represents the root directory of the remote file
storage.
path - Path of the directory where the file should be
stored. Must start with "/" which represents the root
directory of the remote file storage.
fileName - Name of the file where the byte content should be
written to.
fileContent - An array of bytes to save.
overwrite - The file is overwritten if the argument value is true
and the file already exists. Otherwise, if the value is
false and another file with the same name already
exists, an error is returned.
responder - A responder object which receives a callback when

2015 Backendless Corp.


132 Backendless API for .NET

the method successfully completes or if an error


occurs. Applies to the asynchronous methods only.

Return Value (delivered via AsyncCallback):


BackendlessFile - A wrapper around the URL assigned to the uploaded file.
Additional API Classes:
BackendlessFile
using BackendlessAPI.Async;

namespace BackendlessAPI.File
{
public class BackendlessFile
{
public BackendlessFile( string fileURL )
{
FileURL = fileURL;
}

public string FileURL { get; set; }

public void Remove()


{
Backendless.Files.Remove( FileURL );
}

public void Remove( AsyncCallback<object> callback )


{
Backendless.Files.Remove( FileURL, callback );
}
}
}

Example:
The example below describes how to save a file entitled "fox.txt" from the string "The quick
brown fox jumps over the lazy dog." You will need to specify:
content of a new file ("The quick brown fox jumps over the lazy dog")
where to save a new file ("testfolder")
a name of the newly created file ("fox.txt")
whether a new file should overwrite the existing file, if any (true)

static void SaveFile()


{
String content = "The quick brown fox jumps over the lazy dog";
byte[] bytes = UTF8Encoding.UTF8.GetBytes( content );
String savedFileURL = Backendless.Files.SaveFile( "tempfolder", "fox.txt",
bytes, true );
System.Console.WriteLine( "File saved. File URL - " + savedFileURL );
}
The server will return notification and link to the newly added file ("File saved. File URL - " )
or an error.

2015 Backendless Corp.


File Service 133
Errors:
Error codes returned on attempt to save a file from the byte array.
Error Description
Code
6016 When saving a new file from the byte array, the payload exceeds
2,800,000 bytes.
6003 A file you are trying to save already exists in the system and cannot
overwrite since overwrite argument is ether set to false or
omitted.

4.7 File Download

Downloading a File via the Backendless Console


To download a file:
1. Log in to Backendless Console.
2. Select an application for which you want to create a new file. The application page will display
3. Click the Files tab on the left menu. The Root folder containing all files of an application will
display.
4. Locate a file you want to download. Click the Download file icon next to this file.

Downloading a File via API


Downloading a file from the Backendless file storage is the basic HTTP GET operation. The operation
should use the same URL which Backendless returned as the result of the file upload operation.
Alternatively, if the file was uploaded manually using the console, the URL can be composed as:

https://api.backendless.com/<application id>/<version name>/files/


<path>/<file name>

where:
<application id> - ID of the application which can be obtained from the

2015 Backendless Corp.


134 Backendless API for .NET

Manage > App Settings screen of the Backendless


Console.
<version name> - Application's version name.
<path> - Directory path where the file is saved.
<file name> - Name of the file.
Files fetched with the URL scheme defined above are subject to the security constraints and
permissions established by the application developer. See the Files Security section for additional
details on how to secure file storage. Fetching a file secured by an access control list (ACL) policy
requires an additional HTTP header in the request:

user-token:<value>

where:
<value> - Value of the user token established for the current
user session as a result of the user login operation.
The token uniquely identifies the user session. It is
used by Backendless to establish user identity for all
operations where the token is present. This is
necessary in order to determine permissions applicable to the
user and the roles associated with the account.

4.8 File Deletion


To delete a file from the Backendless file storage, it must be identified by the file path/name. Files in the
Backendless storage have the following URL structure:
https://api.backendless.com/<application id>/<version name>/files/
<path>/<file name>

The API to delete a file uses the <path>/<filename> part to identify the file which must be deleted.

Methods:

Synchronous method:
public void BackendlessAPI.Backendless.Files.Remove( string filePath )
Asynchronous method:
public void BackendlessAPI.Backendless.Files.Remove( string filePath,
AsyncCallback<object> callback )
where:
filePath - Path of the file to delete. The path must consist of the file path
and file name.
callback - A responder object which receives a callback when the method
successfully deletes the file or if an error occurs.

Example:
AsyncCallback<object> callback = new AsyncCallback<object>(

2015 Backendless Corp.


File Service 135
result =>
{
System.Console.WriteLine( "File deleted" );
},

fault =>
{
System.Console.WriteLine( "Error - " + fault );
} );

BackendlessAPI.Backendless.Files.Remove( "myfiles/test.txt", callback );

4.9 Directory Deletion


To delete a directory from the Backendless file storage, it must be identified by the its path. Directories
in the Backendless storage have the following URL structure:
https://api.backendless.com/<application id>/<version name>/files/
<path>

The API to delete a directory uses the <path> element from the URL above.

Methods:
Synchronous method:
public void BackendlessAPI.Backendless.Files.RemoveDirectory( string path )
Asynchronous method:
public void BackendlessAPI.Backendless.Files.RemoveDirectory( string path,
AsyncCallback<object> callback )
where:
path - path of the directory to delete.
callback - a responder object which receives a callback when the method
successfully deletes the directory or if an error occurs.

Example:
AsyncCallback<object> callback = new AsyncCallback<object>(
result =>
{
System.Console.WriteLine( "Directory deleted" );
},

fault =>
{
System.Console.WriteLine( "Error - " + fault );
} );

BackendlessAPI.Backendless.Files.Remove( "myfiles/pics", callback );

2015 Backendless Corp.


136 Backendless API for .NET

4.10 Git Integration


Backendless file storage can also function as a git repository. This could be very convenient for
deploying multiple files from the developer's computer with a single command. Git integration is disabled
by default. To enable git for the file storage:
1. Open Backendless Console
2. Select your app/backend
3. Click Manage and scroll to the Enable .git support section
4. Use the toggle to turn git integration on or off:

When the git integration is turned on, all files present in or uploaded to the file storage are immediately
committed to the repository. This integration is bi-directional. It means that any files committed into the
git repository by the means of git, will also be copied into the file storage. When git integration is being
turned off, the git repository is deleted with all the associated history (the files remain in the file storage).

With the git integration enabled, a new folder (.git) appears in the File Browser on the Files screen. The
folder contains the files from the git repository. When a file is uploaded to file storage either via the
Upload API or using the File Browser, it is automatically committed to the repository. Likewise, when a
file is pushed into the repository, it becomes available and visible in the file storage. The same applies to
editing and deleting files either in the Backendless Console or in git repository.

When git is enabled, the repository is available at the following address:


https://git.backendless.com/<application id>/.git

where:
<application id> - application ID available in Backendless Console at Manage >
App Settings .

When the Backendless backend is configured with a custom domain name, the repository URL is:
http://<custom domain name>/.git

The repository uses the same authentication as Backendless Console. That means all git commands
must use the same developer email address and password as for logging in to Backendless Console.

It is important to note that any system level files created by git are also placed into the file storage (the .
git directory). These files are accounted for when calculating the file space used by the app/backend.

Configuring Local Environment

You have no local files and there is a remote GIT repository:


There are files in the Backendless storage and there are no files locally:

Clone existing repository:


mkdir /path/to/your/project

2015 Backendless Corp.


File Service 137
cd /path/to/your/project
git clone http://git.backendless.com/<your application id>/.git
cd <your application id>

Adding a file locally and pushing to Backendless git:


> echo "First file" >> file.txt
> git add file.txt
> git commit -m 'Initial commit with new file'
> git push -u origin master

You have with an existing GIT project in your local


environment:
This applies when you already have a local git project. You also enabled git integration in Backendless
and need to "integrate" your local git project with the git repository in Backendless.
> cd /path/to/my/repo
> git remote add origin http://git.backendless.com/<your application
id>/.git

# pushes the repo and its refs for the first time to Backendless git
> git push -u origin --all

# pushes any tags to Backendless git


> git push -u origin --tags

You have an existing FILE project in your local


environment.
This applies when you have existing files locally and need to add them to the git repository you
initialized in Backendless.
> cd /path/to/my/repo
> git init
> git remote add origin http://git.backendless.com/<your
application id>/.git
> git pull -u origin master
> git add *
> git commit -m merge with existing project
> git push -u origin master

4.11 Web Hosting


Backendless file storage includes a special directory which facilitates web hosting for the app/backend.
The directory name is /web :

2015 Backendless Corp.


138 Backendless API for .NET

The /web folder serves as the web server root. The web server is available at the following URLs:

With custom domain name enabled for the account:


http://custom domain name

Without custom domain name:


https://api.backendless.com/<application id>/<version name>/files/
web

where:
<application id> - ID of the application which can be obtained from the Manage >
App Settings screen of the Backendless Console
<version name> - application's version name

4.12 Custom Domain Name


Backendless File Service supports mapping of a custom domain name to the application's backend. As
a result, once a domain name is mapped, the following backend's resources become available via the
custom URL:
Service API endpoint. The default endpoint for all Backendless services is:
https://api.backendless.com

With a custom domain name, the endpoint is also available at:


http://<custom domain name>/api

Web Hosting. Backendless file storage contains a special directory - /web , which serves as the
web site root. When a custom domain name is mapped to a Backendless application/backend,
the contents of the /web directory are served for the HTTP requests with the domain name. See

2015 Backendless Corp.


File Service 139
the Web Hosting section for additional details.

git endpoint. When the Backendless git integration is enabled, the git endpoint with a custom
domain name is:
http://<custom domain name>/.git

Before a custom domain name is assigned to a Backendless application:


1. Create a CNAME record for the domain name and map it to backendless.com.
2. Open Backendless Console and select your application/backend.
3. Click Manage and scroll down to the "Custom Domain" section.
4. Enter the domain name into the text field and click Save

The Custom Domain mapping is a feature included into Backendless Plus package. The package
enables multiple features for a flat monthly subscription fee. Backendless Plus can be enabled in
console at Manage > Billing .

4.13 Custom Web Template Hosting


A client-to-backend workflow may include interaction with web pages presented to the users of the
application. Consider the following scenarios:
User registration. When a user registers with an application, he receives an email with a link to a
page. Clicking the link acknowledges that the email address is valid and the user account is
confirmed.
Password change. When a user requests password change (or password recovery), an email is
sent to the user with a link to a web page where they can reset the password.
Session expiration. When a user session with the application expires, he is redirected to a
webpage.

All these use cases have something in common - they all force the user to interact with a web page. The
Backendless Plus package allows to customize the look and feel of these pages. Once Backendless
Plus is enabled (use the Manage > Billing section in console to turn it on), Backendless puts the
templates for these pages into the /web/templates path of the backend's file storage:

2015 Backendless Corp.


140 Backendless API for .NET

The default style of these pages is neutral:

Registration confirmation page:

Password change page:

2015 Backendless Corp.


File Service 141

Session expiration page:

The look and feel as well as the logic in the pages can be customized by modifying the HTML/CSS /JS
files provided for each template. For example, the contents of the change_password folder is:

2015 Backendless Corp.


142 Backendless API for .NET

4.14 Files Security


Access to files and directories can be restricted using permissions. Backendless supports the following
permissions for files and directories:
Read - permission to download a file. This permission can be applied to a directory, in that case it
applies recursively to all files contained therein.
Write - permission to upload a file or modify a directory by uploading files into it.
Remove - permission to delete a file or a directory.

To modify the permission matrix for a file or a directory, click the "Edit Permissions" link in file browser
in console. The permission assignment screen contains allows to work with permissions for specific
user accounts or for application roles.

To assign permissions to a user account, type in userid in the "enter user name" field, select the user(s)
and click "Add":

2015 Backendless Corp.


File Service 143
To modify a permission for an operation for a user, click the icon in the corresponding column. The icon
has 3 states:
- inherit GRANT permission from the global permission matrix. This is the default permission.
- explicit GRANT of the permission for the operation. Allows the user to perform the operation.
- DENY permission for the operation. Restricts the user from performing the operation.

Managing permissions for roles is identical to users, except all roles are automatically listed in the table:

5 Geo Service

5.1 Overview
Backendless Geolocation Service is a system supporting management and search of geo points. A geo
point in the most primitive format consists of a pair of coordinates: latitude and longitude. Optionally a
geo point may contain metadata, which is a collection of arbitrary key/value pairs. A geo point belongs
to a category, which is a logical grouping of geo points. The diagram bellow illustrates these concepts:

Backendless allows infinite number of geo points managed for an application. Geo points can be added
via an API call or the import functionality in Backendless console. Once the backend is populated with
geo points, the search API can be used to run the following types of geo queries:
Radius-based search - Searches for geo points in a circular map area defined by the coordinates
of the central point and a radius. Backendless returns all geo points within the area.

2015 Backendless Corp.


144 Backendless API for .NET

Search in a rectangular map area - Searches for geo points in a rectangular map area identified by
the coordinates of two corners defining the area (North West and South East):

Additionally, the geo search API supports the following search options available in the APIs:
Filtering by categories - Both types of search (radius-based and rectangular) can specify the
categories in which the backend should search for the geo points.
Query-based search - The metadata associated with the geo points can be used in queries
which should be formatted using the SQL-92 syntax. For example, the geo point shown in the
image above can be discovered with the following queries:
cuisine = 'French'

cuisine LIKE 'Fr%' and Atmosphere = 'Casual'

cuisine = 'French' and (Price = '$$$$' or Price = '$$$')

Relative search - Runs a search for a subset of metadata key/value pairs to match up to the
specified threshold value. The threshold must be expressed as a percentage of matches.

2015 Backendless Corp.


Geo Service 145

5.2 Setup
To get access to the Backendless services, .NET and Windows Phone applications must reference the
backendless.dll assembly available in the Backendless SDK for .NET. All the Backendless SDK for .
NET classes are available in the BackendlessAPI namespace. Before the .NET/Windows Phone client
uses any of the APIs, the code must initialize the Backendless Application using the following call:
Backendless.InitApp( application-Id, secret-key, version )

Application ID and Secret Key


Values for the application-id and secret-key headers must be obtained through the Backendless
Console:

1. Login to your account and select the application.


2. Click the Manage icon from the vertical icon-menu on the left.
3. The "App Settings" section is selected by default. The interface contains the text fields for
"Application ID" and secret keys for each supported client-side environment.
4. Use the "Copy" button to copy the value into the system clipboard.

The version argument must contain the name of the targeted version. When a new application is
created, the default version name is "v1" . To manage versions, login to the console, select the
"Manage" icon and click "Versioning".

2015 Backendless Corp.


146 Backendless API for .NET

5.3 Error Handling


When the server reports an error, it is delivered to the client through an instance of the
BackendlessFault class. A BackendlessFault object provides access to an error code which uniquely
identifies the root cause of the error. In addition to the error code, the fault object may include an error
message which provides additional information about the error:
using System;
using Weborb.Client;

namespace BackendlessAPI.Exception
{
public class BackendlessFault
{
private readonly string _faultCode;
private readonly string _message;
private readonly string _detail;

public string Detail


{
get { return _detail; }
}

public string FaultCode


{
get { return _faultCode; }
}

public string Message


{
get { return _message; }
}

public override string ToString()


{
return String.Format( "Backendless BackendlessFault. Code: {0},
Message: {1}", FaultCode ?? "N/A", Message ?? "N/A" );
}
}
}

The asynchronous API calls accept the AsyncCallback argument which receives the fault object
through the following delegate:
public delegate void ErrorHandler( Fault fault );

The synchronous API calls declare a checked exception - BackendlessException. The fault object can
be obtained from the exception:
namespace BackendlessAPI
{
public class BackendlessException : Exception
{
public Fault Fault { get; }
public string Code { get; }

2015 Backendless Corp.


Geo Service 147
public override string Message { get; }
public override string ToString();
}
}

5.4 Adding a Geo Category


This API creates a geo category. A geo category is a logical grouping of geo points. Category name
may contain the following literals: a-z, A-Z, numbers 0-9 and the underscore (_ ) character. The name
must start with a literal. Category names can be inspected using Backendless Console (see the image
below) or using the API call retrieving a list of categories.

Adding Categories in Console


Backendless Console supports adding a category via the graphical interface. To create a category:
1. Login to Backendless Console
2. Select your app/backend.
3. Click the Geolocation icon in the menu on the left.
4. Use the "plus" icon in the section containing the list of categories:

2015 Backendless Corp.


148 Backendless API for .NET

5. Enter the category name in the popup and click "Save".

The image below shows the Geolocation screen with categories in the app:

2015 Backendless Corp.


Geo Service 149

Adding Categories with the API

Methods:
Synchronous method:
public GeoCategory BackendlessAPI.Backendless.Geo.AddCategory( string
categoryName )

Asynchronous method:
public void BackendlessAPI.Backendless.Geo.AddCategory( string categoryName,
AsyncCallback<GeoCategory> callback )
where:
categoryName - name of the category to create.
callback - a responder object which receives a callback when the
method successfully creates the category or if an error occurs.

Return Value:
An instance of GeoCategory representing the new category with object properties for category's
objectId, name and number of geo points in it:
GeoCategory.cs
namespace BackendlessAPI.Geo
{
public class GeoCategory

2015 Backendless Corp.


150 Backendless API for .NET

{
public string Id { get; set; }

public string Name { get; set; }

public int Size { get; set; }


}
}
Example:

AsyncCallback<BackendlessAPI.Geo.GeoCategory> callback = new AsyncCallback


<BackendlessAPI.Geo.GeoCategory>(
result =>
{
System.Console.WriteLine( "Category created - " + result.Name );
},
fault =>
{
System.Console.WriteLine( "Error - " + fault );
} );

BackendlessAPI.Backendless.Geo.AddCategory( "my_category", callback );

5.5 Deleting a Geo Category


This API deletes a geo category. If the category does not exist, the service returns an error.

Removing Categories in Console


Backendless Console supports category deletion via the graphical interface. To delete a category:
1. Login to Backendless Console
2. Select your app/backend.
3. Click the Geolocation icon in the menu on the left.
4. Use the "minus" icon in the section containing the list of categories:

2015 Backendless Corp.


Geo Service 151

5. Select 'Yes' in the confirmation popup.

Deleting Categories with the API

Methods:
Synchronous method:
public bool BackendlessAPI.Backendless.Geo.DeleteCategory( string
categoryName )
Asynchronous method:
public void BackendlessAPI.Backendless.Geo.DeleteCategory( string
categoryName, AsyncCallback<bool> callback )
where:

2015 Backendless Corp.


152 Backendless API for .NET

categoryName - name of the category to delete.


callback - a responder object which receives a callback when the
method successfully deletes the category or if an error occurs.

Return Value:
true if the category is deleted, false otherwise.

Example:
AsyncCallback<bool> callback = new AsyncCallback<bool>(
result =>
{
System.Console.WriteLine( "Category deleted - " + result );
},
fault =>
{
System.Console.WriteLine( "Error - " + fault );
} );

BackendlessAPI.Backendless.Geo.DeleteCategory( "my_category", callback );

5.6 Retrieving Geo Categories


This API retrieves a list of all the application's geo categories.
Methods:
Synchronous method:
public List<GeoCategory> BackendlessAPI.Backendless.Geo.GetCategories()
Asynchronous method:
public public void GetCategories( AsyncCallback<List<GeoCategory>> callback )
where:
callback - a responder object which receives a callback when
the method successfully retrieves a list of
application's geo categories.

Return Value:
A generic collection (List) of GeoCategory objects:
GeoCategory.cs
namespace BackendlessAPI.Geo
{
public class GeoCategory
{
public string Id { get; set; }

public string Name { get; set; }

public int Size { get; set; }


}
}
Example:

2015 Backendless Corp.


Geo Service 153
AsyncCallback<List<BackendlessAPI.Geo.GeoCategory>> callback = new
AsyncCallback<List<BackendlessAPI.Geo.GeoCategory>>(
result =>
{
System.Console.WriteLine( "Categories received - " + result.
Count );
},
fault =>
{
System.Console.WriteLine( "Error - " + fault );
} );

BackendlessAPI.Backendless.Geo.GetCategories( callback );

5.7 Adding a GeoPoint


This API adds a geo point to the backend geo location storage. Once a geo point is added, it becomes
searchable through all search mechanisms supported by Backendless. At the present moment there are
two ways to add geo points: (1) using this API or (2) using the Backendless console's import function.

Methods:
Synchronous method:
public GeoPoint SavePoint( GeoPoint geoPoint )

public GeoPoint SavePoint( double latitude,


double longitude,
Dictionary<string, string> metadata )

public GeoPoint SavePoint( double latitude,


double longitude,
List<string> categoryNames,
Dictionary<string, string> metadata )

Asynchronous method:
public void SavePoint( GeoPoint geoPoint,
AsyncCallback<GeoPoint> callback )

public void SavePoint( double latitude,


double longitude,
Dictionary<string, string> metadata,
AsyncCallback<GeoPoint> callback)

public void SavePoint( double latitude,


double longitude,
List<string> categoryNames,
Dictionary<string, string> metadata,
AsyncCallback<GeoPoint> callback)

public void SavePoint( double latitude,


double longitude,
Dictionary<string, object> metadata,
AsyncCallback<GeoPoint> callback)

2015 Backendless Corp.


154 Backendless API for .NET

public void SavePoint( double latitude,


double longitude,
List<string> categoryNames,
Dictionary<string, object> metadata,
AsyncCallback<GeoPoint> callback)
where:
geoPoint - an instance of GeoPoint defining the properties of a
geo point to add. See the class definition in the
"Return Value" section.
latitude - latitude of the point to add.
longitude - longitude of the point to add.
categories - list of categories the point is added to. If a category
does not exist at the time when a point is added,
Backendless creates the category and adds the point
to it. For the methods without this argument, the
point is added to the "Default" category.
metadata - metadata associated with the geo point. Accepted
values for this parameter are: String, Number (integer
and double), and Data Service objects. Date values
must be represented as number in the Unix
timestamp format (number of milliseconds since
January 1, 1970 at UTC). Learn more about using date
in search queries for category, radius, or rectangular
area search.
callback - a responder object which receives a callback when
the method successfully retrieves a list of
application's geo categories.

Return Value:
An instance of the GeoPoint class representing the new geo point added to the application's geo
location storage. Below is a brief version of the class. The complete source code listing is
available in the Backendless github repository.
Example:
AsyncCallback<BackendlessAPI.Geo.GeoPoint> callback = new
AsyncCallback<BackendlessAPI.Geo.GeoPoint>(
result =>
{
System.Console.WriteLine( "Geo point saved - " + result.ObjectId );
},

fault =>
{
System.Console.WriteLine( "Error - " + fault );
} );

List<String> categories = new List<string>();

2015 Backendless Corp.


Geo Service 155
categories.Add( "restaurants" );
categories.Add( "cool_places" );

Dictionary<String, String> metadata = new Dictionary<string, object>();


metadata.Add( "name", "Eatzi's" );
GeoPoint geoPoint = new GeoPoint( 32.81, -96.80, categories, metadata );

BackendlessAPI.Backendless.Geo.SavePoint( geoPoint, callback );

5.8 Updating a GeoPoint


Geo update API relies on the same methods used for Adding a Geo Point. The primary difference is
in order to update a geo point it must have the objectId property assigned by Backendless. The
semantics of the properties in an update request is as follows:
objectId is a required property.
All other properties (latitude , longitude , categories , metadata ) are optional, but at least
one must contain a value.
If latitude or longitude contain values, the new values replace the existing ones.
If categories contains a value, the geo point is moved to the specified categories (with
coordinates and metadata).
If categories is null , the geo point stays in the current category.
If metadata is null , the geo point keeps the current metadata.
If metadata contains any key/value pairs, the new metadata replaces the existing one.
If metadata is an empty object/dictionary, the existing metadata is removed.

5.9 Deleting a GeoPoint


There are two ways to delete a geopoint from the Geolocation storage:
Using the Backendless Console
Using the API

Deleting a GeoPoint using the Backendless Console


To delete a geo point using the Backendless Console:
1. Log in to the Backendless Console, select your app and click the Geolocation icon.
2. Select the geo category from which the geopoint will be deleted.
3. Click the checkboxes next to the geopoint(s) which should be deleted.
4. Click Delete Selected from the button bar as shown below:

2015 Backendless Corp.


156 Backendless API for .NET

5. Click Delete in the confirmation popup to confirm the deletion:

6. A confirmation notification will appear in the top right. The selected geopoint(s) are removed.

Deleting a GeoPoint with API


Synchronous method:
public void RemovePoint( GeoPoint geoPoint )

Asynchronous method:
public void RemovePoint( GeoPoint geoPoint, AsyncCallback<GeoPoint> callback
)

where:
geoPoint - an instance of GeoPoint to delete from the

2015 Backendless Corp.


Geo Service 157
geolocation storage.
callback - a responder object which receives a callback when
the method successfully deletes the geopoint, or an
error returned by the server.
Example:
The example below demonstrates how to delete a geopoint. A geopoint is added first, then
subsequently deleted.

Synchronous API sample:


GeoPoint geoPoint = new GeoPoint( -31.96, 115.84 );
GeoPoint savedGeoPoint = Backendless.Geo.SavePoint( geoPoint );
Backendless.Geo.RemovePoint( savedGeoPoint );

Asynchronous API sample:


AsyncCallback<GeoPoint> removeCallback = new AsyncCallback<GeoPoint>(
r =>
{
System.Console.WriteLine( "Geo point has been removed." );
},
error =>
{
System.Console.WriteLine( "Server reported an error - " + error.Message
);
} );

AsyncCallback<GeoPoint> saveCallback = new AsyncCallback<GeoPoint>(


savedGeoPoint =>
{
System.Console.WriteLine( "Geo point has been saved. Object ID - " +
savedGeoPoint.ObjectId );
Backendless.Geo.RemovePoint( savedGeoPoint, removeCallback );
},
error =>
{
} );

GeoPoint geoPoint = new GeoPoint( -31.96, 115.84 );


Backendless.Geo.SavePoint( geoPoint, saveCallback );

5.10 Importing Geo Data


Backendless console supports bulk import of geo points with metadata. The import procedure
automatically places the geo points into the specified categories. The raw data must be in a comma
separated values (CSV) format. A single line in the file defines one geo point as shown below:
latitude,longitude,"category1,category2","key1=value1|key2=value2"

where:
latitude - the latitude coordinate of a geo point
longitude - the longitude coordinate of a geo point
category1,category2 - comma separated list of categories. The value must
be enclosed in double quotes.

2015 Backendless Corp.


158 Backendless API for .NET

key1=value1|key2=value2 - Geo point metadata. Multiple key/value pairs


must be separated with the pipe "|" character. The
value must be enclosed in double quotes.
Consider the following example:
40.4165,-3.70256,"restaurants,popular","city=MADRID|cuisine=french|
price=high"
41.38879,2.15899,"restaurants,popular","city=BARCELONA|
cuisine=asian|price=low"

To import geo points:


1. Open Backendless console.
2. Select the application/backend.
3. Click Manage, then Import.
4. Click the "add file" button next to "Geo Service" and select the file to import.
5. Click the "Import" button to initiate the import process.

The import process runs asynchronously. When the process is complete, Backendless sends an email
to the application developer. The email text includes the log entries informing about any errors which
could have occurred during the import. Upon successful completion of the import, the Geolocation
section of the console displays the categories, geo points and their metadata:

5.11 Search in Category


This API supports two types of geo searches:
Search in one or more geo categories.

2015 Backendless Corp.


Geo Service 159
Search in one or more categories based on metadata properties.

Methods:
Synchronous method:
public BackendlessCollection<GeoPoint> BackendlessAPI.Backendless.Geo.
GetPoints(BackendlessGeoQuery geoQuery)
Asynchronous method:
public void BackendlessAPI.Backendless.Geo.GetPoints(BackendlessGeoQuery
geoQuery, AsyncCallback<BackendlessCollection<GeoPoint>> callback)
where:
geoQuery - a query object encapsulating the search parameters.
See the Running Search Queries section below for
details.
callback - a responder object which receives a callback when
the search operation successfully completes
(regardless if any points were found) or if an error
occurs.
Return Value:
A collection of GeoPoint objects matching the search query. The class properties are:
ObjectId - an ID assigned to geo point by Backendless when it
is saved in the backend geo location storage.
Latitude - latitude of the geo point.
Longitude - longitude of the geo point.
Categories - an array of geo categories the point belong to.
Metadata - metadata associated with the geo point. Accepted
values for this parameter are: String, Number (integer
and double), and Data Service objects. Date values
must be represented as number in the Unix
timestamp format (number of milliseconds since
January 1, 1970 at UTC). Learn more about using date
in search queries for category, radius, or rectangular
area search.
Geo points returned from the search query are contained inside of BackendlessCollection .
Since the search query may produce a large number of geo points, not all of them are returned
at once. Instead, all found geo points are divided into 'pages'. The size of each page is
determined by the pageSize parameter in the query object. The first response returns the first
page. The collection class includes methods for loading additional pages.
BackendlessCollection also includes the total number of all geo points found by the search
operation (the TotalObjects value).
All geo points in the entire search result are indexed. The index of the first geo point is 0. The
offset parameter in the query object and in some method of BackendlessCollection
specifies the index from which to load the next page of geo points. For example, suppose the

2015 Backendless Corp.


160 Backendless API for .NET

entire search result is 200 points (the TotalObjects value returned in the collection is 200). If
the initial PageSize is 20, then only 20 geo points are returned in the first response. To get the
second page of geo points, they should be loaded from offset 20, third from 40 and so on. The
formula for calculating the offset is:
[value of offset in the current response] + [size of current page ].

Below is a compressed version of the BackendlessCollection class.

Running Search Queries


The geo query object includes multiple parameters, none of them are required. As a result, depending on
which parameters contain values, the semantics of the search would change. Any search must be
performed within at least one category. If no category names are provided, the search is performed in the
Default category.

Search in categories
To search in one or more categories without any constraints on metadata or proximity to a
center point, simply set the names of the categories in the query object. The request returns all
geo points divided into pages of data, one page at a time.
AsyncCallback<BackendlessCollection<GeoPoint>> callback = new AsyncCallback<
BackendlessCollection<GeoPoint>>(
result =>
{
System.Console.WriteLine( "Found geo points - " + result.Data.Count
);
},
fault =>
{
System.Console.WriteLine( "Error - " + fault );
} );

BackendlessGeoQuery geoQuery = new BackendlessGeoQuery();


geoQuery.Categories.Add( "Restaurants" );
Backendless.Geo.GetPoints( geoQuery, callback );

Search in categories with metadata


Metadata-based search finds all geo points which match all specified metadata properties in the
given categories. The example below searches for the geo points in the Restaurants category
with metadata containing "Cuisine = French" and "Atmosphere = Romantic" .
AsyncCallback<BackendlessCollection<GeoPoint>> callback = new AsyncCallback<
BackendlessCollection<GeoPoint>>(
result =>
{
System.Console.WriteLine( "Found geo points - " + result.Data.Count
);
},
fault =>
{
System.Console.WriteLine( "Error - " + fault );
} );

BackendlessGeoQuery geoQuery = new BackendlessGeoQuery();


geoQuery.Categories.Add( "Restaurants" );

2015 Backendless Corp.


Geo Service 161
geoQuery.Metadata.Add( "Cuisine", "French" );
geoQuery.Metadata.Add( "Atmosphere", "Romantic" );

Backendless.Geo.GetPoints( geoQuery, callback );

Search in categories by date


The search query used to retrieve geo points may reference date values. These values must be
stored as a number of milliseconds since January 1st, 1970 at UTC. The example below
demonstrates the use of a date/time timestamp in a search query.
Using dates in where clause when searching in categories
The search query used to retrieve geo points may reference date values. These
values must be stored as a number of milliseconds since January 1st, 1970 at
UTC. The example below demonstrates the usage of a date/time timestamp in a
search query:
Search in category by date by using synchronous call:
static void SearchByDateInCategorySync( )
{
// date
DateTime updated = DateTime.Parse( "2015-01-17 12:00:00Z" );

// create
GeoPoint geoPoint = new GeoPoint( 21.306944, -157.858333 );
geoPoint.Categories.Add( "Coffee" );
geoPoint.Metadata.Add( "Name", "Starbucks" );
geoPoint.Metadata.Add( "Parking", true );
geoPoint.Metadata.Add( "updated", DateTime.Now.Ticks / TimeSpan.
TicksPerMillisecond );

geoPoint = Backendless.Geo.SavePoint( geoPoint );


System.Console.WriteLine( String.Format( "SearchByDateInCategory -> point:
{0}", geoPoint ) );

// search
BackendlessGeoQuery query = new BackendlessGeoQuery();
query.Categories.Add( "Coffee" );
query.WhereClause = String.Format( "updated > {0}", updated.Ticks /
TimeSpan.TicksPerMillisecond );
query.IncludeMeta = true;
BackendlessCollection<GeoPoint> points = Backendless.Geo.GetPoints
( query );

System.Console.WriteLine( String.Format( "SearchByDateInCategory GETPOINTS:


{0}", String.Join( ",", points.GetCurrentPage() ) ) );
}

Search in category by date by using asynchronous call:


static void SearchByDateInCategoryAsync()
{
// date
DateTime updated = DateTime.Parse( "2015-01-17 12:00:00Z" );

AsyncCallback<BackendlessCollection<GeoPoint>> searchCallback = new

2015 Backendless Corp.


162 Backendless API for .NET

AsyncCallback<BackendlessCollection<GeoPoint>>(
result =>
{
System.Console.WriteLine( String.Format( "\nSearchByDateInCategory
GETPOINTS: {0}", String.Join( ",", result.GetCurrentPage() ) ) );
},
fault =>
{
System.Console.WriteLine( "Error - " + fault );
} );

AsyncCallback<GeoPoint> saveGeoPointCallback = new AsyncCallback<GeoPoint>(


result =>
{
System.Console.WriteLine( String.Format( "SearchByDateInCategory ->
point: {0}", result ) );

// search
BackendlessGeoQuery query = new BackendlessGeoQuery();
query.Categories.Add( "Coffee" );
query.WhereClause = String.Format( "updated > {0}", updated.Ticks /
TimeSpan.TicksPerMillisecond );
query.IncludeMeta = true;
Backendless.Geo.GetPoints( query, searchCallback );
},
fault =>
{
System.Console.WriteLine( "Error - " + fault );
} );

// create
GeoPoint geoPoint = new GeoPoint( 21.306944, -157.858333 );
geoPoint.Categories.Add( "Coffee" );
geoPoint.Metadata.Add( "Name", "Starbucks" );
geoPoint.Metadata.Add( "Parking", true );
geoPoint.Metadata.Add( "updated", DateTime.Now.Ticks / TimeSpan.
TicksPerMillisecond );

Backendless.Geo.SavePoint( geoPoint, saveGeoPointCallback );


}

Requesting meta in response


Geo points returned in the search results do not include their metadata properties by default.
The search query object includes a property which can be used to request the metadata to be
included. This property can be used with any search options described above. For example, the
following code runs a search in a category and requests the metadata to be included:
AsyncCallback<BackendlessCollection<GeoPoint>> callback = new AsyncCallback<
BackendlessCollection<GeoPoint>>(
result =>
{
System.Console.WriteLine( "Found geo points - " + result.Data.Count
);
},
fault =>
{
System.Console.WriteLine( "Error - " + fault );
} );

2015 Backendless Corp.


Geo Service 163
BackendlessGeoQuery geoQuery = new BackendlessGeoQuery();
geoQuery.Categories.Add( "Restaurants" );
geoQuery.IncludeMeta = true;
Backendless.Geo.GetPoints( geoQuery, callback );

5.12 Search in Radius


This API supports multiple types of geo searches:
Search for geo points located within specified distance (radius) from a given point.
Search in radius based on metadata.

Methods:
Synchronous method:
public BackendlessCollection<GeoPoint> BackendlessAPI.Backendless.Geo.
GetPoints(BackendlessGeoQuery geoQuery)
Asynchronous method:
public void BackendlessAPI.Backendless.Geo.GetPoints(BackendlessGeoQuery
geoQuery, AsyncCallback<BackendlessCollection<GeoPoint>> callback)
where:
geoQuery - a query object encapsulating the search parameters.
See the Running Search Queries section below for
details.
callback - a responder object which receives a callback when
the search operation successfully completes
(regardless if any points were found) or if an error
occurs.
Return Value:
A collection of GeoPoint objects matching the search query. Below is a brief version of the
GeoPoint class. The complete source code listing is available in the Backendless github
repository.
GeoPoint.cs
using System.Collections.Generic;

namespace BackendlessAPI.Geo
{
public class GeoPoint
{
private List<string> _categories;
private Dictionary<string, string> _metadata;
public string ObjectId { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
public double Distance { get; set; }

public GeoPoint()

2015 Backendless Corp.


164 Backendless API for .NET

{
}

public GeoPoint( double latitude, double longitude )


{
Latitude = latitude;
Longitude = longitude;
}

public GeoPoint( double latitude, double longitude, List<string>


categories, Dictionary<string, string> metadata )
{
Latitude = latitude;
Longitude = longitude;
Categories = categories;
Metadata = metadata;
}

public List<string> Categories


{
get { return _categories ?? (_categories = new List<string>()); }
set { _categories = value; }
}

public Dictionary<string, string> Metadata


{
get { return _metadata ?? (_metadata = new Dictionary<string, string>
()); }
set { _metadata = value; }
}
}
}
where the geo point object properties are:
ObjectId - ID assigned to geo point by Backendless when it is
saved in the backend geo location storage.
Latitude - latitude of the geo point.
Longitude - longitude of the geo point.
Categories - an array of geo categories the point belong to.
Metadata - metadata associated with the geo point. Accepted
values for this parameter are: String, Number (integer
and double), and Data Service objects. Date values
must be represented as number in the Unix
timestamp format (number of milliseconds since
January 1, 1970 at UTC). Learn more about using date
in search queries for category, radius, or rectangular
area search.
Distance - distance between the center point referenced in the
search query and the geo point. The distance is
always in units specified in the search query.

2015 Backendless Corp.


Geo Service 165
Geo points returned from the search query are contained inside of BackendlessCollection .
Since the search query may produce a large number of geo points, not all of them are returned
at once. Instead, all found geo points are divided into 'pages'. The size of each page is
determined by the pageSize parameter in the query object. The first response returns the first
page. The collection class includes methods for loading additional pages.
BackendlessCollection also includes the total number of all geo points found by the search
operation (the TotalObjects value).
All geo points in the entire search result are indexed. The index of the first geo point is 0. The
offset parameter in the query object and in some method of BackendlessCollection
specifies the index from which to load the next page of geo points. For example, suppose the
entire search result is 200 points (the TotalObjects value returned in the collection is 200). If
the initial PageSize is 20, then only 20 geo points are returned in the first response. To get the
second page of geo points, they should be loaded from offset 20, third from 40 and so on. The
formula for calculating the offset is:
[value of offset in the current response] + [size of current page ].

The geo points in the search results will be sorted by their proximity to the central point (center
of the radius): the geo points that are closest to the central point will be listed first.

Below is a compressed version of the BackendlessCollection class. The full source code
listing is available in the Backendless github repository:
BackendlessCollection.cs
using System;
using System.Collections.Generic;
using System.Threading;
using BackendlessAPI.Async;
using BackendlessAPI.Exception;
using BackendlessAPI.Geo;
using BackendlessAPI.Persistence;

namespace BackendlessAPI.Data
{
public class BackendlessCollection<T>
{
public int TotalObjects { get; set; }
public List<T> Data { get; set; }
public IBackendlessQuery Query { get; set; }
public int PageSize
{
get { return Query.PageSize == null ? 0 : (int) Query.PageSize; }
set { Query.PageSize = value; }
}

public List<T> GetCurrentPage()


{
return Data;
}

//Sync methods
public BackendlessCollection<T> NextPage()
public BackendlessCollection<T> PreviousPage()
public BackendlessCollection<T> GetPage( int pageSize, int offset )

2015 Backendless Corp.


166 Backendless API for .NET

//Async methods
public void NextPage( AsyncCallback<BackendlessCollection<T>> responder
)
public void PreviousPage( AsyncCallback<BackendlessCollection<T>>
responder )
public void GetPage( int pageSize, int offset, AsyncCallback<
BackendlessCollection<T>> responder )
}

Running Search Queries


The geo query object includes multiple parameters, none of them are required. As a result, depending on
which parameters contain values, the semantics of the search would change. Any search must be
performed within at least one category. If no category names are provided, the search is performed in the
Default category.

Search in categories with radius


Radius-based search establishes a circular area by setting the coordinates of a central point
and a distance (radius). Backendless searches for geo points in the specified distance from the
coordinates in the center and includes them into the search result. The value of the distance is
interpreted based in the units parameter, which can be METERS , KILOMETERS , MILES , YARDS ,
FEET:
AsyncCallback<BackendlessCollection<GeoPoint>> callback = new AsyncCallback<
BackendlessCollection<GeoPoint>>(
result =>
{
System.Console.WriteLine( "Found geo points - " + result.Data.Count
);
},
fault =>
{
System.Console.WriteLine( "Error - " + fault );
} );

BackendlessGeoQuery geoQuery = new BackendlessGeoQuery();


geoQuery.Categories.Add( "Restaurants" );
geoQuery.Latitude = 41.48;
geoQuery.Longitude = 2.15;
geoQuery.Radius = 100000;
geoQuery.Units = BackendlessAPI.Geo.Units.METERS;

Backendless.Geo.GetPoints( geoQuery, callback );


Search in categories with radius and metadata
This is the same as above, with the difference that the search result includes only geo points
with the matching metadata:
AsyncCallback<BackendlessCollection<GeoPoint>> callback = new AsyncCallback<
BackendlessCollection<GeoPoint>>(
result =>
{
System.Console.WriteLine( "Found geo points - " + result.Data.Count
);
},
fault =>

2015 Backendless Corp.


Geo Service 167
{
System.Console.WriteLine( "Error - " + fault );
} );

BackendlessGeoQuery geoQuery = new BackendlessGeoQuery();


geoQuery.Categories.Add( "Restaurants" );
geoQuery.Latitude = 41.48;
geoQuery.Longitude = 2.15;
geoQuery.Radius = 100000;
geoQuery.Units = BackendlessAPI.Geo.Units.METERS;

geoQuery.Metadata.Add( "Cuisine", "French" );


geoQuery.Metadata.Add( "Atmosphere", "Romantic" );

Backendless.Geo.GetPoints( geoQuery, callback );


Search in radius by date
The search query used to retrieve geo points may reference date values. These values must be
stored as a number of milliseconds since January 1st, 1970 at UTC. The example below
demonstrates the use of a date/time timestamp in a search query.
Using dates in where clause when searching in radius
The search query used to retrieve geo points may reference date values. These
values must be stored as a number of milliseconds since January 1st, 1970 at
UTC. The example below demonstrates the usage of a date/time timestamp in a
search condition:
Search in radius by date by using synchronous call:
static void SearchByDateInRadiusSync()
{
// date
DateTime updated = DateTime.Parse( "2015-01-17 12:00:00Z" );

// create
GeoPoint geoPoint = new GeoPoint( 21.306944, -157.858333 );
geoPoint.Categories.Add( "Coffee" );
geoPoint.Categories.Add( "City" );
geoPoint.Metadata.Add( "Name", "Starbucks" );
geoPoint.Metadata.Add( "Parking", true );
geoPoint.Metadata.Add( "updated", DateTime.Now.Ticks / TimeSpan.
TicksPerMillisecond );

geoPoint = Backendless.Geo.SavePoint( geoPoint );


System.Console.WriteLine( String.Format( "SearchByDateInRadius -> point:
{0}", geoPoint ) );

// search
BackendlessGeoQuery query = new BackendlessGeoQuery( 21.30, -157.85, 50,
Units.KILOMETERS );
query.Categories.Add( "City" );
query.WhereClause = String.Format( "updated > {0}", updated.Ticks /
TimeSpan.TicksPerMillisecond );
query.IncludeMeta = true;
BackendlessCollection<GeoPoint> points = Backendless.Geo.GetPoints
( query );

System.Console.WriteLine( String.Format( "SearchByDateInRadius GETPOINTS:

2015 Backendless Corp.


168 Backendless API for .NET

{0}", String.Join( ",", points.GetCurrentPage() ) ) );


}

Search in radius by date by using asynchronous call:


static void SearchByDateInRadiusAsync()
{
// date
DateTime updated = DateTime.Parse( "2015-01-17 12:00:00Z" );

AsyncCallback<BackendlessCollection<GeoPoint>> searchCallback = new


AsyncCallback<BackendlessCollection<GeoPoint>>(
result =>
{
System.Console.WriteLine( String.Format( "\nSearchByDateInRadius
GETPOINTS: {0}", String.Join( ",", result.GetCurrentPage() ) ) );
},
fault =>
{
System.Console.WriteLine( "Error - " + fault );
} );

AsyncCallback<GeoPoint> saveGeoPointCallback = new AsyncCallback<GeoPoint>(


result =>
{
System.Console.WriteLine( String.Format( "SearchByDateInRadius ->
point: {0}", result ) );

// search
BackendlessGeoQuery query = new BackendlessGeoQuery( 21.30, -157.85, 50
, Units.KILOMETERS );
query.Categories.Add( "City" );
query.WhereClause = String.Format( "updated > {0}", updated.Ticks /
TimeSpan.TicksPerMillisecond );
query.IncludeMeta = true;
Backendless.Geo.GetPoints( query, searchCallback );
},
fault =>
{
System.Console.WriteLine( "Error - " + fault );
} );

// create
GeoPoint geoPoint = new GeoPoint( 21.306944, -157.858333 );
geoPoint.Categories.Add( "Coffee" );
geoPoint.Metadata.Add( "Name", "Starbucks" );
geoPoint.Metadata.Add( "Parking", true );
geoPoint.Metadata.Add( "updated", DateTime.Now.Ticks / TimeSpan.
TicksPerMillisecond );

Backendless.Geo.SavePoint( geoPoint, saveGeoPointCallback );


}

Requesting meta in response


Geo points returned in the search results do not include their metadata properties by default.
The search query object includes a property which can be used to request the metadata to be
included. This property can be used with any search options described above. The syntax for
requesting metadata in response is described in the Search in Category section.

2015 Backendless Corp.


Geo Service 169
5.13 Search in Rectangular Area
This API runs a search within a rectangular area of the map. The area is defined with the coordinates of
the North West and South East corners of the map rectangle.

Methods:
Synchronous method:
public BackendlessCollection<GeoPoint> BackendlessAPI.Backendless.Geo.
GetPoints(BackendlessGeoQuery geoQuery)
Asynchronous method:
public void BackendlessAPI.Backendless.Geo.GetPoints(BackendlessGeoQuery
geoQuery, AsyncCallback<BackendlessCollection<GeoPoint>> callback)
where:
geoQuery - a query object encapsulating the search parameters. See the
Running Search Queries section below for details.
callback - a responder object which receives a callback when the search
operation successfully completes (regardless if any points were
found) or if an error occurs.

Return Value:
A collection of GeoPoint objects matching the search query. Below is a brief version of the
GeoPoint class. The complete source code listing is available in the Backendless github
repository.
GeoPoint.cs
using System.Collections.Generic;

namespace BackendlessAPI.Geo
{
public class GeoPoint
{
private List<string> _categories;
private Dictionary<string, string> _metadata;
public string ObjectId { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
public double Distance { get; set; }

public GeoPoint()
{
}

public GeoPoint( double latitude, double longitude )


{
Latitude = latitude;
Longitude = longitude;
}

public GeoPoint( double latitude, double longitude, List<string>


categories, Dictionary<string, string> metadata )
{
Latitude = latitude;
Longitude = longitude;

2015 Backendless Corp.


170 Backendless API for .NET

Categories = categories;
Metadata = metadata;
}

public List<string> Categories


{
get { return _categories ?? (_categories = new List<string>()); }
set { _categories = value; }
}

public Dictionary<string, string> Metadata


{
get { return _metadata ?? (_metadata = new Dictionary<string, string>
()); }
set { _metadata = value; }
}
}
}

where the geo point object properties are:


ObjectId - ID assigned to geo point by Backendless when it is saved in
the backend geo location storage.
Latitude - latitude of the geo point.
Longitude - longitude of the geo point.
Categories - an array of geo categories the point belong to.
Metadata - metadata associated with the geo point. Accepted values for
this parameter are: String, Number (integer and
double), and Data Service objects. Date values must
be represented as number in the Unix timestamp
format (number of milliseconds since January 1, 1970
at UTC). Learn more about using date in search
queries for category, radius, or rectangular area
search.
Distance - distance between the center point referenced in the search
query and the geo point. The distance is always in units
specified in the search query.

Geo points returned from the search query are contained inside of BackendlessCollection .
Since the search query may produce a large number of geo points, not all of them are returned
at once. Instead, all found geo points are divided into 'pages'. The size of each page is
determined by the pageSize parameter in the query object. The first response returns the first
page. The collection class includes methods for loading additional pages.
BackendlessCollection also includes the total number of all geo points found by the search
operation (the TotalObjects value).
All geo points in the entire search result are indexed. The index of the first geo point is 0. The
offset parameter in the query object and in some method of BackendlessCollection
specifies the index from which to load the next page of geo points. For example, suppose the
entire search result is 200 points (the TotalObjects value returned in the collection is 200). If
the initial PageSize is 20, then only 20 geo points are returned in the first response. To get the
second page of geo points, they should be loaded from offset 20, third from 40 and so on. The
formula for calculating the offset is:

2015 Backendless Corp.


Geo Service 171
[value of offset in the current response] + [size of current page ].

Below is a compressed version of the BackendlessCollection class. The full source code
listing is available in the Backendless github repository:
BackendlessCollection.cs
using System;
using System.Collections.Generic;
using System.Threading;
using BackendlessAPI.Async;
using BackendlessAPI.Exception;
using BackendlessAPI.Geo;
using BackendlessAPI.Persistence;

namespace BackendlessAPI.Data
{
public class BackendlessCollection<T>
{
public int TotalObjects { get; set; }
public List<T> Data { get; set; }
public IBackendlessQuery Query { get; set; }
public int PageSize
{
get { return Query.PageSize == null ? 0 : (int) Query.PageSize; }
set { Query.PageSize = value; }
}

public List<T> GetCurrentPage()


{
return Data;
}

//Sync methods
public BackendlessCollection<T> NextPage()
public BackendlessCollection<T> PreviousPage()
public BackendlessCollection<T> GetPage( int pageSize, int offset )

//Async methods
public void NextPage( AsyncCallback<BackendlessCollection<T>> responder
)
public void PreviousPage( AsyncCallback<BackendlessCollection<T>>
responder )
public void GetPage( int pageSize, int offset, AsyncCallback<
BackendlessCollection<T>> responder )
}

Running Search Queries


The geo query object includes multiple parameters, however, only the coordinates defining the
rectangular area are required. A search query must be performed within at least one category. If no
category names are provided, the search is performed in the Default category.

Search in a rectangle in categories


Rectangle-based search establishes a geographic area by setting the coordinates of the North

2015 Backendless Corp.


172 Backendless API for .NET

West and South East corners of the area. Backendless searches for geo points in the specified
area and includes them into the search result:
AsyncCallback<BackendlessCollection<GeoPoint>> callback = new AsyncCallback<
BackendlessCollection<GeoPoint>>(
result =>
{
System.Console.WriteLine( "Found geo points - " + result.Data.Count
);
},
fault =>
{
System.Console.WriteLine( "Error - " + fault );
} );

BackendlessGeoQuery geoQuery = new BackendlessGeoQuery();


geoQuery.Categories.Add( "Restaurants" );
geoQuery.SearchRectangle = new double[] {32.78, -96.8, 25.79, -80.22};

Backendless.Geo.GetPoints( geoQuery, callback );


Search in categories in a rectangular area and metadata
This is the same as above, with the difference that the search result includes only geo points
with the matching metadata:
AsyncCallback<BackendlessCollection<GeoPoint>> callback = new AsyncCallback<
BackendlessCollection<GeoPoint>>(
result =>
{
System.Console.WriteLine( "Found geo points - " + result.Data.Count
);
},
fault =>
{
System.Console.WriteLine( "Error - " + fault );
} );

BackendlessGeoQuery geoQuery = new BackendlessGeoQuery();


geoQuery.Categories.Add( "Restaurants" );
geoQuery.SearchRectangle = new double[] {32.78, -96.8, 25.79, -80.22};

geoQuery.Metadata.Add( "Cuisine", "French" );


geoQuery.Metadata.Add( "Atmosphere", "Romantic" );

Backendless.Geo.GetPoints( geoQuery, callback );


Search in rectangular area by date
The search query used to retrieve geo points may reference date values. These values must be
stored as a number of milliseconds since January 1st, 1970 at UTC. The example below
demonstrates the use of a date/time timestamp in a search query.
Using dates in where clause when searching in a rectangular area
The search query used to retrieve geo points may reference date values. These
values must be stored as a number of milliseconds since January 1st, 1970 at
UTC. The example below demonstrates the usage of a date/time timestamp in a
search query:
Search in rectangular area by date by using synchronous call:

2015 Backendless Corp.


Geo Service 173
static void SearchByDateInRectangularAreaSync()
{
// date
DateTime openTime = DateTime.Parse( "2015-01-17 07:00:00" );
DateTime closeTime = DateTime.Parse( "2015-01-17 23:00:00" );
DateTime now = DateTime.Parse( "2015-01-17 15:20:00" );

// create
GeoPoint geoPoint = new GeoPoint( 21.306944, -157.858333 );
geoPoint.Categories.Add( "Coffee" );
geoPoint.Metadata.Add( "Name", "Starbucks" );
geoPoint.Metadata.Add( "openTime", openTime.Ticks / TimeSpan.
TicksPerMillisecond );
geoPoint.Metadata.Add( "closeTime", closeTime.Ticks / TimeSpan.
TicksPerMillisecond );
geoPoint = Backendless.Geo.SavePoint( geoPoint );
System.Console.WriteLine( String.Format( "SearchByDateInRectangularAreaSync
-> point: {0}", geoPoint ) );

// search
GeoPoint northWestCorner = new GeoPoint( 21.306944 + 0.5, -157.858333 - 0.5
);
GeoPoint southEastCorner = new GeoPoint( 21.306944 - 0.5, -157.858333 + 0.5
);
BackendlessGeoQuery query = new BackendlessGeoQuery( northWestCorner,
southEastCorner );
query.Categories.Add( "Coffee" );
query.WhereClause = String.Format( "openTime < {0} AND closeTime > {0}",
now.Ticks / TimeSpan.TicksPerMillisecond );
query.IncludeMeta = true;
BackendlessCollection<GeoPoint> points = Backendless.Geo.GetPoints
( query );

System.Console.WriteLine( String.Format( "SearchByDateInRectangularAreaSync


GETPOINTS: {0}", String.Join( ",", points.GetCurrentPage() ) ) );
}

Search in rectangular area by date by using asynchronous call:


static void SearchByDateInRectangularAreaAsync()
{
// date
DateTime openTime = DateTime.Parse( "2015-01-17 07:00:00" );
DateTime closeTime = DateTime.Parse( "2015-01-17 23:00:00" );
DateTime now = DateTime.Parse( "2015-01-17 15:20:00" );

AsyncCallback<BackendlessCollection<GeoPoint>> searchCallback = new


AsyncCallback<BackendlessCollection<GeoPoint>>(
result =>
{
System.Console.WriteLine( String.Format(
"\nSearchByDateInRectangularAreaAsync GETPOINTS: {0}", String.Join( ",",
result.GetCurrentPage() ) ) );
},
fault =>
{
System.Console.WriteLine( "Error - " + fault );
} );

2015 Backendless Corp.


174 Backendless API for .NET

AsyncCallback<GeoPoint> saveGeoPointCallback = new AsyncCallback<GeoPoint>(


result =>
{
System.Console.WriteLine( String.Format(
"SearchByDateInRectangularAreaAsync -> point: {0}", result ) );

// search
GeoPoint northWestCorner = new GeoPoint( 21.306944 + 0.5, -157.858333 -
0.5 );
GeoPoint southEastCorner = new GeoPoint( 21.306944 - 0.5, -157.858333 +
0.5 );
BackendlessGeoQuery query = new BackendlessGeoQuery( northWestCorner,
southEastCorner );
query.Categories.Add( "Coffee" );
query.WhereClause = String.Format( "openTime < {0} AND closeTime > {0}"
, now.Ticks / TimeSpan.TicksPerMillisecond );
query.IncludeMeta = true;
Backendless.Geo.GetPoints( query, searchCallback );
},
fault =>
{
System.Console.WriteLine( "Error - " + fault );
} );

// create
GeoPoint geoPoint = new GeoPoint( 21.306944, -157.858333 );
geoPoint.Categories.Add( "Coffee" );
geoPoint.Metadata.Add( "Name", "Starbucks" );
geoPoint.Metadata.Add( "openTime", openTime.Ticks / TimeSpan.
TicksPerMillisecond );
geoPoint.Metadata.Add( "closeTime", closeTime.Ticks / TimeSpan.
TicksPerMillisecond );
Backendless.Geo.SavePoint( geoPoint, saveGeoPointCallback );
}

Requesting meta in response


Geo points returned in the search results do not include their metadata properties by default.
The search query object includes a property which can be used to request the metadata to be
included. This property can be used with any search options described above. The syntax for
requesting metadata in response is described in the Search in Category section.

5.14 Geo Point Clustering


Geo point search in a category, radius or a rectangular area may return too many geo points within
close geographic proximity from each other. This might be difficult to view and process in a client
application. To address this problem, Backendless supports the geo clustering feature. A geo cluster is
a group of several geo points located close to each other. The two screenshots below demonstrate the
advantages of clustering: the picture on the top displays search results in the Backendless Console with
clustering turned off and the one on the bottom displays search results as clusters when clustering has
been enabled:

Geo Points View:

2015 Backendless Corp.


Geo Service 175

Clusters and Points View:

Backendless creates clusters by splitting the map into a grid of squares. Geo points
which belong to a square are placed into the same cluster. When a square contains
only one point, it remains non-clustered.

Enabling Geo Clustering in Backendless Console


The Geolocation page displays non-clustered geo points by default. To enable clustering:
1. Log in to Backendless Console, select an application and click the Geolocation icon.
2. Click the Map-driven navigation toggle. The toggle changes how the geo points are loaded
from the backend. In the map-driven mode console loads the geo points for the rectangular
area shown in the map.

2015 Backendless Corp.


176 Backendless API for .NET

3. Click the Geo Clustering toggle to enable clustering.

4. Console reloads geo points and clusters for the current viewport of the map and displays the
results. A cluster is visualized as a blue marker on the map with a number indicating how
many geo points it represents.

Geo clustering is also available with the "Search in Radius" option, which searches for geo points in a
circular area. To enable this functionality, click the Search in radius toggle:

2015 Backendless Corp.


Geo Service 177

If you want to see the geo points in a cluster, zoom in the map or double-click a cluster's marker.
Zooming the map in too much (when using the clustering along with the search in radius) may result that
the search radius will be much bigger than the visible part of the map on the screen. In this case, the
pop-up window will display offering you to resize (zoom out) the map. Clicking the Yes button zooms the
map out.

Clicking a cluster's marker will reveal the coordinates and metadata of a cluster.

2015 Backendless Corp.


178 Backendless API for .NET

Retrieving Clustered Geo Points


Geo point clustering can be requested by setting clustering parameters in BackendlessGeoQuery,
which is used in the calls to retrieve geo points from a category, radius or rectangular area:

public void SetClusteringParams( double westLongitude, double eastLongitude,


int mapWidth, int cluisterGridSize )

// same as above, but uses the default clusterGridSize of 100


public void SetClusteringParams( double westLongitude, double eastLongitude,
int mapWidth )
where
westLongitude - the longitude of any point on the western boundary of the map
in degrees.
eastLongitude - the longitude of any point on the eastern boundary of the map in
degrees.
mapWidth - the size of the viewing area of the map in pixels.
clusterGridSize - the size in pixels of the grid's squares used to group
points into clusters. The default value is 100 pixels

Once the clustering parameters are set, the geo point search API will return clustered geo points. The
return value is a collection of GeoCluster and/or GeoPoint objects. Instances of the latter may be
returned when a geo point does not have any neighboring points within the grid's square it belongs to.
The GeoCluster class extends from GeoPoint and supports all the inherited properties: latitude,
longitude, categories and metadata. Additionally, geo cluster has its own property representing the
number of points the cluster consists of. Since a GeoCluster object an instance of the GeoPoint class,
the processing of search responses may look like this:

2015 Backendless Corp.


Geo Service 179
BackendlessGeoQuery geoQuery = new BackendlessGeoQuery();
geoQuery.Radius = 1000;
geoQuery.Units = Units.MILES;
geoQuery.Latitude = 33.217;
geoQuery.Longitude = -97.134;
geoQuery.Categories.Add( "geoservice_sample" );
geoQuery.SetClusteringParams( -164.458, -29.809, 1532, 400 );
BackendlessCollection<GeoPoint> points = Backendless.Geo.GetPoints
( geoQuery );

foreach( GeoPoint point in points.Data )


{
System.Console.WriteLine( "latitude - " + point.Latitude );
System.Console.WriteLine( "longitude - " + point.Longitude );

if( point is GeoCluster )


{
GeoCluster geoCluster = (GeoCluster) point;
System.Console.WriteLine( "Cluster. Number of points - " + geoCluster.
TotalPoints );
}

System.Console.WriteLine( "-------------------------------" );
}

Loading the Geo Points from a Cluster


With the geo clustering feature enabled, you may need to reveal the geo points gathered in a cluster. In
the Backendless Console, you can click the cluster to reveal its details as described above. By using
the calls described below, you will be able to reveal the geo points in a cluster via API.

Method:
public BackendlessCollection<GeoPoint> GetPoints( GeoCluster
geoCluster )
public void GetPoints( GeoCluster geoCluster,
AsyncCallback<BackendlessCollection<GeoPoint>> callback )

where:

geoCluster - a reference to a geo cluster for which to load the geo


points.
callback - a responder object with references to methods
handling successful result of invocation or an error.
Example:
BackendlessGeoQuery geoQuery = new BackendlessGeoQuery();
geoQuery.Radius = 1000;
geoQuery.Units = Units.MILES;
geoQuery.Latitude = 33.217;
geoQuery.Longitude = -97.134;
geoQuery.Categories.Add( "geoservice_sample" );
geoQuery.SetClusteringParams( -164.458, -29.809, 1532, 400 );

2015 Backendless Corp.


180 Backendless API for .NET

AsyncCallback<BackendlessCollection<GeoPoint>> loadGeoPointsResponder;
loadGeoPointsResponder = new AsyncCallback<BackendlessCollection<GeoPoint>>(
result =>
{
System.Console.WriteLine( "points in cluster:" );
foreach( GeoPoint point in result.GetCurrentPage() )
{
System.Console.WriteLine( "Latitude - " + point.Latitude );
System.Console.WriteLine( "Longitude - " + point.Longitude );
}
System.Console.WriteLine( "-------------------------" );
},
error =>
{
System.Console.WriteLine( String.Format( "Server reported an error - {0}"
), error.Message );
});

AsyncCallback<BackendlessCollection<GeoPoint>> responder;
responder = new AsyncCallback<BackendlessCollection<GeoPoint>>(
result =>
{
foreach( GeoPoint point in result.GetCurrentPage() )
{
if( point is GeoCluster )
{
GeoCluster geoCluster = (GeoCluster) point;
System.Console.WriteLine( String.Format( "Cluster. Number of points -
{0}", geoCluster.TotalPoints ) );

Backendless.Geo.GetPoints( geoCluster, loadGeoPointsResponder );


}
}
},
error =>
{
System.Console.WriteLine( String.Format( "Server reported an error - {0}"
), error.Message );
} );

Backendless.Geo.GetPoints( geoQuery, responder );

5.15 Relations with Data Objects


Backendless Data Service manages application's data objects and provides APIs to
work with data objects. Backendless provides integration between data objects
managed by Data Service and geo points managed by Geo Service for the scenarios
when a logical connection between the two types must exist in an application. For
instance, in a taxi ordering app a data object may represent a taxi car, while a geo
point represents its location on the map. It is logical to link the two together so they
can be retrieved and managed at once.
The Geo-to-Data integration is implemented through geo point metadata. A metadata
property may reference one or more data objects. These relations may be created

2015 Backendless Corp.


Geo Service 181
using the API or with Backendless Console. Once a relation is established, the console
displays it in the Metadata column as a link to related data object(s). When a geo
point is retrieved using the API, any related data objects can be retrieved by using the
same principle for loading geo point metadata. The geo-to-data relation is bidirectoral,
that is, a data object may reference a geo point through object properties (table
columns). You can learn more about it in the Relations with Geo Points section of the Data
documentation.

Apart from linking with the data objects, you can also link a geo point with a user
object. Establishing relations with a user objects is performed the same way as with a
data object.

Establishing Relations with a Data Object via


Console
To link a geo point with a data object:
1. Click the Geolocation icon to open the Geo location screen.
2. Select a geo category to get a list of geo points from it.
3. Click the plus icon for the geo point you want to link with a data object.

4. The Add Related Object pop-up window will display.

2015 Backendless Corp.


182 Backendless API for .NET

5. Type in a metadata property name in the Metadata property name field. The new property
will be associated with the related data object.
6. Select a data table from from the Data table drop-down menu. If you want to establish
relation with a user object, select the Users option from the drop-down menu. A list of the
data objects which belong to the selected table will display.
7. Select the check-boxes for the data object(s) you want to link with the geo point.
8. Click the Add Related Objects button to establish a relation and save the changes.

Once the relation is established, the name of the property and the related data table will display next to
the corresponding geo point.

Updating Relations
You can update a geo to data relation (for instance, add or remove objects to/from the relation) by
following the instructions below:
1. Select a geo category and locate the geo point.
2. To update a geo to data relation, click the link with the name of the data table in the geo point
metadata column.

2015 Backendless Corp.


Geo Service 183

3. To add a new geo-to-data metadata property, follow the instructions above.


4. For both scenarios (2) and (3), use the Add Related Object pop-up window to make the
necessary changes.
5. Click the Update Relation button to save the changes.

Deleting Relations
To delete a relation between a geo point and a data object:
1. Select a geo category and locate the geo point.
2. Click the link with the name of the data table in the geo point metadata column. The Add
Related Object pop-up window will display.

3. Un-check the check-boxes next to the data objects you want to unlink from the geo point.
4. Click the Update Relation button to save the changes.

2015 Backendless Corp.


184 Backendless API for .NET

Establishing a Geo to Data Relation by using API


Creating a relationship between a geo point and data objects uses the same API as saving a geo point
with metadata. The data object is also persisted in the Data Service.

The example below adds a geo point representing a location of a taxi cab. The geo point includes the
"TaxiCab" metadata property which references an object from the TaxiCab data table. This is an
example of a one-to-one relation (one geo point is related to one data object).
First, declare the TaxiCab class:
class TaxiCab
{
public String CarMake;
public String CarModel;
public GeoPoint Location { get; set; }
public List<GeoPoint> PreviousDropOffs { get; set; }
}

Create a one-to-one relation:


TaxiCab cab = new TaxiCab();
cab.CarMake = "Ford";
cab.CarModel = "Crown Victoria";
GeoPoint pickupLocation = new GeoPoint( 40.750549, -73.994232 );
pickupLocation.Categories.Add( "Pickups" );
pickupLocation.Metadata.Add( "TaxiCab", cab );
Backendless.Geo.AddPoint( pickupLocation );

Alternatively create a one-to-many relation:


TaxiCab cab1 = new TaxiCab();
cab1.CarMake = "Ford";
cab1.CarModel = "Crown Victoria";

TaxiCab cab2 = new TaxiCab();


cab2.CarMake = "Toyota";
cab2.CarModel = "Prius";

List<TaxiCab> availableCabs = new List<TaxiCab>();


availableCabs.Add( cab1 );
availableCabs.Add( cab2 );

GeoPoint pickupLocation1 = new GeoPoint( 40.750549, -73.994232 );


pickupLocation1.Categories.Add( "Pickups" );
pickupLocation1.Metadata.Add( "AvailableCabs", availableCabs );
Backendless.Geo.AddPoint( pickupLocation1 );

5.16 Geofence Designer

About Geofencing
Geofencing on the surface, comprises drawing a stationary geometric boundary around an area on a
map. This action creates programmatically a set of simple or complex global coordinates which
represent a shape. A boundary represents a fence, which surrounds the area. For Backendless, the
boundary and area become meaningful when a Geopoint crosses the boundary or stays within the area.

Geofences work with Geopoints. A Geopoint is the most elementary Geolocation concept in

2015 Backendless Corp.


Geo Service 185
Backendless. It is a point (latitude and longitude coordinate pairs) on the map that is accessible via API
and allowed to move (change coordinates), i.e., a user carrying a mobile device. In addition to the
coordinates, the Geopoint includes metadata in context for the Geopoint.

The Geofence Designer


Geofence Designer is a feature of the Geolocation service available under Geolocation > Geofencing.
It is a design time tool for drawing Geofences on an interactive global map and associating them with
events and actions, which can be triggered based on the location of registered Geopoints. Backendless
integrates the designer with Google Maps, enabling the developer to design precise Geofence
positions, locations, and shapes.

The Design Tool includes line, rectangle, and circle drawing tools (the cursor changes from hand to
crosshairs when selected) for creating Geofence boundaries. Boundaries can be geometrically
symmetrical or irregular shapes and have no minimum or maximum size constraints. In use cases, a
Geofence conceptually fences in a city block, a shopping center, a sports stadium, or perhaps a mall;
even smaller geographic areas are possible such as the shoe department in a retail store.

The Line Tool


To define an irregular Geofence, the line tool draws editable line segments and control points. For
example, in the United States, the shape of Nevada is irregular. To create this shape, select the line tool
to start drawing lines around it.

Place the cursor on the map where the first control point should be and click. Drag the cursor to the next
place and Click again. The first line segment appears. Repeat these steps until you have nearly
completed the shape of your boundary. (Its not a Geofence just yet.) Click the cursor on the last control
point (which was the first one set). Backendless detects a closed shape and enables a new Geofence.

NOTE: If you accidentally close the Geofence before completing the drawing, the New Geofence dialog

2015 Backendless Corp.


186 Backendless API for .NET

box appears. If you click Cancel, the Geofence will be removed. To keep the Geofence, click Save,
then re-edit the shape as needed.

Immediately after the shape closes, a popup appears prompting you to name the Geofence. Enter a
name in the Geofence Name text box. Since this example uses the state of Nevada, it makes sense to
name it Nevada. Click Save to enable the Geofence. (We will refer to this example again.)

The result is a new item row in the List of Geofences. The Geofence area is filled with green, and the
item row is highlighted in yellow when a Geofence is selected on the map or on the list. See the image
below.

Naming Geofences with intelligible


names is a good practice. Any
alphanumeric character or special
character is permitted. An unusual
scenario could be two cities with the
same name, but in different states,
such as Dallas, Texas and Dallas,

2015 Backendless Corp.


Geo Service 187
Illinois. A solution and a best practice
could be Dallas-Texas and Dallas-
Illinois. This practice should apply to
all three tools.

The Rectangle Tool


The Rectangle Tool is self-describing. A fence can be drawn quickly around a square or rectangular area.
After the Geofence is named and saved, the shape aspect can be adjusted by dragging a line segment
or corner control point. Like the line tool, parameters can be entered in a dialog immediately after the
shape is drawn. Should you need to edit the shape, an undo tool appears and to restore the previous
edit.

The Circle Tool


The Circle Tool is also self-describing. A circle can be drawn quickly around an area, repositioned, and
resized. Like the line tool, parameters can be entered in a dialog immediately after the shape is drawn.

Deleting a Geofence
A Delete button is positioned directly below the interactive map. For each selected checkbox next to the
Geofence hyperlink, the Delete button removes those Geofences. Once a Geofence is deleted, it cannot
be restored.

List of Geofences and Locator Tool


A map filled with Geofences can appear cluttered, especially if the design comprises numerous shapes
across several remotely located areas. Backendless organizes the boundary data and actions in a table

2015 Backendless Corp.


188 Backendless API for .NET

format below the map, the List of Geofences. The table contains a row for each Geofence along with
parameter controls.

From left to right, the second column shows the Geofence name, which is hyperlinked to the Update
Geofence dialog. The Geofence locator icon is next to the Geofence hyperlink (see image below). The
tool repositions the map view to an optimal zoom-level, from which the Geofence boundary can be
easily viewed, accessed, and edited.

For example, two cities in


Texas, Arlington and Plano,
have several Geofences in
each. In the image below the
map is tightly zoomed on an
area in Plano. The work on
Plano is done, so the
developer needs to reposition
the interactive map to
Arlington. Click the locator
icon next to an Arlington
Geofence. Backendless
repositions the map and sets
the optimal zoom level.
Further, it does not matter
whether the two Geofences
are on different continents;
the locator tool works the
same either way.

Geofence and Geopoints Events


Geofences and Geopoints are integrated entities of Geolocation. As such, Backendless tracks three

2015 Backendless Corp.


Geo Service 189
specific events:

When a Geopoint enters a Geofence, crosses the boundary, On Enter action


executes.
When a Geopoint stays inside a shape for a preconfigured amount of time, On
Stay actions executes.
When a Geopoint exits the Geofence, it crosses the boundary and is outside
the shape, On Exit action executes.

Geopoint Qualification Criteria: Exclusion/Inclusion


Tracking every Geopoint within a Geofence is not desirable in every case. A Geofence plan could specify
tracking only Geopoints of a certain nature, for example, visitors or preferred customers.

Qualification Criteria, which identifies the types of Geopoints Backendless traces and tracks for a
specific geogence, can be defined in the Update Geofence dialog. The Geofence hyperlink opens the
dialog. A criterion, in this case, is a special string entered in the Geopoint Qualification Criteria text box.
(The string format is the SQL 92 syntax, regular SQL as relates to a database query WHERE clause.)
For example, if tracking only visitors, the SQL would need something like usertype=visitor . Where
usertype is a Geopoints metadata property. visitor is the metadata property value.

The string can be tested via the Validate button. Upon a successful validation, a success message
displays.

Conversely, Backendless could track only employees, excluding visitors, and function as a time clock
action, such as clock-in and clock-out.

Events and Actions


Detecting, tracing, and tracking geopoints in relationship to a geofence establish the event clockwork for
execution of developer defined actions. An event occurs as a Geopoint transports into and out of or
stays in a Geofence. An action is a set of parameters the developer selects to perform a function, such
as deliver a message to a mobile device or add a record to a database.

Events
Three event types are organized in columns in the List of Geofences. The events types are:

2015 Backendless Corp.


190 Backendless API for .NET

On Enter a Geopoint crosses the Geofence boundary into the defined area
On Stay a Geopoint remains in the Geofence area for at least a specified period
On Exit a Geopoint crosses the Geofence boundary out of the defined area

Actions
For each of the above events, a developer can select an action and specify parameters to be executed
from Backendless. There are four action types:

Push notification
Publish-subscribe (pub/sub) message
Send a custom event
Call a URL

The scenarios for choosing an action are wildly different; however, they drive the action and parameter
choices the developer makes. When an action type is selected for an event, a dialog appears where
action parameters can be entered. The fields in the dialog are specific to the action type.

Whenever an action is configured, visual elements indicate whether the parameters are complete. A gear
icon and green checkmark indicate proper configuration, where as a red X in place of the checkmark
indicates improper configuration. The configuration can be edited by clicking the gear to reopen the
currently assigned action dialog.

Push Notification Action


All three Geofence events can trigger this action. Push Notification, in basic form, is a message sent to
a mobile device associated with a Geopoint or to a group of devices registered with a channel. The
Configure Push Notification Action dialog provides flexible parameter options:

Content Configuration configure Push Notification content look and feel for Android, iOS, or
Windows Phone.
Message Headers allows header name and header value.
Delivery to individual Geopoints or those registered to a channel.

2015 Backendless Corp.


Geo Service 191

Send a Pub/Sub Message Action


This action sends a publish/subscribe message. The developer enters the message parameters in the
Configure Pub/Sub Message Action dialog. (Learn more about Message Publishing.) The dialog contains
the following fields:

Channel name the name for a channel. Backendless creates the channel if it
doesnt exist.
Topic name the name of a topic used for filtered delivery.
Message headers optional. Use the key=value format. Comma delimited.
Message body written in JSON. The body of the message to be delivered.

2015 Backendless Corp.


192 Backendless API for .NET

A probation officer issues an


ankle bracelet to a probationer.
He needs to set area from which
the probationer cannot leave,
such as restricted to travel only
within a state. The PO would set
up a Geofence outlining
Colorados state-line borders. For
that Geofence, he would set the
action event On Exit to send a
notification to the application on
his device that would provide
metadata about the probationer
such as location, the
probationers photo, phone
number, address, etc.

Call URL Action


This action executes an HTTP command on the specified URL. Supported commands are GET, POST,
or PUT. The developer configures the call in the Configure Call URL Action dialog. The dialog contains
the following fields:

Command choice of GET, POST, or PUT


URL a fully formed internet protocol URL.
Request headers any of the HTTP header types in the form of key=value.

2015 Backendless Corp.


Geo Service 193
Body text message for calling the URL.

Send Custom Event


Provides a means for enabling Geofencing processing logic to execute your custom server-side code
deployed to Backendless. Send Custom Event issues an event that you define in the Send Custom
Event dialog box. See Custom Events under Business Logic. Backendless acts as a functional
intermediary for your custom event handler which contains business logic specific to the application
such as sending out an email or saving a record to a database.

2015 Backendless Corp.


194 Backendless API for .NET

Is Active - Geofence Monitoring


Is Active is the final column in the List of Geofences. It indicates whether server-side Geofence
monitoring can be activated. When monitoring is ON, Backendless tracks any movements of the
Geopoints in relation to the corresponding Geofence. The list below shows item content:

Missing Actions look for red X next to the edit action gear. An action is improperly configured.
ON/OFF Toggle click to switch either on or off. ON activates the server-side monitoring for the
selected Geofence.

When an action is properly configured, i.e. complete, the Is Active toggle for the selected Geofence
appears. When set to ON, a popup provides cautionary information and a checkbox option, which
applies actions to Geopoints located within the Geofence at the time when the monitoring is turned on (i.
e. the toggle is being set to ON). See the image below.

2015 Backendless Corp.


Geo Service 195

Once server-side monitoring is activated by setting the Is Active toggle to ON, a play button appears
next to the gear icon. This button executes the action on-demand for any Geopoints within the
Geofence. (This function can be useful when debugging.)

View Geopoints in a Geofence


For any Geofence that is currently active (i.e. is under server-side monitoring), a checkbox option
displays Geopoints located within the Geofence. Geopoints located within the Geofence are
represented by a marker for Google Maps inside the Geofence.

The frequency of refresh on the screen is controlled by the refresh interval. The value is in seconds and
can be set to a value from 10 to 300. You can force a refresh by clicking the refresh button. See the
image below.

5.17 Geofence API


Client-side geofence monitoring is the process of tracking the position of the device in relation to the
geofences defined in Backendless. Functionality in Backendless client libraries loads information about

2015 Backendless Corp.


196 Backendless API for .NET

geofences (or a specific geofence) and tracks device positional changes. When the device crosses,
stays in, or exits a geofence boundary, the Backendless client executes a callback. Based on this,
Backendless client-side monitoring supports the following options:

In-app callback for the on enter, on stay and on exit events. A callback is executed on the
device when it's location enters, stays in or exits a geofence. With this approach the client
application decides how to handle a geofence event.
In-app callback interface
Client applications must use a special class to receive in-app callbacks. The class includes
delegate methods invoked by the Backendless library when the current device's location
enters, stays in or exits a geofence. The callback's delegate methods include information
about the current location.

The LocationInfo class passed as the argument has the following structure:

Consider the following example of a callback implementation. The example creates and saves
a geopoint with dummy coordinates (0,0). As the device changes its location, the in-app
callback is executed and the code saves the device's location on the server. See the example
below.

Remote callback for the on enter, on stay and on exit event. The Backendless client
automatically notifies the server when a geofence event occurs. If there is an action associated
with the event, Backendless executes on the server-side.

The API applies the options above either to a specific or all geofences. It is important to note that a
Backendless client can monitor only the geofences which are not activated for the server-side
monitoring. In other words, a geofence with the "Is Active toggle in the Backendless console set to ON
cannot be tracked on the client-side.

Windows Phone App Configuration


In addition to the general requirements, a Windows Phone application which uses the Backendless
Geofence API must enable the ID_CAP_LOCATION capability as shown below:

2015 Backendless Corp.


Geo Service 197

Geofence APIs
The Geolocation service provides the following APIs:
Client-side location monitoring:
Start location monitoring for a specific geofence with an in-app callback
Start location monitoring for all geofences with an in-app callback
Start location monitoring for a specific geofence with a remote callback
Start location monitoring for all geofences with a remote callback
Stop location monitoring for a specific geofence
Stop location monitoring for all geofences
Executing a geofence action:
Run the OnEnter action
Run the OnStay action
Run the OnExit action
Retrieve geopoints from a geofence

Start location monitoring for a specific geofence with an in-


app callback
Starts client-side monitoring of the device's location for the geofence. Uses the callback to notify when
the device enters, stays in, or exits the geofence boundary.

where:
geofenceName - name of a geofence, which monitors the device's location.
callback - a callback object that the Backendless library notifies when the
device crosses, stays in, or exits the geofence boundary.
responder - a responder that notifies the calling program when the operation
started successfully geofence monitoring or resulted in error.

2015 Backendless Corp.


198 Backendless API for .NET

Example:

Start location monitoring for all geofences with an in-app


callback
Starts client-side monitoring of the device's location for all geofences. Uses the callback to notify when
the device enters, stays in or exits a geofence boundary.

where:
callback - a callback object that the Backendless library notifies when the
device crosses, stays in, or exits the geofence boundary.
responder - a responder that notifies the calling program when the operation
started successfully geofence monitoring or resulted in error.

Example:

Start location monitoring for a specific geofence with a


remote callback
Starts client-side monitoring of the device's location for a specific geofence. This function notifies the
server when the device enters, stays in, or exits the geofence boundary.

where:
geofenceName - name of a geofence, which monitors the device's location.
geoPoint - the geopoint object to pass to the server. The geopoint
represents the current device location. It may be a geopoint
stored in the Geolocation storage (with objectId assigned to it)
or a new geopoint object. The Backendless client assigns the
current location coordinates to the geoPoint object before
sending it to the server.
responder - a responder that notifies the calling program when the operation
has started successfully geofence monitoring or has resulted in
error.

Example:

Start location monitoring for all geofences with a remote


callback
Starts client-side monitoring of the device's location for all geofences. This function notifies the server
when the device enters, stays in or exits a geofence boundary.

where:
geoPoint - the geopoint object to pass to the server. The geopoint
represents the current device location. It may be a geopoint
stored in the Geolocation storage (with objectId assigned to it)
or a new geopoint object. The Backendless client assigns
current location coordinates to the geoPoint object before
sending it to the server.
responder - a responder used for to notify the calling program when the

2015 Backendless Corp.


Geo Service 199
operation has either successfully started geofence monitoring or
resulted in error.

Example:

Stop location monitoring for a specific geofence


Stops client-side monitoring of the device's location for the geofence.

where:
geofenceName - name of the geofence for which device location monitoring will
stop.

Example:

Stop location monitoring for all geofences


Stops client-side monitoring of device locations for all geofences.

Example:

Run the OnEnter Action


Requests the server to run the configured OnEnter action for a geofence either for all geopoints located
within the geofence or for the specified geopoint.

Synchronous method:
Asynchronous method:
where:
geofenceName - name of the geofence on which the OnEnter action will run.
geoPoint - a geopoint which will be used as the context for the action
execution. Any substitutions which the action may be configured
with will be resolved against the geopoint.
callback - a responder that notifies the calling program when the operation
has requested successfully the action to be executed or resulted
in error.

Example:

Run the OnStay Action


Requests the server to run the configured OnStay action for a geofence either for all geopoints located
within the geofence or for the specified geopoint.

Synchronous method:
Asynchronous method:
where:
geofenceName - name of a geofence on which the OnStay action will run.
geoPoint - a geopoint which will be used as the context for the action

2015 Backendless Corp.


200 Backendless API for .NET

execution. Any substitutions which the action may be configured


with will be resolved against the geopoint.
callback - a responder that notifies the calling program when the operation
has requested successfully the action to be executed or resulted
in error.

Example:

Run the OnExit Action


Requests the server to run the configured OnExit action for a geofence either for all geopoints located
within the geofence or for the specified geopoint.

Synchronous method:
Asynchronous method:
where:
geofenceName - name of a geofence on which the OnExit action will run.
geoPoint - a geopoint which will be used as the context for the action
execution. Any substitutions which the action may be configured
with will be resolved against the geopoint.
callback - a responder that notifies the calling program when the operation
has requested successfully the action to be executed or resulted
in error.

Example:

Retrieve Geopoints from a Geofence


Retrieves a collection of geopoints currently located within a geofence

Synchronous method:
Asynchronous method:
where:
geofenceName - name of a geofence to retrieve the geopoints from.
query - a BackendlessGeoQuery object controlling various aspects of
geopoint retrieval such as paging, inclusion of metadata and/or
SQL search query.
callback - a responder that notifies the calling program when the operation
has successfully retrieved geopoints or resulted in error.

Example:
The example loads geopoints from a geofence called "Manhattan". The returned geopoints will have
metadata properties and will match the SQL query:

2015 Backendless Corp.


Index 201

Index
-B-
backendless.jar 6, 79, 122, 145

-I-
Identity 10

-L-
Login 16
Logout 22

-P-
Password
property 10
recovery 23

-U-
User Properties
defining with API 10
defining with console 10
retrieve user entity description 11
update user registration 19
User Registration
API call 13
disable registration 13
email confirmation 13
registration with external system 13

2015 Backendless Corp.


202 Backendless API for .NET

Endnotes 2... (after index)

2015 Backendless Corp.


Back Cover