Example #1
0
    /// <summary>
    /// Setup control.
    /// </summary>
    private void SetupControl()
    {
        if (ProcessID > 0)
        {
            listElem.WhereCondition = "(StateWorkflowID = " + ProcessID + ") ";
        }

        listElem.OnExternalDataBound += listElem_OnExternalDataBound;
        listElem.RememberStateByParam = String.Empty;

        // Register scripts for contact details dialog
        ScriptHelper.RegisterDialogScript(Page);
        ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "ViewContactDetails", ScriptHelper.GetScript(
                                                   "function Refresh() {" +
                                                   "__doPostBack('" + this.ClientID + @"', '');" +
                                                   "}"));

        // Hide filtered fields that are on separated database, since the query that the filter
        // returns couldn't be executed anyways
        if (SqlInstallationHelper.DatabaseIsSeparated())
        {
            listElem.FilterForm.FieldsToHide.Add("ContactLastName");
            listElem.FilterForm.FieldsToHide.Add("ContactFirstName");
            listElem.FilterForm.FieldsToHide.Add("ContactEmail");
        }
    }
    /// <summary>
    /// Validates control, returns error if failed.
    /// </summary>
    public bool ValidateForSeparation()
    {
        // Check if separation is not already completed
        if (SqlInstallationHelper.DatabaseIsSeparated())
        {
            DisplaySeparationError(GetString("separationDB.separationerror"));
            return(false);
        }

        // Check the server name
        if (String.IsNullOrEmpty(txtServerName.Text))
        {
            DisplaySeparationError(ResHelper.GetFileString("Install.ErrorServerEmpty"));
            return(false);
        }

        // Check if it is possible to connect to the database
        string res = TestNewConnection();

        if (!string.IsNullOrEmpty(res))
        {
            DisplaySeparationError(res);
            return(false);
        }

        return(true);
    }
Example #3
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!SqlInstallationHelper.DatabaseIsSeparated())
        {
            var connectionString = new SqlConnectionStringBuilder(ConnectionHelper.ConnectionString);
            if (connectionString.IntegratedSecurity)
            {
                btnLaunch.Visible = false;
                ShowWarning(GetString("separationDB.errorwinauth"));
            }
            else
            {
                btnLaunch.ResourceString = "separationDB.launchseparation";
                ShowInformation(GetString("separationDB.separatedescription"));
                btnLaunch.OnClientClick = "modalDialog('" + Page.ResolveUrl("~/CMSInstall/SeparateDB.aspx") + "','DBSeparation', 620, 598); return false;";
            }
        }
        else
        {
            btnLaunch.ResourceString = "separationDB.launchjoin";
            ShowInformation(GetString("separationDB.joindescription"));
            btnLaunch.OnClientClick = "modalDialog('" + Page.ResolveUrl("~/CMSInstall/JoinDB.aspx") + "','DBJoin', 620, 598); return false;";
        }

        ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "RefreshPageScript", ScriptHelper.GetScript("function RefreshPage() { window.location.replace(window.location.href); }"));
        ScriptHelper.RegisterDialogScript(Page);
    }
    /// <summary>
    /// Installs database (table structure + default data).
    /// </summary>
    /// <param name="parameter">Async action param</param>
    private void InstallDatabase(object parameter)
    {
        if (!DBInstalled)
        {
            TryResetUninstallationTokens();

            var settings = new DatabaseInstallationSettings
            {
                ConnectionString = Info.ConnectionString,
                ScriptsFolder    = Info.ScriptsFullPath,
                ApplyHotfix      = true,
                DatabaseObjectInstallationErrorMessage = ResHelper.GetFileString("Installer.LogErrorCreateDBObjects"),
                DataInstallationErrorMessage           = ResHelper.GetFileString("Installer.LogErrorDefaultData"),
                Logger = Log
            };
            bool success = SqlInstallationHelper.InstallDatabase(settings);

            if (success)
            {
                LogProgressState(LogStatusEnum.Finish, ResHelper.GetFileString("Installer.DBInstallFinished"));
            }
            else
            {
                throw new Exception("[InstallDatabase]: Error during database creation.");
            }
        }
    }
    private bool CreateDatabase(string collation)
    {
        try
        {
            var message = $"{ResHelper.GetFileString("Installer.LogCreatingDatabase")} {databaseDialog.NewDatabaseName}";
            AddResult(message);
            LogProgressState(LogStatusEnum.Info, message);

            var connectionString = ConnectionHelper.BuildConnectionString(AuthenticationType, userServer.ServerName, String.Empty, userServer.DBUsername, Password, SqlInstallationHelper.DB_CONNECTION_TIMEOUT);

            // Use default collation, if none specified
            if (String.IsNullOrEmpty(collation))
            {
                collation = DatabaseHelper.DatabaseCollation;
            }

            if (!DBCreated)
            {
                SqlInstallationHelper.CreateDatabase(databaseDialog.NewDatabaseName, connectionString, collation);
            }

            return(true);
        }
        catch (Exception ex)
        {
            DisplayLog = true;
            var message = $"{ResHelper.GetFileString("Intaller.LogErrorCreateDB")} {ex.Message}";
            AddResult(message);
            LogProgressState(LogStatusEnum.Error, message);
        }

        return(false);
    }
Example #6
0
    /// <summary>
    /// Finish button click.
    /// </summary>
    protected void FinishNextButton_Click(object sender, EventArgs e)
    {
        if (!SqlInstallationHelper.DatabaseIsSeparated())
        {
            string error = String.Empty;
            bool   dbEngineSupportsOpenqueryCommand = !DatabaseSeparationHelper.IsUsingAzureDatabase;

            if (dbEngineSupportsOpenqueryCommand)
            {
                var separationHelper = new DatabaseSeparationHelper();

                separationHelper.InstallScriptsFolder           = SqlInstallationHelper.GetSQLInstallPathToObjects();
                separationHelper.ScriptsFolder                  = Server.MapPath("~/App_Data/DBSeparation");
                separationHelper.InstallationConnStringSeparate = EncryptionHelper.DecryptData(hdnConnString.Value);
                error = separationHelper.DeleteSourceTables(separationFinished.DeleteOldDB, false);
            }

            if (!String.IsNullOrEmpty(error))
            {
                separationFinished.ErrorLabel.Visible = true;
                separationFinished.ErrorLabel.Text    = error;
                EventLogProvider.LogEvent(EventType.ERROR, "Contact management database join", "DELETEOLDDATA", error, RequestContext.CurrentURL);
            }
            else
            {
                EnableTasks();
                TakeSitesOnline();
                WebFarmHelper.CreateTask(SystemTaskType.RestartApplication, "RestartApplication", "", null);
                ScriptHelper.RegisterStartupScript(this, typeof(string), "Close dialog", ScriptHelper.GetScript("RefreshParent(); CloseDialog();"));
            }
        }
    }
Example #7
0
    /// <summary>
    /// Setup control.
    /// </summary>
    private void SetupControl()
    {
        // Show site column only for these two values from selector
        if ((SiteID != UniSelector.US_GLOBAL_AND_SITE_RECORD) && (SiteID != UniSelector.US_ALL_RECORDS))
        {
            // Site column
            listElem.GridColumns.Columns[5].Visible = false;
        }

        listElem.EditActionUrl += "&siteid=" + SiteID;
        if (ProcessID > 0)
        {
            listElem.WhereCondition = "(StateWorkflowID = " + ProcessID + ") ";
        }

        // Prepare site filtering
        string siteCondition = "AND (StateSiteID {0})";

        switch (SiteID)
        {
        case UniSelector.US_GLOBAL_RECORD:
            siteCondition = String.Format(siteCondition, "IS NULL");
            break;

        case UniSelector.US_GLOBAL_AND_SITE_RECORD:
            siteCondition = String.Format(siteCondition, "IS NULL OR StateSiteID = " + CurrentSite.SiteID);
            break;

        case UniSelector.US_ALL_RECORDS:
            siteCondition = String.Empty;
            break;

        default:
            siteCondition = String.Format(siteCondition, "= " + SiteID);
            break;
        }

        listElem.WhereCondition += siteCondition;

        listElem.OnExternalDataBound += listElem_OnExternalDataBound;
        listElem.RememberStateByParam = String.Empty;

        // Register scripts for contact details dialog
        ScriptHelper.RegisterDialogScript(Page);
        ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "ViewContactDetails", ScriptHelper.GetScript(
                                                   "function Refresh() {" +
                                                   "__doPostBack('" + this.ClientID + @"', '');" +
                                                   "}"));

        // Hide filtered fields that are on separated database, since the query that the filter
        // returns couldn't be executed anyways
        if (SqlInstallationHelper.DatabaseIsSeparated())
        {
            listElem.FilterForm.FieldsToHide.Add("ContactLastName");
            listElem.FilterForm.FieldsToHide.Add("ContactFirstName");
            listElem.FilterForm.FieldsToHide.Add("ContactEmail");
        }
    }
Example #8
0
    /// <summary>
    /// Returns data of automation states for my pending contacts.
    /// </summary>
    private DataSet GetPendingContacts(UserInfo user, string completeWhere, string currentOrder, int currentTopN, string columns, int currentOffset, int currentPageSize, ref int totalRecords)
    {
        // Get all pending contacts from automation state where status is Pending
        var allPendingContacts = AutomationStateInfo.Provider.Get()
                                 .WhereEquals("StateStatus", (int)ProcessStatusEnum.Pending)
                                 .WhereEquals("StateObjectType", ContactInfo.OBJECT_TYPE);


        // Get complete where condition for pending steps
        var condition = WorkflowStepInfoProvider.GetAutomationPendingStepsWhereCondition(user, SiteContext.CurrentSiteID);

        if (!String.IsNullOrEmpty(condition?.WhereCondition))
        {
            // Get automation steps specified by condition with permission control
            var automationWorkflowSteps = WorkflowStepInfo.Provider.Get()
                                          .Where(condition)
                                          .Column("StepID")
                                          .WhereEquals("StepWorkflowType", (int)WorkflowTypeEnum.Automation);

            allPendingContacts.WhereIn("StateStepID", automationWorkflowSteps);
        }

        // Get contact IDs based on filtering or ownership
        ObjectQuery <ContactInfo> contactIDs = null;

        if (ShowOnlyMyPendingContacts || !String.IsNullOrEmpty(completeWhere))
        {
            contactIDs = ContactInfo.Provider.Get()
                         .Column("ContactID")
                         .Where(completeWhere);
            if (ShowOnlyMyPendingContacts)
            {
                contactIDs.WhereEquals("ContactOwnerUserID", user.UserID);
            }
        }

        var query = allPendingContacts.OrderBy(currentOrder).TopN(currentTopN).Columns(columns);

        if (contactIDs != null)
        {
            // Add restriction based on selected contacts
            query.WhereIn("StateObjectID", SqlInstallationHelper.DatabaseIsSeparated() ? contactIDs.AsMaterializedList("ContactID") : contactIDs);
        }

        query.IncludeBinaryData = false;
        query.Offset            = currentOffset;
        query.MaxRecords        = currentPageSize;

        var data = query.Result;

        totalRecords = query.TotalRecords;

        return(data);
    }
    /// <summary>
    /// Check if exists SQL script for this object in /App_Data/Install
    /// </summary>
    /// <param name="objName">Name of the object</param>
    private bool SQLScriptExists(string objName, ref string fileName)
    {
        if (!String.IsNullOrEmpty(objName))
        {
            fileName = SqlInstallationHelper.GetSQLInstallPathToObjects() + "\\" + objName + ".sql";

            return(File.Exists(fileName));
        }
        fileName = null;

        return(TableManager.IsGeneratedSystemView(objName));
    }
Example #10
0
    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);

        if (!SqlInstallationHelper.DatabaseIsSeparated() && !StopProcessing)
        {
            var filterLabel = listElem.FilterForm.FieldLabels["ContactFirstName"];
            if (filterLabel != null)
            {
                filterLabel.ResourceString = "filter.searchbyname";
            }
        }
    }
    protected void Page_PreRender(object sender, EventArgs e)
    {
        txtDBPassword.Enabled = radSQLAuthentication.Checked;
        txtDBUsername.Enabled = radSQLAuthentication.Checked;

        if (IsDBSeparation)
        {
            plcRadSQL.Visible  = false;
            plcWinAuth.Visible = false;

            if (SqlInstallationHelper.DatabaseIsSeparated())
            {
                DisplaySeparationError(GetString("separationDB.separationerror"));
            }
        }
    }
    /// <summary>
    /// Runs SQL installation scripts
    /// </summary>
    private void RunSQLInstallation()
    {
        // Setup the installation
        var info = Info;

        info.ScriptsFullPath  = SqlInstallationHelper.GetSQLInstallPath();
        info.ConnectionString = ConnectionString;

        info.ClearLog();

        // Start the installation process
        ctlAsyncDB.RunAsync(InstallDatabase, WindowsIdentity.GetCurrent());

        NextButton.Attributes.Add("disabled", "true");
        PreviousButton.Attributes.Add("disabled", "true");
        wzdInstaller.ActiveStepIndex = 3;
    }
    /// <summary>
    /// Validates control, returns error if failed.
    /// </summary>
    public bool ValidateForSeparation()
    {
        // Check if separation is not already completed
        if (SqlInstallationHelper.DatabaseIsSeparated())
        {
            DisplaySeparationError(GetString("separationDB.separationerror"));
            return(false);
        }

        // Check the server name
        if (String.IsNullOrEmpty(txtServerName.Text))
        {
            DisplaySeparationError(ResHelper.GetFileString("Install.ErrorServerEmpty"));
            return(false);
        }

        if (radSQLAuthentication.Checked)
        {
            // Check the user name and password
            if (String.IsNullOrEmpty(txtDBUsername.Text) || String.IsNullOrEmpty(txtDBPassword.Text))
            {
                DisplaySeparationError(ResHelper.GetFileString("install.errorusernamepasswordempty"));
                return(false);
            }
        }

        // Check if it is possible to connect to the database
        string res = TestNewConnection();

        if (string.IsNullOrEmpty(res))
        {
            return(true);
        }

        DisplaySeparationError(res);
        return(false);
    }
Example #14
0
    /// <summary>
    /// Loads the data.
    /// </summary>
    protected void LoadData()
    {
        lblValueAlocatedMemory.Text = DataHelper.GetSizeString(GC.GetTotalMemory(false));

        lblValueVirtualMemory.Text  = "N/A";
        lblValuePhysicalMemory.Text = "N/A";
        lblValuePeakMemory.Text     = "N/A";

        // Process memory
        try
        {
            lblValueVirtualMemory.Text  = DataHelper.GetSizeString(SystemHelper.GetVirtualMemorySize());
            lblValuePhysicalMemory.Text = DataHelper.GetSizeString(SystemHelper.GetWorkingSetSize());
            lblValuePeakMemory.Text     = DataHelper.GetSizeString(SystemHelper.GetPeakWorkingSetSize());
        }
        catch
        {
        }

        lblValuePages.Text         = GetViewValues(RequestHelper.TotalPageRequests.GetValue(null), Statistics.RPSPageRequests);
        lblValuePagesNotFound.Text = GetViewValues(RequestHelper.TotalPageNotFoundRequests.GetValue(null), Statistics.RPSPageNotFoundRequests);
        lblValueSystemPages.Text   = GetViewValues(RequestHelper.TotalSystemPageRequests.GetValue(null), Statistics.RPSSystemPageRequests);
        lblValueNonPages.Text      = GetViewValues(RequestHelper.TotalNonPageRequests.GetValue(null), Statistics.RPSNonPageRequests);
        lblValueGetFilePages.Text  = GetViewValues(RequestHelper.TotalGetFileRequests.GetValue(null), Statistics.RPSGetFileRequests);

        long pending = RequestHelper.PendingRequests.GetValue(null);

        if (pending > 1)
        {
            // Current request does not count as pending at the time of display
            pending--;
        }
        if (pending < 0)
        {
            pending = 0;
        }

        lblValuePending.Text = pending.ToString();

        lblCacheItemsValue.Text      = Cache.Count.ToString();
        lblCacheExpiredValue.Text    = CacheHelper.Expired.GetValue(null).ToString();
        lblCacheRemovedValue.Text    = CacheHelper.Removed.GetValue(null).ToString();
        lblCacheUnderusedValue.Text  = CacheHelper.Underused.GetValue(null).ToString();
        lblCacheDependencyValue.Text = CacheHelper.DependencyChanged.GetValue(null).ToString();

        // GC collections
        try
        {
            plcGC.Controls.Clear();

            int generations = GC.MaxGeneration;
            for (int i = 0; i <= generations; i++)
            {
                int    count     = GC.CollectionCount(i);
                string genString = "<div class=\"form-group\"><div class=\"editing-form-label-cell\"><span class=\"control-label\">" + GetString("GC.Generation") + " " + i +
                                   ":</span></div><div class=\"editing-form-value-cell\"><span class=\"form-control-text\">" + count + "</span></div></div>";

                plcGC.Controls.Add(new LiteralControl(genString));
            }
        }
        catch
        {
        }

        TableManager tm = new TableManager(null);

        lblDBNameValue.Text        = HTMLHelper.HTMLEncode(tm.DatabaseName);
        lblServerVersionValue.Text = HTMLHelper.HTMLEncode(tm.DatabaseServerVersion);

        // DB information
        if (!RequestHelper.IsPostBack())
        {
            lblDBSizeValue.Text     = HTMLHelper.HTMLEncode(tm.DatabaseSize);
            lblServerNameValue.Text = HTMLHelper.HTMLEncode(tm.DatabaseServerName);

            // Check if DB is separated
            bool separated = SqlInstallationHelper.DatabaseIsSeparated();
            if (separated)
            {
                tm = new TableManager(DatabaseSeparationHelper.OM_CONNECTION_STRING);

                lblSeparatedServerName.Text = HTMLHelper.HTMLEncode(tm.DatabaseServerName);
                lblSeparatedVersion.Text    = HTMLHelper.HTMLEncode(tm.DatabaseServerVersion);
                lblSeparatedName.Text       = HTMLHelper.HTMLEncode(tm.DatabaseName);
                lblSeparatedSize.Text       = HTMLHelper.HTMLEncode(tm.DatabaseSize);
            }
        }
    }
Example #15
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Init actions
        // Page view
        if (HeaderActions != null)
        {
            HeaderActions.ActionPerformed += HeaderActionsOnActionPerformed;
            InitHeaderActions();
        }
        // Widget view
        else
        {
            InitButtons();
        }

        timRefresh.Interval = 1000 * ValidationHelper.GetInteger(drpRefresh.SelectedValue, 0);
        isSeparatedDB       = SqlInstallationHelper.DatabaseIsSeparated();

        // Check permissions
        RaiseOnCheckPermissions("READ", this);

        if (StopProcessing)
        {
            return;
        }

        Statistics.EvaluateRequests();

        // Do not count this page with async postback
        if (RequestHelper.IsAsyncPostback())
        {
            RequestHelper.TotalSystemPageRequests.Decrement(null);
        }

        lblServerName.Text             = GetString("Administration-System.ServerName");
        lblServerVersion.Text          = GetString("Administration-System.ServerVersion");
        lblDBName.Text                 = GetString("Administration-System.DatabaseName");
        lblDBSize.Text                 = GetString("Administration-System.DatabaseSize");
        lblMachineName.Text            = GetString("Administration-System.MachineName");
        lblMachineNameValue.Text       = HTMLHelper.HTMLEncode(SystemContext.MachineName);
        lblAspAccount.Text             = GetString("Administration-System.Account");
        lblValueAspAccount.Text        = HTMLHelper.HTMLEncode(WindowsIdentity.GetCurrent().Name);
        lblPool.Text                   = GetString("Administration-System.Pool");
        lblValuePool.Text              = GetString("General.NA");
        plcSeparatedName.Visible       = isSeparatedDB;
        plcSeparatedServerName.Visible = isSeparatedDB;
        plcSeparatedSize.Visible       = isSeparatedDB;
        plcSeparatedVersion.Visible    = isSeparatedDB;
        plcSeparatedHeader.Visible     = isSeparatedDB;

        lblValuePool.Text = HTMLHelper.HTMLEncode(SystemContext.ApplicationPoolName);

        // Get application trust level
        lblTrustLevel.Text      = GetString("Administration-System.TrustLevel");
        lblValueTrustLevel.Text = GetString("General.NA");

        lblValueTrustLevel.Text = HTMLHelper.HTMLEncode(SystemContext.CurrentTrustLevel.ToString());

        lblAspVersion.Text      = GetString("Administration-System.Version");
        lblValueAspVersion.Text = HTMLHelper.HTMLEncode(Environment.Version.ToString());

        lblAlocatedMemory.Text = GetString("Administration-System.Memory");
        lblPeakMemory.Text     = GetString("Administration-System.PeakMemory");
        lblVirtualMemory.Text  = GetString("Administration-System.VirtualMemory");
        lblPhysicalMemory.Text = GetString("Administration-System.PhysicalMemory");
        lblIP.Text             = GetString("Administration-System.IP");

        lblPageViewsValues.Text = GetString("Administration-System.PageViewsValues");

        lblPages.Text         = GetString("Administration-System.Pages");
        lblSystemPages.Text   = GetString("Administration-System.SystemPages");
        lblNonPages.Text      = GetString("Administration-System.NonPages");
        lblGetFilePages.Text  = GetString("Administration-System.GetFilePages");
        lblPagesNotFound.Text = GetString("Administration-System.PagesNotFound");
        lblPending.Text       = GetString("Administration-System.Pending");

        lblCacheExpired.Text    = GetString("Administration-System.CacheExpired");
        lblCacheRemoved.Text    = GetString("Administration-System.CacheRemoved");
        lblCacheUnderused.Text  = GetString("Administration-System.CacheUnderused");
        lblCacheItems.Text      = GetString("Administration-System.CacheItems");
        lblCacheDependency.Text = GetString("Administration-System.CacheDependency");

        LoadData();

        if (!RequestHelper.IsPostBack())
        {
            switch (QueryHelper.GetString("lastaction", String.Empty).ToLowerCSafe())
            {
            case "restarted":
                ShowConfirmation(GetString("Administration-System.RestartSuccess"));
                break;

            case "webfarmrestarted":
                if (ValidationHelper.ValidateHash("WebfarmRestarted", QueryHelper.GetString("restartedhash", String.Empty)))
                {
                    ShowConfirmation(GetString("Administration-System.WebframRestarted"));
                    // Restart other servers - create webfarm task for application restart
                    WebFarmHelper.CreateTask(SystemTaskType.RestartApplication, "RestartApplication");
                }
                else
                {
                    ShowError(GetString("general.actiondenied"));
                }
                break;

            case "countercleared":
                ShowConfirmation(GetString("Administration-System.CountersCleared"));
                break;

            case "winservicesrestarted":
                ShowConfirmation(GetString("Administration-System.WinServicesRestarted"));
                break;
            }
        }

        lblRunTime.Text    = GetString("Administration.System.RunTime");
        lblServerTime.Text = GetString("Administration.System.ServerTime");

        // Remove milliseconds from the end of the time string
        string timeSpan = (DateTime.Now - CMSApplication.ApplicationStart).ToString();
        int    index    = timeSpan.LastIndexOfCSafe('.');

        if (index >= 0)
        {
            timeSpan = timeSpan.Remove(index);
        }

        // Display application run time
        lblRunTimeValue.Text    = timeSpan;
        lblServerTimeValue.Text = Convert.ToString(DateTime.Now) + " " + TimeZoneHelper.GetUTCStringOffset(TimeZoneHelper.ServerTimeZone);

        lblIPValue.Text = HTMLHelper.HTMLEncode(RequestContext.UserHostAddress);
    }
    protected void btnHiddenNext_onClick(object sender, EventArgs e)
    {
        StepOperation = 1;
        StepIndex++;

        switch (wzdInstaller.ActiveStepIndex)
        {
        case 0:
            // Set the authentication type
            AuthenticationType = userServer.WindowsAuthenticationChecked ? SQLServerAuthenticationModeEnum.WindowsAuthentication : SQLServerAuthenticationModeEnum.SQLServerAuthentication;

            // Check the server name
            if (String.IsNullOrEmpty(userServer.ServerName))
            {
                HandleError(ResHelper.GetFileString("Install.ErrorServerEmpty"));
                return;
            }

            // Do not allow to use empty user name or password
            bool isSQLAuthentication = AuthenticationType == SQLServerAuthenticationModeEnum.SQLServerAuthentication;
            if (isSQLAuthentication && (String.IsNullOrEmpty(userServer.DBUsername) || String.IsNullOrEmpty(userServer.DBPassword)))
            {
                HandleError(ResHelper.GetFileString("Install.ErrorUserNamePasswordEmpty"));
                return;
            }

            Password = userServer.DBPassword;

            // Check if it is possible to connect to the database
            string res = ConnectionHelper.TestConnection(AuthenticationType, userServer.ServerName, String.Empty, userServer.DBUsername, Password);
            if (!String.IsNullOrEmpty(res))
            {
                HandleError(res, "Install.ErrorSqlTroubleshoot", HELP_TOPIC_SQL_ERROR_LINK);
                return;
            }

            // Set credentials for the next step
            databaseDialog.AuthenticationType = AuthenticationType;
            databaseDialog.Password           = Password;
            databaseDialog.Username           = userServer.DBUsername;
            databaseDialog.ServerName         = userServer.ServerName;

            // Move to the next step
            wzdInstaller.ActiveStepIndex = 1;
            break;

        case 1:
        case COLLATION_DIALOG_INDEX:
            // Get database name
            Database = TextHelper.LimitLength(databaseDialog.CreateNewChecked ? databaseDialog.NewDatabaseName : databaseDialog.ExistingDatabaseName, 100);

            if (String.IsNullOrEmpty(Database))
            {
                HandleError(ResHelper.GetFileString("Install.ErrorDBNameEmpty"));
                return;
            }

            // Set up the connection string
            if (ConnectionHelper.IsConnectionStringInitialized)
            {
                ConnectionString = ConnectionHelper.ConnectionString;
            }
            else
            {
                ConnectionString = ConnectionHelper.BuildConnectionString(AuthenticationType, userServer.ServerName, Database, userServer.DBUsername, Password, SqlInstallationHelper.DB_CONNECTION_TIMEOUT);
            }

            // Check if existing DB has the same version as currently installed CMS
            if (databaseDialog.UseExistingChecked && !databaseDialog.CreateDatabaseObjects)
            {
                string dbVersion = null;
                try
                {
                    dbVersion = SqlInstallationHelper.GetDatabaseVersion(ConnectionString);
                }
                catch
                {
                }

                if (String.IsNullOrEmpty(dbVersion))
                {
                    // Unable to get DB version => DB objects missing
                    HandleError(ResHelper.GetFileString("Install.DBObjectsMissing"));
                    return;
                }

                if (dbVersion != CMSVersion.MainVersion)
                {
                    // Get wrong version number
                    HandleError(ResHelper.GetFileString("Install.WrongDBVersion"));
                    return;
                }
            }

            Info.LogContext = ctlAsyncDB.LogContext;

            // Use existing database
            if (databaseDialog.UseExistingChecked)
            {
                // Check if DB exists
                if (!DatabaseHelper.DatabaseExists(ConnectionString))
                {
                    HandleError(String.Format(ResHelper.GetFileString("Install.ErrorDatabseDoesntExist"), Database));
                    return;
                }

                // Get collation of existing DB
                string collation = DatabaseHelper.GetDatabaseCollation(ConnectionString);
                DatabaseHelper.DatabaseCollation = collation;

                if (wzdInstaller.ActiveStepIndex != COLLATION_DIALOG_INDEX)
                {
                    // Check target database collation and inform the user if it is not fully supported
                    if (!DatabaseHelper.IsSupportedDatabaseCollation(collation))
                    {
                        ucCollationDialog.IsSqlAzure = AzureHelper.IsSQLAzureServer(userServer.ServerName);
                        ucCollationDialog.Collation  = collation;
                        ucCollationDialog.InitControls();

                        // Move to "collation dialog" step
                        wzdInstaller.ActiveStepIndex = COLLATION_DIALOG_INDEX;
                        return;
                    }
                }
                else
                {
                    // Change database collation for regular database
                    if (ucCollationDialog.ChangeCollationRequested)
                    {
                        DatabaseHelper.ChangeDatabaseCollation(ConnectionString, Database, DatabaseHelper.DEFAULT_DB_COLLATION);
                    }
                }
            }
            else
            {
                // Create a new database
                if (!CreateDatabase(null))
                {
                    HandleError(String.Format(ResHelper.GetFileString("Install.ErrorCreateDB"), databaseDialog.NewDatabaseName));
                    return;
                }

                databaseDialog.ExistingDatabaseName = databaseDialog.NewDatabaseName;
                databaseDialog.CreateNewChecked     = false;
                databaseDialog.UseExistingChecked   = true;
            }

            if ((!SystemContext.IsRunningOnAzure && writePermissions) || ConnectionHelper.IsConnectionStringInitialized)
            {
                if (databaseDialog.CreateDatabaseObjects)
                {
                    if (DBInstalled && DBCreated)
                    {
                        ctlAsyncDB.RaiseFinished(this, EventArgs.Empty);
                    }
                    else
                    {
                        // Run SQL installation
                        RunSQLInstallation();
                    }
                }
                else
                {
                    CreateDBObjects = false;

                    // Set connection string
                    if (SettingsHelper.SetConnectionString(ConnectionHelper.ConnectionStringName, ConnectionString))
                    {
                        // Set the application connection string
                        SetAppConnectionString();

                        // Check if license key for current domain is present
                        LicenseKeyInfo lki = LicenseKeyInfoProvider.GetLicenseKeyInfo(hostName);
                        wzdInstaller.ActiveStepIndex = (lki == null) ? 4 : 5;
                        ucLicenseDialog.SetLicenseExpired();
                    }
                    else
                    {
                        ManualConnectionStringInsertion();
                    }
                }
            }
            else
            {
                ManualConnectionStringInsertion();
            }

            break;

        // After connection string save error
        case 2:
            // Check whether connection string is defined
            if (String.IsNullOrWhiteSpace(Service.Resolve <IConnectionStringService>()[ConnectionHelper.ConnectionStringName]))
            {
                HandleError(ResHelper.GetFileString("Install.ErrorAddConnString"));
                return;
            }

            ConnectionString = Service.Resolve <IConnectionStringService>()[ConnectionHelper.ConnectionStringName];

            if (CreateDBObjects)
            {
                if (DBInstalled)
                {
                    FinalizeDBInstallation();
                }
                else
                {
                    // Run SQL installation
                    RunSQLInstallation();
                }
            }
            else
            {
                // If this is installation to existing DB and objects are not created
                if ((hostName != "localhost") && (hostName != "127.0.0.1"))
                {
                    wzdInstaller.ActiveStepIndex = 4;
                }
                else
                {
                    wzdInstaller.ActiveStepIndex = 5;
                }
            }
            break;

        // After DB install
        case 3:
            break;

        // After license entering
        case 4:
            try
            {
                if (ucLicenseDialog.Visible)
                {
                    ucLicenseDialog.SetLicenseKey();
                    wzdInstaller.ActiveStepIndex = 5;
                }
                else if (ucWagDialog.ProcessRegistration(ConnectionString))
                {
                    wzdInstaller.ActiveStepIndex = 5;
                }
            }
            catch (Exception ex)
            {
                HandleError(ex.Message);
            }
            break;

        default:
            wzdInstaller.ActiveStepIndex++;
            break;
        }
    }