<%@ Page Language="C#" Debug="true" ValidateRequest="true" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Collections" %>
<%@ Import Namespace="System.Collections.Specialized" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Security.Cryptography" %>
<%@ Import Namespace="System.Text" %>


<script runat="server">
/**************************************************************
To enable the web based installer change the
line beneath this section to ‘true?

After running the installer it is highly recommended that you 
set this value back to false to disable unauthorized access.
**************************************************************/
bool INSTALLER_ENABLED = true;



// flag indicating that the web.config file was successfully updated. This only works if you have write access
// to your virtual directory.
bool updatedConfigFile = false;

//Flag for aspnet 2.0 membership (this requires that the site be using the aspnet 2.0 binaries under aspent 2.0)
bool use20Membership = true;

// consant string used to allow host to pass the database name to the wizard. If the database can be found in the 
// list of database returned, the wizard will skip the database selection page.
private const string QSK_DATABASE = "database"; // query string key

// arraylist of InstallerMessages. We contruct this on every page requrest to only keep track of the errors
// that have occurred during this web request. We don't store it in viewstate because we only want the errors
// that have happened on each page request
private ArrayList messages;

// Class to encapsulate the module (method) along with the error message that occurred within the module(method)
public class InstallerMessage {
	public string Module;
	public string Message;
	
	public InstallerMessage( string module, string message ) {
		Module = module;
		Message = message;
	}
};


public WizardPanel CurrentWizardPanel {
	get {
		if (ViewState["WizardPanel"] != null)
			return (WizardPanel) ViewState["WizardPanel"];

		return WizardPanel.Welcome;
	}
	set {
		ViewState["WizardPanel"] = value;		
	}
}

protected string ValidationKey
{
	get
	{
		string key = ViewState["ValidationKey"] as string;
		if(key == null)
		{
			key = CreateKey(20);
			ViewState["ValidationKey"] = key;
		}
		return key;	
	}
}

protected string DecryptionKey
{
	get
	{
		string key = ViewState["DecryptionKey"] as string;
		if(key == null)
		{
			key = CreateKey(24);
			ViewState["DecryptionKey"] = key;
		}
		return key;	
	}
}

protected string DatabasePassword
{
	get
	{
		string pass = ViewState["dbPass"] as string;
		if(pass  == null)
		{
			pass  = "";
			ViewState["dbPass"] = pass;
		}
		return pass;	
	}
	set
	{
		ViewState["dbPass"] = value;
	}
}

public enum WizardPanel {
	Welcome,
	License,
	ConnectToDb,
	SelectDb,
	ScriptOptions,
	CreateCommunity,
	Done,
	SchemaExists,
	Errors,
}


void HideAllPanels() {
	Welcome.Visible = false;
	License.Visible = false;
	ConnectToDb.Visible = false;
	CreateCommunity.Visible = false;
	Done.Visible = false;
	Errors.Visible = false;
}

public void Page_Load() {
	// We use the installer enabled flag to prevent someone from accidentally running the web installer, or
	// someone trying to maliciously trying to run the installer 
	if (!INSTALLER_ENABLED) {
		Response.Write("<h1>Community Server Installation Wizard is disabled.</h1>");
		Response.Flush();
		Response.End();
	}
	else {
		messages = new ArrayList();

		if (!Page.IsPostBack)
			SetActivePanel (WizardPanel.Welcome, Welcome);
	}
}

public void ReportException( string module, Exception e ) {
	ReportException( module, e.Message );
}

public void ReportException( string module, string message ) {
	messages.Add( new InstallerMessage( module, message ));
}

void SetActivePanel (WizardPanel panel, Control controlToShow) {

	Panel currentPanel = FindControl(CurrentWizardPanel.ToString()) as Panel;
	if( currentPanel != null )
		currentPanel.Visible = false;
	
	switch( panel ) {
		case WizardPanel.Welcome:
			Previous.Enabled = false;
			License.Visible = false;
			break;
		case WizardPanel.Done:
			Next.Enabled = false;
			Previous.Enabled = false;
			pnl20Membership.Visible = use20Membership;
			break;
		case WizardPanel.SchemaExists:
			Previous.Enabled = true;
			Next.Enabled = false;
			break;
		case WizardPanel.Errors:
			Previous.Enabled = false;
			Next.Enabled = false;
			break;
		default:
			Previous.Enabled = true;
			Next.Enabled = true;
			break;
	}

	controlToShow.Visible = true;
	CurrentWizardPanel = panel;

}

private bool InstallDatabase() {
	bool retValue = false;
	
	if( chkScriptMemberRoles.Checked ) {
		if( !ExecuteSqlInFile( Server.MapPath("SqlScripts/InstallCommon.sql"))) return false;
		
		if( !ExecuteSqlInFile( Server.MapPath("SqlScripts/InstallMembership.sql"))) return false;
		
		if( !ExecuteSqlInFile( Server.MapPath("SqlScripts/InstallProfile.sql"))) return false;
		
		if( !ExecuteSqlInFile( Server.MapPath("SqlScripts/InstallRoles.sql"))) return false;

		if(use20Membership)
			if( !ExecuteSqlInFile( Server.MapPath("SqlScripts/InstallMembership2.sql"))) return false;
	}
	

	// create the community server schema
	if( chkScriptCommunity.Checked ) {
		
		if( !ExecuteSqlInFile( Server.MapPath("SqlScripts/cs_Schema.sql"))) return false;
		
		if( !ExecuteSqlInFile( Server.MapPath("SqlScripts/cs_Default.sql"))) return false;

		if( !ExecuteSqlInFile( Server.MapPath("SqlScripts/cs_UpdateSchemaAndProcedures.sql"))) return false;
	}
	
	// we might not have dbo access, so we need to ensure that our user is a member of the 
	// aspnet database roles
	if( !AddUserToRole("aspnet_Roles_FullAccess") ) return false;
	
	if( !AddUserToRole("aspnet_Profile_FullAccess") ) return false;
	
	if( !AddUserToRole("aspnet_Membership_FullAccess" ) ) return false;

	if( chkCreateCommunity.Checked ) {
		if( !ExecuteCreateCommunity()) return false;
	}

	// try to update the web.config file with the new connection string. No big deal if we can't
	UpdateWebConfig();

	return true;
}

protected bool UpdateWebConfig() {
	bool returnValue = false;
	try {
		System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
		if( doc == null ) 
			return false;
		
		doc.PreserveWhitespace  = true;
		
		string configFile = HttpContext.Current.Server.MapPath("~/web.config");
		
		doc.Load(configFile);
		bool dirty = false;


		if(use20Membership)
		{
		System.Xml.XmlNode connectionStrings = doc.SelectSingleNode("configuration/connectionStrings");
		foreach( System.Xml.XmlNode setting in connectionStrings ) {
			if( setting.Name == "add" ) {
				System.Xml.XmlAttribute attrKey = setting.Attributes["name"];
				if( attrKey != null)
				{
					if(attrKey.Value == "SiteSqlServer" ) 
					{					
						System.Xml.XmlAttribute attrSqlValue = setting.Attributes["connectionString"];
						if( attrSqlValue != null ) 
						{
							attrSqlValue.Value = GetDatabaseConnectionString();
							dirty = true;
					
						}	
					}

				}
			}
		}
		}

		System.Xml.XmlNode appSettings = doc.SelectSingleNode("configuration/appSettings");
		foreach( System.Xml.XmlNode setting in appSettings ) {
			if( setting.Name == "add" ) {
				System.Xml.XmlAttribute attrKey = setting.Attributes["key"];
				if( attrKey != null)
				{
					if(attrKey.Value == "SiteSqlServer" ) 
					{					
						System.Xml.XmlAttribute attrSqlValue = setting.Attributes["value"];
						if( attrSqlValue != null ) 
						{
							attrSqlValue.Value = GetDatabaseConnectionString();
							dirty = true;
					
						}	
					}
					else if(attrKey.Value == "MachineValidationKey")
					{
						System.Xml.XmlAttribute attrMVKValue = setting.Attributes["value"];
						if( attrMVKValue != null ) 
						{
							attrMVKValue.Value = ValidationKey;
							dirty = true;
					
						}	

					}
					else if(attrKey.Value == "MachineDecryptionKey")
					{
						System.Xml.XmlAttribute attrMDKValue = setting.Attributes["value"];
						if( attrMDKValue != null ) 
						{
							attrMDKValue.Value = DecryptionKey;
							dirty = true;
					
						}	

					}

				}
			}
		}
		
		if( dirty ) {
			// Save the document to a file and auto-indent the output.
			System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(configFile, System.Text.Encoding.UTF8);
			writer.Formatting = System.Xml.Formatting.Indented;
			doc.Save(writer);
			
			updatedConfigFile = true;
		}
	}
	catch(Exception e ) {
		ReportException("UpdateWebConfig", e );
	}
	
	return returnValue;
}

	protected string CreateKey(int len)
	{
            byte[] bytes = new byte[len];
            new RNGCryptoServiceProvider().GetBytes(bytes);
            
			StringBuilder sb = new StringBuilder();
			for(int i = 0; i < bytes.Length; i++)
			{	
				sb.Append(string.Format("{0:X2}",bytes[i]));
			}
			
			return sb.ToString();
	}

protected bool AddUserToRole( string roleName ) {
	bool returnValue = false;
	using( SqlConnection connection = new SqlConnection(GetDatabaseConnectionString()) ) {
		connection.Open();
		
		SqlCommand cmd = new SqlCommand(
			"declare @username sysname "															+ Environment.NewLine + 
			"set @username = USER "																	+ Environment.NewLine + 
			"if( @username <> 'dbo' ) "																+ Environment.NewLine + 
			"begin "																				+ Environment.NewLine + 
			"    declare @statement varchar(2000) "													+ Environment.NewLine + 
			"    set @statement = 'sp_addrolemember N''" + roleName + "'', ''' + @username + ''''"	+ Environment.NewLine + 
			"    exec(@statement)"																	+ Environment.NewLine + 
			"end" 
			, connection);
		
		cmd.CommandType = CommandType.Text;
		int recordsAffected = 0;
		try {
			recordsAffected = cmd.ExecuteNonQuery();
			
			returnValue = true;
		}
		catch(Exception e ) {
			ReportException( "AddUserToRole:" + roleName, e );
		}
	}
	
	return returnValue;
}
public bool IsSchemaExisting() {
	bool returnValue = false;
	using( SqlConnection connection = new SqlConnection(GetDatabaseConnectionString()) ) {
		connection.Open();
		
		SqlCommand cmd = new SqlCommand("select count(*) from cs_SchemaVersion", connection);
		
		cmd.CommandType = CommandType.Text;
		SqlDataReader reader = null;
		try {
			reader = cmd.ExecuteReader();
		}
		catch(Exception e ) {
			ReportException( "IsSchemaExisting", e );
		}
		
		if( reader != null ) {
			reader.Read();
			
			if( reader[0] != null && Int32.Parse(reader[0].ToString()) > 0 ) {
				returnValue = true;
			}
		}
	}
	
	return returnValue;
}

public bool IsForumsSchemaExisting() {
	bool returnValue = false;
	using( SqlConnection connection = new SqlConnection(GetDatabaseConnectionString()) ) {
		connection.Open();
		
		SqlCommand cmd = new SqlCommand("select count(*) from forums_Users", connection);
		
		cmd.CommandType = CommandType.Text;
		SqlDataReader reader = null;
		try {
			reader = cmd.ExecuteReader();

			if( reader != null ) {
				reader.Read();
				
				if( reader[0] != null && Int32.Parse(reader[0].ToString()) > 0 ) {
					returnValue = true;
				}
			}
		} 
		catch(Exception e ) {
			ReportException( "IsForumExisting", e );
		}
		
	}
	
	return returnValue;
}

public bool ExecuteCreateCommunity() {
	bool returnValue = false;
	using( SqlConnection connection = new SqlConnection(GetDatabaseConnectionString()) ) {
		connection.Open();
		
		SqlCommand cmd = new SqlCommand("cs_system_CreateCommunity", connection);
		
		cmd.CommandType = CommandType.StoredProcedure;
		
		cmd.Parameters.Add("@SiteUrl", SqlDbType.NVarChar, 512).Value = cs_siteurl.Text;
		cmd.Parameters.Add("@ApplicationName", SqlDbType.NVarChar, 512).Value = "dev";
		cmd.Parameters.Add("@AdminEmail", SqlDbType.NVarChar, 256).Value = cs_admin_email.Text;
		cmd.Parameters.Add("@AdminUserName", SqlDbType.NVarChar, 256).Value = cs_username_login.Text;
		cmd.Parameters.Add("@AdminPassword", SqlDbType.NVarChar, 256).Value = cs_password_login.Text;
		cmd.Parameters.Add("@PasswordFormat", SqlDbType.Int).Value = 0;
		cmd.Parameters.Add("@CreateSamples", SqlDbType.Bit).Value = chkCreateSample.Checked;
			
		try {
			cmd.ExecuteNonQuery();
			
			returnValue = true;
		}
		catch( Exception e ) {
			ReportException( "CreateCommunity", e );
		}
		
		return returnValue;
	}
}

public bool ExecuteSqlInFile(string pathToScriptFile ) {
	SqlConnection connection;

	try {
		StreamReader _reader			= null;

		string sql	= "";

		if( false == System.IO.File.Exists( pathToScriptFile )) {
			throw new Exception("File " + pathToScriptFile + " does not exists");
		}
		using( Stream stream = System.IO.File.OpenRead( pathToScriptFile ) ) {
			_reader = new StreamReader( stream );

			connection = new SqlConnection(GetDatabaseConnectionString());

			SqlCommand	command = new SqlCommand();

			connection.Open();
			command.Connection = connection;
			command.CommandType	= System.Data.CommandType.Text;

			while( null != (sql = ReadNextStatementFromStream( _reader ) )) {
				command.CommandText = sql;

				command.ExecuteNonQuery();
			}

			_reader.Close();
		}

		return true;
	}
	catch(Exception ex) {
		ReportException( "ExecuteSqlInFile" , "Error in file:" + pathToScriptFile + "<br/>" + "Message:" + ex.Message );
		return false;
	}

	connection.Close();
}

private static string ReadNextStatementFromStream( StreamReader _reader ) {
	try {
		StringBuilder sb = new StringBuilder();

		string lineOfText;
	
		while(true) {
			lineOfText = _reader.ReadLine();
			if( lineOfText == null ) {

				if( sb.Length > 0 ) {
					return sb.ToString();
				}
				else {
					return null;
				}
			}

			if( lineOfText.TrimEnd().ToUpper() == "GO" ) {
				break;
			}
				
			sb.Append(lineOfText + Environment.NewLine);
		}

		return sb.ToString();
	}
	catch( Exception ex ) {
		return null;
	}
}

private string GetConnectionString() {
	return String.Format("server={0};uid={1};pwd={2};Trusted_Connection={3}", db_server.Text, db_login.Text, this.DatabasePassword, (db_Connect.SelectedIndex == 0 ? "yes" : "no"));
}

private string GetDatabaseConnectionString() {
	return String.Format("{0};database={1}", GetConnectionString(), db_name_list.SelectedValue);
}

private bool Validate_ConnectToDb(out string errorMessage) {

//	ConnectionString = "server=" + db_server.Text + ";uid="+ db_login.Text +";pwd=" + this.DatabasePassword + ";Trusted_Connection=" + (db_Connect.SelectedIndex == 0 ? "yes" : "no");

	try {

		SqlConnection connection = new SqlConnection(GetConnectionString());
		connection.Open();
		connection.Close();
		
		errorMessage = "";
		
		return true;
	} catch (Exception e) {
		errorMessage = e.Message;
		return false;
	}
}

private bool Validate_SelectDb(out string errorMessage) {

	try {
	
		using( SqlConnection connection = new SqlConnection(GetDatabaseConnectionString() )) {
			connection.Open();
			connection.Close();
		}
		
		errorMessage = "";
		
		return true;
	}
	catch( SqlException se ) {
		switch( se.Number ) {
			case 4060:	// login fails
				if( db_Connect.SelectedIndex == 0) {
					errorMessage = "The installer is unable to access the specified database using the Windows credentials that the web server is running under. Contact your system administrator to have them add	" + Environment.UserName + " to the list of authorized logins";
				}
				else {
					errorMessage = "You can't login to that database. Please select another one<br />" + se.Message;
				}
				break;
			default:
				errorMessage = String.Format("Number:{0}:<br/>Message:{1}", se.Number, se.Message);
				break;
		}
		return false;
	}
	catch( Exception e ) {
		errorMessage = e.Message;
		return false;
	}
}

private bool Validate_SelectDb_ListDatabases(out string errorMessage) {

	try {
		SqlConnection connection = new SqlConnection(GetConnectionString());
		SqlDataReader dr;
		SqlCommand command = new SqlCommand("select name from master..sysdatabases order by name asc", connection);

		connection.Open();

		// Change to the master database
		//
		connection.ChangeDatabase("master");

		dr = command.ExecuteReader();

		db_name_list.Items.Clear();

		while (dr.Read()) 
		{
			string dbName = dr["name"] as String;
			if( dbName != null ) {
				if( dbName == "master" ||
					dbName == "msdb" ||
					dbName == "tempdb" ||
					dbName == "model" ) {
					
					// skip the system databases
					continue;
				}
				else {
					db_name_list.Items.Add( dbName );
				}
			}
		}

		connection.Close();
		
		errorMessage = "";
		
		return true;
	}
	catch( Exception e ) {
		errorMessage = e.Message;
		return false;
	}
}

private bool CheckLoginValid() 
{
	if ( cs_username_login.Text.Trim().Length == 0 )
	{
		req_cs_username_login.IsValid = false;
		return false;
	}
	
	if ( cs_admin_email.Text.Trim().Length == 0 )
	{
		req_cs_admin_email.IsValid = false;
		return false;
	}

	if ( !CheckPassword(cs_password_login.Text) )
	{
		req_cs_password_login.IsValid = false;
		return false;
	}

	return true;
}

private bool CheckPassword(string pwd)
{
	return (pwd.Length > 4);

	//if (pwd.Length < 7)
	//    return false;
	//bool lwr = false, upr = false, sym = false;
	//foreach (char c in pwd)
	//{
	//    if (char.IsLower(c))
	//        lwr = true;
	//    if (char.IsUpper(c))
	//        upr = true;
	//    if (char.IsSymbol(c) || char.IsPunctuation(c) || char.IsNumber(c))
	//        sym = true;
	//}
	//return (lwr && upr && sym);
}




public void NextPanel (Object sender, EventArgs e) {
	string errorMessage = "";
	
	switch (CurrentWizardPanel) {

		case WizardPanel.Welcome:
			SetActivePanel (WizardPanel.License, License);
			lit11Compat.Visible = !use20Membership;
			break;

		case WizardPanel.License:
			if( chkIAgree.Checked )
				SetActivePanel (WizardPanel.ConnectToDb, ConnectToDb);
			break;
		
		case WizardPanel.ConnectToDb:
			this.DatabasePassword = db_password.Text;
			if (Validate_ConnectToDb(out errorMessage)) {
				if( Validate_SelectDb_ListDatabases(out errorMessage)) {
					if( this.Request.QueryString[QSK_DATABASE] != null &&
						this.Request.QueryString[QSK_DATABASE] != String.Empty ) {
						
						try {
							db_name_list.SelectedValue = HttpUtility.UrlDecode(this.Request.QueryString[QSK_DATABASE]);
							SetActivePanel(WizardPanel.ScriptOptions, ScriptOptions );
						}
						catch {
							// an error occured setting the database, lets let the user select the database
							SetActivePanel(WizardPanel.SelectDb, SelectDb);
						}
					}
					else
						SetActivePanel (WizardPanel.SelectDb, SelectDb);
				}
				else {
					lblErrMsgConnect.Text = errorMessage;
				}
			}
			else {
				lblErrMsgConnect.Text = errorMessage;
			}
			break;
	
		case WizardPanel.SelectDb:
			if (Validate_SelectDb(out errorMessage)) {
				SetActivePanel (WizardPanel.ScriptOptions, ScriptOptions);
			
				if( IsSchemaExisting() || IsForumsSchemaExisting() ) {
					SetActivePanel( WizardPanel.SchemaExists, SchemaExists );
				}
			}
			else {
				lblErrMsg.Text = errorMessage;
			}
			
			break;
	
		case WizardPanel.ScriptOptions:
			SetActivePanel (WizardPanel.CreateCommunity, CreateCommunity);
			
			if( cs_siteurl != null )
			{
				string hostName = Request.Url.Host.Replace("www.",string.Empty);
				string applicationPath = Request.ApplicationPath;

				if(applicationPath.EndsWith("/"))
					applicationPath = applicationPath.Remove(applicationPath.Length-1,1);

				cs_siteurl.Text = hostName + applicationPath;
			}
			
			break;
		case WizardPanel.CreateCommunity:
//			SetActivePanel( WizardPanel.Install, Install );

			if (CheckLoginValid())
			{
				if (InstallDatabase()) {
					SetActivePanel (WizardPanel.Done, Done);
					
					if( updatedConfigFile ) {
						pnlConfigDoneUpdating.Visible = true;
						pnlConfigNeedUpdating.Visible = false;
					}
				}
				else {
					lstMessages.DataSource = messages;
					lstMessages.DataBind();

					SetActivePanel( WizardPanel.Errors, Errors );
				}
			}
			break;

	}
}


public void PreviousPanel (Object sender, EventArgs e) {
	switch (CurrentWizardPanel) {

		case WizardPanel.Welcome:
			break;

		case WizardPanel.License:
			SetActivePanel (WizardPanel.Welcome, Welcome);
			break;
		
		case WizardPanel.ConnectToDb:
			SetActivePanel (WizardPanel.License, License);
			break;
	
		case WizardPanel.SelectDb:
			SetActivePanel (WizardPanel.ConnectToDb, ConnectToDb);
			break;
	
		case WizardPanel.ScriptOptions:
			if( Page.Request.QueryString[QSK_DATABASE] != null &&
				Page.Request.QueryString[QSK_DATABASE] != String.Empty ) {
			
				SetActivePanel (WizardPanel.ConnectToDb, ConnectToDb);
			}
			else {
				SetActivePanel (WizardPanel.SelectDb, SelectDb);
			}
			break;
			
		case WizardPanel.CreateCommunity:
			SetActivePanel (WizardPanel.ScriptOptions, ScriptOptions);
			break;

		case WizardPanel.Done:
			SetActivePanel (WizardPanel.SelectDb, SelectDb);
			break;

		case WizardPanel.SchemaExists:
			SetActivePanel (WizardPanel.SelectDb, SelectDb);
			break;
	}
}

</script>
<html>
<head>
<title>Community Server Web Installer</title>
<style>
body
{
	background-color: #606060;
	color: #000000;
	font-family: Tahoma, Arial, Helvetica;
}

div, td, a, a:visited {
	font-family: Tahoma, Arial, Helvetica;
	font-size: 11px;
	color: #000000;
}
h2 {
	font-family: Tahoma, Arial, Helvetica;
	font-size: 20px;
}
.buttons {
	font-family: Tahoma, Arial, Helvetica;
	font-size: 11px;
	width:90px;
}
.mainTitle {
	font-family: Tahoma, Arial, Helvetica;
	font-size: 14px;
	font-weight: 900;
	color: #91723f;
}
.thisframe {
	font-family:  Tahoma, Arial, Helvetica;
	font-size: 11px;
}
.bold 
{
	font-weight: 900;
}
.dataentry
{
	width:150px;
}
TABLE.err {
	border: 1px solid #999999;
	margin-top: 8px;
}
TH.err {
	background-color:#999999;
	color: #000000;
	font-family:  Tahoma, Arial, Helvetica;
	font-size: 12px;
	font-weight: bold;
	padding: 2px;
}
TD.err {
	background-color:#ffffff;
	color: #000000;
	font-family:  Tahoma, Arial, Helvetica;
	font-size: 10px;
	padding: 2px;
}

</style>
</head>
<body>
<form runat="server">
<table height="100%" width="100%" align="center"><tr><td align="center" valign="middle">
	<table height="525" cellSpacing="0" cellPadding="0" width="650" border="0" style="background-color: #ffffff; border: solid 1px #999999;">
		<tbody>
			<tr>
				<td valign="top" height="98" background="images/headerbg.gif" style="background-repeat:repeat-x"><img src="images/topHeader.gif" width="496" height="98"></td>
			</tr>
			<tr>
				<td valign="top">

<div style="padding-right: 10px; padding-left: 10px; padding-bottom: 10px; padding-top: 30px">
<asp:panel id="Welcome" runat="server" Visible="false">
    <div class="mainTitle">Welcome to the Community Server remote installation wizard.</div>
	<div><br/><strong>Requirements:</strong></div>
    <div style="padding-left: 10px; padding-top: 10px">
		<ul>
			<li style="margin-bottom: 8px;"><div class="bold">Microsoft .NET Framework</div>
				<div>Version 			<asp:Literal id="lit11Compat" Runat=server >1.1 or </asp:Literal>2.0 of the .NET framework must be installed</div>
				<div><a href="http://www.asp.net/Default.aspx?tabindex=0&tabid=1" target="_blank">Get help installing the .NET framework</a></div>
			</li>
			<li style="margin-bottom: 8px;"><div class="bold">Internet Information Server</div>
				<div>IIS or compatible web server software must be installed</div>
				<div><a href="http://www.google.com/search?q=install+iis" target="_blank">Get help installing IIS</a></div>
			</li>
			<li><div class="bold">Microsoft SQL Server</div></li>
		</ul>
	</div>
</asp:panel>
<asp:panel id="License" runat="server" Visible="false">
	<table cellpadding="0" cellspacing="0" border="0">
		<tr>
			<td><span class="mainTitle">Community Server License</span></td>
			<td nowrap="true" align="right"><img src="images/printerIcon.gif"> <a href="eula.txt" target="new">Printable Version</a></td>
		</td>
		<tr>
			<td>&nbsp;</td>
		</tr>
		<tr>
			<td valign="top" align="right" colspan="2"><iframe frameborder="1" scrolling="yes" src="eula.html" height="250" width="600"></iframe></td>
		</tr>
	</table>
	</div> <br>
	<div align="right" style="padding-right: 20px;">
		<asp:Checkbox id="chkIAgree" runat=server Text=" I Agree" Checked="false" />
	</div>
</asp:panel>
<asp:panel id="ConnectToDb" runat="server" Visible="false">
    <div class="mainTitle">Community Server Database Login</div>
	<div>Select the database login that Community Server will use to connect to the database.</div>
	<div style="color:red;"><asp:Literal EnableViewState=False id="lblErrMsgConnect" Runat=server /></div>
	<div style="padding-left: 20px; padding-top: 20px">IP address or Server Name:
		<asp:textbox CssClass="dataentry" id="db_server" runat="server" value="(local)"></asp:textbox><br/>
		<asp:RadioButtonList id="db_Connect" runat="server" SelectedIndexChanged="ConnectToDb_CheckChanged">
			<asp:ListItem Value="Windows Authentication" Selected="True">Windows Authentication</asp:ListItem>
			<asp:ListItem Value="SQL Server Authentication">SQL Server Authentication</asp:ListItem>
		</asp:RadioButtonList>
		<div style="padding-left: 20px; padding-top: 20px">
			<table>
				<tr>
					<td align="left">Username:</TD>
					<td align="left">
						<asp:textbox cssclass="dataentry" id="db_login" runat="server"></asp:textbox>
					</td>
				</tr>
				<tr>
					<td align="left">Password:</TD>
					<td align="left">
						<asp:textbox CssClass="dataentry" id="db_password" runat="server" TextMode="Password"></asp:textbox>
					</td>
				</tr>
			</table>
		</div>
	</div>
</asp:panel>
<asp:panel id="SelectDb" runat="server" Visible="false">
    <span class="mainTitle">Select Database Instance</span><br><br>
    <div>Choose the database where you would like to to install Community Server.</div>
    <div style="padding-left: 20px; padding-top: 20px">
		<div style="padding-left: 20px; padding-top: 10px;color: red"><asp:Literal EnableViewState=False id="lblErrMsg" Runat=server /></div>
		<div style="padding-left: 20px; padding-top: 10px">Available databases:
			<asp:DropDownList id="db_name_list" runat="server"></asp:DropDownList>
		</div>
	</div>
</asp:panel>
<asp:panel id="ScriptOptions" runat="server" Visible="false">
	<span class="mainTitle">Choose Installation Options</span><br><br>
	<div>Select the installation options below to control how your database is created.</div>
	<div style="padding-left: 20px; width: 100%; padding-top: 20px">
		<asp:CheckBox id="chkScriptMemberRoles" runat="server" Text="Script ASP.NET MemberRoles" Checked="True" CssClass="bold"></asp:CheckBox>
		<div style="padding-left: 20px; padding-bottom: 10px">
			This option will create the ASP.NET MemberRoles information and remove the objects if they are already present. If you're installing into a shared database with other MemberRole compatible applications please uncheck this option.
		</div>
		<asp:CheckBox id="chkScriptCommunity" runat="server" Text="Script Community Server" Checked="True" CssClass="bold"></asp:CheckBox>
		<div style="padding-left: 20px; padding-bottom: 10px">
			Select this option if you are installing for the first time or you wish to recreate the Community Server schema. If you already have a working schema then please uncheck this option to keep your current schema intact.
		</div>
		<asp:CheckBox id="chkCreateCommunity" runat="server" Text="Create Community" Checked="True" CssClass="bold"></asp:CheckBox>
		<div style="padding-left: 20px; padding-bottom: 10px">
			Choose this option to have the installer create a new community for you or if you already have an existing community in the database this will allow you to create another community.
		</div>
	</div>
</asp:panel>
<asp:panel id="CreateCommunity" runat="server" Visible="false">
	<span class="mainTitle">Create new Community</span><br><br>
	<div>Enter the following information to create a new Community Server instance in the database. </div>
	<div style="padding-left: 15px; padding-top: 15px">
			<table cellpadding="2" cellspacing="0" border="0">
				<tr>
					<td align="left" valign="top">
						Community Url:
					</td>
					<td align="left">
						<asp:TextBox CssClass="dataentry" id="cs_siteurl" runat=server>localhost/cs</asp:TextBox>
						<asp:RequiredFieldValidator id="req_cs_siteurl" runat="server" ControlToValidate="cs_siteurl" enabled="true" display="Dynamic"><br>* Community URL is required!</asp:RequiredFieldValidator>
					</td>
					<td width="50%" nowrap>example: domain.com</td>
				</tr>
				<tr>
					<td colspan="3" align="left" style="padding-top: 20px; padding-bottom: 10px;">
						Enter the username, password, and email address you would like to use for the administrator account of your new Community Server site.
					</td>
				</tr>
				<tr>
					<td align="left" valign="top">Username:</TD>
					<td align="left" colspan="2">
						<asp:textbox CssClass="dataentry" id="cs_username_login" runat="server">admin</asp:textbox>
						<asp:requiredfieldvalidator id="req_cs_username_login" runat="server" controltovalidate="cs_username_login" enabled="true" display="Dynamic"><br>* Username is required!</asp:requiredfieldvalidator>
					</td>
				</tr>
				<tr>
					<td align="left" valign="top">Password:</TD>
					<td align="left">
						<asp:textbox CssClass="dataentry" id="cs_password_login" runat="server" TextMode="Password"></asp:textbox>
						<asp:requiredfieldvalidator id="req_cs_password_login" runat="server" controltovalidate="cs_password_login" enabled="true" display="Dynamic"><br>* Password does not meet requirements!</asp:requiredfieldvalidator>
					</td>
					<td rowspan="2" valign="top">The password must be at least 5 characters.</td>
				</tr>
				<tr>
					<td align="left" valign="top">Confirm Password:</td>
					<td align="left">
						<asp:textbox CssClass="dataentry" id="cs_password_login_confirm" runat="server" TextMode="Password"></asp:textbox>
						<asp:comparevalidator EnableClientScript="True" Enabled="True" id="ComparePassword" runat="server" ControlToValidate="cs_password_login_confirm" ControlToCompare="cs_password_login" Cssclass="color:red" display="Dynamic"><br>* Passwords do not match!</asp:comparevalidator>
					</td>
				</tr>
				<tr>
					<td align="left" valign="top">Admin Email Address:</TD>
					<td align="left" colspan="2">
						<asp:textbox cssclass="dataentry" id="cs_admin_email" runat="server"></asp:textbox>
						<asp:requiredfieldvalidator id="req_cs_admin_email" runat="server" controltovalidate="cs_admin_email" enabled="true" display="Dynamic"><br>* Admin Email is required!</asp:requiredfieldvalidator>
					</td>
				</tr>
				<tr>
					<td>&nbsp;</td>
					<td align="left">
						<asp:Checkbox id="chkCreateSample" runat=server Text="Create Sample Data" Checked=false />
					</td>
				</tr>
			</TABLE>
		</P>
	</DIV>
</asp:panel>
<asp:panel id="Install" runat="server" Visible="false">
	<span class="mainTitle">Installing Database</span>
</asp:panel>
<asp:panel id="Done" runat="server" Visible="false">
	<span class="mainTitle">Complete!</span><br><br>
	<div>
		<asp:Panel id="pnlConfigNeedUpdating" Runat=server Visible=True>
			Please update your web.config with the following information:<br />
			<pre>
			<asp:Panel id="pnl20Membership" Runat=server Visible="False" >
&lt;connectionStrings&gt;
  &lt;add name="SiteSqlServer" connectionString ="<span style="color:red"><%= GetDatabaseConnectionString() %></span>" /&gt;
&lt;/connectionStrings&gt;
			</asp:panel>
&lt;appSettings&gt;
  &lt;add key="SiteSqlServer" value="<span style="color:red"><%= GetDatabaseConnectionString() %></span>" /&gt;
  &lt;add key="SiteSqlServerOwner" value="dbo" /&gt;
  &lt;add key="MachineValidationKey" value="<span style="color:red"><%= ValidationKey %></span>" /&gt;
  &lt;add key="MachineDecryptionKey" value="<span style="color:red"><%= DecryptionKey %></span>" /&gt;
  &lt;add key="MachineValidationMode" value="SHA1" /&gt;
  &lt;add key="ComponentArt.Web.UI.ClientScriptLocation" value="~/Utility/componentart_webui_client" /&gt;
  &lt;add key="Telligent.Web.UI.ClientScriptPath" value="~/Utility/telligent_web_ui" /&gt;
&lt;/appSettings&gt;</pre>
			<p>Once you've updated your web.config click <a href='<%= @"http://" + cs_siteurl.Text %>'/>here</a> to navigate to your new site.</p>
		</asp:Panel>
		<asp:Panel id="pnlConfigDoneUpdating" runat=server Visible=False>
			Your web.config file was successfully updated with the new connection string
			<p>Click <a href='<%= @"http://" + cs_siteurl.Text %>'/>here</a> to navigate to your new site.</p>
		</asp:Panel>
		<div style="color:red">
		<b><u>IMPORTANT</u></b>: You should now have a working Community Server installation. It is <u>strongly recommended</u> that you disable the Community Server Web Wizard to prevent unauthorized access to your server. To disable the Community Server Web Installation Wizard open the /Installer/default.aspx file found on your web server and follow the instructions (in the file) to disable the installer.
		</div>
	</div>
</asp:panel>
<asp:Panel id="SchemaExists" runat=server Visible=false >
	<span class="mainTitle">Schema Already Exists</span><br><br>
	<div>
		The Installer does not support installing Community Server into a database with an existing Community Server schema. Please run the appropriate upgrade script to upgrade your database.
	</div>
</asp:Panel>
<asp:Panel id="Errors" runat=server Visible=false >
	<span class="mainTitle">Errors Occurred</span><br><br>
	<div>
		Errors occured during the execution of this wizard.
	</div>
	<asp:Repeater id="lstMessages" Runat="server">
		<HeaderTemplate>
			<table class="err" width="580px" border=0 cellpadding=0 cellspacing=0 >
				<tr>
					<th class="err" width="100px">Module</th>
					<th class="err" >Message</th>
				</tr>
		</HeaderTemplate>
		<ItemTemplate>
				<tr valign="top">
					<td class="err"><%# ((InstallerMessage)Container.DataItem).Module %></td>
					<td class="err"><%# ((InstallerMessage)Container.DataItem).Message %></td>
				</tr>
		</ItemTemplate>
		<FooterTemplate>
			</table>
		</FooterTemplate>
	</asp:Repeater>
</asp:Panel>
</div>
				</td>
			</tr>
			<tr>
				<td valign="bottom">
				<table cellpadding="0" cellspacing="0" border="0" width="100%">
					<tr>
						<td><img src="images/blcorner.gif"></td>
						<td align="right"><img src="images/brCorner.gif"></td>
					</tr>
				</table>
				</td>
			</tr>
			<tr>
				<td align="right" bgcolor="#bbde79" height="45"><div style="padding-right: 30px;"><asp:button id="Previous" onclick="PreviousPanel" runat="server" text="< Previous" cssClass="buttons"></asp:button>&nbsp;<asp:button id="Next" onclick="NextPanel" runat="server" text="Next >" cssClass="buttons"></asp:button></div></td>
			</tr>
		</tbody>
	</table>
</td></tr></table>
</form>
</body>
</html>
