Code sample: Creating your first application

The following code sample demonstrates how to find an existing user account on your BlackBerry® Enterprise Server.

using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using System.Net;
using System.Net.Security;
using System.IO;

namespace BASClient {

		enum AuthenticationType {
     Unspecified,
     BlackBerryAdministrationService,
     ActiveDirectory,
  }

  class BASClient {

    /**
     * The stub objects of the various BlackBerry Adminstrative API web services used.
     */
    public BAAServiceCore coreWebService = new BAAServiceCore();
    public BAAServiceUtil utilWebService = new BAAServiceUtil();
    public BAAServiceEmailExchange emailExchangeWebService = new BAAServiceEmailExchange();
    public BAAServiceDispatcher dispatcherWebService = new BAAServiceDispatcher();

    /**
     * URL for the BlackBerry Administration Service server. This does not 
     * include the path; it is just the servername and protocol.
     */
    private String BASUrl = null;

    /**
     * Contains the credentials (username, password, domain) to authenticate with.
     */
    private Credentials credentials = new Credentials();

    /**
     * Pointer to the BlackBerry Administration Servic dispatcher service.
     */
    private DispatcherService dispatcherService = null;

    /**
     * Map associating BlackBerry Enterprise Server instance names with dispatcher 
     * service instances. Used to create new users in the given instance.
     */
    private SortedDictionary<String, DispatcherHostServiceInstance> servers = new SortedDictionary<String, DispatcherHostServiceInstance>();

    /**
     * Returns the dispatcher service object. Every domain has a single instance of 
     * this service. It is used later to retrieve dispatcher instances, which we 
     * identify with BlackBerry Enterprise Servers for ease of understanding.
     * 
     * Flow:
     *  - findServices returns all servicec.
     *  - We iterate over the results to find the service of the right type.
     */
    private DispatcherService getDispatcherService() {
      if (dispatcherService == null) {
        findServices request = new findServices();
        request.locale = "en_US";
        request.includeSettings = true;
        FindServicesResult result = coreWebService.findServices(request).returnValue;
        if (result.findServicesReturnStatus.code != FindServicesReturnStatusEnumType.SUCCESS) {
          throw new Exception(String.Format("Error retrieving services: {0}", result.findServicesReturnStatus.message));
        }
        for (int i = 0; i < result.services.Length; i++) {
          ServiceType svc = result.services[i];
          if (svc.GetType().Equals(typeof(DispatcherService))) {
            dispatcherService = (DispatcherService) svc;
          }
        }
      }
      if (dispatcherService == null) {
        throw new Exception("Dispatcher service not found");
      }
      return dispatcherService;
    }

    /**
     * Builds a sorted dictionary of all dispatcher instances ('servers') in the 
     * BlackBerry Enterprise Server domain. The dictionary is keyed on the instance 
     * name and has an object representing the instance as values. These objects are
     * later used when creating BlackBerry device users.
     * 
     * Note: BlackBerry Administration API 5.0.2 also has a getDispatcherNames()
     *       method on the dispatcher web service. We cannot use this call because 
     *       it does not return the actual dispatcher instances, which we need to 
     *       create BlackBerry device users.
     * 
     * Flow:
     *  - Find all service instances with the dispatcher service ID, which we 
     *    obtained using the getDispatcherService() method. The service instances 
     *    are found using the findServiceInstanceByService method from the core 
     *    service.
     *  - We iterate over all the results and ensure that the objects returned are 
     *    in fact of the correct type.
     *  - If they are, we add them to the 'servers' dictionary.
     */
    private void readServers() {
      DispatcherService ds = getDispatcherService();

      findServiceInstancesByService request = new findServiceInstancesByService();
      request.serviceId = ds.serviceId;
      request.locale = "en_US";
      request.includeExtendedData = true;
      request.includeStatus = false;
      request.loadServiceConsumerRelationships = false;
      request.loadServiceProducerRelationships = false;
      FindServiceInstancesByServiceResult result = coreWebService.findServiceInstancesByService(request).returnValue;
      if (result.findServiceInstancesByServiceReturnStatus.code != FindServiceInstancesByServiceReturnStatusEnumType.SUCCESS) {
        Console.WriteLine("Error retrieving service instances: {0}", result.findServiceInstancesByServiceReturnStatus.message);
        return;
      }
      for (int i = 0; i < result.serviceInstances.Length; i++) {
        ServiceInstanceType sit = result.serviceInstances[i];
        if (sit.GetType().Equals(typeof(DispatcherHostServiceInstance))) {
          DispatcherHostServiceInstance dhsi = sit as DispatcherHostServiceInstance;
          servers.Add(dhsi.name, dhsi);
        }
      }
    }

    /**
     * Returns the Authenticator object to use to encode the user name. The
     * BlackBerry Administration Service supports a number of authentication 
     * methods. Since authentication is performed using HTTP 
     * basic authentication, which only supports user name and password being 
     * transmitted from client to server, the type of authentication to be 
     * performed and any other data needed (e.g. domain in the case of 
     * Microsoft Active Directory authentication) must be encoded in the user name. 
     * This encoding is performed by calling a method on the (not secured) util 
     * web service. 
     * 
     * This sample supports Microsoft Active Directory and BlackBerry 
     * Administration Service authentication.  It does not support IBM Lotus 
     * Domino Mailbox authentication.
     * 
     * Flow:
     *  - Obtain all supported authenticators using the findAuthenticators method 
     *    in the util service.
     *  - Find the authenticator with the name matching the requested 
     *    authentication type.
     */
    private Authenticator getAuthenticator() {
      Authenticator ret = null;
      findAuthenticators request = new findAuthenticators();
      request.locale = "en_US";
      Authenticator[] authenticators = utilWebService.findAuthenticators(request);
      for (int i = 0; i < authenticators.Length; i++) {
        if (authenticators[i].name.Equals(credentials.authenticationTypeAsString)) {
          ret = authenticators[i];
        }
      }
      if (ret == null) {
        throw new Exception("Could not find the " + credentials.authenticationTypeAsString + " authenticator");
      }
      return ret;
    }

    /**
     * Returns the encoded username. The BlackBerry Administration Service supports a 
     * number of authentication methods. Since authentication is performed using HTTP
     * basic authentication, which only supports user name and password being 
     * transmitted from client to server, the type of authentication to performed and
     * any other data needed (e.g. domain in the case of Microsoft Active Directory 
     * authentication) must be encoded in the user name. This encoding is performed
     * by calling a method on the (not secured) util web service. 
     * 
     * This sample program supports Microsoft Active Directory and BlackBerry 
     * Administration Service authentication,  It does not support IBM Lotus Domino 
     * Mailbox authentication.
     * 
     * Flow:
     *  - Obtain the authenticator to be used using the getAuthenticator() method
     *  - Pass the authenticator type, ID, and the provided user name and domain to
     *    the encodeUsername method of the util service.
     */
    public String encodeUsername() {
      Authenticator authenticator = getAuthenticator();
      encodeUsername request = new encodeUsername();
      request.username = credentials.username;
      request.type = authenticator.authenticatorType;
      request.domain = credentials.domain;
      request.identifier = authenticator.id;
      request.credentialType = "0";
      encodeUsernameResponse response = utilWebService.encodeUsername(request);
      return response.returnValue;
    }

    /**
     * Initialize the various web services used. This includes setting the URL to the
     * various services based on the address of the BlackBerry Adminstration Service
     * server as provided, encoding the user name to be used, and setting
     * HTTP basic authentication credentials on the proxy objects.
     * 
     * Flow:
     *  - Prompt the user for the URL to the BlackBerry Adminstration Service server.
     *  - Prompt the user for the login credentials. This includes the authentication
     *    type.
     *  - Initialize the various web services used.
     */
    public void setup() {
      BASUrl = Prompt.prompt("BAS URL");
      if (!BASUrl.StartsWith("https://")) {
        BASUrl = "https://" + BASUrl;
      }
      credentials.query();

      utilWebService.Url = BASUrl + "/baaws/core/wsutil?wsdl";
      String encodedUsername = encodeUsername();

      coreWebService.Url = BASUrl + "/baaws/core/ws?wsdl";
      coreWebService.Credentials = new NetworkCredential(encodedUsername, credentials.password);
      coreWebService.PreAuthenticate = true;

      emailExchangeWebService.Url = BASUrl + "/baaws/emailexchange/ws?wsdl";
      emailExchangeWebService.Credentials = new NetworkCredential(encodedUsername, credentials.password);
      emailExchangeWebService.PreAuthenticate = true;

      dispatcherWebService.Url = BASUrl + "/baaws/dispatcher/ws?wsdl";
      dispatcherWebService.Credentials = new NetworkCredential(encodedUsername, credentials.password);
      dispatcherWebService.PreAuthenticate = true;
    }

    /**
     * Displays the names of the dispatcher instances ('servers') found by
     * readServers. These are all instances of the BlackBerry Enterprise
     * Server available within the domain to create users on.
     */
    private void listServers() {
      Console.WriteLine("Available servers:");
      foreach (String svc in servers.Keys) {
        Console.WriteLine("  " + svc);
      }
      Console.WriteLine();
    }

    /**
     * Creates a new BlackBerry device user in the domain. Creating a BlackBerry
     * device user is done by associating a new BlackBerry device user with an
     * existing mail store (Microsoft Exchange) user. This new user needs to be
     * assigned to a dispatcher instance a.k.a. a BlackBerry Enterprise Server
     * instance or server. So we query the user for the server to create the 
     * user on, and for the email address of the user in the mail store. If there
     * is exactly one match in the mail store, we go ahead and copy the relevant
     * user attributes from the mail store and perform the creation in the 
     * BlackBerry Adminstration Service.
     * 
     * Flow:
     *  - Query user for server name and user email address
     *  - Query mail store for email address using the findMailStoreUsers method
     *    in the exchange service. Note that we make the page size 2. This allows
     *    us to detect that there is more than one match while not returning
     *    potential large amounts of data. We also only query for email addresses
     *    that are not already tied to BlackBerry device users using the 
     *    isNewUserOnly flag.
     *  - Report various error conditions (no or multiple matches).
     *  - Ask for confirmation that we can do what we're going to do.
     *  - Gather relevant BlackBerry device user attributes from the mail store
     *    using the gatherEnableBlackBerryUserAttributes method on the exchange
     *    service. This method uses a result object from findMailStoreUsers as its
     *    input.
     *  - Use the retrieved user attributes, the server instance, and other
     *    information to create the BlackBerry Adminstration Service user using
     *    createUser in the core service.
     *  - Report the user ID assigned to the new user.
     */
    private void createUser() {
      DispatcherHostServiceInstance server = null;
      while (server == null) {
        listServers();
        String serverName = Prompt.prompt("Server to create user on");
        server = servers[serverName];
      }

      String email = Prompt.prompt("Email address of user to create");

      findMailStoreUsers request1 = new findMailStoreUsers();
      MailStoreUserSearchCriteria criteria = new MailStoreUserSearchCriteria();
      criteria.emailAddress = email;

      // Only include users that are not yet present on the
      // BlackBerry Enterprise Server
      criteria.isNewUserOnly = true;
      criteria.isNewUserOnlySpecified = true;

      request1.searchCriteria = criteria;

      MailStoreUserSearchResultSortByEnum sortByEnum = new MailStoreUserSearchResultSortByEnum();
      sortByEnum.@enum = MailStoreUserSearchResultSortByEnumType.DISPLAY_NAME;
      sortByEnum.enumSpecified = true;
      request1.sortByCriteria = sortByEnum;

      request1.sortByAscendingOrder = true;
      request1.criteriaAndResultSetLocale = "en_US";
      request1.pageCriteria = null;
      request1.pageSize = 2;

      FindMailStoreUsersResult result1 = emailExchangeWebService.findMailStoreUsers(request1).returnValue;
      if (result1.findMailStoreUsersReturnStatus.code != FindMailStoreUsersReturnStatusEnumType.SUCCESS) {
        throw new Exception("Error querying mail store for users: " + result1.findMailStoreUsersReturnStatus.message);
      }
      if ((result1.mailStoreUserSearchResult == null) || (result1.mailStoreUserSearchResult.Length == 0)) {
        Console.WriteLine("Email address " + email + " not found in mail store");
        return;
      }
      if (result1.mailStoreUserSearchResult.Length > 1) {
        Console.WriteLine("More than one email address matching " + email + " found in mail store:");
        return;
      }

      MailStoreUserSearchResult msu = result1.mailStoreUserSearchResult[0];
      Console.WriteLine("Display Name: " + msu.displayName);
      Console.WriteLine("Email Address: " + msu.emailAddress);

      if (!Prompt.confirm("Create user for this email address?"))
        return;

      gatherEnableBlackBerryUserAttributes request2 = new gatherEnableBlackBerryUserAttributes();
      request2.result = msu;
      request2.locale = "en_US";
      GatherEnableBlackBerryUserAttributesResult result2 =
          emailExchangeWebService.gatherEnableBlackBerryUserAttributes(request2).returnValue;
      if (result2.gatherEnableBlackBerryUserAttributesReturnStatus.code != GatherEnableBlackBerryUserAttributesReturnStatusEnumType.SUCCESS) {
        throw new Exception("Error gathering BlackBerry device user attributes: " + result2.gatherEnableBlackBerryUserAttributesReturnStatus.message);
      }

      createUser createUserRequest = new createUser();

      UserEnableBlackBerryAttributes userEnableBBAttributes = new UserEnableBlackBerryAttributes();
      userEnableBBAttributes.enableBlackBerryUserAttributes = new EnableBlackBerryUserAttributesType[result2.enableBlackBerryUserAttributes.Length];
      for (int j = 0; j < result2.enableBlackBerryUserAttributes.Length; j++) {
        userEnableBBAttributes.enableBlackBerryUserAttributes[j] = result2.enableBlackBerryUserAttributes[j];
      }
      userEnableBBAttributes.serviceInstance = server;
      userEnableBBAttributes.targetServiceInstance = server;
      userEnableBBAttributes.ignoreDuplicateWarning = false;
      userEnableBBAttributes.ignoreDuplicateWarningSpecified = true;
      userEnableBBAttributes.ignoreEncryptionWarning = false;
      userEnableBBAttributes.ignoreEncryptionWarningSpecified = true;
      userEnableBBAttributes.ignoreInactiveTargetWarnings = false;
      userEnableBBAttributes.ignoreInactiveTargetWarningsSpecified = true;
      userEnableBBAttributes.failOutstandingJobs = false;
      userEnableBBAttributes.failOutstandingJobsSpecified = true;
      userEnableBBAttributes.organizationId = 0;
      userEnableBBAttributes.organizationIdSpecified = true;
      createUserRequest.userEnableBlackBerryAttributes = userEnableBBAttributes;

      createUserRequest.locale = "en_US";
      createUserRequest.group = null;
      createUserRequest.itpolicy = null;
      createUserRequest.softwareConfiguration = null;

      CreateUserResult createUserResult = coreWebService.createUser(createUserRequest).returnValue;
      if (createUserResult.createUserReturnStatus.code != CreateUserReturnStatusEnumType.SUCCESS) {
        Console.WriteLine("Error creating user: " + createUserResult.createUserReturnStatus.message);
      } else {
        Console.WriteLine("User added with ID " + createUserResult.userId);
      }
    }

    /**
     * Displays a list of users matching a search pattern as entered by the user.
     * Also shows some common features of the API (metadata access), and rainbow
     * objects, used to segregate different aspects of objects. In the case of
     * users, data is returned separately for core BlackBerry Administration
     * Service user data, mail store dependent data, and dispatcher instance
     * dependent data.
     * 
     * Flow:
     *  - Query user for search pattern to use.
     *  - Build criteria depending on pattern type selected.
     *  - Find first page of users using findUsers method in core service.
     *  - Display users found.
     *  - Try to retrieve next page using findUsers method again.
     *  - Repeat until no more users found.
     */
    private void findUsers() {
      FindUsersResult result;
      findUsers request = new findUsers();
      UserSearchResult lastResult = null;

      String query = Prompt.prompt("Search for users matching");

      UserSearchCriteriaServiceAttributesType critAttrs = null;
      while (critAttrs == null) {
        String matchtype = Prompt.prompt("Search by [D]isplay name or [E]mail address").ToUpper();
        if (matchtype.StartsWith("D")) {
          BASUserSearchCriteriaServiceAttributes basUserCritAttrs = new BASUserSearchCriteriaServiceAttributes();
          basUserCritAttrs.displayName = query;
          critAttrs = basUserCritAttrs;
        } else if (matchtype.StartsWith("E")) {
          EmailCommonUserSearchCriteriaServiceAttributesType emailCritAttrs = new EmailExchangeUserSearchCriteriaServiceAttributes();
          emailCritAttrs.userEmailAddress = query;
          critAttrs = emailCritAttrs;
        }
      }
      UserSearchCriteria criteria = new UserSearchCriteria();
      criteria.userSearchCriteriaServiceAttributes = new UserSearchCriteriaServiceAttributesType[1];
      criteria.userSearchCriteriaServiceAttributes[0] = critAttrs;
      request.searchCriteria = criteria;

      BASUserSearchResultSortByEnum sortBy = new BASUserSearchResultSortByEnum();
      sortBy.@enum = BASUserSearchResultSortByEnumType.DISPLAY_NAME;
      sortBy.enumSpecified = true;
      request.sortBy = sortBy;

      request.locale = "en_US";
      request.sortAscendingOrder = true;
      request.pageSize = 5;
      request.lastResultElement = lastResult;

      result = coreWebService.findUsers(request).returnValue;

      while (result.userSearchResult != null) {
        Metadata md = result.metadata;
        System.Console.WriteLine("API Status [{0}]; Execution Time [{1}]s",
            md.APIStatusSpecified ? md.APIStatus : APIStatusEnumType.NOT_YET_IMPLEMENTED,
            md.executionTimeSpecified ? md.executionTime / 1000000000.0 : -1);

        if (result.findUsersReturnStatus.code != FindUsersReturnStatusEnumType.SUCCESS) {
          Console.Error.WriteLine(result.findUsersReturnStatus.message);
          break;
        }

        System.Console.WriteLine("results # [{0}]", result.userSearchResult.Length);
        for (int i = 0; i < result.userSearchResult.Length; i++) {
          UserSearchResult entry = result.userSearchResult[i];
          UserSearchResultServiceAttributesType[] serviceAttributes = entry.userSearchResultServiceAttributes;
          for (int j = 0; j < serviceAttributes.Length; j++) {
            if (serviceAttributes[j].GetType().Equals(typeof(BASUserSearchResultServiceAttributes))) {
              BASUserSearchResultServiceAttributesType basServiceResultAttributes = serviceAttributes[j] as BASUserSearchResultServiceAttributesType;
              System.Console.WriteLine("\tName: " + basServiceResultAttributes.displayName);
            } else if (serviceAttributes[j].GetType().Equals(typeof(DispatcherUserSearchResultServiceAttributes))) {
              DispatcherUserSearchResultServiceAttributesType dispatcherResultAttributes = serviceAttributes[j] as DispatcherUserSearchResultServiceAttributesType;
              System.Console.WriteLine("\tServer name: " + dispatcherResultAttributes.dispatcherServiceInstanceName);
            } else if (serviceAttributes[j].GetType().Equals(typeof(EmailExchangeUserSearchResultServiceAttributes))) {
              EmailExchangeUserSearchResultServiceAttributesType emailResultAttributes = serviceAttributes[j] as EmailExchangeUserSearchResultServiceAttributesType;
              System.Console.WriteLine("\tEmail Server: " + emailResultAttributes.mailServerName);
              System.Console.WriteLine("\tEmail Address: " + emailResultAttributes.userEmailAddress);
              System.Console.WriteLine("\tUser State: " + emailResultAttributes.userState);
              if (emailResultAttributes.lastContactDateSpecified) {
                System.Console.WriteLine("\tLast Contact Date/Time: " + emailResultAttributes.lastContactDate.ToString());
              }
            } else {
              System.Console.WriteLine("\tAttribute " + serviceAttributes[j].GetType().Name);
            }

          }
          System.Console.WriteLine("");
          lastResult = entry;
        }
        request.lastResultElement = lastResult;
        result = coreWebService.findUsers(request).returnValue;
      }
    }
    
    class Prompt
    {
        public static String prompt(String msg)
        {
            return prompt(msg, null);
        }

        public static String prompt(String msg, String defval)
        {
            String ret = null;
            while ((ret == null) || (ret.Length == 0))
            {
                Console.Write(msg);
                if (defval != null)
                    Console.Write(" [" + defval + "]");
                Console.Write(": ");
                ret = Console.ReadLine().Trim();
                if ((ret.Length == 0) && (defval != null))
                    ret = defval;
            }
            return ret;
        }

        public static bool confirm(String msg)
        {
            while (true)
            {
                String yn = prompt(msg + " (y/n)");
                if (yn.StartsWith("Y"))
                {
                    return true;
                }
                else if (yn.StartsWith("N"))
                {
                    return false;
                }
            }
        }
    }

    class Credentials
    {
        private String _username = null;
        private String _password = null;
        private String _domain = null;
        private AuthenticationType _authType = AuthenticationType.Unspecified;

        public String username
        {
            get
            {
                if (_username == null)
                {
                    _username = Prompt.prompt("Username");
                }
                return _username;
            }
            set
            {
                _username = value;
            }
        }

        public String password
        {
            get
            {
                if (_password == null)
                {
                    _password = Prompt.prompt("Password");
                }
                return _password;
            }
            set
            {
                _password = value;
            }
        }

        public AuthenticationType authenticationType
        {
            get
            {
                while (_authType == AuthenticationType.Unspecified)
                {
                    String t = Prompt.prompt("Authentication type (BAS [1] Active Directory [2])");
                    if (t.Equals("1"))
                    {
                        _authType = AuthenticationType.BlackBerryAdministrationService;
                    }
                    else if (t.Equals("2"))
                    {
                        _authType = AuthenticationType.ActiveDirectory;
                    }
                }
                return _authType;
            }
        }

        public String authenticationTypeAsString
        {
            get
            {
                return (authenticationType == AuthenticationType.ActiveDirectory) ? "Active Directory" : "BlackBerry Administration Service";
            }
        }

        public String domain
        {
            get
            {
                if (_domain == null)
                {
                    if (authenticationType == AuthenticationType.ActiveDirectory)
                    {
                        _domain = Prompt.prompt("Domain");
                    }
                    else
                    {
                        _domain = "";
                    }
                }
                return _domain;
            }
            set
            {
                _domain = value;
            }
        }

        public void query()
        {
            String s = username;
            s = password;
            s = authenticationTypeAsString;
            s = domain;
        }

    }

    /**
     * Command line shell.
     */
    public void run() {
      setup();
      readServers();

      bool ok = true;
      while (ok) {
        String cmd = Prompt.prompt("[L]ist servers - [F]ind users - [C]reate user - [Q]uit");
        cmd = cmd.Substring(0, 1).ToUpper();
        if (cmd.Equals("Q")) {
          Console.WriteLine("Goodbye!");
          ok = false;
        } else if (cmd.Equals("L")) {
          listServers();
        } else if (cmd.Equals("F")) {
          findUsers();
        } else if (cmd.Equals("C")) {
          createUser();
        }
      }
    }

    /**
     * Main entry point.
     */
    static void Main(string[] args) {
      try {
        BASClient client = new BASClient();
        client.run();
      } catch (System.Exception e) {
        Console.Error.WriteLine(e.Message);
      }
    }
  }
}
Next topic: Glossary
Previous topic: Create a project

Was this information helpful? Send us your comments.