Chapter 10. Programming with Location Server APIs

Microsoft Location Server exposes APIs for building real-time location-based applications as well as server management and administration applications. You develop location-based applications using Microsoft Location Server Web Service , and you develop management and administration applications using the Microsoft Location Server management API. As you will see later in this chapter, most of the administrative tasks that can be performed with the Location Server Web Service can be accomplished by the Server Management API as well; however, it is important to keep in mind that the web service runs under the context of the currently logged-in user, whereas the management API runs under the context of the administrator.

In this chapter, let’s take a detailed look at programming both Location Server Web Service and Location Server Management APIs.

Programming with Location Server Web Service

Microsoft Location Server Web Service provides APIs for functionalities such as finding real-time locations, finding nearby points of interest, finding contacts, and adding and removing contacts. Because this web service is hosted within your enterprise, you need your network domain credentials to access it. In the following sections of this chapter, we will examine the Microsoft Location Server Web Service APIs in detail.

Anatomy of Location Web Service APIs

As you learned in Chapter 9, Location Server Web Service is hosted within your enterprise and not hosted by Microsoft. So, in order to develop with the Location Server Web Service, you need to access the WSDL (Web Service Description Language) document for the Location Server Web Service. If your enterprise’s Location Server is installed on a domain (www.YourFullDomainName.com), your Location Server Web Service WSDL can be accessed using the following URL:

https://www.YourFullDomainName.com/mmlsservice/locationserver.wsdl

Note that the Location Server Web Service is only accessible to valid provisioned domain user accounts; to access the above WSDL, you must be a domain user on your enterprise’s network and provisioned in the Microsoft Location Server as a user.

The previous WSDL contains only one SOAP endpoint (LocationService.asmx) which translates into the LocationServiceSoap class when added to your current project as a web reference. The LocationServiceSoap class provides all the necessary functionalities, such as getting real-time location, adding, updating and removing contacts, and changing personal privacy settings. Table 10-1 shows the methods offered by the LocationServiceSoap class. In this table, the current user is the original submitter of the request.

Table 10-1. LocationServiceSoap class methods

Method

Description

GetPositions

Returns the user’s or contact’s positions synchronously as an instance of the PositionResults class.

GetPositionsAsync

Returns the user’s or contact’s positions asynchronously. This method is an asynchronous version of the GetPositions method. However, you must call the GetPositionsAsyncResults method to complete the process of getting positions.

GetPositionsAsyncResults

Completes the asynchronous request invoked by the GetPositionsAsync method. This method returns the positions that correspond to the domain and alias pairs as an instance of the PositionResults class. This method must be called with a valid token obtained by calling the GetPositionsAsync method.

GetNearbyCategories

Gets Find Nearby categories based on the current user’s culture.

GetVisibility

Gets the status for the current user’s Visible property.

SetVisibility

Sets the status for the current user’s Visible property.

GetNewContactNotification

Gets the value of the NotifyOnNewContact property for the current locatable user.

SetNewContactNotification

Sets the value of the “Notify on Contact” option for the current user.

GetDefaultCulture

Returns the default culture for the current user in string format; for example: “en-US” for English, United States.

SetDefaultCulture

Sets the default culture for the current user.

GetUserInfo

Returns the current user’s information as an instance of the LocatableUser class.

AddContact

Adds a contact to the current user’s list of contacts.

UpdateContact

Updates the specified contact in the current user’s contact list.

DeleteContact

Deletes the specified contact entry from the current user’s list of contacts.

FindProvisionedUser

Allows partial input of the LocatableUser object properties or a user’s email address to search the provisioned users on the location server and returns contact information as an array of LocatableContact class instances.

GetContacts

Returns a list of contacts for the current user as an array of LocatableContact objects.

The categorizations of various methods provided by the LocationServiceSoap class are shown in Figure 10-1.

LocationServiceSoap method categorization
Figure 10-1. LocationServiceSoap method categorization

The methods available on the LocationServiceSoap type fall into three main categories:

Real-Time Location APIs

Provide core functionality to get real-time location based on mobile phone numbers; the methods in this category are GetPositions and GetPositionsAsync.

Privacy Management APIs

Provide core functionality to manage self privacy, including the GetVisibility, SetVisibility, GetNewContactNotification, and SetNewContactNotification methods.

Contact Management APIs

Provide core functionality to add new contacts and delete or update existing contacts. The methods in this category include GetContacts, AddContact, and DeleteContact.

All these methods that run from LocationServiceSoap run the context of a provisioned user; in other words, LocationServiceSoap methods cannot be used to manipulate the privacy settings or contact management for users other than the logged-in user. Since Location Server depends on the Active Directory-based domain accounts to provision users within an enterprise, the authentication to the Location Server Web Service is performed using the enterprise domain account credentials:

    //Create an instance of the LocationServiceSoap proxy class
    LocationServiceSoap locationService = new LocationServiceSoap( );
    //Create an instance of the NetworkCredential class
    //and add the credentials required to access the Web service
       NetworkCredential credentials =
           new NetworkCredential("user", "password", "domain");
    locationService.Credentials = credentials;

Next, let’s look at various tasks that can be performed using the Location Server Web Service.

Finding a Real-Time Location

MapPoint Location Server Web Service exposes the GetPositions method, which you can use to request a real-time location of yourself or your contacts (such as your colleagues within the same enterprise).

If you are requesting your own location, pass your domain alias as an argument to the GetPositions method; however, you must be a valid provisioned user to successfully request your location.

If you are requesting the location of your contacts, you need to pass the following criteria:

  • You must be a valid provisioned user.

  • Your contacts must be valid provisioned users.

  • Your contacts have granted you permission to locate them.

  • Your contacts have their status set to visible (not in stealth mode).

Once you meet the above criteria, you can pass the domain aliases of the contact users whose location you want to find as an argument to this method. If you fail to meet any of the above criteria, your request to locate your contact results in a failure. The third and fourth bullets act as layers of defense to protect your contacts’ privacy.

When a location request succeeds, GetPositions returns an instance of the PositionResults class, which contains the positions for the domain aliases passed to the method. The PositionResults class instance contains a property that exposes an array of Position class instances that contain the position information expressed as latitude and longitude coordinates. The order of the Position array elements corresponds to the order of the domain aliases passed to this method. The following code snippet shows how to invoke the GetPositions method:

     //Create an instance of the LocationServiceSoap proxy class
    LocationServiceSoap locationService = new LocationServiceSoap( );

    //Create an instance of the NetworkCredential class
    //and add the credentials required to access the Web service
    NetworkCredential credentials =
           new NetworkCredential("user", "password", "domain");
    locationService.Credentials = credentials;
    try
     {
         //Get the positions from the GetPositions method
      PositionResults positionResults =
         locationService.GetPositions(new string[] {@"domaincontact"});
      //Process the positions
      foreach(Position position in positionResults.Positions)
      {
       //Get each contact's lat/long
       LatLong ll = position.LatLong;

      }
       }
    catch(System.Web.Services.Protocols.SoapException MyException)
     {
      //Process exceptions here
     }

Once a location is obtained as latitude/longitude coordinates, you can display it on a map using the MapPoint Web Service Rendering Service .

Microsoft Location Server Web Service also exposes the GetPositionsAsync method and a corresponding GetPositionsAsyncResults method for invoking asynchronous location requests. The difference between these methods and the proxy-generated asynchronous methods (BeginGetPositions and EndGetPositions) generated by Visual Studio .NET is that the Visual Studio .NET-generated methods run the invocation process on a background thread to free up the UI thread, which keeps the HTTP connection open until the response from Microsoft Location Server Web Service is complete. The GetPositionsAsync method closes the HTTP connection as soon as the request is complete, making the request and response truly asynchronous. The GetPositionsAsync method may be required with mobile operators that cannot locate a mobile device when an HTTP connection is open. If you are working with a mobile operator that does not have this issue and you are developing your client application using the asynchronous model, use the asynchronous methods generated by Visual Studio .NET.

Adding and Removing Contacts

MapPoint Location Web Service offers two methods, AddContact and DeleteContact, which can be used to add and remove contacts for provisioned users. You can use the FindProvisionedUser method to look up the provisioned users within your enterprise so that you can to add them to your contact list. Note that although you can add a contact to your contacts list, you can locate that contact only if he grants you permission to do so. This explicit opt-in model is an important privacy feature of Microsoft Location Server.

The following code snippet shows how to add a contact to your contact list. First, find a provisioned user using his phone number:

    //Create a LocationService Proxy.
    LocationServiceSoap locationService = new LocationServiceSoap( );

    //Define and add credentials to the proxy
    . . .

    //Create a ProvisionedUser instance and
    //assign the search value.
    ProvisionedUser provisionedUser = new ProvisionedUser( );
    provisionedUser.DomainAlias = @"DOMAINuser";

    //Create a locatable device instance and assign the value.
    LocatablePhoneNumber phone = new LocatablePhoneNumber( );
    phone.CountryCode = "001";
    phone.LocalCode = "111";
    phone.ShortNumber = "1111111";

    //Find out if this user is provisioned
    try
     {
      LocatableContact[] users = locationService.FindProvisionedUser(
                                     provisionedUser, phone,  -1);

      foreach(LocatableContact user in users)
      {
       //Process found provisioned users
       . . .
      }
     }
    catch(SoapException exception)
     {
      //Your exception process goes here
     }

As you can see, FindProvisionedUser takes either a partially-defined ProvisionedUser instance or a LocatablePhoneNumber instance to look up the provisioned users to match from the Active Directory within an enterprise. It is important to note that at least one of these two arguments is required. When both are present, both arguments are used for the lookup. The rules detailed in the following sections must be followed for the partially defined ProvisionedUser instance used for the lookup.

If lookup is based on domain alias

Partial domain alias searching is permitted. For example, if there is a user “John Doe” in domain “XYZ” with an user alias “jdoe,” the following searches return valid results:

  • “jdoe” returns an exact match for “XYZjdoe”.

  • “XYZjdoe” returns an exact match for “XYZjdoe”.

  • “XYZ/jdoe” returns an exact match for “XYZjdoe”.

The following searches fail to return the provisioned user:

  • “Doe” will fail. (This case assumes that the alias “Doe” does not belong to another valid user.)

  • Searching for “jdo” will fail. (This case assumes that the alias “jdo” does not belong to another valid user.)

If lookup is based on display name

Partial display name searching is allowed. This search is performed using a “starts-with” condition . For example, if the display name is “Mr. Jon Doe,” searching for “John” will yield “Mr. Jon Doe” as one of the results.

The minimum number of characters that needs to be supplied for a display name partial search is two.

If lookup is based on first name and last name

Partial searching is allowed for first and last name searches. The only rule is that the sum of the characters from both first name and last name together must be greater than or equal to two. The following searches return results for “John Doe:”

  • Searching for “John” as the first name and “Doe” as the last name will return “John Doe” as one of the matches.

  • Searching for “J” as the first name and “Doe” as the last name will return “John Doe” as one of the matches.

  • Searching for “John” as the first name and “D” as the last name will return “John Doe” as one of the matches.

  • Searching for “Jon” as the first name and “” (empty) as the last name will return “John Doe” as one of the matches (or may fail due to too many matches).

  • Finally, searching for “J” as the first name and “D” as the last name may fail due to too many matches.

If lookup is based on phone number

The locatablePhonenumber parameter is optional and can be null; however, when provided, an exact match is returned if its match is in the database. When a phone number is provided, the short number (last seven digits of the phone number) must be provided to be considered for the search.

If lookup is based on email address

Email address searches allow a “starts-with” partial search. If you provide a complete email address including a @ sign, however, an exact match is returned if its match is in the database.

The third argument for the FindProvisionedUser method indicates the number of provisioned users to return that match the input query; value -1 indicates the Location Server Web Service to return all found provisioned users. When the requested number of provisioned users does not match the matched provisioned user count, an exception is thrown.

Once a provisioned user is found using a query such as the one shown previously, you can add her as your contact:

    //Create an instance of the LocationServiceSoap proxy class
    LocationServiceSoap MyLocationService = new LocationServiceSoap( );
    //Create an instance of the NetworkCredential class
    //and add the credentials required to access the Web service
    NetworkCredential MyCredentials =
          new NetworkCredential("user", "password", "domain");
    MyLocationService.Credentials = MyCredentials;
     try
    {
     //Add a new contact for the current user
        LocatableContact MyLocatableContact =
         MyLocationService.AddContact(@"domaincontactuser",
                                      true, true);
    }
    catch(SoapException MyException)
    {
     //Process exceptions here
     . . .
    }

As you can see, the AddContact method takes three arguments:

contact user domain alias

Indicates the domain alias of the contact that is being added

isActive flag

Indicates whether the contact relationship is active; you may add someone as a contact but block her from locating you by setting this flag to false. If you set this value to true, it means that the contact can locate you.

notifyOnLocate flag

Indicates via an SMS message or email that you are being located by your contact when this flag is set to true. This flag works as a record of all locate attempts made by your contacts.

Note that if you try to add a contact that you already have in your contact list, this method throws an exception. Along similar lines, the methods DeleteContact and UpdateContact take the contact domain alias to either remove the contact relationship or modify the existing contact relationship respectively.

Programming Privacy Settings

As a Location Server user, you may be worried about your privacy—specifically, you don’t want to be tracked all the time even if you give permission to your contacts to track you. For situations like this, Location Server gives you the flexibility to control the privacy settings so that you can enable who can track you; it even gives you a way to go into stealth mode by becoming completely invisible to your contacts.

Managing contact privacy settings

Using the LocationServiceSoap.UpdateContact method, you can enable or disable the ability for your contacts to locate you. Similar to the AddContact method, this method takes three arguments that indicate the contact user, locatable permissions flag (isActive), and notification on the locate flag. To disable a contact from locating you, set the isActive flag to false:

    //Create a LocationServiceSoap proxy instance
    LocationServiceSoap locationService = new LocationServiceSoap( );
    //Create and add the credentials required to access the Web service
    NetworkCredential credentials =
                new NetworkCredential("user", "password", "DOMAIN");
    locationService.Credentials = credentials;

    try
    {
     //Update the contact - turn off their ability to locate you
        LocatableContact locatableContact =
                 MyLocationService.UpdateContact(@"DOMAINcontactuser",
                                                 false, false);
    }
    catch(SoapException MyException)
    {
     //Your exception processing goes here
     . . .
    }

To enable the same contact to be able to locate you, you just need to call the same method with the isActive flag set to true:

    //Update the contact - turn on their ability to locate you
    LocatableContact locatableContact =
                 MyLocationService.UpdateContact(@"DOMAINcontactuser",
                                                 true, true);

Going into stealth mode—becoming invisible to all contacts

Using the LocationServiceSoap.SetVisibility method, you can become completely invisible to all of your contacts, meaning that even if your contacts have permission to locate you, they will be not be able to if you set your visibility to false. The following code snippet shows how to turn off your visibility completely using the SetVisibility method:

    //Create a LocationServiceSoap proxy instance
    LocationServiceSoap locationService = new LocationServiceSoap( );
    //Create and add the credentials required to access the Web service
    NetworkCredential credentials =
              new NetworkCredential("user", "password", "DOMAIN");
    locationService.Credentials = credentials;

    try
    {
     //Set the visibility for the current user - Go Stealth mode
        locationService.SetVisibility(false);
    }
    catch(SoapException MyException)
    {
     //Your exception processing goes here
     . . .
    }

Similarly, you can set your visibility to true so that your contacts can locate you:

    //Set the visibility for the current user - Become visible
    locationService.SetVisibility(true);

If your visibility is set to false and your contacts try to locate you, they get an error indicating that you are not locatable; however, it does not indicate that you chose to be invisible to your contacts.

Finding Nearby Points of Interest

To find nearby points of interest, MapPoint Location Web Service exposes the LocationServiceSoap.GetNearbyCategories method, which returns find nearby categories. Find nearby categories are groups of points of interest of the same type; for example, banks, ATMs, pizza shops, and pubs could belong to these categories. You can use this list of categories to search for points of interest that are close to your location. The following code shows how to retrieve find nearby categories.

    //Create an instance of the LocationServiceSoap proxy class
    LocationServiceSoap locationService = new LocationServiceSoap( );
    //Create an instance of the NetworkCredential class
    //and add the credentials required to access the Web service
    NetworkCredential credentials =
            new NetworkCredential("user", "password", "domain");
    locationService.Credentials = MyCredentials;

    //Get the Find Nearby categories
    try
    {
        FindNearbyCategory[] findNearbyCategories =
                  locationService.GetNearbyCategories( );

     foreach(FindNearbyCategory findNearbyCategory in
                                            findNearbyCategories)
     {
       //Process find nearby category
       . . .
     }
    }
    catch(SoapException exception)
    {
     //Process exceptions here
     . . .
    }

Once you retrieve the find nearby categories using this method, you can call the FindServiceSoap.FindNearby method to retrieve the actual points of interest. So, why do you need this layer of abstraction from the huge yellow page categories and listings available in MapPoint Web Service? Enterprise customization! As an enterprise, you may have business requirements to make specific find nearby categories available to your employees. In this case, a system administrator can define specific find nearby categories that are useful for provisioned users that can later be exposed to your enterprise users via the Location Server client, enabling them to find the specific groups of points of interest around their current location.

Programming with the Location Server Management API

You use the Microsoft Location Server management API to develop server-side applications for Microsoft Location Server. Server-side applications include applications for provisioning users within an enterprise, automating the addition and removal of contact lists for provisioned users, removing provisioned users, and so on. Note that the management API does not expose a real-time location API. To program with the management API, you need to add the following assemblies as references to your project:

Microsoft.MapPoint.LocationServer.Types.dll

Contains Microsoft Location Server data types.

Microsoft.MapPoint.LocationServer.Management.dll

Contains classes that provide methods for managing Microsoft Location Server. In this assembly, the type ServerAPI exposes methods to manage Microsoft Location Server.

Microsoft.MapPoint.LocationServer.Core.dll

Contains classes required by the management API types. This assembly should be used only to add as a reference to your project; do not use types from this assembly directly in your source code.

In the following sections, we’ll look at the Microsoft Location Server management API in detail.

Anatomy of Location Server Management APIs

Microsoft Location Server provides the Server Management APIs to build applications to automate administrative tasks such as adding users, managing contacts for users, and managing find nearby categories. All of the Server Management APIs are provided via the ServerAPI class in the Microsoft.MapPoint.LocationServer.Types.dll assembly; this class provides a set of methods that enables you to develop applications in four major categories:

User management

Enables you to develop applications to add new users and update existing users in the Microsoft Location Server.

Contact management

Enables you to develop applications to add, update, and remove the contacts for the provisioned users.

Privacy management

Enables you to develop applications to modify provisioned user privacy settings.

Find nearby category management

Enables you to develop applications to add, update and remove find nearby categories.

Table 10-2 shows the methods exposed by the ServerAPI class .

Table 10-2. ServerAPI class methods

Method

Description

Initialize

Initializes a connection to the MapPoint Location Server database. Call this method on a ServerAPI instance.

GetContacts

Returns a list of contacts as an array of LocatableContact objects for the user represented by the domain and alias.

AddContact

Adds a new contact for a given user.

UpdateContact

Updates a specified contact in a given user’s contacts list.

DeleteContact

Deletes the specified contact from the contacts list of a given user.

FindProvisionedUser

Allows partial input of LocatableUser object properties or an email address of a user to search provisioned MapPoint Location Server users and returns contact information as an array of LocatableContact instances.

GetDefaultCulture

Retrieves the default culture for a given user, in string format (e.g., “en-US” for English, United States).

SetDefaultCulture

Sets the default culture for a given user.

AddUser

Adds a new user to MapPoint Location Server. Adding a user is also called provisioning a user.

UpdateUser

Updates an existing user (a user that has already been provisioned) in MapPoint Location Server.

DeleteUser

Deletes an existing (provisioned) user from the MapPoint Location Server.

GetAllUsers

Returns all provisioned users as an array of strings in MapPoint Location Server.

GetLocatableUser

Searches for a provisioned user by domain and alias.

GetNewContactNotification

Gets the NotifyOnNewContact property of the LocatableUser object for the user identified by the domain and alias.

SetNewContactNotification

Sets the NotifyOnNewContact property of the LocatableUser object for the user identified by the domain and alias.

GetVisibility

Gets the Visible property of the LocatableUser object that represents the user identified by the domain and alias.

SetVisibility

Determines whether the user is visible to other users or contacts.

GetNearbyCategories

Gets the Find Nearby categories as an array of FindNearbyCategory objects based on the culture name.

AddNearbyCategory

Adds a Find Nearby category to MapPoint Location Server.

UpdateNearbyCategory

Updates an existing nearby category in the MapPoint Location Server.

DeleteNearbyCategory

Deletes an existing Find Nearby category from the MapPoint Location Server.

Figure 10-2 shows the methods and their categorization.

The server management APIs provide everything that the Location Server Web Service provides except for the real-time location APIs. In this section, let’s look at each of the categories in detail.

Tip

If you are using the ServerAPI class to develop applications for Microsoft Location Server, make sure to invoke the Initialize method before calling any other methods of the ServerAPI class. This method call is required to establish a connection to the Microsoft Location Server database.

Programming User Management

Before getting into the details of user management, let’s take a brief look at how the users are organized within Microsoft Location Server. All enterprise users provisioned within the Microsoft Location Server are represented using the ProvisionedUser class. The ProvisionedUser class acts as a base class for locatable users and contacts. A locatable user is essentially a provisioned user with a valid locatable phone number; along the same lines, a locatable contact is a provisioned user with a valid contact relationship. Figure 10-3 shows this relationship pictorially.

Server management API categorization
Figure 10-2. Server management API categorization
User object model in Location Server
Figure 10-3. User object model in Location Server

In essence, the previous discussion can be summarized as:

    Locatable User = Provisioned User + Locatable Phone Number
    Locatable Contact = Provisioned User + Contact Relationship

With this introduction, let’s look at user management API in the Location Server APIs.

Adding users

The ServerAPI class in the Microsoft.MapPoint.LocationServer.Management.dll assembly exposes the method AddUser, which is used to provision users for Microsoft Location Server. This method takes a LocatableUser instance as an input parameter. A LocatableUser instance is an object representation of a domain user with a unique locatable endpoint (a phone number). The following code shows how to provision a user:

    //Create a new instance of the ServerAPI class.
    ServerAPI serverAPI = new ServerAPI( );
    try
    {
     //Create a new instance of the LocatableUser class.
     LocatableUser newUser = new LocatableUser( );
     //Set the domain and alias.
     newUser.DomainAlias = @"domainuser";
     //Set the culture name.
     newUser.CultureName = "en-US";
     //Set the locatable endpoint (the user's mobile device number).
     newUser.LocatableEndpoint =
            new LocatablePhoneNumber("001", "111", "1111111");
     //Set the location provider name
     newUser.LocationProviderName = "Your Location Provider Name";
     //Set the notification provider name
     newUser.NotificationProviderName =
                    "Your Notification Provider Name";
     //Set the notification endpoint
     newUser.NotificationEndpoint = "user email address";
     //Initialize the database connection for ServerAPI operations.
        serverAPI.Initialize("SQL Server Name", "LocationServerDB");
     //Add the new domain user to Microsoft Location Server.
        serverAPI.AddUser(newUser);
    }
    catch(Exception exception)
    {
     //Process exceptions
     . . .
    }

In this code, a user with the domain alias “domainuser” has been added to the Microsoft Location Server. Note that the LocatableEndPoint (phone number), LocationProviderName, NotificationEndPoint (email address or SMS number), and NotificationProviderName are optional parameters; however, domain alias and default culture name are mandatory to add a new user. Also note that any newly added provisioned user will be visible by default.

Managing provisioned users

Similar to the AddUser method, the ServerAPI class also provides methods for managing users who are already provisioned. You can use the DeleteUser method to delete a provisioned user from Microsoft Location Server, and the UpdateUser method to update the properties of a provisioned user. The following code shows how to update a provisioned user’s locatable phone number:

    //Create a new instance of the ServerAPI class 
 

    ServerAPI serverAPI = new ServerAPI( );
    try
    {
      //Create a LocatableUser instance
      LocatableUser user = new LocatableUser( );
      //Set the domain alias
      user.DomainAlias = @"DOMAINuser";
      //Update the culture name
      user.CultureName = "de-DE";
      //Update the Locatable end point - This is the user's new mobile device number
      user.LocatableEndpoint = new LocatablePhoneNumber("001", "425", "2222222");

      //Initialize the database connection for ServerAPI operations
         serverAPI.Initialize("SQL Server Name", "MSLocationServer");
      //Now Update the domain user profile
         serverAPI.UpdateUser(user);
    }
    catch(Exception MyException)
    {
      //Process your exceptions
      . . .
    }

In this code, both the default culture and phone number are updated using the ServerAPI.UpdateUser method. Note that you cannot update the user’s domain alias using the UpdateUser method.

Programming Privacy Management

If you recall from our earlier discussions, Location Server Web Service can only update privacy settings for the logged-in user; however, the ServerAPI class can be used in administrative mode to update the privacy settings of any provisioned users in the Microsoft Location Server, including enabling and disabling contact relationships and visibility for any given provisioned user. You can use the ServerAPI.GetVisibility and ServerAPI.SetVisibility methods to set the user level visibility settings.

The following code snippet shows how to set visibility for a provisioned user within Microsoft Location Server:

    //Create a new instance of the ServerAPI class 
 
 
 

    ServerAPI serverAPI = new ServerAPI( );
    try
    {
      //Initialize the database connection for ServerAPI operations
      serverAPI.Initialize("SQL Server Name", "MSLocationServer");

      //Now Set the Visibility flag for the domain alias DOMAINuser
      //false means that the user is not visible and others can not
      //locate this user even if he/she is on their contact list
         serverAPI.SetVisibility(@"DOMAINuser", false);

    }
    catch(Exception exception)
    {
      //Process your exceptions
      . . .
    }

The only difference between the SetVisibility of the ServerAPI and the LocationServiceSoap is that you need to pass the domain alias that you want to modify the privacy settings for; this makes sense since you are running ServerAPI in administrator mode; Location Server Web Service, however, implicitly assumes the logged-in user’s settings.

Programming Contact Management

Using the ServerAPI class, you can add, remove, and update contacts for provisioned users. The capability to manage contacts is extremely useful if you are setting up a standard contact list for all provisioned users within your enterprise. The ServerAPI class exposes the methods AddContact, UpdateContact, and DeleteContact for adding, updating, and deleting contacts, respectively. As mentioned earlier, the primary difference between the Microsoft Location Server Web Service methods and the ServerAPI class methods is that the web service method calls run in the current user’s context and the ServerAPI methods calls run under the administrator’s context. Therefore, when you call the AddContact method using the Microsoft Location Server Web Service, you are adding a contact to your own contact list, whereas when you call the AddContact method of the ServerAPI class, you are adding a contact for the provisioned user whom you specify as an argument to this method.

The following code snippet shows how to call the AddContact method to add a contact for a provisioned user.

    //Create a new instance of the ServerAPI class.
    ServerAPI serverAPI = new ServerAPI( );

    //Call the Initialize method.
     serverAPI.Initialize("sql server name", "LocationServerDB");

    //Original user to whom the contact is being added
    string userAlias = @"domainuser";
    //Contact domain alias
    string contactAlias = @"domain
ewcontact";
    try
    {
        LocatableContact locatableContact =
                  serverAPI.AddContact(userAlias, contactAlias, true, true);
     . . .
    }
    catch(Exception exception)
    {
     //Process exceptions
     . . .
    }

In this code, a new contact, "domain ewcontact" has been added to the provisioned user "domainuser" using the ServerAPI.AddContact method; the two boolean flags passed to this method indicate whether the contact relationship is active and whether the user wants to be notified when the contact tries to locate him, respectively.

Along the same lines, you can also update an existing contact relationship using the ServerAPI.UpdateContact method:

    //Original user to whom the contact is being added
    string userAlias = @"domainuser";
    //Contact domain alias
    string contactAlias = @"domain
ewcontact";
    try
    {
        LocatableContact locatableContact =
                  serverAPI.UpdateContact(userAlias, contactAlias, false, true);
     . . .
    }
    catch(Exception exception)
    {
     //Process exceptions
     . . .
    }

This call updates the contact relationship to be a “non-active” relationship (due to the flag isActive being set to false), and as a result, the provisioned user newcontact cannot locate the provisioned user user.

Programming Find Nearby Category Management

Using the ServerAPI class you can add, update, and delete find nearby categories that are appropriate for your enterprise. The ServerAPI class exposes the methods AddNearbyCategory, UpdateNearbyCategory, and DeleteNearbyCategory for adding , updating, and removing find nearby categories.

Find nearby categories are logical groupings of points of interest; they directly map to the entity model presented in the MapPoint Web Service. If you plan to define a find nearby category by the name “dining places,” you need to specify the exact entity type name and the associated data source name that corresponds to the find nearby category in MapPoint Web Service. In this case, if you plan to use NavTeq’s provided yellow page listing categories to define the “dining places” category, you need to specify the entity type name as “SIC3578” and the data source name as “NavTech.NA.”

So, to add a find nearby category, you need to complete the following steps:

  1. Find nearby category name.

  2. Find nearby category culture and distance unit.

  3. Find nearby category localized names (to display them in different cultures).

  4. Find the entity type that defines the find nearby category.

  5. Apply this to a MapPoint Web Service data source name that contains the entity type specified in item 4.

Use the method AddNearbyCategory to add a nearby category; this method takes a valid instance of the FindNearbyCategory class as an argument to add the nearby category; a valid FindNearbyCategory object defines the aforementioned five properties for the ServerAPI to be able to add a nearby category successfully.

The following code shows adding a find nearby category called Dining Places and maps the entity type SIC3578 from the data source NavTech.NA:

    //Create a new instance of the ServerAPI class
    ServerAPI serverAPI = new ServerAPI( );

    //Initialize the database connection for ServerAPI operations
    serverAPI.Initialize("SQL Server Name", "LocationServerDB");

    //Step 1 & 2

    //Create a new instance of the FindNearbyCategory class 

    FindNearbyCategory category = new FindNearbyCategory( );
    //Set the default culture.
    category.DefaultCulture = "en-US";
    //Set the distance units.
    category.DistanceUnit = DistanceUnit.Mile;
    //Set the key name.
    category.KeyName = "DiningPlaces";

    //Step 3

    //Set the localized names.
    //In this case we have two localized names
    //Set the name for English (US)
    FindNearbyCategoryName[] findNearbyCategoryNames
                          = new FindNearbyCategoryName[2];

    findNearbyCategoryNames[0] = new FindNearbyCategoryName( );
    findNearbyCategoryNames[0].Culture = "en-US";
    findNearbyCategoryNames[0].DisplayName
                       = "Dining Places";
    findNearbyCategoryNames[0].DisplayDescription
                       = "Dining Places related to my enterprise.";
    //Set the name for German (Germany) Culture.
    findNearbyCategoryNames[1] = new FindNearbyCategoryName( );
    findNearbyCategoryNames[1].Culture = "de-DE";
    findNearbyCategoryNames[1].DisplayName
                         = "Speisenden Pl?tze";
    findNearbyCategoryNames[1].DisplayDescription
                         = "Speisenden Pl?tze";

    //Assign the localized names to the instance
    //of the FindNearbyCategory class
    category.Names = findNearbyCategoryNames;


    //Step 4 & 5

    //Create a new instance of the FindNearbySpecification class
    FindNearbySpecification findNearbyCategorySpecification =
                                         new FindNearbySpecification( );
    //Define the data source
    findNearbyCategorySpecification.DataSourceName = "NavTech.NA";

    //Define the entity type
    findNearbyCategorySpecification.Filter = new FindFilter( );
    findNearbyCategorySpecification.Filter.EntityTypeName = "SIC3578";

    //Assign the FindNearbySpecification to the category
    category.FindNearbySpecification = findNearbyCategorySpecification;

    //Finally . . .
    //Add the find nearby category
       serverAPI.AddNearbyCategory(category);
    . . .

Note that the find nearby category key name (DiningPlaces, in this example) is a required field and should not exceed 128 characters in length. Also, the default culture must be always defined, along with an associated localized name. For example, if you define the default culture as “fr-FR” with no associated localized French name for your find nearby category, the AddNearbyCategory throws an exception.

Along similar lines, you can also update a find nearby category using the ServerAPI.UpdateNearbyCategory method. To update the entity type and data source mapping to a find nearby category that you have already defined, use the UpdateNearbyCategory method. The following code snippet shows updating the entity type and data source mapping for the dining places nearby category that we created previously:

    //Create an instance of the ServerAPI and initialize
    . . .

    //Create a FindNearbySpecification
    FindNearbySpecification findNearbyCategorySpecification
                     = new FindNearbySpecification( );
    //Update this value from NavTech.NA to Acxiom.US.SIC_G.58
       findNearbyCategorySpecification.DataSourceName = "Acxiom.US.SIC_G.58";

    findNearbyCategorySpecification.Filter = new FindFilter( );

    //Update this value from SIC3578 to SIC5813
       MyFindNearbyCategorySpecification.Filter.EntityTypeName = "SIC5813";

    //Assign the FindNearbySpecification to the category
    category.FindNearbySpecification = MyFindNearbyCategorySpecification;

    //Now update the category
    serverAPI.UpdateNearbyCategory(category);

The find nearby category data source and entity type mapping have been changed from NavTech.NA and SIC3578 to Acxion.US.SIC_G.58 and SIC5813, respectively.

Finally, you can use the ServerAPI.DeleteNearbyCategory method to delete the existing nearby category definitions in the Microsoft Location Server. The DeleteNearbyCategory method takes the nearby category key name as an argument to delete the existing nearby category method. To delete the nearby category, dining places, call the DeleteNearbyCategory method:

    //Delete the category using the keyname value
    serverAPI.DeleteNearbyCategory("DiningPlaces");

The key name of the nearby category is the primary key within an instance of the Microsoft Location Server.

Comparing Location Server API to Location Web Service API

So far in this chapter, you have seen both Microsoft Location Server Web Service APIs and the Location Server Management APIs and learned how to program with them. Since most of the API functionality is common across these two sets of APIs, I thought it would be a good idea to wrap up the discussion with a comparison table by pointing out key differences as shown in Table 10-3.

Table 10-3. API comparison chart

API feature

Available with Location Web Service

Available with Location Web Server

Get Real-time Location

Yes

No

Add Contacts

Yes

Yes

Update Contacts

Yes

Yes

Delete Contacts

Yes

Yes

Set Visibility

Yes

Yes

Add Nearby Categories

No

Yes

Update Nearby Categories

No

Yes

Delete Nearby Categories

No

Yes

Get Nearby Categories

Yes

Yes

Provision Users

No

Yes

Update Provisioned Users

No

Yes

Delete Provisioned Users

No

Yes

Find Provisioned Users

Yes

Yes

It is important to keep in mind that the applications built with the Server APIs always run in the context of the Microsoft Location Server Administrator, while the applications built with the Location Server Web Server always run in the context of a provisioned user.

Where Are We?

In this chapter, you have seen how to develop:

  • Real-time location applications using Location Server Web Service

  • User, Contact, and Privacy Management applications using Location Server Web Service and the Server APIs

  • Find nearby category management applications using the Location Server APIs

In the case of real-time location applications, the Location Server Web Service is hosted within your enterprise, providing a SOAP XML-enabled web service to obtain the real-time location of a provisioned mobile phone number from the mobile operator networks. For building server applications, you will need to access the server API assemblies directly so that you can build and use them on a Microsoft Location Server instance installed in your enterprise.

Finally, keep in mind that Microsoft Location Server works with different network providers to provide the real-time location using mobile phone numbers; the list of providers may change from time to time, and it is recommended that you check the Microsoft Location Server product home page (http://www.microsoft.com/mappoint/products/locationserver/default.mspx) for up-to-date information about the supported network providers.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.49.247