Skip to Content
Mobile

Afaria API 202 - Build Your Own Enrollment Portal - Server Settings + Non-iOS Enrollment

Tags:

Introduction

This is the second in a series of documents on creating your own Enrollment Portal or End-User Self-Service portal. It is meant as a continuation of our previous efforts in Afaria API 101 and Afaria API 201, and assumes completion of those sections. Best coding practices are not necessarily followed to allow for clarity in the instruction of use of the Afaria API.

Requirements & Assumptions

Table of Contents

Modifying the Preexisting Portal

  1. First, open the project created in Afaria API 201.
  2. In Index.aspx, source view, add a label between ButtonGetCode and HyperLinkMDMFirstUrl, and name it LabelUserInstructions, cleat the Text and set Enabled to false.
  3. Still in Index.aspx, add a couple of line breaks and a label item below all previous items, but still in the form. Name the Label LabelUserWarning, clear the Text, set Font-Bold to true, ForeColor to red and Enabled to false. We will use this to output messages to the user when there is a problem.
  4. After performing the previous steps, your Index.aspx should look like this:

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="AfariaAPI201.index" %>

    <!DOCTYPE html>

    <html xmlns="http://www.w3.org/1999/xhtml">

    <head runat="server">

        <title>AfariaAPI-SSP</title>

    </head>

        <body>

            <form id="form1" runat="server">

            <div>

                <asp:Label ID="LabelUserName" runat="server" Text="UserName:"></asp:Label>

                <asp:TextBox ID="TextBoxUserName" runat="server"></asp:TextBox>

                <asp:Label ID="LabelEmailAddress" runat="server" Text="Email Address:"></asp:Label>

                <asp:TextBox ID="TextBoxEmailAddress" runat="server"></asp:TextBox>

                <asp:DropDownList ID="DropDownListClientType" runat="server" DataSourceID="ObjectDataSourceClientType"></asp:DropDownList>

                <asp:ObjectDataSource ID="ObjectDataSourceClientType" runat="server" SelectMethod="getClientTypes" TypeName="AfariaAPI201.AfariaHelper"></asp:ObjectDataSource>

            </div>

            <div><asp:Button ID="ButtonGetCode" runat="server" Text="Get Code" OnClick="ButtonGetCode_Click" /></div>

                <div>

                    <asp:Label ID="LabelUserInstructions" runat="server" Text="" Enabled="False"></asp:Label><br />

                    <asp:HyperLink ID="HyperLinkMDMFirstUrl" runat="server" Enabled="False" Visible="False">HyperLink</asp:HyperLink>

                </div>

                <div>

                    <br /><br />

                    <asp:Label ID="LabelUserWarning" runat="server" Text="" Font-Bold="True" ForeColor="Red" Enabled="False"></asp:Label>

                </div>

            </form>

        </body>

    </html>

  5. In Index.aspx.cs, add a private void function called setHyperlinkEnrollmentLink, which will set the NavigateUrl, Text, Enabled and Visible values for the HyperLinkEnrollmentLink based on a passed string. Set the previous code which did this for iOS to call the new function instead.
  6. Modify getEnrollmentUrl() to take an extra parameter of ClientType, with a default ClientType of ClientType.Ios. and change the line calling getActivationID to reflect the new parameter. After this, inside the if statement checking if activationID is not null, add a line to remove the spaces from the activationID, so that this doesn't have to be done under each client type.

    public string getEnrollmentUrl(string userAccount, string enrollCode, string userEmail, ClientType deviceType = ClientType.Ios)

    {

      string url = string.Empty;

      string activationID = string.Empty;

      activationID = getActivationID(userAccount, enrollCode, userEmail, deviceType);

      if (!(string.IsNullOrEmpty(activationID)) && (isPolicyServiceOperable()))

      {

          activationID = activationID.replace(" ", string.empty);

    ...

  7. Modify the line getting the object plcySettings to be of the more generic type EnrollmentPolicySettings, we will change the type of enrollment policy setting later based on the ClientType.
  8. Add a switch on the ClientType parameter to getEnrollmentUrl(), so that we can return different values based on requested ClientType.

    AfariaPolicy.DataState ds = svcPolicy.OpenPolicy(enrollCode);

    EnrollmentPolicySettings plcySettings = svcPolicy.EnrollmentGetPolicySettings(ds);

    svcPolicy.Release(ds);

    if (plcySettings != null)

    {

        switch (deviceType)

        {

              case ClientType.Ios:

                  url = ((EnrollmentPolicySettingsIos)plcySettings).MdmEnrollmentUrl;

                  url = url.Replace(enrollCode, activationID);

                  break;

              case ClientType.Android:

                  url = "afaria://e=" + activationID;

                  break;

              case ClientType.WinPhone:

                  url = ((EnrollmentPolicySettingsWinPhone)plcySettings).MdmEnrollmentUrl;

                  url = url.Replace(enrollCode, activationID);

                  break;

              default:

                  return string.Empty; //not supported at this time

        }

    }

    else

    {

        throw new Exception("Specified enrollment code is invalid.");

    }

    1. Modify the previously existing code which prepared the url string, so that plcySettings is cast as EnrollmentPolicySettingsIos. Move the code modifying the url string inside of the switch for case ClientType.Ios.
    2. For ClientType.Android, set the url to "afaria://e=" + activationID. This will redirect into the client from the url.
    3. For ClientType.WinPhone, cast plcySettings to type EnrollmentPolicySettingsWinPhone and get the MdmEnrollmentUrl property. As with iOS, on the url, string replace enrollmentCode with activationID.
  9. Add a service reference for the ServerPorperties Service, following the instructions given in Afaria 101 and call it AfariaServerProps. We won't add an using statement to the project to keep from creating ambiguous references between AfariaServerProperties and AfariaPolicy.
  10. In AfariaHelper, add an instance variable for the AfariaServer.ServerPropertiesServiceClient called svcServerProperties.
  11. Add a function to the AfariaHelper called initServerPropertiesService that takes no parameters. Copy initPolicyService and modify to initiate a service channel for the ServerProperties service. Since SetTenantIdContext will be likely to have been called prior to this function, we can check to make sure that the TenantID is specified in the ContextInfo and skip the call if so.

    protected void initServerPropertiesService()

    {

        svcServerProperties = new AfariaServerProperties.ServerPropertiesServiceClient("NetTcpBinding_IServerPropertiesService"

                                                          , "net.tcp://" + APIaddress + ":7982/AfariaService/ServerProperties");

        svcServerProperties.ClientCredentials.Windows.ClientCredential.Domain = APIdomain;

        svcServerProperties.ClientCredentials.Windows.ClientCredential.UserName = APIaccount;

        svcServerProperties.ClientCredentials.Windows.ClientCredential.Password = APIpassword;

        AfariaServerProperties.ContextInfo ci = svcServerProperties.InitContext(contextID);

        if (ci.TenantId == -1) //TenantId not set

        {

              svcServerProperties.SetTenantIdContext(TenantID);

        }

        contextCount++;

    }

  12. Similar to the previous step, Add a function to the AfariaHelper called isServerPropertiesServiceOperable that takes no parameters. Copy isPolicyServiceOperable and modify for the ServerProperties service channel.
  13. In AfariaHelper, create a new function called getNewPortalGUID which takes a string (the Portal's name) and returns a string.
    1. Call isServerPropertiesServiceOperable to make sure whether the service is available and to determine whether to continue further.
    2. Call svcServerProperties.AddSelfServicePortal with the passed string to create the Portal in Afaria and to get the GUID assigned to the portal. This call makes it possible to use the Afaria Administrator to modify the enrollment codes used by the Portal, as you would with the standard Self Service Portal.
    3. Convert the returned GUID from step 2 to a string and return this value.

      public string getNewPortalGUID(string portalName)

      {

          string outString = string.Empty;

          if (!string.IsNullOrWhiteSpace(portalName))

          {

                if (isServerPropertiesServiceOperable())

                {

                    Guid portalGUID = svcServerProperties.AddSelfServicePortal(portalName);

                    outString = portalGUID.ToString();

                }

                else

                {

                    throw new Exception("ServerProperties Service is not operable");

                }

          }

          return outString;

      }

  14. In AfariaHelper, create a new function called getPortalProperties which takes a string (the Portal's GUID) and returns a Dictionary<string, string>.
    1. Using the passed string, generate a new GUID
    2. Call GetSelfServicePortalConfigurations with the new GUID and save the output to a SelfServicePortalConfiguration array named sspConfigs. If the length of this is greater than 1, that means that there is no existing SSP tied to the passed GUID. If one row is returned, the SSP exists, and we can return the enrollment codes associated with the specified SSP. The data returned by this call has information about the Portal being used, but more importantly for this project, it contains the enrollment codes for the portal.
    3. Add each enrollment code in  sspConfigs.enrollmentCodes.EnrollmentCodes to the dictionary to return from the function.

      public Dictionary<string, string> getPortalCodes(string portalGUID)

      {

          Dictionary<string, string> outDict = new Dictionary<string, string>();

          if (!string.IsNullOrWhiteSpace(portalGUID))

          {

                Guid guid = new Guid();

                try

                {

                    guid = new Guid(portalGUID);

                }

                catch (FormatException)

                {

                    throw new Exception("Portal GUID is invalid.");

                }

                catch (OverflowException)

                {

                    throw new Exception("Portal GUID is invalid.");

                }

                AfariaServerProperties.SelfServicePortalConfiguration[] sspConfigs;

                sspConfigs = svcServerProperties.GetSelfServicePortalConfigurations(new Guid[] { guid });

                if (sspConfigs.Length == 1)

                {

                    foreach (AfariaServerProperties.SelfServicePortalEnrollmentCodeInfo code in sspConfigs[0].EnrollmentCodes)

                    {

                          outDict.Add(code.ClientType.ToString(), code.EnrollmentCode);

                    }

                }

                else

                {

                    throw new Exception("Portal does not exist for this GUID.");

                }

          }

          return outDict;

      }

  15. In the constructor for AfariaHelper, add a call to initServerPropertiesService, so that it will be available.
  16. Back in the main class, add a new function called SetConfigurationSetting, which takes a key and value, which will modify the web.config file to insert or modify the passed setting. Below is an example:

    private void setConfigSetting(string key, string value)

    {

        System.Configuration.Configuration config = null;

        try

        {

              config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");

              config.AppSettings.Settings[key].Value = value;

              config.Save();

        }

        catch (NullReferenceException ex)

        {

              //add key, it doesn't exist

              if(config != null)

              {

                  config.AppSettings.Settings.Add(key, value);

                  config.Save();

              }

        }

        catch(Exception ex)

        {

              System.Diagnostics.Debug.WriteLine("Exception Message: " + ex.Message + "\r\nException Stack: " + ex.StackTrace);

              throw ex;

        }

    }

  17. In the Page_Load function:
    1. Comment out or delete the lines that previously existed in Page_Load, which selected iOS client and disabled selection with the DropDownListClientType.
    2. Create an instance of the AfariaHelper object which will be disposed of at the end of the function.
    3. Retrieve the GUID of the Portal from the config settings.
    4. If the returned GUID is not null, get the codes by calling the Afaria Helper's getPortalCodes method from above with the GUID, and save the enrollment codes to a dictionary. No other work is necessary if the GUID is specified.
    5. If the returned GUID is null, that means that this is a new Portal and will need to initiate it's settings on the server.
    6. Retrieve the Portal's name from the config settings (if present). If it isn't present call setConfigSetting with a default name to set the value.
    7. Call the Afaria Helper's getNewPortalGUID method with the portal's name from step 5.
    8. Call setConfigSetting with the new GUID from step 6 for future use.
    9. Set UI elements to warn the user that the portal had not been configured. At this point, the portal is configurable through the Admin UI, so enrollment codes should be chosen, just as with the standard SAP Afaria Portal.

      using (AfariaHelper apiHelper = new AfariaHelper(getConfigSetting("AfariaAPIServiceAccountDomain")

                                                  , getConfigSetting("AfariaAPIServiceAccountUsername")

                                                  , getConfigSetting("AfariaAPIServiceAccountPassword")

                                                  , getConfigSetting("AfariaAPIServiceAddress")))

      {

          string sspGUID = getConfigSetting("AfariaSSPGUID");

          if (string.IsNullOrWhiteSpace(sspGUID))

          {

                string sspName = getConfigSetting("AfariaSSPName");

                if(string.IsNullOrWhiteSpace(sspName))

                {

                    sspName = "NewCustomPortal";

                    setConfigSetting("AfariaSSPName", sspName);

                }

                sspGUID = apiHelper.getNewPortalGUID(sspName);

                setConfigSetting("AfariaSSPGUID", sspGUID);

                resetUI();

                ButtonGetCode.Enabled = false;

                LabelUserWarning.Text = "Portal not configured. Please contact support. REF:SSP=[" + sspName + "]";

          }

          else

          {

                m_codeDict = apiHelper.getPortalCodes(sspGUID);

          }

      }

  18. In Index.aspx and Index.aspx.cs, rename the Label, HyperLinkMDMFirstUrl to HyperLinkEnrollmentLink, so that it more accurately reflects the general nature of the hyperlink, as it will be used for redirecting the the Afaria client in iOS and Android.
  19. In the ButtonGetCode_Click function:
    1. Add a switch for possible selection values around the code in ButtonGetCode_Click, which got the URL and set UI elements related to it. By default, set the Label from  to reflect unsupported client type for types.
    2. In the switch, for client types iOS, Android and WindowsPhone, call SetHyperlinkEnrollmentLink with a parameter of a call to getEnrollmentUrl whose parameters will be: the text from TextBoxUsername, the enrollment code from our dictionary created in step 17.4, and the text from TextBoxEmailAddress.
    3. Set the instructions for LabelUserInstructions as necessary for each type.
    4. For Windows Mobile, the code should be presented to the user in LabelUserInstructions, simply use the code from the dictionary.

      switch(DropDownListClientType.SelectedValue)

      {

          case "Ios":

                setHyperlinkEnrollmentLink(apiHelper.getEnrollmentUrl(TextBoxUserName.Text,

                    m_codeDict["Ios"],

                    TextBoxEmailAddress.Text));

                LabelUserInstructions.Text = "Click on the below URL and follow the prompts to enroll.";

                break;

          case "Android":

                setHyperlinkEnrollmentLink(apiHelper.getEnrollmentUrl(TextBoxUserName.Text,

                    m_codeDict["Android"],

                    TextBoxEmailAddress.Text,

                    ClientType.Android));

                LabelUserInstructions.Text = "Download the Afaria client from the Google Play store, and return to this page and click on the below link.";

                break;

          case "WinPhone":

                setHyperlinkEnrollmentLink(apiHelper.getEnrollmentUrl(TextBoxUserName.Text,

                    m_codeDict["WinPhone"],

                    TextBoxEmailAddress.Text,

                    ClientType.WinPhone));

                LabelUserInstructions.Text = "Copy the Enrollment Code URL below to enter it into the Server address field on Company Apps of your device.";

                LabelUserInstructions.Enabled = true;

                break;

          case "WinMobileProfessional":

                LabelUserInstructions.Text = "Copy the Enrollment Code following to enter it into the client on your device for enrollment:";

                LabelUserInstructions.Text += "\r\n\r\n" + m_codeDict["WinMobileProfessional"];

                LabelUserInstructions.Enabled = true;

                break;

          case "WinMobileStandard":

                LabelUserInstructions.Text = "Copy the Enrollment Code following to enter it into the client on your device for enrollment:";

                LabelUserInstructions.Text += "\r\n\r\n" + m_codeDict["WinMobileStandard"];

                LabelUserInstructions.Enabled = true;

                break;

          case "Win32":

          case "BlackBerry":

          default:

                LabelUserWarning.Text += "\r\nUnsupported Client Type.";

                break;

      }

  20. The Portal is now ready... time for QA!

Full Example Program

  • Index.aspx.cs

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Web;

    using System.Web.UI;

    using System.Web.UI.WebControls;

    using AfariaAPI201.AfariaPolicy;

    using AfariaAPI201;

    namespace AfariaAPI201

    {

        public partial class index : System.Web.UI.Page

        {

            Dictionary<string, string> m_codeDict;

            protected void Page_Load(object sender, EventArgs e)

            {

                //DropDownListClientType.Enabled = false;

                //DropDownListClientType.SelectedIndex = 2;

                using (AfariaHelper apiHelper = new AfariaHelper(getConfigSetting("AfariaAPIServiceAccountDomain")

                                                    , getConfigSetting("AfariaAPIServiceAccountUsername")

                                                    , getConfigSetting("AfariaAPIServiceAccountPassword")

                                                    , getConfigSetting("AfariaAPIServiceAddress")))

                {

                  string sspGUID = getConfigSetting("AfariaSSPGUID");

          

                    if (string.IsNullOrWhiteSpace(sspGUID))

                    {

                        string sspName = getConfigSetting("AfariaSSPName");

                        if(string.IsNullOrWhiteSpace(sspName))

                        {

                            sspName = "NewCustomPortal";

                            setConfigSetting("AfariaSSPName", sspName);

                        }

                        sspGUID = apiHelper.getNewPortalGUID(sspName);

                        setConfigSetting("AfariaSSPGUID", sspGUID);

                        resetUI();

                        ButtonGetCode.Enabled = false;

                        LabelUserWarning.Text = "Portal not configured. Please contact support. REF:SSP=[" + sspName + "]";

                    }

                    else

                    {

                        m_codeDict = apiHelper.getPortalCodes(sspGUID);

                    }

                }

            }

            protected void ButtonGetCode_Click(object sender, EventArgs e)

            {

                resetUI();

                try

                {

                    using (AfariaHelper apiHelper = new AfariaHelper(getConfigSetting("AfariaAPIServiceAccountDomain")

                                                                    , getConfigSetting("AfariaAPIServiceAccountUsername")

                                                                    , getConfigSetting("AfariaAPIServiceAccountPassword")

                                                                    , getConfigSetting("AfariaAPIServiceAddress")))

                    {

                        switch(DropDownListClientType.SelectedValue)

                        {

                            case "Ios":

                                setHyperlinkEnrollmentLink(apiHelper.getEnrollmentUrl(TextBoxUserName.Text,

                                    m_codeDict["Ios"],

                                    TextBoxEmailAddress.Text));

                                LabelUserInstructions.Text = "Click on the below URL and follow the prompts to enroll.";

                                break;

                            case "Android":

                                setHyperlinkEnrollmentLink(apiHelper.getEnrollmentUrl(TextBoxUserName.Text,

                                    m_codeDict["Android"],

                                    TextBoxEmailAddress.Text,

                                    ClientType.Android));

                                LabelUserInstructions.Text = "Download the Afaria client from the Google Play store, and return to this page and click on the below link.";

                                break;

                            case "WinPhone":

                                setHyperlinkEnrollmentLink(apiHelper.getEnrollmentUrl(TextBoxUserName.Text,

                                    m_codeDict["WinPhone"],

                                    TextBoxEmailAddress.Text,

                                    ClientType.WinPhone));

                                LabelUserInstructions.Text = "Copy the Enrollment Code URL below to enter it into the Server address field on Company Apps of your device.";

                                LabelUserInstructions.Enabled = true;

                                break;

                            case "WinMobileProfessional":

                                LabelUserInstructions.Text = "Copy the Enrollment Code following to enter it into the client on your device for enrollment:";

                                LabelUserInstructions.Text += "\r\n\r\n" + m_codeDict["WinMobileProfessional"];

                                LabelUserInstructions.Enabled = true;

                                break;

                            case "WinMobileStandard":

                                LabelUserInstructions.Text = "Copy the Enrollment Code following to enter it into the client on your device for enrollment:";

                                LabelUserInstructions.Text += "\r\n\r\n" + m_codeDict["WinMobileStandard"];

                                LabelUserInstructions.Enabled = true;

                                break;

                            case "Win32":

                            case "BlackBerry":

                            default:

                                LabelUserWarning.Text += "\r\nUnsupported Client Type.";

                                break;

                        }

                    }

                }

                catch (Exception ex)

                {

                    System.Diagnostics.Trace.WriteLine(ex.Message);

                    System.Diagnostics.Trace.WriteLine(ex.StackTrace);

                    LabelUserWarning.Text += "\r\nAn error occurred while processing, please try again and notify Support if this message persists.";

                }

            }

            private void setHyperlinkEnrollmentLink(string url)

            {

                HyperLinkEnrollmentLink.NavigateUrl = url;

                HyperLinkEnrollmentLink.Text = url;

                HyperLinkEnrollmentLink.Enabled = true;

                HyperLinkEnrollmentLink.Visible = true;

            }

            private string getConfigSetting(string setting)

            {

                string value = string.Empty;

                if (System.Configuration.ConfigurationManager.AppSettings.Count > 0)

                {

                    value = System.Configuration.ConfigurationManager.AppSettings[setting];

                }

                return value;

            }

            private void setConfigSetting(string key, string value)

            {

                System.Configuration.Configuration config = null;

                try

                {

                    config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");

                    config.AppSettings.Settings[key].Value = value;

                    config.Save();

                }

                catch (NullReferenceException ex)

                {

                    //add key, it doesn't exist

                    if(config != null)

                    {

                        config.AppSettings.Settings.Add(key, value);

                        config.Save();

                    }

                }

                catch(Exception ex)

                {

                    System.Diagnostics.Debug.WriteLine("Exception Message: " + ex.Message + "\r\nException Stack: " + ex.StackTrace);

                    throw ex;

                }

            }

            private void resetUI()

            {

                LabelUserWarning.Text = string.Empty;

                HyperLinkEnrollmentLink.Text = string.Empty;

                HyperLinkEnrollmentLink.NavigateUrl = string.Empty;

                HyperLinkEnrollmentLink.Enabled = false;

                HyperLinkEnrollmentLink.Visible = false;

                LabelUserInstructions.Text = string.Empty;

                LabelUserInstructions.Enabled = false;

            }

        }

        public class AfariaHelper : IDisposable

        {

            public string contextID { get; private set; }

            int contextCount;

            string APIdomain, APIaccount, APIpassword, APIaddress;

            PolicyServiceClient svcPolicy;

            AfariaServerProperties.ServerPropertiesServiceClient svcServerProperties;

          bool disposed = false;

            int TenantID;

    #region Static Methods

            public static List<string> getClientTypes()

            {

                List<string> types = new List<string>();

                foreach (string type in Enum.GetNames(typeof(ClientType)))

                {

                    if (type != "All" && type != "Undefined")

                    {

                        types.Add(type);

                    }

                }

                return types;

            }

    #endregion Statics

    #region Public Instance Methods & Constructor/Destructor

            public AfariaHelper(string APIdomain, string APIaccount, string APIpassword, string APIaddress = "127.0.0.1", int TenantID = 0)

            {

                this.APIdomain = APIdomain;

                this.APIaccount = APIaccount;

                this.APIpassword = APIpassword;

                this.APIaddress = APIaddress;

                this.TenantID = TenantID;

                contextID = Guid.NewGuid().ToString();

                contextCount = 0;

                initPolicyService();

                initServerPropertiesService();

            }

            public void Dispose()

            {

                Dispose(true);

            }

            protected void Dispose(bool disposing)

            {

                if (disposed)

                {

                    return;

                }

                if (disposing)

                {

                    contextCleanup();

                    if (svcPolicy != null)

                    {

                        svcPolicy.Close();

                        svcPolicy = null;

                    }

                }

                disposed = true;

            }

            public string getEnrollmentUrl(string userAccount, string enrollCode, string userEmail, ClientType deviceType = ClientType.Ios)

            {

                string url = string.Empty;

                string activationID = string.Empty;

                activationID = getActivationID(userAccount, enrollCode, userEmail, deviceType);

                if (!(string.IsNullOrEmpty(activationID)) && (isPolicyServiceOperable()))

                {

                    activationID = activationID.Replace(" ", string.Empty); //remove spaces from returned activation ID

                    AfariaPolicy.DataState ds = svcPolicy.OpenPolicy(enrollCode);

                    EnrollmentPolicySettings plcySettings = svcPolicy.EnrollmentGetPolicySettings(ds);

                    svcPolicy.Release(ds);

                    if (plcySettings != null)

                    {

                        switch (deviceType)

                        {

                            case ClientType.Ios:

                                url = ((EnrollmentPolicySettingsIos)plcySettings).MdmEnrollmentUrl;

                                url = url.Replace(enrollCode, activationID);

                                break;

                            case ClientType.Android:

                                url = "afaria://e=" + activationID;

                                break;

                            case ClientType.WinPhone:

                                url = ((EnrollmentPolicySettingsWinPhone)plcySettings).MdmEnrollmentUrl;

                                url = url.Replace(enrollCode, activationID);

                                break;

                            default:

                                return string.Empty; //not supported at this time

                        }

                    }

                    else

                    {

                        throw new Exception("Specified enrollment code is invalid.");

                    }

                    return url;

                }

                else

                {

                    throw new Exception("Policy Service is not operable");

                }

            }

            public string getActivationID(string userAccount, string enrollCode, string userEmail, ClientType deviceClientType)

            {

                string output = string.Empty;

                if (isPolicyServiceOperable())

                {

                    EnrollmentCodeActivationIdInfo activationID = svcPolicy.EnrollmentCodeGenerateActivationIdWithAddress(userAccount, enrollCode, userEmail, deviceClientType);

                    output = activationID.CompleteActivationId;

                }

                else

                {

                    throw new Exception("Policy Service is not operable");

                }

                return output;

            }

            public string getNewPortalGUID(string portalName)

            {

                string outString = string.Empty;

                if (!string.IsNullOrWhiteSpace(portalName))

                {

                    if (isServerPropertiesServiceOperable())

                    {

                        Guid portalGUID = svcServerProperties.AddSelfServicePortal(portalName);

                        outString = portalGUID.ToString();

                    }

                    else

                    {

                        throw new Exception("ServerProperties Service is not operable.");

                    }

                }

                return outString;

            }

            public Dictionary<string, string> getPortalCodes(string portalGUID)

            {

                Dictionary<string, string> outDict = new Dictionary<string, string>();

                if (!string.IsNullOrWhiteSpace(portalGUID))

                {

                    Guid guid = new Guid();

                    try

                    {

                        guid = new Guid(portalGUID);

                    }

                    catch (FormatException)

                    {

                        throw new Exception("Portal GUID is invalid.");

                    }

                    catch (OverflowException)

                    {

                        throw new Exception("Portal GUID is invalid.");

                    }

                    AfariaServerProperties.SelfServicePortalConfiguration[] sspConfigs;

                    sspConfigs = svcServerProperties.GetSelfServicePortalConfigurations(new Guid[] { guid });

                    if (sspConfigs.Length == 1)

                    {

                        foreach (AfariaServerProperties.SelfServicePortalEnrollmentCodeInfo code in sspConfigs[0].EnrollmentCodes)

                        {

                            outDict.Add(code.ClientType.ToString(), code.EnrollmentCode);

                        }

                    }

                    else

                    {

                        throw new Exception("Portal does not exist for this GUID.");

                    }

                }

                return outDict;

            }

    #endregion Public Instance Methods & Constructor/Destructor

    #region Protected/Private Instance Methods

            protected void initPolicyService()

            {

                svcPolicy = new PolicyServiceClient("NetTcpBinding_IPolicyService", "net.tcp://" + APIaddress + ":7982/AfariaService/Policy");

                svcPolicy.ClientCredentials.Windows.ClientCredential.Domain = APIdomain;

                svcPolicy.ClientCredentials.Windows.ClientCredential.UserName = APIaccount;

                svcPolicy.ClientCredentials.Windows.ClientCredential.Password = APIpassword;

                ContextInfo ci = svcPolicy.InitContext(contextID);

                svcPolicy.SetTenantIdContext(TenantID);

                contextCount++;

            }

            protected void initServerPropertiesService()

            {

                svcServerProperties = new AfariaServerProperties.ServerPropertiesServiceClient("NetTcpBinding_IServerPropertiesService"

                                                        , "net.tcp://" + APIaddress + ":7982/AfariaService/ServerProperties");

                svcServerProperties.ClientCredentials.Windows.ClientCredential.Domain = APIdomain;

                svcServerProperties.ClientCredentials.Windows.ClientCredential.UserName = APIaccount;

                svcServerProperties.ClientCredentials.Windows.ClientCredential.Password = APIpassword;

                AfariaServerProperties.ContextInfo ci = svcServerProperties.InitContext(contextID);

                if (ci.TenantId == -1) //TenantId not set

                {

                    svcServerProperties.SetTenantIdContext(TenantID);

                }

                contextCount++;

            }

            protected bool isPolicyServiceOperable()

            {

                bool ret = false;

                if (svcPolicy != null)

                {

                    if (svcPolicy.State == System.ServiceModel.CommunicationState.Faulted)

                    {

                        svcPolicy.Abort();

                        contextCleanup();

                        svcPolicy = null;

                        try

                        {

                            initPolicyService();

                            ret = true;

                        }

                        catch (Exception ex)

                        {

                            throw new Exception("Error initializing service in isPolicyServiceOperable.", ex);

                        }

                    }

                    else if (svcPolicy.State == System.ServiceModel.CommunicationState.Opened)

                    {

                        ret = true;

                    }

                }

                return ret;

            }

            protected bool isServerPropertiesServiceOperable()

            {

                bool ret = false;

                if (svcServerProperties != null)

                {

                    if (svcServerProperties.State == System.ServiceModel.CommunicationState.Faulted)

                    {

                        svcServerProperties.Abort();

                        contextCleanup();

                        svcServerProperties = null;

                        try

                        {

                            initServerPropertiesService();

                            ret = true;

                        }

                        catch (Exception ex)

                        {

                            throw new Exception("Error initializing service in isServerPropertiesServiceOperable.", ex);

                        }

                    }

                    else if (svcServerProperties.State == System.ServiceModel.CommunicationState.Opened)

                    {

                        ret = true;

                    }

                }

                return ret;

            }

            protected bool contextCleanup()

            {

                if (contextCount > 1)

                {

                    contextCount--;

                }

                else if (contextCount == 1 || contextCount == 0)

                {

                    PolicyServiceClient svcTemp = new PolicyServiceClient("NetTcpBinding_IPolicyService", "net.tcp://" + APIaddress + ":7982/AfariaService/Policy");

                    svcTemp.ClientCredentials.Windows.ClientCredential.Domain = APIdomain;

                    svcTemp.ClientCredentials.Windows.ClientCredential.UserName = APIaccount;

                    svcTemp.ClientCredentials.Windows.ClientCredential.Password = APIpassword;

                    svcTemp.InitContext(contextID);

                    svcTemp.CloseContext();

                    contextCount = 0;

                    return true;

                }

                else

                {

                    throw new Exception("We've lost track of our contexts!");

                }

                return false;

            }

    #endregion Protected/Private Instance Methods

        }

    }

  • Index.aspx

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="AfariaAPI201.index" %>

    <!DOCTYPE html>

    <html xmlns="http://www.w3.org/1999/xhtml">

    <head runat="server">

        <title>AfariaAPI-SSP</title>

    </head>

        <body>

            <form id="form1" runat="server">

            <div>

                <asp:Label ID="LabelUserName" runat="server" Text="UserName:"></asp:Label>

                <asp:TextBox ID="TextBoxUserName" runat="server"></asp:TextBox>

                <asp:Label ID="LabelEmailAddress" runat="server" Text="Email Address:"></asp:Label>

                <asp:TextBox ID="TextBoxEmailAddress" runat="server"></asp:TextBox>

                <asp:DropDownList ID="DropDownListClientType" runat="server" DataSourceID="ObjectDataSourceClientType"></asp:DropDownList>

                <asp:ObjectDataSource ID="ObjectDataSourceClientType" runat="server" SelectMethod="getClientTypes" TypeName="AfariaAPI201.AfariaHelper"></asp:ObjectDataSource>

            </div>

            <div><asp:Button ID="ButtonGetCode" runat="server" Text="Get Code" OnClick="ButtonGetCode_Click" /></div>

                <div>

                    <asp:Label ID="LabelUserInstructions" runat="server" Text="" Enabled="False"></asp:Label><br />

                    <asp:HyperLink ID="HyperLinkEnrollmentLink" runat="server" Enabled="False" Visible="False">HyperLink</asp:HyperLink>

                </div>

                <div>

                    <br /><br />

                    <asp:Label ID="LabelUserWarning" runat="server" Text="" Font-Bold="True" ForeColor="Red" Enabled="False"></asp:Label>

                </div>

            </form>

        </body>

    </html>