using System;
using System.Web.UI;
using System.Net;
using System.Xml;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
    // In this implementation sessionKey is public to the class 
    // The client page runat attribute is set to 'server' and has access to  
    // this variable. The client page will then access this variable with this call 
    // Dmp.Env.Connections["SS"].init("<%=sessionKey%>", afterInit); 
    // during page load. 
	
    public string sessionKey = "";
    protected void Page_Load(object sender, EventArgs e)
    {


        if (!this.IsPostBack)
        {
           
           
            

            try
            {
                // Replace with the parameters for your SpatialStream account 
                sessionKey = GetDMPSIK("<User name Here>", "<Account Name Here>", "<Group Name Here>", "http://spatialstream.com", "< Base Referer Here>"); 
            }
            catch (Exception ex)
            {
                // Handle authentication errors here
                throw ex;
            }

            
           
        }

    }

    /// <summary>
    /// Make a request to SpatialStream to retrieve an authentication token
    /// </summary>
    /// <param name="login">SpatialStream account login name</param>
    /// <param name="account">SpatialStream account name</param>
    /// <param name="group">SpatialStream group name. If unknown use Group1</param>
    /// <param name="loginURL"></param>
    /// <param name="baseReferer">Example: If your website is http://yourwebsite.com then use yourwebsite</param>
    /// <returns>authentication token GUID</returns>
    private static string GetDMPSIK(string login, string account, string group, string loginURL, string baseReferer)
    {
        // create request
        string sLoginRequest = loginURL + "/admin/getSIK.aspx?ACCOUNT=" + account + "&LOGIN=" + login + "&baseReferrer=" + baseReferer;

        HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(sLoginRequest);

        HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();
        XmlDocument responseXML = new XmlDocument();
        responseXML.Load(httpResponse.GetResponseStream());

        // check for authentication errors
        XmlNodeList resNodes = responseXML.SelectNodes("/Response/Error/@message");
        if (resNodes.Count != 0)
        {
           throw new ApplicationException("Error authenticating to service! Error=" + resNodes[0].InnerText);
        }

        // check for success
        resNodes = responseXML.SelectNodes("/Response/Success/@message");
        String authToken = "";
        if (resNodes.Count == 1)
        {
            authToken = resNodes[0].InnerText;
        }

        // return the authentication token
        return authToken;

    }
 

}