Esempio n. 1
0
        /// <summary>
        /// Executes the given <see cref="QueryInfo" /> asynchronously
        /// </summary>
        /// <param name="queryClassName">The CLASS_NAME of the <see cref="QueryInfo" /></param>
        /// <param name="queryCodeName">The CODE_NAME of the <see cref="QueryInfo" /></param>
        /// <param name="parameters">Query parameters</param>
        /// <param name="queryMacros">Query macro values</param>
        /// <param name="token">Cancellation token</param>
        /// <returns>A dataset with its first table populated by executing the <see cref="QueryInfo" /> with the given parameters</returns>
        /// <execption cref="Exception">Thrown if the <see cref="QueryInfo" /> cannot be found</execption>
        public static async Task <DataSet> ExecuteQueryAsync(string queryClassName, string queryCodeName, QueryDataParameters parameters, QueryMacros?queryMacros = null, CancellationToken token = default)
        {
            var query = await GetCachedQueryAsync(queryClassName, queryCodeName, token : token);

            if (query is null)
            {
                throw new Exception($"No query found for class name [{queryClassName}] and query name [{queryCodeName}]");
            }

            using var context = new CMSConnectionScope(query.QueryConnectionString);

            string?queryText = (queryMacros ?? new QueryMacros()).ResolveMacros(query.QueryText);

            var reader = await ConnectionHelper.ExecuteReaderAsync(queryText, parameters, query.QueryType, CommandBehavior.Default, token);

            var table = new DataTable();

            table.Load(reader);

            var ds = new DataSet();

            ds.Tables.Add(table);

            return(ds);
        }
Esempio n. 2
0
    /// <summary>
    /// Delete items.
    /// </summary>
    private void DeleteItems()
    {
        // Set long timeout so that mass delete can finish successfully
        SqlConnectionStringBuilder connectionString = new SqlConnectionStringBuilder(ConnectionHelper.GetConnection().DataConnection.ConnectionString);

        connectionString.ConnectTimeout = SQL_TIMEOUT;
        using (var cs = new CMSConnectionScope(connectionString.ToString(), true))
        {
            // Delete the accounts
            AccountInfo ai = null;
            foreach (string accountId in accountIds)
            {
                ai = AccountInfoProvider.GetAccountInfo(ValidationHelper.GetInteger(accountId, 0));
                if (ai != null)
                {
                    // Display name of deleted account
                    AddLog(ai.AccountName);

                    // Delete account with its dependencies
                    AccountHelper.Delete(ai, chkChildren.Checked, chkBranches.Checked);
                }
            }
        }
    }
    /// <summary>
    /// Delete items.
    /// </summary>
    private void DeleteItems()
    {
        SqlConnectionStringBuilder connectionString = new SqlConnectionStringBuilder(ConnectionHelper.GetConnection().DataConnection.ConnectionString);
        connectionString.ConnectTimeout = SQL_TIMEOUT;
        using (var cs = new CMSConnectionScope(connectionString.ToString(), true))
        {
            ContactInfo ci = null;
            // Delete the contacts
            foreach (string contactId in contactIds)
            {
                ci = ContactInfoProvider.GetContactInfo(ValidationHelper.GetInteger(contactId, 0));
                if (ci != null)
                {
                    // Display name of deleted contact
                    AddLog((ci.ContactLastName + " " + ci.ContactFirstName).Trim());

                    // Delete contact with its dependencies
                    ContactHelper.Delete(ci, chkChildren.Checked, chkMoveRelations.Checked);
                }
            }
        }
    }
    /// <summary>
    /// Performs the application initialization on the first request.
    /// </summary>
    private static void FirstRequestInitialization(object sender, EventArgs e)
    {
        // Initialized properly
        if (mApplicationInitialized == true)
        {
            return;
        }

        // Not initialized, must install
        if ((mApplicationInitialized == false) && InstallerFunctions.InstallRedirect(true))
        {
            return;
        }

        // Do not init application on request to just physical file
        string relativePath = URLHelper.CurrentRelativePath;
        ExcludedSystemEnum excludedEnum = URLHelper.IsExcludedSystemEnum(relativePath);
        if (excludedEnum == ExcludedSystemEnum.PhysicalFile)
        {
            return;
        }

        // Initialize application in a locked context
        lock (mLock)
        {
            if (ApplicationInitialized)
            {
                return;
            }

            // Remember date and time of the application start
            mApplicationStart = DateTime.Now;

            // Init run from web applicaiton - DON'T MOVE LATER
            SystemHelper.IsWebSite = true;

            mWindowsIdentity = WindowsIdentity.GetCurrent();

            ViewModeOnDemand viewMode = new ViewModeOnDemand();

            // Log application start
            if (CMSFunctions.AnyDebugEnabled)
            {
                RequestSettings settings = RequestSettings.Current;
                bool liveSite = (viewMode.Value == ViewModeEnum.LiveSite);

                settings.DebugRequest = RequestHelper.DebugRequests && liveSite;
                RequestHelper.LogRequestOperation("BeforeApplicationStart", null, 0);

                settings.DebugSQLQueries = SqlHelperClass.DebugQueries && liveSite;
                settings.DebugFiles = File.DebugFiles && liveSite;
                settings.DebugCache = CacheHelper.DebugCache && liveSite;
                settings.DebugSecurity = SecurityHelper.DebugSecurity && liveSite;
                settings.DebugOutput = OutputHelper.DebugOutput && liveSite;
                settings.DebugMacros = MacroResolver.DebugMacros && liveSite;
                settings.DebugWebFarm = WebSyncHelperClass.DebugWebFarm && liveSite;
                settings.DebugAnalytics = AnalyticsHelper.DebugAnalytics && liveSite;

                DebugHelper.SetContext("App_Start");
            }

            // Handle the event
            var h = CMSApplicationEvents.Start.StartEvent(e);
            if (h.Continue)
            {
                //ConnectionHelper.UseContextConnection = true;
                //CacheHelper.CacheItemPriority = System.Web.Caching.CacheItemPriority.NotRemovable;

                if (SqlHelperClass.IsConnectionStringInitialized)
                {
                    using (CMSConnectionScope scope = new CMSConnectionScope())
                    {
                        // Use single open connection for the application start
                        GeneralConnection conn = (GeneralConnection)scope.Connection;
                        bool closeConnection = false;
                        try
                        {
                            // Open the connection
                            conn.Open();
                            closeConnection = true;

                            // Check for the table existence
                            if (!TableManager.TableExists("CMS_SettingsKey"))
                            {
                                mApplicationInitialized = false;

                                if (InstallerFunctions.InstallRedirect(true))
                                {
                                    return;
                                }
                            }

                            // Check the version
                            string version = SettingsKeyProvider.GetStringValue("CMSDBVersion");
                            if (version != CMSContext.SYSTEM_VERSION)
                            {
                                // Report error about not being able to connect
                                mConnectionErrorMessage = "The database version '" + version + "' does not match the project version '" + CMSContext.SYSTEM_VERSION + "', please check your connection string.";
                                HttpContext.Current.Server.Transfer("~/CMSMessages/error.aspx");
                            }
                            else
                            {
                                // Initialize the environment
                                CMSFunctions.Init();

                                // Update the system !! IMPORTANT - must be first
                                UpgradeProcedure.Update(conn);
                                try
                                {
                                    // Write "Application start" event to the event log
                                    EventLogProvider ev = new EventLogProvider();

                                    ev.DeleteOlderLogs = false;
                                    ev.LogEvent(EventLogProvider.EVENT_TYPE_INFORMATION, DateTime.Now, "Application_Start", "STARTAPP", 0, null, 0, null, null, null, 0, HTTPHelper.GetAbsoluteUri());
                                }
                                catch
                                {
                                    // can't write to log, do not process any code
                                }
                                UserInfoProvider.OnFormattedUserName += new UserInfoProvider.FormattedUserNameEventHandler(Functions.GetFormattedUserName);

                                // Delete memory synchronization tasks
                                WebSyncHelper.DeleteMemorySynchronizationTasks();

                                // Create web farm server if running on Azure
                                if (AzureHelper.IsRunningOnAzure)
                                {
                                    // Set webfarm server name
                                    WebSyncHelperClass.ServerName = ValidationHelper.GetCodeName(AzureHelper.CurrentInstanceID);

                                    if (WebFarmServerInfoProvider.GetWebFarmServerInfo(WebSyncHelperClass.ServerName) == null)
                                    {
                                        // Create webfarm server
                                        WebFarmServerInfo wfsi = new WebFarmServerInfo();
                                        wfsi.ServerName = WebSyncHelperClass.ServerName;
                                        wfsi.ServerEnabled = true;
                                        wfsi.ServerDisplayName = AzureHelper.CurrentInstanceID;
                                        wfsi.ServerURL = AzureHelper.CurrentInternalEndpoint;

                                        WebFarmServerInfoProvider.SetWebFarmServerInfo(wfsi);
                                    }
                                }

                                // Wait until initialization is complete
                                CMSFunctions.WaitForInitialization();
                            }
                        }
                        catch (Exception ex)
                        {
                            if (closeConnection)
                            {
                                // Server connected succesfully but something else went wrong
                                throw ex;
                            }
                            else
                            {
                                // Report error about not being able to connect
                                mConnectionErrorMessage = ex.Message;

                                HttpContext.Current.Server.Transfer("~/CMSMessages/error.aspx");
                            }
                        }
                        finally
                        {
                            if (closeConnection)
                            {
                                // Close the connection
                                conn.Close();
                            }
                        }
                    }
                }
                else
                {
                    // Register virtual path provider
                    if (ValidationHelper.GetBoolean(SettingsHelper.AppSettings["CMSUseVirtualPathProvider"], true))
                    {
                        CMS.VirtualPathHelper.VirtualPathHelper.RegisterVirtualPathProvider();
                    }
                }

                // Register the CMS view engine
                CMSViewEngine.RegisterViewEngine();
            }

            // Finalize the event
            h.FinishEvent();

            DebugHelper.ReleaseContext();

            // Log when the overall application start finished its execution
            mApplicationStartFinished = DateTime.Now;
            mApplicationInitialized = true;

            RequestHelper.LogRequestOperation("AfterApplicationStart", null, 0);
        }
    }
    /// <summary>
    /// Gets the macros from the system
    /// </summary>
    /// <param name="startIndex">Start index</param>
    /// <param name="endIndex">End index</param>
    /// <param name="maxTotalRecords">Maximum number of total records to process</param>
    /// <param name="totalRecords">Returns the total number of records found</param>
    private IEnumerable <MacroExpr> GetMacros(int startIndex, int endIndex, int maxTotalRecords, out int totalRecords)
    {
        var index = 0;

        var textToSearch       = txtTextToSearch.Text;
        var searchByText       = !String.IsNullOrEmpty(textToSearch);
        var reportProblems     = chkReportProblems.Checked;
        var skipTestingObjects = SystemContext.DevelopmentMode && chkSkipTestingObjects.Checked;
        var type = drpType.Text;

        var result = new List <MacroExpr>();

        foreach (var objectType in GetObjectTypes())
        {
            // Skip certain object types
            switch (objectType)
            {
            case ObjectVersionHistoryInfo.OBJECT_TYPE:
            case VersionHistoryInfo.OBJECT_TYPE:
            case StagingTaskInfo.OBJECT_TYPE:
            case IntegrationTaskInfo.OBJECT_TYPE:
                continue;
            }

            // Process all objects of the given type
            var infos = new ObjectQuery(objectType)
                        .TopN(maxTotalRecords)
                        .BinaryData(false);

            var typeInfo = infos.TypeInfo;

            if (skipTestingObjects)
            {
                ExcludeTestingObjects(infos);
            }

            // Search particular expression or search macros of specific type
            infos.WhereAnyColumnContains(searchByText ? textToSearch : "{" + type);

            Action <DataRow> collectMacros = dr =>
            {
                // Process all expressions
                MacroProcessor.ProcessMacros(new DataRowContainer(dr), (context, colName) =>
                {
                    // Get original macro text with hash
                    string macroType;
                    string originalExpression  = MacroProcessor.RemoveMacroBrackets(context.GetOriginalExpression(), out macroType);
                    string processedExpression = context.Expression;

                    // Decode macro from XML if needed
                    if (MacroProcessor.IsXMLColumn(colName))
                    {
                        originalExpression  = HTMLHelper.HTMLDecode(originalExpression);
                        processedExpression = HTMLHelper.HTMLDecode(processedExpression);
                    }

                    MacroExpr e = null;
                    bool add    = false;

                    if (!searchByText || (originalExpression.IndexOf(textToSearch, StringComparison.InvariantCultureIgnoreCase) >= 0))
                    {
                        // If not tracking errors, count immediately
                        if (!reportProblems)
                        {
                            // Apply paging. (endIndex is -1 when paging is off)
                            if ((endIndex < 0) || ((index >= startIndex) && (index < endIndex)))
                            {
                                e   = GetMacroExpr(originalExpression, processedExpression);
                                add = true;
                            }

                            index++;
                        }
                        else
                        {
                            e = GetMacroExpr(originalExpression, processedExpression);

                            // Filter invalid signature / syntax
                            if (!e.SignatureValid || e.Error)
                            {
                                // Apply paging. (endIndex is -1 when paging is off)
                                if ((endIndex < 0) || ((index >= startIndex) && (index < endIndex)))
                                {
                                    add = true;
                                }

                                index++;
                            }
                        }
                    }

                    if (add)
                    {
                        // Fill in the object information
                        e.ObjectType = objectType;
                        e.ObjectID   = (typeInfo.IDColumn == ObjectTypeInfo.COLUMN_NAME_UNKNOWN) ? 0 : ValidationHelper.GetInteger(dr[typeInfo.IDColumn], 0);
                        e.Field      = colName;

                        result.Add(e);
                    }

                    return(context.Expression);
                }, new List <string> {
                    type
                });

                if ((maxTotalRecords != -1) && (index >= maxTotalRecords))
                {
                    // Enough data - cancel enumeration
                    throw new ActionCancelledException();
                }
            };

            using (var scope = new CMSConnectionScope())
            {
                scope.CommandTimeout = ConnectionHelper.LongRunningCommandTimeout;

                infos.ForEachRow(collectMacros);
            }

            if (((maxTotalRecords != -1) && (index >= maxTotalRecords)) || !CMSHttpContext.Current.Response.IsClientConnected)
            {
                break;
            }
        }

        totalRecords = index;
        return(result);
    }
    /// <summary>
    /// Gets the macros from the system
    /// </summary>
    /// <param name="startIndex">Start index</param>
    /// <param name="endIndex">End index</param>
    /// <param name="maxTotalRecords">Maximum number of total records to process</param>
    /// <param name="totalRecords">Returns the total number of records found</param>
    private IEnumerable<MacroExpr> GetMacros(int startIndex, int endIndex, int maxTotalRecords, ref int totalRecords)
    {
        var index = 0;
        IEnumerable<string> objectTypes = null;

        // Get object types to search
        var selectedType = ValidationHelper.GetString(selObjectType.Value, "");
        if (!String.IsNullOrEmpty(selectedType))
        {
            if (ObjectTypeManager.GetRegisteredTypeInfo(selectedType) != null)
            {
                objectTypes = new List<string> { selectedType };
            }
        }

        if (objectTypes == null)
        {
            objectTypes = ObjectTypeManager.ObjectTypesWithMacros;
        }

        var result = new List<MacroExpr>();
        var search = txtFilter.Text;

        var invalid = chkInvalid.Checked;
        var skipTesting = SystemContext.DevelopmentMode && chkSkipTesting.Checked;

        var type = drpType.Text;

        foreach (var objectType in objectTypes)
        {
            // Skip certain object types
            switch (objectType)
            {
                case ObjectVersionHistoryInfo.OBJECT_TYPE:
                case VersionHistoryInfo.OBJECT_TYPE:
                case StagingTaskInfo.OBJECT_TYPE:
                case IntegrationTaskInfo.OBJECT_TYPE:
                    continue;
            }

            // Process all objects of the given type
            var infos = new ObjectQuery(objectType)
                .TopN(maxTotalRecords)
                .BinaryData(false);

            var typeInfo = infos.TypeInfo;

            if (skipTesting)
            {
                ExcludeTestingObjects(infos);
            }

            if (!String.IsNullOrEmpty(search))
            {
                // Search particular expression
                infos.WhereAnyColumnContains(search);
            }
            else
            {
                // Search just type
                infos.WhereAnyColumnContains("{" + type);
            }

            Action<DataRow> collectMacros = dr =>
            {
                var drc = new DataRowContainer(dr);

                // Process all expressions
                MacroProcessor.ProcessMacros(drc, (expression, colName) =>
                    {
                        var originalExpression = expression;

                        // Decode macro from XML
                        if (MacroProcessor.IsXMLColumn(colName))
                        {
                            expression = HTMLHelper.HTMLDecode(expression);
                        }

                        MacroExpr e = null;
                        bool add = false;

                        if (String.IsNullOrEmpty(search) || (expression.IndexOfCSafe(search, true) >= 0))
                        {
                            // If not tracking errors, count immediately
                            if (!invalid)
                            {
                                // Apply paging. Endindex is -1 when paging is off
                                if ((endIndex < 0) || ((index >= startIndex) && (index <= endIndex)))
                                {
                                    e = GetMacroExpr(expression);
                                    add = true;
                                }

                                index++;
                            }
                            else
                            {
                                e = GetMacroExpr(expression);

                                // Filter invalid signature / syntax
                                var pass = !e.SignatureValid || e.Error;
                                if (pass)
                                {
                                    // Apply paging. Endindex is -1 when paging is off
                                    if ((endIndex < 0) || ((index >= startIndex) && (index <= endIndex)))
                                    {
                                        add = true;
                                    }

                                    index++;
                                }
                            }
                        }

                        if (add)
                        {
                            // Fill in the object information
                            e.ObjectType = objectType;
                            e.ObjectID = (typeInfo.IDColumn == ObjectTypeInfo.COLUMN_NAME_UNKNOWN) ? 0 : ValidationHelper.GetInteger(dr[typeInfo.IDColumn], 0);
                            e.Field = colName;

                            result.Add(e);
                        }

                        return originalExpression;
                    },
                    new List<string> { type }
                );

                if ((maxTotalRecords != -1) && (index >= maxTotalRecords))
                {
                    // Enough data - cancel enumeration
                    throw new ActionCancelledException();
                }
            };

            using (var scope = new CMSConnectionScope())
            {
                scope.Connection.CommandTimeout = ConnectionHelper.LongRunningCommandTimeout;

                infos.ForEachRow(collectMacros);
            }

            if (((maxTotalRecords != -1) && (index >= maxTotalRecords)) || !CMSHttpContext.Current.Response.IsClientConnected)
            {
                break;
            }
        }

        totalRecords = index;
        return result;
    }
Esempio n. 7
0
    /// <summary>
    /// Gets the macros from the system
    /// </summary>
    /// <param name="startIndex">Start index</param>
    /// <param name="endIndex">End index</param>
    /// <param name="maxTotalRecords">Maximum number of total records to process</param>
    /// <param name="totalRecords">Returns the total number of records found</param>
    private IEnumerable <MacroExpr> GetMacros(int startIndex, int endIndex, int maxTotalRecords, ref int totalRecords)
    {
        var index = 0;
        IEnumerable <string> objectTypes = null;

        // Get object types to search
        var selectedType = ValidationHelper.GetString(selObjectType.Value, "");

        if (!String.IsNullOrEmpty(selectedType))
        {
            if (ObjectTypeManager.GetRegisteredTypeInfo(selectedType) != null)
            {
                objectTypes = new List <string> {
                    selectedType
                };
            }
        }

        if (objectTypes == null)
        {
            objectTypes = ObjectTypeManager.ObjectTypesWithMacros;
        }

        var result = new List <MacroExpr>();
        var search = txtFilter.Text;

        var invalid     = chkInvalid.Checked;
        var skipTesting = SystemContext.DevelopmentMode && chkSkipTesting.Checked;

        var type = drpType.Text;

        foreach (var objectType in objectTypes)
        {
            // Skip certain object types
            switch (objectType)
            {
            case ObjectVersionHistoryInfo.OBJECT_TYPE:
            case VersionHistoryInfo.OBJECT_TYPE:
            case StagingTaskInfo.OBJECT_TYPE:
            case IntegrationTaskInfo.OBJECT_TYPE:
                continue;
            }

            // Process all objects of the given type
            var infos = new ObjectQuery(objectType)
                        .TopN(maxTotalRecords)
                        .BinaryData(false);

            var typeInfo = infos.TypeInfo;

            if (skipTesting)
            {
                ExcludeTestingObjects(infos);
            }

            if (!String.IsNullOrEmpty(search))
            {
                // Search particular expression
                infos.WhereAnyColumnContains(search);
            }
            else
            {
                // Search just type
                infos.WhereAnyColumnContains("{" + type);
            }

            Action <DataRow> collectMacros = dr =>
            {
                var drc = new DataRowContainer(dr);

                // Process all expressions
                MacroProcessor.ProcessMacros(drc, (expression, colName) =>
                {
                    var originalExpression = expression;

                    // Decode macro from XML
                    if (MacroProcessor.IsXMLColumn(colName))
                    {
                        expression = HTMLHelper.HTMLDecode(expression);
                    }

                    MacroExpr e = null;
                    bool add    = false;

                    if (String.IsNullOrEmpty(search) || (expression.IndexOfCSafe(search, true) >= 0))
                    {
                        // If not tracking errors, count immediately
                        if (!invalid)
                        {
                            // Apply paging. Endindex is -1 when paging is off
                            if ((endIndex < 0) || ((index >= startIndex) && (index <= endIndex)))
                            {
                                e   = GetMacroExpr(expression);
                                add = true;
                            }

                            index++;
                        }
                        else
                        {
                            e = GetMacroExpr(expression);

                            // Filter invalid signature / syntax
                            var pass = !e.SignatureValid || e.Error;
                            if (pass)
                            {
                                // Apply paging. Endindex is -1 when paging is off
                                if ((endIndex < 0) || ((index >= startIndex) && (index <= endIndex)))
                                {
                                    add = true;
                                }

                                index++;
                            }
                        }
                    }

                    if (add)
                    {
                        // Fill in the object information
                        e.ObjectType = objectType;
                        e.ObjectID   = (typeInfo.IDColumn == ObjectTypeInfo.COLUMN_NAME_UNKNOWN) ? 0 : ValidationHelper.GetInteger(dr[typeInfo.IDColumn], 0);
                        e.Field      = colName;

                        result.Add(e);
                    }

                    return(originalExpression);
                },
                                             new List <string> {
                    type
                }
                                             );

                if ((maxTotalRecords != -1) && (index >= maxTotalRecords))
                {
                    // Enough data - cancel enumeration
                    throw new ActionCancelledException();
                }
            };

            using (var scope = new CMSConnectionScope())
            {
                scope.Connection.CommandTimeout = ConnectionHelper.LongRunningCommandTimeout;

                infos.ForEachRow(collectMacros);
            }

            if (((maxTotalRecords != -1) && (index >= maxTotalRecords)) || !CMSHttpContext.Current.Response.IsClientConnected)
            {
                break;
            }
        }

        totalRecords = index;
        return(result);
    }
    /// <summary>
    /// Delete items.
    /// </summary>
    private void DeleteItems()
    {
        // Set long timeout so that mass delete can finish successfully
        SqlConnectionStringBuilder connectionString = new SqlConnectionStringBuilder(ConnectionHelper.GetConnection().DataConnection.ConnectionString);
        connectionString.ConnectTimeout = SQL_TIMEOUT;
        using (var cs = new CMSConnectionScope(connectionString.ToString(), true))
        {
            // Delete the accounts
            AccountInfo ai = null;
            foreach (string accountId in accountIds)
            {
                ai = AccountInfoProvider.GetAccountInfo(ValidationHelper.GetInteger(accountId, 0));
                if (ai != null)
                {
                    // Display name of deleted account
                    AddLog(ai.AccountName);

                    // Delete account with its dependencies
                    AccountHelper.Delete(ai, chkChildren.Checked, chkBranches.Checked);
                }
            }
        }
    }
    /// <summary>
    /// Performs the application initialization on the first request.
    /// </summary>
    private static void FirstRequestInitialization(object sender, EventArgs e)
    {
        // PreInitialize the application
        if (!mApplicationPreInitialized)
        {
            lock (mLock)
            {
                if (!mApplicationPreInitialized)
                {
                    // Remember date and time of the application start
                    mApplicationStart = DateTime.Now;

                    // Init run from web application - DON'T MOVE LATER
                    SystemHelper.IsWebSite = true;

                    mWindowsIdentity = WindowsIdentity.GetCurrent();

                    // PreInitialize the environment
                    CMSFunctions.PreInit();

                    mApplicationPreInitialized = true;
                }
            }
        }

        // Initialized properly
        bool? initialized = mApplicationInitialized.Value;
        if (initialized == true)
        {
            return;
        }

        // Not initialized, must install
        if ((initialized == false) && InstallerFunctions.InstallRedirect(true))
        {
            return;
        }

        // Do not init application on request to just physical file
        string relativePath = URLHelper.CurrentRelativePath;
        ExcludedSystemEnum excludedEnum = URLHelper.IsExcludedSystemEnum(relativePath, true);

        if ((excludedEnum == ExcludedSystemEnum.PhysicalFile) ||
            (excludedEnum == ExcludedSystemEnum.GetResource) ||
            (excludedEnum == ExcludedSystemEnum.AppThemes))
        {
            return;
        }

        // Initialize application in a locked context
        lock (mLock)
        {
            if (ApplicationInitialized)
            {
                return;
            }

            ViewModeOnDemand viewMode = new ViewModeOnDemand();

            // Log application start
            if (CMSFunctions.AnyDebugEnabled)
            {
                RequestSettings settings = RequestSettings.Current;
                bool liveSite = (viewMode.Value == ViewModeEnum.LiveSite);

                settings.DebugRequest = RequestHelper.DebugRequests && liveSite;
                RequestHelper.LogRequestOperation("BeforeApplicationStart", null, 0);

                settings.DebugSQLQueries = SqlHelperClass.DebugQueries && liveSite;
                settings.DebugFiles = File.DebugFiles && liveSite;
                settings.DebugCache = CacheHelper.DebugCache && liveSite;
                settings.DebugSecurity = SecurityHelper.DebugSecurity && liveSite;
                settings.DebugOutput = OutputHelper.DebugOutput && liveSite;
                settings.DebugMacros = MacroResolver.DebugMacros && liveSite;
                settings.DebugWebFarm = WebSyncHelperClass.DebugWebFarm && liveSite;
                settings.DebugAnalytics = AnalyticsHelper.DebugAnalytics && liveSite;

                DebugHelper.SetContext("App_Start");
            }

            // Initialize MacroResolver with child of GlobalResolver
            MacroResolver.OnGetInstance += new MacroResolver.GetInstanceEventHandler(MacroResolver_OnGetInstance);

            // Handle the event
            using (var h = CMSApplicationEvents.Start.StartEvent(e))
            {
                if (h.Continue)
                {
                    // Initialize the storage methods
                    CMSFunctions.InitStorage();

                    if (SqlHelperClass.IsConnectionStringInitialized)
                    {
                        using (CMSConnectionScope scope = new CMSConnectionScope())
                        {
                            // Use single open connection for the application start
                            GeneralConnection conn = (GeneralConnection)scope.Connection;
                            bool closeConnection = false;
                            try
                            {
                                // Open the connection
                                conn.Open();
                                closeConnection = true;

                                TableManager tm = new TableManager(null);

                                // Check for the table existence
                                if (!tm.TableExists("CMS_SettingsKey"))
                                {
                                    ApplicationInitialized = false;

                                    if (InstallerFunctions.InstallRedirect(true))
                                    {
                                        return;
                                    }
                                }

                                // Check the version
                                string version = SettingsKeyProvider.GetStringValue("CMSDBVersion");
                                if (!CMSContext.IsCorrectDatabaseVersion)
                                {
                                    // Report error about not being able to connect
                                    ConnectionErrorMessage = "The database version '" + version + "' does not match the project version '" + CMSContext.SYSTEM_VERSION + "', please check your connection string.";
                                    HttpContext.Current.Server.Transfer("~/CMSMessages/error.aspx");
                                }
                                else
                                {
                                    // Initialize the environment
                                    CMSFunctions.Init();

                                    // Update the system !! IMPORTANT - must be first
                                    UpgradeProcedure.Update(conn);
                                    try
                                    {
                                        // Write "Application start" event to the event log
                                        EventLogProvider ev = new EventLogProvider();

                                        ev.DeleteOlderLogs = false;
                                        ev.LogEvent(EventLogProvider.EVENT_TYPE_INFORMATION, DateTime.Now, "Application_Start", "STARTAPP", 0, null, 0, null, null, null, 0, HTTPHelper.GetAbsoluteUri());
                                    }
                                    catch
                                    {
                                        // can't write to log, do not process any code
                                    }
                                    UserInfoProvider.OnFormattedUserName += new UserInfoProvider.FormattedUserNameEventHandler(Functions.GetFormattedUserName);

                                    // Initialize the web farm
                                    CMSFunctions.InitWebFarm();

                                    // Handle admin emergency reset
                                    string adminReset = ValidationHelper.GetString(SettingsHelper.AppSettings["CMSAdminEmergencyReset"], null);
                                    if (!string.IsNullOrEmpty(adminReset))
                                    {
                                        string[] resetParams = adminReset.Split(';');
                                        if ((resetParams.Length >= 1) && (resetParams.Length <= 3))
                                        {
                                            // Check if create user if she doesn't exist
                                            bool forceCreate = (resetParams.Length == 3) ? ValidationHelper.GetBoolean(resetParams[2], false) : false;
                                            string userName = resetParams[0];
                                            UserInfo ui = UserInfoProvider.GetUserInfo(userName);

                                            // Create new user
                                            if ((ui == null) && forceCreate)
                                            {
                                                if (UserInfoProvider.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.GlobalAdmininistrators, VersionActionEnum.Insert, false))
                                                {
                                                    if (ValidationHelper.IsUserName(userName))
                                                    {
                                                        ui = new UserInfo();
                                                        ui.UserName = resetParams[0];
                                                        ui.UserIsGlobalAdministrator = true;
                                                        ui.UserEnabled = true;

                                                        string error = null;
                                                        UserInfoProvider.CheckLicenseLimitation(ui, ref error);
                                                        if (!string.IsNullOrEmpty(error))
                                                        {
                                                            throw new Exception(string.Format("[FirstRequestInitialization.AdminEmergencyReset: {0}]", error));
                                                        }
                                                    }
                                                    else
                                                    {
                                                        throw new Exception("[FirstRequestInitialization.AdminEmergencyReset: Specified username for newly created user is not valid.]");
                                                    }
                                                }
                                            }

                                            // Unlock account and set new specified password
                                            if (ui != null)
                                            {
                                                UserInfoProvider.SetPassword(ui, (resetParams.Length > 1) ? resetParams[1] : "", false);
                                                AuthenticationHelper.UnlockUserAccount(ui);
                                            }

                                            // Remove key from web.config
                                            SettingsHelper.RemoveConfigValue("CMSAdminEmergencyReset");
                                            URLHelper.Redirect(URLHelper.CurrentURL);
                                        }
                                    }

                                    // Wait until initialization is complete
                                    CMSFunctions.WaitForInitialization();
                                }
                            }
                            catch (Exception ex)
                            {
                                if (closeConnection)
                                {
                                    // Server connected successfully but something else went wrong
                                    throw ex;
                                }
                                else
                                {
                                    // Report error about not being able to connect
                                    ConnectionErrorMessage = ex.Message;

                                    HttpContext.Current.Server.Transfer("~/CMSMessages/error.aspx");
                                }
                            }
                            finally
                            {
                                if (closeConnection)
                                {
                                    // Close the connection
                                    conn.Close();
                                }
                            }
                        }

                        DBSeparationCheck();
                    }
                    else
                    {
                        // Register virtual path provider
                        if (ValidationHelper.GetBoolean(SettingsHelper.AppSettings["CMSUseVirtualPathProvider"], true))
                        {
                            VirtualPathHelper.RegisterVirtualPathProvider();
                        }
                    }

                    // Register the CMS view engine
                    CMSWebFormViewEngine.RegisterViewEngine();
                }

                // Finalize the event
                h.FinishEvent();
            }

            DebugHelper.ReleaseContext();

            // Log when the overall application start finished its execution
            mApplicationStartFinished = DateTime.Now;
            ApplicationInitialized = true;

            RequestHelper.LogRequestOperation("AfterApplicationStart", null, 0);
        }
    }