Exemple #1
0
    protected void Page_Load(object sender, EventArgs e)
    {
        p.LogEvent("I", DateTime.Now, "ShoppingCartPaymentGateway ", "");
        // No payment provider loaded -> skip payment
        if (ShoppingCartControl.PaymentGatewayProvider == null)
        {
            // Clean current order payment result when editing existing order and payment was skipped
            if ((ShoppingCartControl.CheckoutProcessType == CheckoutProcessEnum.CMSDeskOrderItems) &&
                !ShoppingCartControl.IsCurrentStepPostBack)
            {
                p.LogEvent("I", DateTime.Now, "CleanUpOrderPaymentResult ", "");
                CleanUpOrderPaymentResult();
            }

            // Raise payment skipped
            ShoppingCartControl.RaisePaymentSkippedEvent();

            // When on the live site
            if (!ShoppingCartControl.IsInternalOrder)
            {
                // Get Url the user should be redirected to
                string url = ShoppingCartControl.GetRedirectAfterPurchaseUrl();

                // Remove shopping cart data from database and from session
                ShoppingCartControl.CleanUpShoppingCart();

                if (!string.IsNullOrEmpty(url))
                {
                    URLHelper.Redirect(url);
                }
                else
                {
                    URLHelper.Redirect(ShoppingCartControl.PreviousPageUrl);
                }
            }
            return;
        }
        else if (ShoppingCart != null)
        {
            p.LogEvent("I", DateTime.Now, "ShoppingCartControl.PaymentGatewayProvider != null ", "");
            LoadData();
        }

        lblTitle.Text      = GetString("PaymentSummary.Title");
        lblTotalPrice.Text = GetString("PaymentSummary.TotalPrice");
        lblOrderId.Text    = GetString("PaymentSummary.OrderId");
        lblPayment.Text    = GetString("PaymentSummary.Payment");
        this.ShoppingCartControl.ButtonNextClickAction();
    }
    protected void btnClone_Click(object sender, EventArgs e)
    {
        try
        {
            CloneResult result = cloneObjectElem.CloneObject();
            if (result != null)
            {
                if (result.Errors.Count > 0)
                {
                    ShowError(ResHelper.LocalizeString(string.Join("\n", result.Errors.ToArray())));
                    SwitchToErrorMode();
                }
                else if (result.Warnings.Count > 0)
                {
                    ShowWarning(GetString("cloning.savedwithwarnings"), ResHelper.LocalizeString(string.Join("<br/>", result.Warnings.ToArray())), null);
                    SwitchToErrorMode();
                }
                else
                {
                    ScriptHelper.RegisterStartupScript(this.Page, typeof(string), "CloneRefresh", cloneObjectElem.CloseScript, true);
                }
            }
        }
        catch (Exception ex)
        {
            EventLogProvider provider = new EventLogProvider();
            provider.LogEvent(string.IsNullOrEmpty(objectType) ? "System" : objectType.ToLowerCSafe(), "CLONEOBJECT", ex);
            ShowError(ex.Message);

            if (!cloneObjectElem.UseTransaction)
            {
                SwitchToErrorMode();
            }
        }
    }
Exemple #3
0
    /// <summary>
    /// Gets data from SharePoint.
    /// </summary>
    /// <returns>Dataset or XmlNode as object</returns>
    protected override object GetDataSourceFromDB()
    {
        // Mark loading was tried
        retrieved = true;

        object data = null;

        try
        {
            // Check if URL address of web service is valid
            if (!ValidationHelper.IsURL(this.SPServiceURL))
            {
                ShowError(ResHelper.GetString("SharePoint.invalidURL"));
                return(null);
            }

            // Get SharePoint data and set datasource
            data = GetSharePointData();
        }
        catch (Exception ex)
        {
            EventLogProvider ep = new EventLogProvider();
            ep.LogEvent("SharePointDataSource", "GetSharePointData", ex);
        }

        return(data);
    }
Exemple #4
0
        protected void SetupControl()
        {
            if (!StopProcessing)
            {
                var rawData = new JavaScriptSerializer().Deserialize <List <DynamicPricingRawData> >(DocumentContext.CurrentDocument.GetStringValue("ProductDynamicPricing", string.Empty));

                if (rawData == null || rawData.Count == 0)
                {
                    var basePrice = DocumentContext.CurrentDocument.GetDoubleValue("SKUPrice", 0);
                    ltlTableContent.Text = string.Format(_TableRowTemplate, ResHelper.GetString("Kadena.Product.BasePriceTitle", LocalizationContext.CurrentCulture.CultureCode), basePrice.ToString("C"));
                }
                else
                {
                    List <DynamicPricingData> data;
                    if (new DynamicPricingDataHelper().ConvertDynamicPricingData(rawData, out data))
                    {
                        var result = new StringBuilder();
                        foreach (var item in data)
                        {
                            result.Append(string.Format(_TableRowTemplate, string.Format(ResHelper.GetString("Kadena.Product.PiecesFormatString", LocalizationContext.CurrentCulture.CultureCode), item.Min, item.Max), item.Price.ToString("C")));
                        }
                        ltlTableContent.Text = result.ToString();
                    }
                    else
                    {
                        EventLogProvider.LogEvent("E", "Dynamic pricing table", "Display dynamic pricing data", "Dynamic pricing data couldn't be restored");
                    }
                }
            }
        }
Exemple #5
0
    /// <summary>
    /// Inits the async dialog.
    /// </summary>
    private void InitAsyncDialog()
    {
        btnCancel.Text          = GetString("general.cancel");
        btnCancel.OnClientClick = ucAsync.GetCancelScript(true) + " return false;";

        ucAsync.OnRequestLog += (sender, args) =>
        {
            ucAsync.Log = AsyncLogContext.Log;
        };

        ucAsync.OnCancel += (sender, args) =>
        {
            EventLogProvider.LogEvent(EventType.INFORMATION, (string)ucAsync.Parameter, "CANCELLED");

            plcAsyncLog.Visible = false;
            AsyncLogContext.Close();

            ShowConfirmation(GetString("general.actioncanceled"));
        };

        ucAsync.OnFinished += (sender, args) =>
        {
            EventLogProvider.LogEvent(EventType.INFORMATION, (string)ucAsync.Parameter, "FINISHED");

            plcAsyncLog.Visible = false;
            AsyncLogContext.Close();

            ShowConfirmation(GetString("general.actionfinished"));
        };
    }
Exemple #6
0
        public int GetDocumentID(Guid DocumentGuid)
        {
            var DocumentID = CacheHelper.Cache(cs =>
            {
                var Document = new DocumentQuery()
                               .WhereEquals(nameof(TreeNode.DocumentGUID), DocumentGuid)
                               .TopN(1)
                               .Columns(nameof(TreeNode.DocumentID))
                               .FirstOrDefault();

                if (Document == null)
                {
                    EventLogProvider.LogEvent("W", "PartialWidgetPage", "CouldNotLocateDocument", eventDescription: $"Could not locate a document with DocumentGuid {DocumentGuid}.");
                    return(0);
                }
                if (cs.Cached)
                {
                    cs.CacheDependency = CacheHelper.GetCacheDependency(new string[]
                    {
                        $"documentid|{Document.DocumentID}"
                    });
                }

                return(Document.DocumentID);
            }, new CacheSettings(1440, "PartialWidgetPage_GetDocumentID", DocumentGuid));

            // Add dependencies to response manually
            AddCacheItemDependency($"documentid|{DocumentID}");

            return(DocumentID);
        }
Exemple #7
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();"));
            }
        }
    }
Exemple #8
0
    /// <summary>
    /// OnClick event handler for cancel impersonation.
    /// </summary>
    protected void lnkCancelImpersonate_OnClick(object sender, EventArgs e)
    {
        string originalUserName = ValidationHelper.GetString(SessionHelper.GetValue("OriginalUserName"), "");

        if (RequestHelper.IsFormsAuthentication())
        {
            UserInfo ui = UserInfoProvider.GetUserInfo(originalUserName);

            AuthenticationHelper.SetCurrentUser(null);
            AuthenticationHelper.AuthenticateUser(ui.UserName, false, false);

            EventLogProvider.LogEvent(EventType.INFORMATION, "Administration", "Impersonate", "User " + ui.UserName + " has returned to his account.");

            UIContextHelper.RegisterAdminRedirectScript(Page);
        }
        else
        {
            SessionHelper.SetValue("ImpersonateUserName", null);
            SessionHelper.SetValue("OriginalUserName", null);

            MembershipContext.AuthenticatedUser.Generalized.Invalidate(false);

            // Log event
            EventLogProvider.LogEvent(EventType.INFORMATION, "Administration", "Impersonate", "User " + originalUserName + " has returned to his account.", RequestContext.CurrentURL, 0, null, 0, null, null, SiteContext.CurrentSiteID);

            URLHelper.Redirect(RequestContext.CurrentURL);
        }
    }
        private void btnUse_ServerClick(object sender, EventArgs e)
        {
            var btn = sender as HtmlButton;

            if (btn != null)
            {
                var url         = URLHelper.URLDecode(Request.QueryString["url"]);
                var containerId = btn.ID;
                var templateId  = string.IsNullOrWhiteSpace(url) ? string.Empty : URLHelper.GetUrlParameter(url, "templateid");
                var workspaceId = string.IsNullOrWhiteSpace(url) ? string.Empty : URLHelper.GetUrlParameter(url, "workspaceid");
                var use3d       = string.IsNullOrWhiteSpace(url) ? false : bool.Parse(URLHelper.GetUrlParameter(url, "use3d"));
                var quantity    = btn.Attributes["quantity"];
                if (!string.IsNullOrWhiteSpace(containerId) && !string.IsNullOrWhiteSpace(templateId) && !string.IsNullOrWhiteSpace(workspaceId))
                {
                    var templateClient = DIContainer.Resolve <ITemplatedClient>();
                    var setResult      = templateClient.SetMailingList(containerId, templateId, workspaceId, use3d).Result;
                    if (!setResult.Success)
                    {
                        EventLogProvider.LogEvent(EventType.ERROR, "SET MAILING LIST", "ERROR", setResult.ErrorMessages);
                    }
                    url += $"&containerId={containerId}&quantity={quantity}";
                    Response.Redirect(url);
                }
            }
        }
Exemple #10
0
    /// <summary>
    /// Button destroy history click.
    /// </summary>
    protected void btnDestroy_Click(object sender, EventArgs e)
    {
        if (Object != null)
        {
            // Check permissions
            if (CheckPermissions && !AllowDestroy)
            {
                lblError.Text     = GetString("History.ErrorNotAllowedToDestroy");
                plcLabels.Visible = true;
                return;
            }
            ObjectVersionManager.DestroyObjectHistory(Object.ObjectType, Object.ObjectID);

            UserInfo currentUser = CMSContext.CurrentUser;
            string   objType     = GetString("Objecttype." + Object.ObjectType.Replace(".", "_"));
            string   description = GetString(String.Format("objectversioning.historydestroyed", SqlHelperClass.GetSafeQueryString(Object.ObjectDisplayName, false)));

            EventLogProvider ev = new EventLogProvider();
            ev.LogEvent(EventLogProvider.EVENT_TYPE_INFORMATION, DateTime.Now, objType, "DESTROYHISTORY", HTTPHelper.GetAbsoluteUri(), description);

            ReloadData();
        }
        else
        {
            CMSPage.EditedObject = null;
        }
    }
Exemple #11
0
    private void gridElem_OnAction(string actionName, object actionArgument)
    {
        switch (actionName.ToLowerCSafe())
        {
        case "edit":
            SelectedItemID = ValidationHelper.GetInteger(actionArgument, 0);
            RaiseOnEdit();
            break;

        case "delete":
            MediaLibraryInfo mli = MediaLibraryInfoProvider.GetMediaLibraryInfo(ValidationHelper.GetInteger(actionArgument, 0));
            // Check 'Manage' permission
            if (!MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(mli, PERMISSION_MANAGE))
            {
                ShowError(MediaLibraryHelper.GetAccessDeniedMessage(PERMISSION_MANAGE));
                return;
            }
            try
            {
                MediaLibraryInfoProvider.DeleteMediaLibraryInfo(ValidationHelper.GetInteger(actionArgument, 0));
            }
            catch (Exception ex)
            {
                EventLogProvider eventLog = new EventLogProvider();
                eventLog.LogEvent("Media library", "DELETEOBJ", ex, CMSContext.CurrentSiteID);

                ShowError(ex.Message, EventLogProvider.GetExceptionLogMessage(ex), null);
            }
            break;
        }

        RaiseOnAction(actionName, actionArgument);
    }
    protected void btnClone_Click(object sender, EventArgs e)
    {
        try
        {
            CloneResult result = cloneObjectElem.CloneObject();
            if (result != null)
            {
                if (result.Errors.Count > 0)
                {
                    ShowError(ResHelper.LocalizeString(string.Join("\n", result.Errors.ToArray())));
                    SwitchToErrorMode();
                }
                else if (result.Warnings.Count > 0)
                {
                    ShowWarning(GetString("cloning.savedwithwarnings"), ResHelper.LocalizeString(string.Join("<br/>", result.Warnings.ToArray())), null);
                    SwitchToErrorMode();
                }
                else
                {
                    ScriptHelper.RegisterStartupScript(this.Page, typeof(string), "CloneRefresh", cloneObjectElem.CloseScript, true);
                }
            }
        }
        catch (Exception ex)
        {
            EventLogProvider provider = new EventLogProvider();
            provider.LogEvent(string.IsNullOrEmpty(objectType) ? "System" : objectType.ToLowerCSafe(), "CLONEOBJECT", ex);
            ShowError(ex.Message);

            if (!cloneObjectElem.UseTransaction)
            {
                SwitchToErrorMode();
            }
        }
    }
Exemple #13
0
    protected void btnPostAtTwitter_Click(object sender, EventArgs e)
    {
        if (txtTemplateTwitter.Text.Trim() == "")
        {
            ShowError(ResHelper.GetString("socialnetworking.twitter.emptyerror"));
            return;
        }

        string template = txtTemplateTwitter.Text;

        // Process template.
        MacroResolver mr         = MacroResolver.GetInstance();
        string        textToSend = mr.ResolveMacros(template);

        // Shorten URLs.
        textToSend = URLShortenerHelper.ShortenURLsInText(textToSend, SocialNetworkType.Twitter);

        ShowInformation(String.Format(ResHelper.GetString("socialnetworking.lengthafterprocessing"), textToSend.Length));

        // Send tweet
        string tweetUrl = TwitterProvider.PublishTweet(textToSend, CMSContext.CurrentSiteName);

        // Check if tweet was succesfully published.
        bool success = !string.IsNullOrEmpty(tweetUrl);

        if (success)
        {
            ShowConfirmation(ResHelper.GetString("socialnetworking.twitter.sendsuccess"));

            dataElement.IsPublished             = true;
            dataElement.PostURL                 = tweetUrl;
            dataElement.AutoPostAfterPublishing = false;
            dataElement.Template                = txtTemplateTwitter.Text;

            try
            {
                // Save dataElement into database
                node.SetValue(FieldInfo.Name, SerializeData().OuterXml);
                if (IsWorkflow)
                {
                    DocumentHelper.UpdateDocument(node, node.TreeProvider);
                }
                else
                {
                    node.Update();
                }

                RenderControls();
            }
            catch (Exception ex)
            {
                EventLogProvider ev = new EventLogProvider();
                ev.LogEvent("TwitterAutoPost", "AfterPost", ex, CMSContext.CurrentSiteID);
            }
        }
        else
        {
            ShowError(ResHelper.GetString("socialnetworking.twitter.senderror"));
        }
    }
Exemple #14
0
    /// <summary>
    /// Restart application.
    /// </summary>
    protected void Restart(object sender = null, EventArgs args = null)
    {
        if (StopProcessing)
        {
            return;
        }

        if (SystemHelper.RestartApplication(Request.PhysicalApplicationPath))
        {
            if (SystemContext.IsRunningOnAzure)
            {
                // Log event
                EventLogProvider.LogEvent(EventType.INFORMATION, "System", "ENDAPP", GetString("admin.system.restartazure"));
                ShowConfirmation(GetString("admin.system.restartazure"));
            }
            else
            {
                // Log event
                EventLogProvider.LogEvent(EventType.INFORMATION, "System", "ENDAPP", GetString("Administration-System.RestartSuccess"));

                string url = URLHelper.UpdateParameterInUrl(RequestContext.CurrentURL, "lastaction", "Restarted");
                URLHelper.Redirect(url);
            }
        }
        else
        {
            ShowError(GetString("System.Restart.Failed"));
        }
    }
Exemple #15
0
    /// <summary>
    /// Finish button click.
    /// </summary>
    protected void FinishNextButton_Click(object sender, EventArgs e)
    {
        if (SqlInstallationHelper.DatabaseIsSeparated())
        {
            string error = String.Empty;
            // If it doesn't support OpenQuery command, data could not have been moved so we cannot delete tables.
            if (SqlServerCapabilities.SupportsOpenQueryCommand)
            {
                var separationHelper = new DatabaseSeparationHelper();

                separationHelper.InstallationConnStringSeparate = DatabaseSeparationHelper.ConnStringSeparate;
                separationHelper.InstallScriptsFolder           = SqlInstallationHelper.GetSQLInstallPathToObjects();
                separationHelper.ScriptsFolder = Server.MapPath("~/App_Data/DBSeparation");
                error = separationHelper.DeleteSourceTables(false, true);
            }

            if (!String.IsNullOrEmpty(error))
            {
                separationFinished.ErrorLabel.Visible = true;
                separationFinished.ErrorLabel.Text    = error;
                EventLogProvider.LogEvent(EventType.ERROR, "Contact management database separation", "DELETEOLDDATA", error, RequestContext.CurrentURL);
            }
            else
            {
                EnableTasks();
                TakeSitesOnline();
                WebFarmHelper.CreateTask(SystemTaskType.RestartApplication, "RestartApplication");
                ScriptHelper.RegisterStartupScript(this, typeof(string), "Close dialog", ScriptHelper.GetScript("RefreshParent(); CloseDialog();"));
            }
        }
    }
Exemple #16
0
        /// <summary>
        /// Executes the task.
        /// </summary>
        /// <param name="ti">Task info</param>
        public string Execute(TaskInfo ti)
        {
            EventLogProvider ev = new EventLogProvider();
            ev.LogEvent(EventLogProvider.EVENT_TYPE_INFORMATION, DateTime.Now, "MyTask", "Execute", null, "This task was executed from '~/App_Code/Global/CMS/CMSCustom.cs'.");

            return null;
        }
    /// <summary>
    /// Sets page size dropdown list according to PageSize property.
    /// </summary>
    private void SetPageSize(bool forceReload)
    {
        if ((drpPageSize.Items.Count == 0) || forceReload)
        {
            string currentPagesize = CurrentPageSize.ToString();

            if (!PagerLoaded && (PagerMode != UniPagerMode.Querystring))
            {
                currentPagesize = DefaultPageSize.ToString();
            }

            drpPageSize.Items.Clear();

            PageSizeOptionsData pageSizeOptionsData;

            if (!TryParsePageSizeOptions(PageSizeOptions, out pageSizeOptionsData))
            {
                EventLogProvider.LogEvent(EventType.ERROR, "UIPager", "ParseCustomOptions", "Could not parse custom page size options: '" + PageSizeOptions + "'. Correct format is values separated by comma.");
                TryParsePageSizeOptions(DEFAULT_PAGE_SIZE_OPTIONS, out pageSizeOptionsData);
            }

            // Add default page size if not present
            if ((DefaultPageSize > 0) && !pageSizeOptionsData.Options.Contains(DefaultPageSize))
            {
                pageSizeOptionsData.Options.Add(DefaultPageSize);
            }

            // Sort list of page sizes
            pageSizeOptionsData.Options.Sort();

            FillPageSizeDropdown(pageSizeOptionsData, currentPagesize);
        }
    }
    /// <summary>
    /// Callback event handler.
    /// </summary>
    /// <param name="argument">Callback argument</param>
    public void RaiseCallbackEvent(string argument)
    {
        // Get arguments
        string[] args          = argument.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
        bool     cancel        = ValidationHelper.GetBoolean(args[0], false);
        int      messageLength = 0;
        int      errorLength   = 0;
        int      warningLength = 0;

        if (args.Length == 4)
        {
            messageLength = ValidationHelper.GetInteger(args[1], 0);
            errorLength   = ValidationHelper.GetInteger(args[2], 0);
            warningLength = ValidationHelper.GetInteger(args[3], 0);
        }

        try
        {
            // Cancel Import
            if (cancel)
            {
                ImportManager.Settings.Cancel();
            }

            hdnLog.Value = ImportManager.Settings.GetLimitedProgressLog(messageLength, errorLength, warningLength);
        }
        catch (Exception ex)
        {
            EventLogProvider ev = new EventLogProvider();
            ev.LogEvent("LicenseImport", "IMPORT", ex);

            hdnLog.Value = ImportManager.Settings.GetLimitedProgressLog(messageLength, errorLength, warningLength);
        }
    }
Exemple #19
0
    protected void lnkBreakWithClear_Click(Object sender, EventArgs e)
    {
        // Check permission
        CheckModifyPermission(true);

        // Break permission inheritance and clear permissions
        AclInfoProvider.BreakInheritance(Node, false);

        // Log staging task and flush cache
        DocumentSynchronizationHelper.LogDocumentChange(Node, TaskTypeEnum.BreakACLInheritance, Node.TreeProvider, SynchronizationInfoProvider.ENABLED_SERVERS, null, Node.TreeProvider.AllowAsyncActions);
        Node.ClearCache();

        // Insert information about this event to event log.
        if (DocumentManager.Tree.LogEvents)
        {
            EventLogProvider.LogEvent(EventType.INFORMATION, "Content", "DOCPERMISSIONSMODIFIED", ResHelper.GetAPIString("security.documentpermissionsbreakclear", "Inheritance of the parent page permissions have been broken."), eventUrl, currentUser.UserID, currentUser.UserName, Node.NodeID, DocumentName, ipAddress, Node.NodeSiteID);
        }

        lblInheritanceInfo.Text = GetString("Security.InheritsInfo.DoesNotInherit");
        SwitchBackToPermissionsMode();

        // Clear and reload
        securityElem.InvalidateAcls();
        securityElem.LoadOperators(true);
    }
Exemple #20
0
    protected void ClearCache(object sender = null, EventArgs args = null)
    {
        if (StopProcessing)
        {
            return;
        }

        // Clear the cache
        CacheHelper.ClearCache(null, true);
        Functions.ClearHashtables();

        // Drop the routes
        CMSDocumentRouteHelper.DropAllRoutes();

        // Disposes all zip files
        ZipStorageProvider.DisposeAll();

        // Collect the memory
        GC.Collect();
        GC.WaitForPendingFinalizers();

        // Log event
        EventLogProvider.LogEvent(EventType.INFORMATION, "System", "CLEARCACHE", GetString("Administration-System.ClearCacheSuccess"));

        ShowConfirmation(GetString("Administration-System.ClearCacheSuccess"));

        LoadData();
    }
Exemple #21
0
    /// <summary>
    /// Handles after validation event of UIForm.
    /// </summary>
    protected void OnAfterValidate(object sender, EventArgs e)
    {
        // Perform additional validation if web farm server is enabled
        if (ValidationHelper.GetBoolean(Control.GetFieldValue("ServerEnabled"), false))
        {
            // Get the web farm server object
            var serverId = QueryHelper.GetInteger("objectid", 0);
            var webFarm  = WebFarmServerInfoProvider.GetWebFarmServerInfo(serverId) ?? new WebFarmServerInfo();

            // Get current license
            var currentLicense = LicenseContext.CurrentLicenseInfo;
            if (currentLicense == null)
            {
                return;
            }

            // Enabling or new server as action insert
            var action = ((webFarm.ServerID > 0) && webFarm.ServerEnabled) ? ObjectActionEnum.Edit : ObjectActionEnum.Insert;
            if (!currentLicense.CheckServerCount(WebSyncHelper.ServerCount, action))
            {
                // Set validation message
                Control.ValidationErrorMessage = ResHelper.GetStringFormat("licenselimitation.infopagemessage", FeatureEnum.Webfarm.ToStringRepresentation());
                Control.StopProcessing         = true;

                // Log "servers exceeded" event
                var message = ResHelper.GetString("licenselimitation.serversexceeded");
                EventLogProvider.LogEvent(EventType.WARNING, "WebFarms", LicenseHelper.LICENSE_LIMITATION_EVENTCODE, message, RequestContext.CurrentURL);
            }
        }
    }
Exemple #22
0
    /// <summary>
    /// Clear counters.
    /// </summary>
    protected void ClearCounters(object sender = null, EventArgs args = null)
    {
        if (StopProcessing)
        {
            return;
        }

        try
        {
            // Reset values of health monitoring counters
            HealthMonitoringManager.ResetCounters();
            // Clear application counters
            HealthMonitoringLogHelper.ClearApplicationCounters();

            // Log event
            EventLogProvider.LogEvent(EventType.INFORMATION, "System", "CLEARCOUNTERS", GetString("Administration-System.CountersCleared"));

            string url = URLHelper.UpdateParameterInUrl(RequestContext.CurrentURL, "lastaction", "CounterCleared");
            URLHelper.Redirect(url);
        }
        catch (Exception ex)
        {
            // ThreadAbortException is thrown when response is ended (redirect)
            if (!(ex is ThreadAbortException))
            {
                LogAndShowError("System", "CLEARCOUNTERS", ex);
            }
        }
    }
Exemple #23
0
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            string videoUrl = VideoURL.Trim();

            if (!ValidationHelper.IsURL(videoUrl))
            {
                EventLogProvider.LogEvent(EventType.ERROR, "YouTubeVideo", "INVALIDVIDEOURL", String.Format("YouTube video web part couldn't load the video because the given URL is not valid: {0}", HTMLHelper.HTMLEncode(videoUrl)));
                return;
            }

            // If no wmode is set, append 'transparent' wmode. Fix IE issue with widget (widgets buttons are beyond YouTube video)
            if (String.IsNullOrEmpty(URLHelper.GetQueryValue(videoUrl, "wmode")))
            {
                videoUrl = URLHelper.UpdateParameterInUrl(videoUrl, "wmode", "transparent");
            }

            YouTubeVideoParameters ytParams = new YouTubeVideoParameters
            {
                Url           = videoUrl,
                FullScreen    = FullScreen,
                AutoPlay      = AutoPlay,
                RelatedVideos = Rel,
                Width         = Width,
                Height        = Height,
            };

            ltlPlaceholder.Text = MediaHelper.GetYouTubeVideo(ytParams);
        }
    }
Exemple #24
0
        private DiscountCouponInfo GetDiscountByOrderId(int orderID)
        {
            var ev = new EventLogProvider();

            try
            {
                DiscountCouponInfo discountCouponInfo = new DiscountCouponInfo();
                string             sql = "SELECT [DiscountCouponID],[DiscountCouponValue],[DiscountCouponIsFlatValue],[DiscountCouponValidTo] FROM [COM_DiscountCoupon] " +
                                         "INNER JOIN [COM_Order] ON [COM_Order].[OrderDiscountCouponID] = [COM_DiscountCoupon].[DiscountCouponID] " +
                                         "WHERE [COM_Order].[OrderID] = @orderID";
                var param = new QueryDataParameters();
                param.Add(new DataParameter("@orderID", orderID));
                DataSet ds = ConnectionHelper.ExecuteQuery(sql, param, QueryTypeEnum.SQLQuery);
                if (!DataHelper.DataSourceIsEmpty(ds))
                {
                    foreach (DataRow reader in ds.Tables[0].Rows)
                    {
                        discountCouponInfo.DiscountCouponID          = ValidationHelper.GetInteger(reader["DiscountCouponID"], 0);
                        discountCouponInfo.DiscountCouponIsFlatValue = ValidationHelper.GetBoolean(reader["DiscountCouponIsFlatValue"], false);
                        discountCouponInfo.DiscountCouponValue       = ValidationHelper.GetDouble(reader["DiscountCouponValue"], 0);
                        discountCouponInfo.DiscountCouponValidTo     = ValidationHelper.GetDateTime(reader["DiscountCouponValidTo"], DateTime.MinValue);
                        return(discountCouponInfo);
                    }
                }
                return(discountCouponInfo);
            }
            catch (Exception ex)
            {
                ev.LogEvent("E", DateTime.Now, "CMSModuleLoader.GetDiscountValueById", ex.Message);
            }
            return(null);
        }
Exemple #25
0
        private void DownloadFile()
        {
            if (_containerId != Guid.Empty)
            {
                var mailingListClient = DIContainer.Resolve <IMailingListClient>();

                var mailingListResponse = mailingListClient.GetMailingList(_containerId).Result;
                if (mailingListResponse.Success)
                {
                    var mailingList    = mailingListResponse.Payload;
                    var exportClient   = DIContainer.Resolve <IExportClient>();
                    var exportResponse = exportClient.ExportMailingList(_containerId, SiteContext.CurrentSiteName).Result;
                    if (exportResponse.Success)
                    {
                        var exportedStream = exportResponse.Payload;
                        Response.Clear();
                        Response.ContentType = "text/csv";
                        Response.AddHeader("Content-Disposition", $"attachment; filename=\"{mailingList.Name}.csv\";");
                        Response.BufferOutput = false;
                        exportedStream.Seek(0, SeekOrigin.Begin);
                        exportedStream.CopyTo(Response.OutputStream);
                        Response.End();
                    }
                    else
                    {
                        EventLogProvider.LogEvent(EventType.ERROR, GetType().Name, "ExportClient", exportResponse.ErrorMessages);
                    }
                }
                else
                {
                    EventLogProvider.LogEvent(EventType.ERROR, GetType().Name, "MailingListClient", mailingListResponse.ErrorMessages);
                }
            }
        }
    protected void btnDestroy_Click(object sender, EventArgs e)
    {
        if (Node == null)
        {
            return;
        }

        // Check permissions
        if (!CanDestroy || (CheckedOutByAnotherUser && !CanCheckIn))
        {
            ShowError(GetString("History.ErrorNotAllowedToDestroy"));
            return;
        }
        VersionManager.ClearDocumentHistory(Node.DocumentID);
        ShowConfirmation(GetString("VersionProperties.VersionsCleared"));

        EventLogProvider.LogEvent(EventType.INFORMATION, "Content", "DESTROYHISTORY", String.Format(ResHelper.GetAPIString("contentedit.documenthistorydestroyed", "History of the page '{0}' has been destroyed."), HTMLHelper.HTMLEncode(Node.NodeAliasPath)), RequestContext.RawURL, TreeProvider.UserInfo.UserID, TreeProvider.UserInfo.UserName, Node.NodeID, Node.GetDocumentName(), RequestContext.UserHostAddress, Node.NodeSiteID);

        InvalidateNode();
        ReloadData();

        if (AfterDestroyHistory != null)
        {
            AfterDestroyHistory(sender, e);
        }
    }
    /// <summary>
    /// Button destroy history click.
    /// </summary>
    protected void btnDestroy_Click(object sender, EventArgs e)
    {
        var obj = Object;

        if (obj != null)
        {
            // Check permissions
            if (CheckPermissions && !AllowDestroy)
            {
                ShowError(GetString("History.ErrorNotAllowedToDestroy"));
                return;
            }

            var ti = obj.TypeInfo;

            ObjectVersionManager.DestroyObjectHistory(ti.ObjectType, obj.Generalized.ObjectID);

            string objType     = GetString("Objecttype." + ti.ObjectType.Replace(".", "_"));
            string description = String.Format(GetString("objectversioning.historydestroyed"), SqlHelper.GetSafeQueryString(obj.Generalized.ObjectDisplayName, false));

            EventLogProvider.LogEvent(EventType.INFORMATION, objType, "DESTROYHISTORY", description, RequestContext.RawURL);

            ReloadData();
        }
        else
        {
            UIContext.EditedObject = null;
        }
    }
Exemple #28
0
    protected void btnClearCache_Click(object sender, EventArgs e)
    {
        if (StopProcessing)
        {
            return;
        }

        // Clear the cache
        CacheHelper.ClearCache(null, true);
        Functions.ClearHashtables();

        // Drop the routes
        CMSMvcHandler.DropAllRoutes();

        // Collect the memory
        GC.Collect();
        GC.WaitForPendingFinalizers();

        // Log event
        EventLogProvider eventLog = new EventLogProvider();

        eventLog.LogEvent(EventLogProvider.EVENT_TYPE_INFORMATION, DateTime.Now, "System", "CLEARCACHE", null, GetString("Administration-System.ClearCacheSuccess"));

        lblInfo.Text = GetString("Administration-System.ClearCacheSuccess");

        LoadData();
    }
Exemple #29
0
    /// <summary>
    /// Restart windows services.
    /// </summary>
    protected void btnRestartServices_Click(object sender, EventArgs e)
    {
        if (StopProcessing)
        {
            return;
        }

        // Resets values of counters
        try
        {
            WinServiceHelper.RestartService(null);

            // Log event
            EventLogProvider eventLog = new EventLogProvider();
            eventLog.LogEvent(EventLogProvider.EVENT_TYPE_INFORMATION, DateTime.Now, "System", "RESTARTWINSERVICES", null, GetString("Administration-System.WinServicesRestarted"));
        }
        catch (Exception ex)
        {
            EventLogProvider.LogException("WinServiceHelper", "RestartService", ex);
        }

        string url = URLHelper.UpdateParameterInUrl(URLRewriter.CurrentURL, "lastaction", "WinServicesRestarted");

        URLHelper.Redirect(url);
    }
Exemple #30
0
    /// <summary>
    /// Restart application.
    /// </summary>
    protected void btnRestart_Click(object sender, EventArgs e)
    {
        if (StopProcessing)
        {
            return;
        }

        if (RestartApplication())
        {
            if (AzureHelper.IsRunningOnAzure)
            {
                // Log event
                EventLogProvider eventLog = new EventLogProvider();
                eventLog.LogEvent(EventLogProvider.EVENT_TYPE_INFORMATION, DateTime.Now, "System", "ENDAPP", null, GetString("admin.system.restartazure"));
                lblInfo.Text = ResHelper.GetString("admin.system.restartazure");
            }
            else
            {
                // Log event
                EventLogProvider eventLog = new EventLogProvider();
                eventLog.LogEvent(EventLogProvider.EVENT_TYPE_INFORMATION, DateTime.Now, "System", "ENDAPP", null, GetString("Administration-System.RestartSuccess"));

                string url = URLHelper.UpdateParameterInUrl(URLRewriter.CurrentURL, "lastaction", "Restarted");
                URLHelper.Redirect(url);
            }
        }
        else
        {
            lblError.Visible = true;
            lblError.Text    = GetString("System.Restart.Failed");
        }
    }
Exemple #31
0
    /// <summary>
    /// Sends notification email to the administrator.
    /// </summary>
    private void SendAdminNotification(UserInfo ui)
    {
        if (NotifyAdministrator && (FromAddress != String.Empty) && (ToAddress != String.Empty))
        {
            var resolver      = MembershipResolvers.GetRegistrationResolver(ui);
            var emailTemplate = EmailTemplateProvider.GetEmailTemplate(AdminApprovalRequired ? "Registration.Approve" : "Registration.New", CurrentSiteName);

            if (emailTemplate == null)
            {
                EventLogProvider.LogEvent(EventType.ERROR, "RegistrationForm", "GetEmailTemplate", eventUrl: RequestContext.RawURL);
            }
            else
            {
                EmailMessage message = new EmailMessage();
                message.EmailFormat = EmailFormatEnum.Default;
                message.From        = FromAddress;
                message.Recipients  = ToAddress;
                message.Subject     = GetString("RegistrationForm.EmailSubject");

                try
                {
                    EmailSender.SendEmailWithTemplateText(CurrentSiteName, message, emailTemplate, resolver, false);
                }
                catch
                {
                    EventLogProvider.LogEvent(EventType.ERROR, "Membership", "RegistrationEmail");
                }
            }
        }
    }
Exemple #32
0
 /// <summary>
 /// Load filter control according filterpath.
 /// </summary>
 private void LoadFilter()
 {
     if (this.mFilterControl == null)
     {
         if (this.FilterControlPath != null)
         {
             try
             {
                 if (File.Exists(Server.MapPath(this.FilterControlPath)))
                 {
                     this.mFilterControl = (this.Page.LoadControl(this.FilterControlPath)) as CMSAbstractBaseFilterControl;
                     if (this.mFilterControl != null)
                     {
                         this.mFilterControl.ID = "filterControl";
                         this.Controls.AddAt(0, this.mFilterControl);
                         this.mFilterControl.FilterName = this.FilterName;
                         if (this.Page != null)
                         {
                             this.mFilterControl.Page = this.Page;
                         }
                     }
                 }
             }
             catch (Exception ex)
             {
                 EventLogProvider log = new EventLogProvider();
                 log.LogEvent("Filter control", "LOADFILTER", ex);
             }
         }
     }
 }
Exemple #33
0
    /// <summary>
    /// Removes the item from the cache.
    /// </summary>
    /// <param name="key">Cache key</param>
    protected override object RemoveInternal(string key)
    {
        // Log the event that the user was updated
        EventLogProvider ev = new EventLogProvider();
        ev.LogEvent(EventLogProvider.EVENT_TYPE_INFORMATION, DateTime.Now, "MyCustomCacheHelper", "Remove", null, "The cache item was removed");

        return base.RemoveInternal(key);
    }
    /// <summary>
    /// Sets the specified site data.
    /// </summary>
    /// <param name="siteInfoObj">New site info data</param>
    protected override void SetSiteInfoInternal(SiteInfo siteInfoObj)
    {
        base.SetSiteInfoInternal(siteInfoObj);

        // Log the event that the site was updated
        EventLogProvider ev = new EventLogProvider();
        ev.LogEvent(EventLogProvider.EVENT_TYPE_INFORMATION, DateTime.Now, "MyCustomSiteInfoProvider", "SetSiteInfo", null, "The site was updated");
    }
    /// <summary>
    /// OkClick Handler.
    /// </summary>
    protected void btnOk_Click(object sender, EventArgs e)
    {
        string culture = ValidationHelper.GetString(cultureSelector.Value, "");

        if ((culture != "") && ((currentCulture.ToLower() != culture.ToLower()) || chkDocuments.Checked))
        {
            // Set new culture
            SiteInfo si = SiteInfoProvider.GetSiteInfo(siteId);
            if (si != null)
            {
                try
                {
                    // Set default culture and change current culture label
                    ObjectHelper.SetSettingsKeyValue(si.SiteName + ".CMSDefaultCultureCode", culture.Trim());

                    // Change culture of documents
                    if (chkDocuments.Checked)
                    {
                        // Change culture of the documents
                        TreeProvider tree = new TreeProvider(CMSContext.CurrentUser);
                        tree.ChangeCulture(si.SiteName, currentCulture, culture);
                    }

                    if (!LicenseHelper.CheckFeature(URLHelper.GetCurrentDomain(), FeatureEnum.Multilingual))
                    {
                        // If not multilingual, remove all cultures from the site and assign new culture
                        CultureInfoProvider.RemoveSiteCultures(si.SiteName);
                        CultureInfoProvider.AddCultureToSite(culture, si.SiteName);
                    }

                    ltlScript.Text = ScriptHelper.GetScript("wopener.ChangeCulture('" + chkDocuments.Checked.ToString() + "'); window.close();");
                }
                catch (Exception ex)
                {
                    EventLogProvider ev = new EventLogProvider();
                    ev.LogEvent("SiteManager", "ChangeDefaultCulture", ex);
                }
            }
        }
        else
        {
            ltlScript.Text = ScriptHelper.GetScript("window.close();");
        }
    }
Exemple #36
0
    /// <summary>
    /// Logs error.
    /// </summary>
    /// <param name="message">Error message</param>
    /// <param name="eventCode">Event code</param>
    protected void LogEvent(string message, string eventCode)
    {
        try
        {
            // Add some additional information to the error message
            string info = "ORDER ID: " + orderId + "\r\n";
            info += "TRANSACTION ID: " + transactionId + "\r\n";
            info += "PAYMENT STATUS: " + paymentStatus + "\r\n";

            message = info + message;

            EventLogProvider evenLog = new EventLogProvider();
            evenLog.LogEvent(EventLogProvider.EVENT_TYPE_ERROR, DateTime.Now, "PayPal IPN", eventCode, 0, "", 0, "", "", message, 0, "");
        }
        catch
        {
            // Unable to log the event
        }
    }
    /// <summary>
    /// Deletes sample data.
    /// </summary>
    private void DeleteData()
    {
        try
        {
            QueryDataParameters parameters = new QueryDataParameters();
            parameters.Add("siteId", CMSContext.CurrentSiteID);

            ConnectionHelper.ExecuteQuery("ecommerce.order.deleteSampleData", parameters);

            // Log successful attempt
            EventLogProvider eventLog = new EventLogProvider();
            eventLog.LogEvent("I", DateTime.Now, "E-commerce data generator", "DATADELETED", CMSContext.CurrentSiteID);
            ShowConfirmation(GetString("com.reports.datadeleted"));
        }
        catch (Exception ex)
        {
            EventLogProvider.LogException("Reports", "Delete", ex);
            ShowError(GetString("com.reports.operationFailed"));
        }
    }
    protected void btnHiddenImpersonate_Click(object sender, EventArgs e)
    {
        string originalUserName = ValidationHelper.GetString(SessionHelper.GetValue("OriginalUserName"), "");
        if (RequestHelper.IsFormsAuthentication())
        {
            UserInfo ui = UserInfoProvider.GetUserInfo(originalUserName);
            CMSContext.CurrentUser.UserImpersonate(ui);
        }
        else
        {
            SessionHelper.SetValue("ImpersonateUserName", null);
            SessionHelper.SetValue("OriginalUserName", null);

            CMSContext.CurrentUser.Invalidate(false);

            // Log event
            EventLogProvider log = new EventLogProvider();
            log.LogEvent(EventLogProvider.EVENT_TYPE_INFORMATION, DateTime.Now, "Administration", "Impersonate", 0, null, 0, null, null, "User " + originalUserName + " has returned to his account.", CMSContext.CurrentSiteID, URLHelper.CurrentURL);

            URLHelper.Redirect(URLHelper.CurrentURL);
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        string domain = QueryHelper.GetText("domainname", String.Empty);

        if (domain != String.Empty)
        {
            LicenseKeyInfo lki = LicenseKeyInfoProvider.GetLicenseKeyInfo(domain);
            if (lki != null)
            {
                LabelMessage.Text = GetString("CMSSiteManager.FeatureNotAvailable");

                // Log message to event log
                EventLogProvider eventLog = new EventLogProvider();
                eventLog.LogEvent(EventLogProvider.EVENT_TYPE_WARNING, DateTime.Now, "Feature not available page", "FeatureNotAvailable", URLHelper.CurrentURL, "The requested feature is not available in the CMS edition you are using: " + LicenseHelper.GetEditionName(lki.Edition));
            }
            else
            {
                LabelMessage.Text = GetString("CMSSiteManager.LicenseNotFound").Replace("%%name%%", domain);
            }
        }
        titleElem.TitleText = GetString("CMSSiteManager.AccesDenied");
        titleElem.TitleImage = GetImageUrl("Others/Messages/denied.png");
    }
    /// <summary>
    /// Initializes common properties used for processing image.
    /// </summary>
    void baseImageEditor_InitializeProperties()
    {
        // Process media file
        if (baseImageEditor.ImageType == ImageHelper.ImageTypeEnum.MediaFile)
        {

            // Get mediafile
            mfi = MediaFileInfoProvider.GetMediaFileInfo(mediafileGuid, this.CurrentSiteName);
            // If file is not null
            if (mfi != null)
            {
                MediaLibraryInfo mli = MediaLibraryInfoProvider.GetMediaLibraryInfo(mfi.FileLibraryID);

                if ((mli != null) && (MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(mli, "filemodify")))
                {
                    // Load media file thumbnail
                    if (isPreview)
                    {
                        PreviewPath = MediaFileInfoProvider.GetPreviewFilePath(mfi);
                        if (PreviewPath != null)
                        {
                            OldPreviewExt = Path.GetExtension(PreviewPath);
                            try
                            {
                                // Get file contents from file system
                                previewFile = File.ReadAllBytes(PreviewPath);
                            }
                            catch (Exception ex)
                            {
                                EventLogProvider ev = new EventLogProvider();
                                ev.LogEvent("ImageEditor", "GetPreviewFile", ex);
                            }
                            if (previewFile != null)
                            {
                                baseImageEditor.ImgHelper = new ImageHelper(previewFile);
                            }
                            else
                            {
                                baseImageEditor.LoadingFailed = true;
                                baseImageEditor.LblLoadFailed.ResourceString = "img.errors.loading";
                            }
                        }
                        else
                        {
                            baseImageEditor.LoadingFailed = true;
                            baseImageEditor.LblLoadFailed.ResourceString = "img.errors.loading";
                        }
                    }
                    // Load media file
                    else
                    {
                        mfi.FileBinary = MediaFileInfoProvider.GetFile(mfi, mli.LibraryFolder, this.CurrentSiteName);
                        // Ensure metafile binary data
                        if (mfi.FileBinary != null)
                        {
                            baseImageEditor.ImgHelper = new ImageHelper(mfi.FileBinary);
                        }
                        else
                        {
                            baseImageEditor.LoadingFailed = true;
                            baseImageEditor.LblLoadFailed.ResourceString = "img.errors.loading";
                        }
                    }
                }
                else
                {
                    baseImageEditor.LoadingFailed = true;
                    baseImageEditor.LblLoadFailed.ResourceString = "img.errors.filemodify";
                }
            }
            else
            {
                baseImageEditor.LoadingFailed = true;
                baseImageEditor.LblLoadFailed.ResourceString = "img.errors.loading";
            }
        }

        // Check that image is in supported formats
        if ((!baseImageEditor.LoadingFailed) && (baseImageEditor.ImgHelper.ImageFormatToString() == null))
        {
            baseImageEditor.LoadingFailed = true;
            baseImageEditor.LblLoadFailed.ResourceString = "img.errors.format";
        }
    }
    private static void Upgrade60Import()
    {
        EventLogProvider evp = new EventLogProvider();
        // Import
        try
        {
            RequestStockHelper.Remove("CurrentDomain", true);

            SiteImportSettings importSettings = new SiteImportSettings(CMSContext.CurrentUser)
                                                    {
                                                        DefaultProcessObjectType = ProcessObjectEnum.All,
                                                        SourceFilePath = mUpgradePackagePath,
                                                        WebsitePath = mWebsitePath
                                                    };

            ImportProvider.ImportObjectsData(importSettings);

            // Regenerate time zones
            TimeZoneInfoProvider.GenerateTimeZoneRules();

            #region "Separability"

            String webPartsPath = mWebsitePath + "CMSWebParts\\";
            List<String> files = new List<string>();
            // Create list of files to remove
            if (!ModuleEntry.IsModuleLoaded(ModuleEntry.BIZFORM))
            {
                files.AddRange(GetAllFiles(webPartsPath + "BizForms"));
            }
            if (!ModuleEntry.IsModuleLoaded(ModuleEntry.BLOGS))
            {
                files.AddRange(GetAllFiles(webPartsPath + "Blogs"));
            }
            if (!ModuleEntry.IsModuleLoaded(ModuleEntry.COMMUNITY))
            {
                files.AddRange(GetAllFiles(webPartsPath + "Community"));
            }
            if (!ModuleEntry.IsModuleLoaded(ModuleEntry.ECOMMERCE))
            {
                files.AddRange(GetAllFiles(webPartsPath + "Ecommerce"));
            }
            if (!ModuleEntry.IsModuleLoaded(ModuleEntry.EVENTMANAGER))
            {
                files.AddRange(GetAllFiles(webPartsPath + "Events"));
            }
            if (!ModuleEntry.IsModuleLoaded(ModuleEntry.FORUMS))
            {
                files.AddRange(GetAllFiles(webPartsPath + "Forums"));
            }
            if (!ModuleEntry.IsModuleLoaded(ModuleEntry.MEDIALIBRARY))
            {
                files.AddRange(GetAllFiles(webPartsPath + "MediaLibrary"));
            }
            if (!ModuleEntry.IsModuleLoaded(ModuleEntry.MESSAGEBOARD))
            {
                files.AddRange(GetAllFiles(webPartsPath + "MessageBoards"));
            }
            if (!ModuleEntry.IsModuleLoaded(ModuleEntry.MESSAGING))
            {
                files.AddRange(GetAllFiles(webPartsPath + "Messaging"));
            }
            if (!ModuleEntry.IsModuleLoaded(ModuleEntry.NEWSLETTER))
            {
                files.AddRange(GetAllFiles(webPartsPath + "Newsletters"));
            }
            if (!ModuleEntry.IsModuleLoaded(ModuleEntry.NOTIFICATIONS))
            {
                files.AddRange(GetAllFiles(webPartsPath + "Notifications"));
            }
            if (!ModuleEntry.IsModuleLoaded(ModuleEntry.ONLINEMARKETING))
            {
                files.AddRange(GetAllFiles(webPartsPath + "OnlineMarketing"));
            }
            if (!ModuleEntry.IsModuleLoaded(ModuleEntry.POLLS))
            {
                files.AddRange(GetAllFiles(webPartsPath + "Polls"));
            }
            if (!ModuleEntry.IsModuleLoaded(ModuleEntry.PROJECTMANAGEMENT))
            {
                files.AddRange(GetAllFiles(webPartsPath + "ProjectManagement"));
            }
            if (!ModuleEntry.IsModuleLoaded(ModuleEntry.REPORTING))
            {
                files.AddRange(GetAllFiles(webPartsPath + "Reporting"));
            }

            // Remove webparts for separated modules
            foreach (String file in files)
            {
                try
                {
                    File.Delete(file);
                }
                catch (Exception ex)
                {
                    evp.LogEvent("Upgrade to 6.0", "Upgrade", ex);
                }
            }

            #endregion

            evp.LogEvent("I", DateTime.Now, "Upgrade to 6.0", "Upgrade - Finish");
        }
        catch (Exception ex)
        {
            evp.LogEvent("Upgrade to 6.0", "Upgrade", ex);
        }
    }
    public static void Update60()
    {
        EventLogProvider evp = new EventLogProvider();
        evp.LogEvent("I", DateTime.Now, "Upgrade to 6.0", "Upgrade - Start");

        DataClassInfo dci = null;

        #region "CMS.UserSettings"

        try
        {
            dci = DataClassInfoProvider.GetDataClass("cms.usersettings");
            if (dci != null)
            {
                FormInfo fi = new FormInfo(dci.ClassFormDefinition);
                if (fi != null)
                {
                    FormFieldInfo ffi = new FormFieldInfo();
                    ffi.Name = "UserAuthenticationGUID";
                    ffi.DataType = FormFieldDataTypeEnum.GUID;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "UserBounces";
                    ffi.DataType = FormFieldDataTypeEnum.Integer;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.TextBoxControl;
                    ffi.Visible = false;
                    ffi.Caption = "UserBounces";

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "UserLinkedInID";
                    ffi.DataType = FormFieldDataTypeEnum.Text;
                    ffi.Size = 100;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "UserLogActivities";
                    ffi.DataType = FormFieldDataTypeEnum.Boolean;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "UserPasswordRequestHash";
                    ffi.DataType = FormFieldDataTypeEnum.Text;
                    ffi.Size = 100;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    dci.ClassFormDefinition = fi.GetXmlDefinition();

                    TableManager tm = new TableManager(dci.ClassConnectionString);
                    dci.ClassXmlSchema = tm.GetXmlSchema("CMS_UserSettings");

                    DataClassInfoProvider.SetDataClass(dci);

                    // Generate queries
                    SqlGenerator.GenerateDefaultQueries(dci, true, false);
                    tm.RefreshCustomViews("CMS_UserSettings");
                }
            }
        }
        catch (Exception ex)
        {
            evp.LogEvent("CMS.UserSettings - Upgrade", "Upgrade", ex);
        }

        #endregion

        #region "Ecommerce - Customer"

        try
        {
            dci = DataClassInfoProvider.GetDataClass("ecommerce.customer");
            if (dci != null)
            {
                FormInfo fi = new FormInfo(dci.ClassFormDefinition);
                if (fi != null)
                {
                    FormFieldInfo ffi = new FormFieldInfo();
                    ffi.Name = "CustomerSiteID";
                    ffi.DataType = FormFieldDataTypeEnum.Integer;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.TextBoxControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    TableManager tm = new TableManager(dci.ClassConnectionString);

                    dci.ClassFormDefinition = fi.GetXmlDefinition();
                    dci.ClassXmlSchema = tm.GetXmlSchema("COM_Customer");

                    DataClassInfoProvider.SetDataClass(dci);

                    // Generate queries
                    SqlGenerator.GenerateDefaultQueries(dci, true, false);

                    tm.RefreshCustomViews("COM_Customer");
                }
            }
        }
        catch (Exception ex)
        {
            evp.LogEvent("Ecommerce.Customer - Upgrade", "Upgrade", ex);
        }

        #endregion

        #region "Ecommerce - Order"

        try
        {
            dci = DataClassInfoProvider.GetDataClass("ecommerce.order");
            if (dci != null)
            {
                FormInfo fi = new FormInfo(dci.ClassFormDefinition);
                if (fi != null)
                {
                    FormFieldInfo ffi = new FormFieldInfo();
                    ffi.Name = "OrderCulture";
                    ffi.DataType = FormFieldDataTypeEnum.Text;
                    ffi.Size = 10;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "OrderIsPaid";
                    ffi.DataType = FormFieldDataTypeEnum.Boolean;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "OrderTotalPriceInMainCurrency";
                    ffi.DataType = FormFieldDataTypeEnum.Decimal;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = fi.GetFormField("OrderStatusID");
                    if (ffi != null)
                    {
                        ffi.AllowEmpty = true;
                        fi.UpdateFormField("OrderStatusID", ffi);
                    }

                    ffi = fi.GetFormField("OrderShippingAddressID");
                    if (ffi != null)
                    {
                        ffi.AllowEmpty = true;
                        fi.UpdateFormField("OrderShippingAddressID", ffi);
                    }

                    dci.ClassFormDefinition = fi.GetXmlDefinition();

                    TableManager tm = new TableManager(dci.ClassConnectionString);
                    dci.ClassXmlSchema = tm.GetXmlSchema("COM_Order");

                    DataClassInfoProvider.SetDataClass(dci);

                    // Generate queries
                    SqlGenerator.GenerateDefaultQueries(dci, true, false);
                    tm.RefreshCustomViews("COM_Order");
                }
            }
        }
        catch (Exception ex)
        {
            evp.LogEvent("Ecommerce.Order - Upgrade", "Upgrade", ex);
        }

        #endregion

        #region "Ecommerce - OrderItem"

        try
        {
            dci = DataClassInfoProvider.GetDataClass("ecommerce.orderitem");
            if (dci != null)
            {
                FormInfo fi = new FormInfo(dci.ClassFormDefinition);
                if (fi != null)
                {
                    FormFieldInfo ffi = new FormFieldInfo();
                    ffi.Name = "OrderItemBundleGUID";
                    ffi.DataType = FormFieldDataTypeEnum.GUID;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "OrderItemIsPrivate";
                    ffi.DataType = FormFieldDataTypeEnum.Boolean;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "OrderItemPrice";
                    ffi.DataType = FormFieldDataTypeEnum.Decimal;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "OrderItemSendNotification";
                    ffi.DataType = FormFieldDataTypeEnum.Boolean;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "OrderItemSKU";
                    ffi.DataType = FormFieldDataTypeEnum.LongText;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "OrderItemText";
                    ffi.DataType = FormFieldDataTypeEnum.LongText;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "OrderItemTotalPriceInMainCurrency";
                    ffi.DataType = FormFieldDataTypeEnum.Decimal;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "OrderItemValidTo";
                    ffi.DataType = FormFieldDataTypeEnum.DateTime;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    dci.ClassFormDefinition = fi.GetXmlDefinition();

                    TableManager tm = new TableManager(dci.ClassConnectionString);
                    dci.ClassXmlSchema = tm.GetXmlSchema("COM_OrderItem");

                    DataClassInfoProvider.SetDataClass(dci);

                    // Generate queries
                    SqlGenerator.GenerateDefaultQueries(dci, true, false);
                    tm.RefreshCustomViews("COM_OrderItem");
                }
            }
        }
        catch (Exception ex)
        {
            evp.LogEvent("Ecommerce.OrderItem - Upgrade", "Upgrade", ex);
        }

        #endregion

        #region "Ecommerce - Shopping cart item"

        try
        {
            dci = DataClassInfoProvider.GetDataClass("ecommerce.shoppingcartitem");
            if (dci != null)
            {
                FormInfo fi = new FormInfo(dci.ClassFormDefinition);
                if (fi != null)
                {
                    FormFieldInfo ffi = new FormFieldInfo();
                    ffi.Name = "CartItemBundleGUID";
                    ffi.DataType = FormFieldDataTypeEnum.GUID;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "CartItemIsPrivate";
                    ffi.DataType = FormFieldDataTypeEnum.Boolean;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "CartItemPrice";
                    ffi.DataType = FormFieldDataTypeEnum.Decimal;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "CartItemText";
                    ffi.DataType = FormFieldDataTypeEnum.LongText;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "CartItemValidTo";
                    ffi.DataType = FormFieldDataTypeEnum.DateTime;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = fi.GetFormField("CartItemGuid");
                    if (ffi != null)
                    {
                        ffi.AllowEmpty = true;
                        fi.UpdateFormField("CartItemGuid", ffi);
                    }

                    dci.ClassFormDefinition = fi.GetXmlDefinition();

                    TableManager tm = new TableManager(dci.ClassConnectionString);
                    dci.ClassXmlSchema = tm.GetXmlSchema("COM_ShoppingCartSKU");

                    DataClassInfoProvider.SetDataClass(dci);

                    // Generate queries
                    SqlGenerator.GenerateDefaultQueries(dci, true, false);
                    tm.RefreshCustomViews("COM_ShoppingCartSKU");
                }
            }
        }
        catch (Exception ex)
        {
            evp.LogEvent("Ecommerce.ShoppingCartItem - Upgrade", "Upgrade", ex);
        }

        #endregion

        #region "Ecommerce - SKU"

        try
        {
            dci = DataClassInfoProvider.GetDataClass("ecommerce.sku");
            if (dci != null)
            {
                FormInfo fi = new FormInfo(dci.ClassFormDefinition);
                if (fi != null)
                {
                    FormFieldInfo ffi = new FormFieldInfo();
                    ffi.Name = "SKUBundleInventoryType";
                    ffi.DataType = FormFieldDataTypeEnum.Text;
                    ffi.Size = 50;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUConversionName";
                    ffi.DataType = FormFieldDataTypeEnum.Text;
                    ffi.Size = 100;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUConversionValue";
                    ffi.DataType = FormFieldDataTypeEnum.Text;
                    ffi.Size = 200;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUMaxDownloads";
                    ffi.DataType = FormFieldDataTypeEnum.Integer;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUMaxItemsInOrder";
                    ffi.DataType = FormFieldDataTypeEnum.Integer;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUMaxPrice";
                    ffi.DataType = FormFieldDataTypeEnum.Decimal;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUMembershipGUID";
                    ffi.DataType = FormFieldDataTypeEnum.GUID;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUMinPrice";
                    ffi.DataType = FormFieldDataTypeEnum.Decimal;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUNeedsShipping";
                    ffi.DataType = FormFieldDataTypeEnum.Boolean;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUPrivateDonation";
                    ffi.DataType = FormFieldDataTypeEnum.Boolean;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUProductType";
                    ffi.DataType = FormFieldDataTypeEnum.Text;
                    ffi.Size = 50;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUSiteID";
                    ffi.DataType = FormFieldDataTypeEnum.Integer;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUValidFor";
                    ffi.DataType = FormFieldDataTypeEnum.Integer;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUValidity";
                    ffi.DataType = FormFieldDataTypeEnum.Text;
                    ffi.Size = 50;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = new FormFieldInfo();
                    ffi.Name = "SKUValidUntil";
                    ffi.DataType = FormFieldDataTypeEnum.DateTime;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    ffi = fi.GetFormField("SKUDepartmentID");
                    if (ffi != null)
                    {
                        ffi.AllowEmpty = true;
                        fi.UpdateFormField("SKUDepartmentID", ffi);
                    }

                    dci.ClassFormDefinition = fi.GetXmlDefinition();

                    TableManager tm = new TableManager(dci.ClassConnectionString);
                    dci.ClassXmlSchema = tm.GetXmlSchema("COM_SKU");

                    DataClassInfoProvider.SetDataClass(dci);

                    // Generate queries
                    SqlGenerator.GenerateDefaultQueries(dci, true, false);
                    tm.RefreshCustomViews("COM_SKU");
                }
            }
        }
        catch (Exception ex)
        {
            evp.LogEvent("Ecommerce.SKU - Upgrade", "Upgrade", ex);
        }

        #endregion

        #region "Community - Group"

        try
        {
            dci = DataClassInfoProvider.GetDataClass("Community.Group");
            if (dci != null)
            {
                FormInfo fi = new FormInfo(dci.ClassFormDefinition);
                if (fi != null)
                {
                    FormFieldInfo ffi = new FormFieldInfo();
                    ffi.Name = "GroupLogActivity";
                    ffi.DataType = FormFieldDataTypeEnum.Boolean;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.CheckBoxControl;
                    ffi.Visible = true;
                    ffi.DefaultValue = "true";
                    ffi.Caption = "GroupLogActivity";

                    fi.AddFormField(ffi);

                    dci.ClassFormDefinition = fi.GetXmlDefinition();

                    TableManager tm = new TableManager(dci.ClassConnectionString);
                    dci.ClassXmlSchema = tm.GetXmlSchema("Community_Group");

                    DataClassInfoProvider.SetDataClass(dci);

                    // Generate queries
                    SqlGenerator.GenerateDefaultQueries(dci, true, false);
                    tm.RefreshCustomViews("Community_Group");
                }
            }
        }
        catch (Exception ex)
        {
            evp.LogEvent("Community.Group - Upgrade", "Upgrade", ex);
        }

        #endregion

        #region "Newsletter - Subscriber"

        try
        {
            dci = DataClassInfoProvider.GetDataClass("newsletter.subscriber");
            if (dci != null)
            {
                FormInfo fi = new FormInfo(dci.ClassFormDefinition);
                if (fi != null)
                {
                    FormFieldInfo ffi = new FormFieldInfo();
                    ffi.Name = "SubscriberBounces";
                    ffi.DataType = FormFieldDataTypeEnum.Boolean;
                    ffi.AllowEmpty = true;
                    ffi.PublicField = false;
                    ffi.System = true;
                    ffi.FieldType = FormFieldControlTypeEnum.LabelControl;
                    ffi.Visible = false;

                    fi.AddFormField(ffi);

                    dci.ClassFormDefinition = fi.GetXmlDefinition();

                    TableManager tm = new TableManager(dci.ClassConnectionString);
                    dci.ClassXmlSchema = tm.GetXmlSchema("Newsletter_Subscriber");

                    DataClassInfoProvider.SetDataClass(dci);

                    // Generate queries
                    SqlGenerator.GenerateDefaultQueries(dci, true, false);
                    tm.RefreshCustomViews("Newsletter_Subscriber");
                }
            }
        }
        catch (Exception ex)
        {
            evp.LogEvent("Newsletter.Subscriber - Upgrade", "Upgrade", ex);
        }

        #endregion

        #region "CMS.Document"

        try
        {
            dci = DataClassInfoProvider.GetDataClass("cms.document");
            if (dci != null)
            {
                SearchSettings ss = dci.ClassSearchSettingsInfos;
                SearchSettingsInfo ssi = ss.GetSettingsInfo("42f446ee-9818-4596-8124-54a38f64aa05");
                if (ssi != null)
                {
                    ssi.Searchable = true;
                    ss.SetSettingsInfo(ssi);
                }

                DataClassInfoProvider.SetDataClass(dci);
            }
        }
        catch (Exception ex)
        {
            evp.LogEvent("CMS.Document - Upgrade", "Upgrade", ex);
        }

        #endregion

        // Set the path to the upgrade package
        mUpgradePackagePath = HttpContext.Current.Server.MapPath("~/CMSSiteUtils/Import/upgrade_55R2_60.zip");

        mWebsitePath = HttpContext.Current.Server.MapPath("~/");

        TableManager dtm = new TableManager(null);

        // Update all views
        dtm.RefreshDocumentViews();

        // Set data version
        ObjectHelper.SetSettingsKeyValue("CMSDataVersion", "6.0");

        // Clear hashtables
        CMSObjectHelper.ClearHashtables();

        // Clear the cache
        CacheHelper.ClearCache(null, true);

        // Drop the routes
        CMSMvcHandler.DropAllRoutes();

        // Init the Mimetype helper (required for the Import)
        MimeTypeHelper.LoadMimeTypes();

        CMSThread thread = new CMSThread(Upgrade60Import);
        thread.Start();
    }
    /// <summary>
    /// Restart application.
    /// </summary>
    protected void btnRestart_Click(object sender, EventArgs e)
    {
        if (StopProcessing)
        {
            return;
        }

        if (RestartApplication())
        {
            if (AzureHelper.IsRunningOnAzure)
            {
                // Log event
                EventLogProvider eventLog = new EventLogProvider();
                eventLog.LogEvent(EventLogProvider.EVENT_TYPE_INFORMATION, DateTime.Now, "System", "ENDAPP", null, GetString("admin.system.restartazure"));
                ShowConfirmation(GetString("admin.system.restartazure"));
            }
            else
            {
                // Log event
                EventLogProvider eventLog = new EventLogProvider();
                eventLog.LogEvent(EventLogProvider.EVENT_TYPE_INFORMATION, DateTime.Now, "System", "ENDAPP", null, GetString("Administration-System.RestartSuccess"));

                string url = URLHelper.UpdateParameterInUrl(URLRewriter.CurrentURL, "lastaction", "Restarted");
                URLHelper.Redirect(url);
            }
        }
        else
        {
            ShowError(GetString("System.Restart.Failed"));
        }
    }
Exemple #44
0
    /// <summary>
    /// Delete attribute button clicked.
    /// </summary>
    protected void btnDeleteItem_Click(Object sender, System.Web.UI.ImageClickEventArgs e)
    {
        if (Mode == FieldEditorModeEnum.BizFormDefinition)
        {
            // Check 'EditForm' permission
            if (!CMSContext.CurrentUser.IsAuthorizedPerResource("cms.form", "EditForm"))
            {
                RedirectToAccessDenied("cms.form", "EditForm");
            }
        }

        // Raise on before definition update event
        if (OnBeforeDefinitionUpdate != null)
        {
            OnBeforeDefinitionUpdate(this, EventArgs.Empty);
        }

        FormFieldInfo ffiSelected = null;
        DataClassInfo dci = null;
        WebPartInfo wpi = null;
        string errorMessage = null;
        string newSelectedValue = null;
        string deletedItemPreffix = null;

        // Clear settings
        simpleMode.Settings = new Hashtable();
        controlSettings.Settings = new Hashtable();

        // Load current xml form definition
        LoadFormDefinition();

        if ((!string.IsNullOrEmpty(SelectedItemName)) && (!IsNewItemEdited))
        {
            if (SelectedItemType == FieldEditorSelectedItemEnum.Field)
            {
                ffiSelected = fi.GetFormField(SelectedItemName);
                deletedItemPreffix = fieldPreffix;

                if (ffiSelected != null)
                {
                    // Do not allow deleting of the primary key except for external fields
                    if (ffiSelected.PrimaryKey && !ffiSelected.External)
                    {
                        if (!this.DevelopmentMode)
                        {
                            lblError.Visible = true;
                            lblError.ResourceString = "TemplateDesigner.ErrorCannotDeletePK";
                            return;
                        }
                        else
                        {
                            // Check if at least one primary key stays
                            if (fi.GetFields(true, true, false, true).Length < 2)
                            {
                                lblError.Visible = true;
                                lblError.ResourceString = "TemplateDesigner.ErrorCannotDeletePK";
                                return;
                            }
                        }
                    }

                    // Check if at least two fields stay in document type definition
                    if ((this.Mode == FieldEditorModeEnum.ClassFormDefinition) && (fi.GetFields(true, true, true).Length < 3))
                    {
                        lblError.Visible = true;
                        lblError.ResourceString = "TemplateDesigner.ErrorCannotDeleteAllCustomFields";
                        return;
                    }

                    // Do not allow deleting of the system field
                    if (ffiSelected.System && !ffiSelected.External && !DevelopmentMode)
                    {
                        lblError.Visible = true;
                        lblError.ResourceString = "TemplateDesigner.ErrorCannotDeleteSystemField";
                        return;
                    }

                    // Remove specifield field from xml form definition
                    fi.RemoveFormField(SelectedItemName);

                    // Get updated definition
                    FormDefinition = fi.GetXmlDefinition();

                    switch (mMode)
                    {
                        case FieldEditorModeEnum.WebPartProperties:
                            // Web part properties
                            {
                                wpi = WebPartInfoProvider.GetWebPartInfo(mWebPartId);
                                if (wpi != null)
                                {
                                    wpi.WebPartProperties = FormDefinition;
                                    try
                                    {
                                        WebPartInfoProvider.SetWebPartInfo(wpi);
                                    }
                                    catch (Exception ex)
                                    {
                                        errorMessage = ex.Message;
                                    }
                                }
                                else
                                {
                                    errorMessage = GetString("FieldEditor.WebpartNotFound");
                                }
                            }
                            break;

                        case FieldEditorModeEnum.ClassFormDefinition:
                        case FieldEditorModeEnum.BizFormDefinition:
                        case FieldEditorModeEnum.SystemTable:
                        case FieldEditorModeEnum.CustomTable:
                            {
                                // Standard classes
                                dci = DataClassInfoProvider.GetDataClass(mClassName);
                                if (dci != null)
                                {
                                    // If document type is edited AND field that should be removed is FILE
                                    if ((mMode == FieldEditorModeEnum.ClassFormDefinition) && (!string.IsNullOrEmpty(ClassName)) &&
                                        (ffiSelected.DataType == FormFieldDataTypeEnum.File))
                                    {
                                        DocumentHelper.DeleteDocumentAttachments(ClassName, ffiSelected.Name, null);
                                    }

                                    // If bizform is edited AND field that should be removed is FILE
                                    if ((mMode == FieldEditorModeEnum.BizFormDefinition) && (!string.IsNullOrEmpty(ClassName)) &&
                                        (ffiSelected.FieldType == FormFieldControlTypeEnum.UploadControl))
                                    {
                                        BizFormInfoProvider.DeleteBizFormFiles(ClassName, ffiSelected.Name, CMSContext.CurrentSiteID);
                                    }

                                    // Update xml definition
                                    dci.ClassFormDefinition = FormDefinition;

                                    try
                                    {
                                        if (!ffiSelected.External)
                                        {
                                            // Remove corresponding column from table
                                            TableManager.DropTableColumn(dci.ClassTableName, SelectedItemName);

                                            // Update xml schema
                                            dci.ClassXmlSchema = TableManager.GetXmlSchema(dci.ClassTableName);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        errorMessage = ex.Message;
                                    }

                                    // Deleted field is used as ClassNodeNameSource -> remove node name source
                                    if (dci.ClassNodeNameSource == SelectedItemName)
                                    {
                                        dci.ClassNodeNameSource = "";
                                    }

                                    // Update changes in database
                                    try
                                    {
                                        using (CMSActionContext context = new CMSActionContext())
                                        {
                                            // Do not log synchronization for BizForm
                                            if (mMode == FieldEditorModeEnum.BizFormDefinition)
                                            {
                                                context.DisableLogging();
                                            }

                                            // Save the data class
                                            DataClassInfoProvider.SetDataClass(dci);

                                            // Update inherited classes with new fields
                                            FormHelper.UpdateInheritedClasses(dci);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        errorMessage = ex.Message;
                                    }

                                    // Refresh views and quries only if changes to DB were made
                                    if (!ffiSelected.External)
                                    {
                                        // Generate default view
                                        if (mMode == FieldEditorModeEnum.BizFormDefinition)
                                        {
                                            SqlGenerator.GenerateDefaultView(dci, CMSContext.CurrentSiteName);
                                        }
                                        else
                                        {
                                            SqlGenerator.GenerateDefaultView(dci, null);
                                        }

                                        // Regenerate queries
                                        SqlGenerator.GenerateDefaultQueries(dci, true, true);

                                        // Updates custom views
                                        if ((mMode == FieldEditorModeEnum.SystemTable) || (mMode == FieldEditorModeEnum.ClassFormDefinition))
                                        {
                                            try
                                            {
                                                TableManager.RefreshCustomViews(dci.ClassTableName);

                                                string lowClassName = dci.ClassName.ToLower();
                                                if (lowClassName == "cms.document" || lowClassName == "cms.tree")
                                                {
                                                    TableManager.RefreshDocumentViews();
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                errorMessage = ResHelper.GetString("fieldeditor.refreshingviewsfailed");
                                                EventLogProvider ev = new EventLogProvider();
                                                ev.LogEvent("Field Editor", "EXCEPTION", ex);
                                            }
                                        }
                                    }

                                    // Clear hashtables
                                    ClearHashtables();
                                }
                                else
                                {
                                    errorMessage = GetString("FieldEditor.ClassNotFound");
                                }
                            }
                            break;
                    }
                }
            }
            else if (SelectedItemType == FieldEditorSelectedItemEnum.Category)
            {
                deletedItemPreffix = categPreffix;

                // Remove specifield category from xml form definition
                fi.RemoveFormCategory(SelectedItemName);

                // Get updated form definition
                FormDefinition = fi.GetXmlDefinition();

                switch (mMode)
                {
                    case FieldEditorModeEnum.WebPartProperties:
                        wpi = WebPartInfoProvider.GetWebPartInfo(mWebPartId);
                        if (wpi != null)
                        {
                            wpi.WebPartProperties = FormDefinition;
                            try
                            {
                                WebPartInfoProvider.SetWebPartInfo(wpi);
                            }
                            catch (Exception ex)
                            {
                                errorMessage = ex.Message;
                            }
                        }
                        else
                        {
                            errorMessage = GetString("FieldEditor.WebpartNotFound");
                        }
                        break;

                    case FieldEditorModeEnum.ClassFormDefinition:
                    case FieldEditorModeEnum.BizFormDefinition:
                    case FieldEditorModeEnum.SystemTable:
                    case FieldEditorModeEnum.CustomTable:
                        dci = DataClassInfoProvider.GetDataClass(mClassName);

                        if (dci != null)
                        {
                            // Update xml definition
                            dci.ClassFormDefinition = FormDefinition;

                            // Update changes in database
                            try
                            {
                                using (CMSActionContext context = new CMSActionContext())
                                {
                                    // Do not log synchronization for BizForm
                                    if (mMode == FieldEditorModeEnum.BizFormDefinition)
                                    {
                                        context.DisableLogging();
                                    }

                                    // Save the data class
                                    DataClassInfoProvider.SetDataClass(dci);

                                    // Update inherited classes with new fields
                                    FormHelper.UpdateInheritedClasses(dci);
                                }
                            }
                            catch (Exception ex)
                            {
                                errorMessage = ex.Message;
                            }
                        }
                        else
                        {
                            errorMessage = GetString("FieldEditor.ClassNotFound");
                        }
                        break;
                }
            }

            if (!string.IsNullOrEmpty(errorMessage))
            {
                lblError.Visible = true;
                lblError.Text = "[ FieldEditor.btnDeleteItem_Click() ]: " + errorMessage;
            }
        }
        else
        {
            // "delete" new item from the list
            IsNewItemEdited = false;
        }

        // Set new selected value
        ListItem deletedItem = lstAttributes.Items.FindByValue(deletedItemPreffix + SelectedItemName);
        int deletedItemIndex = lstAttributes.Items.IndexOf(deletedItem);

        if ((deletedItemIndex > 0) && (lstAttributes.Items[deletedItemIndex - 1] != null))
        {
            newSelectedValue = lstAttributes.Items[deletedItemIndex - 1].Value;
        }

        // Reload data
        Reload(newSelectedValue);

        // Raise on after definition update event
        if (OnAfterDefinitionUpdate != null)
        {
            OnAfterDefinitionUpdate(this, EventArgs.Empty);
        }
    }
    /// <summary>
    /// When exception occurs, log it to event log.
    /// </summary>
    /// <param name="ex">Exception to log</param>
    private void LogExceptionToEventLog(Exception ex)
    {
        EventLogProvider log = new EventLogProvider();

        log.LogEvent(EventLogProvider.EVENT_TYPE_ERROR, DateTime.Now, "Content", "IMPORTFILE", CMSContext.CurrentUser.UserID, CMSContext.CurrentUser.UserName, 0, null, HTTPHelper.UserHostAddress, EventLogProvider.GetExceptionLogMessage(ex), CMSContext.CurrentSiteID, HTTPHelper.GetAbsoluteUri());

        AddError(GetString("tools.fileimport.failed") + " (" + ex.Message + ")");
    }
    public void RaisePostBackEvent(string eventArgument)
    {
        CurrentUserInfo currentUser = CMSContext.CurrentUser;

        // Current Node ID
        int nodeId = ValidationHelper.GetInteger(Param1, 0);

        TreeProvider tree = new TreeProvider(currentUser);
        EventLogProvider log = new EventLogProvider();

        string documentName = string.Empty;
        string action = Action.ToLower();
        string siteName = CMSContext.CurrentSiteName;

        // Process the request
        switch (action)
        {
            case "refresh":
                treeContent.NodeID = nodeId;
                AddScript("currentNodeId = " + nodeId + ";\n");

                break;

            case "moveup":
            case "movedown":
            case "movetop":
            case "movebottom":
                // Move the document up (document order)
                try
                {
                    if (nodeId == 0)
                    {
                        AddAlert(GetString("ContentRequest.ErrorMissingSource"));
                        return;
                    }

                    // Get document to move
                    TreeNode node = tree.SelectSingleNode(nodeId);

                    // Check the permissions for document
                    if (currentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Allowed)
                    {
                        switch (action)
                        {
                            case "moveup":
                                node = tree.MoveNodeUp(nodeId);
                                break;

                            case "movedown":
                                node = tree.MoveNodeDown(nodeId);
                                break;

                            case "movetop":
                                node = tree.SelectSingleNode(nodeId);
                                tree.SetNodeOrder(nodeId, DocumentOrderEnum.First);
                                break;

                            case "movebottom":
                                node = tree.SelectSingleNode(nodeId);
                                tree.SetNodeOrder(nodeId, DocumentOrderEnum.Last);
                                break;
                        }

                        if (node != null)
                        {
                            // Log the synchronization tasks for the entire tree level
                            if (SettingsKeyProvider.GetBoolValue(siteName + ".CMSStagingLogChanges"))
                            {
                                // Log the synchronization tasks for the entire tree level
                                DocumentSynchronizationHelper.LogDocumentChangeOrder(siteName, node.NodeAliasPath, tree);
                            }

                            // Select the document in the tree
                            documentName = node.DocumentName;

                            treeContent.ExpandNodeID = node.NodeParentID;
                            treeContent.NodeID = node.NodeID;
                            AddScript("currentNodeId = " + node.NodeID + ";\n");
                        }
                        else
                        {
                            AddAlert(GetString("ContentRequest.MoveFailed"));
                        }
                    }
                    else
                    {
                        // Select the document in the tree
                        treeContent.NodeID = nodeId;

                        AddAlert(GetString("ContentRequest.MoveDenied"));
                    }
                }
                catch (Exception ex)
                {
                    log.LogEvent(EventLogProvider.EVENT_TYPE_ERROR, DateTime.Now, "Content", "MOVE", currentUser.UserID, currentUser.UserName, nodeId, documentName, HTTPHelper.GetUserHostAddress(), EventLogProvider.GetExceptionLogMessage(ex), CMSContext.CurrentSite.SiteID, HTTPHelper.GetAbsoluteUri());
                    AddAlert(GetString("ContentRequest.MoveFailed") + " : " + ex.Message);
                }
                break;

            case "setculture":
                // Set the preferred culture code
                try
                {
                    // Set the culture code
                    string language = ValidationHelper.GetString(Param2, "");
                    if (!string.IsNullOrEmpty(language))
                    {
                        CMSContext.PreferredCultureCode = language;
                    }

                    // Refresh the document
                    if (nodeId > 0)
                    {
                        treeContent.NodeID = nodeId;

                        AddScript("SelectNode(" + nodeId + "); \n");
                    }
                }
                catch (Exception ex)
                {
                    log.LogEvent(EventLogProvider.EVENT_TYPE_ERROR, DateTime.Now, "Content", "SETCULTURE", currentUser.UserID, currentUser.UserName, nodeId, documentName, HTTPHelper.GetUserHostAddress(), EventLogProvider.GetExceptionLogMessage(ex), CMSContext.CurrentSite.SiteID, HTTPHelper.GetAbsoluteUri());
                    AddAlert(GetString("ContentRequest.ErrorChangeLanguage"));
                }
                break;

            // Sorting
            case "sortalphaasc":
            case "sortalphadesc":
            case "sortdateasc":
            case "sortdatedesc":
                // Set the preferred culture code
                try
                {
                    // Get document to sort
                    TreeNode node = tree.SelectSingleNode(nodeId);

                    // Check the permissions for document
                    if ((currentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Allowed)
                        && (currentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.ExploreTree) == AuthorizationResultEnum.Allowed))
                    {
                        switch (action)
                        {
                            case "sortalphaasc":
                                tree.OrderNodesAlphabetically(nodeId, true);
                                break;

                            case "sortalphadesc":
                                tree.OrderNodesAlphabetically(nodeId, false);
                                break;

                            case "sortdateasc":
                                tree.OrderNodesByDate(nodeId, true);
                                break;

                            case "sortdatedesc":
                                tree.OrderNodesByDate(nodeId, false);
                                break;
                        }

                        // Log the synchronization tasks for the entire tree level
                        if (SettingsKeyProvider.GetBoolValue(siteName + ".CMSStagingLogChanges"))
                        {
                            // Log the synchronization tasks for the entire tree level
                            string fakeAlias = node.NodeAliasPath.TrimEnd('/') + "/child";
                            DocumentSynchronizationHelper.LogDocumentChangeOrder(siteName, fakeAlias, tree);
                        }
                    }
                    else
                    {
                        AddAlert(GetString("ContentRequest.SortDenied"));
                    }

                    // Refresh the tree
                    if (nodeId > 0)
                    {
                        treeContent.ExpandNodeID = nodeId;
                        treeContent.NodeID = nodeId;
                        AddScript("SelectNode(" + nodeId + "); \n");
                    }
                }
                catch (Exception ex)
                {
                    log.LogEvent(EventLogProvider.EVENT_TYPE_ERROR, DateTime.Now, "Content", "SORT", currentUser.UserID, currentUser.UserName, nodeId, documentName, HTTPHelper.GetUserHostAddress(), EventLogProvider.GetExceptionLogMessage(ex), CMSContext.CurrentSite.SiteID, HTTPHelper.GetAbsoluteUri());
                    AddAlert(GetString("ContentRequest.ErrorSort"));
                }
                break;
        }

        // Maintain scrollbar position
        string script =
        @"var elm = jQuery('#handle_" + nodeId + @"');
          var pnl = jQuery('#" + pnlTreeArea.ClientID + @"');
          var origScroll = " + ScrollPosition + @";
          var elmOff = elm.offset();
          var elmPos = (elmOff == null) ? 0 : elmOff.top;
          var scroll = ((elmPos < origScroll) || (elmPos > (origScroll + pnl.height())));
          pnl.scrollTop(origScroll);
          if(scroll){pnl.animate({ scrollTop: elmPos - 20 }, 300);};";

        ScriptHelper.RegisterStartupScript(Page, typeof(string), "MaintainScrollbar", script, true);
    }
Exemple #47
0
    /// <summary>
    /// Reloads the grid data.
    /// </summary>
    public override void ReloadData()
    {
        try
        {
            // Ensure grid definition before realod data
            LoadGridDefinition();

            RaiseOnBeforeDataReload();
            rowIndex = 1;

            // Get Current TOP N
            if (CurrentPageSize > 0)
            {
                int currentPageIndex = Pager.CurrentPage;
                int pageSize = (CurrentPageSize > 0) ? CurrentPageSize : UniGridView.PageSize;

                CurrentTopN = pageSize * (currentPageIndex + Pager.CurrentPagesGroupSize);
            }

            if (CurrentTopN < TopN)
            {
                CurrentTopN = TopN;
            }

            // If first/last button and direct page contol in pager is hidden use current topN for better performance
            if (!Pager.ShowDirectPageControl && !Pager.ShowFirstLastButtons)
            {
                TopN = CurrentTopN;
            }

            // Retrieve data
            UniGridView.DataSource = RetrieveData();

            // Sort external dataset only if no query and info object is set
            if (string.IsNullOrEmpty(Query) && (InfoObject == null) && (!DataHelper.DataSourceIsEmpty(UniGridView.DataSource) && !DataSourceIsSorted))
            {
                SortUniGridDataSource();
            }

            RaiseOnAfterDataReload();

            SetUnigridControls();

            // Check if datasource is loaded
            if (DataHelper.DataSourceIsEmpty(GridView.DataSource) && (pagerElem.CurrentPage > 1))
            {
                pagerElem.UniPager.CurrentPage = 1;
                ReloadData();
            }

            // Resolve the edit action URL
            if (!String.IsNullOrEmpty(EditActionUrl))
            {
                EditActionUrl = CMSContext.ResolveMacros(EditActionUrl);
            }

            SortColumns.Clear();
            UniGridView.DataBind();

            mRowsCount = DataHelper.GetItemsCount(UniGridView.DataSource);

            CheckFilterVisibility();
        }
        catch (Exception ex)
        {
            lblError.Text = GetString("unigrid.error.reload");
            lblError.Visible = true;

            // Display tooltip only development mode is enabled
            if (SettingsKeyProvider.DevelopmentMode)
            {
                lblError.ToolTip = ex.Message;
            }

            // Log exception
            EventLogProvider ev = new EventLogProvider();
            ev.LogEvent("UniGrid", "RELOADDATA", ex.InnerException ?? ex);
        }
    }
    /// <summary>
    /// Reload data.
    /// </summary>
    public override void ReloadData(bool forceLoad)
    {
        try
        {
            // Load value info object
            ReportValueInfo rvi = ValueInfo;

            if (rvi != null)
            {
                //Test security
                ReportInfo ri = ReportInfoProvider.GetReportInfo(rvi.ValueReportID);
                if (ri.ReportAccess != ReportAccessEnum.All)
                {
                    if (!CMSContext.CurrentUser.IsAuthenticated())
                    {
                        this.Visible = false;
                        return;
                    }
                }

                ContextResolver resolver = CMSContext.CurrentResolver;
                // Resolve dynamic data macros
                if (DynamicMacros != null)
                {
                    for (int i = 0; i <= this.DynamicMacros.GetUpperBound(0); i++)
                    {
                        resolver.AddDynamicParameter(DynamicMacros[i, 0], DynamicMacros[i, 1]);
                    }
                }

                this.QueryIsStoredProcedure = rvi.ValueQueryIsStoredProcedure;
                this.QueryText = resolver.ResolveMacros(rvi.ValueQuery);

                //Set default parametrs directly if not set
                if (this.ReportParameters == null)
                {
                    if (ri != null)
                    {
                        FormInfo fi = new FormInfo(ri.ReportParameters);
                        // Get datarow with required columns
                        this.ReportParameters = fi.GetDataRow();
                        fi.LoadDefaultValues(this.ReportParameters);
                    }
                }
            }

            // Only use base parameters in case of stored procedure
            if (this.QueryIsStoredProcedure)
            {
                this.AllParameters = SpecialFunctions.ConvertDataRowToParams(this.ReportParameters, null);
            }

            // Load data
            DataSet ds = this.LoadData();

            // If datasource is emptry, create empty dataset
            if (!DataHelper.DataSourceIsEmpty(ds))
            {
                // Set literal text
                string value = rvi.ValueFormatString;
                if ((value == null) || (value == ""))
                {
                    value = ValidationHelper.GetString(ds.Tables[0].Rows[0][0], "");
                }
                else
                {
                    value = string.Format(value, ds.Tables[0].Rows[0].ItemArray);
                }

                lblValue.Text = HTMLHelper.HTMLEncode(ResolveMacros(value));
            }
        }
        catch (Exception ex)
        {
            // Display error message, if data load fail
            lblError.Visible = true;
            lblError.Text = "[ReportValue.ascx] Error loading the data: " + ex.Message;
            EventLogProvider ev = new EventLogProvider();
            ev.LogEvent("Report value", "E", ex);
        }
    }
    /// <summary>
    /// Moves document.
    /// </summary>
    private void PerformAction(object parameter)
    {
        if (Action.ToLower() == "copy")
        {
            AddLog(GetString("media.copy.startcopy"));
        }
        else
        {
            AddLog(GetString("media.move.startmove"));
        }

        if (LibraryInfo != null)
        {
            // Library path (used in recursive copy process)
            string libPath = MediaLibraryInfoProvider.GetMediaLibraryFolderPath(CMSContext.CurrentSiteName, LibraryInfo.LibraryFolder);

            // Ensure libPath is in original path type
            libPath = Path.GetFullPath(libPath);

            // Original path on disk from query
            string origPath = Path.GetFullPath(DirectoryHelper.CombinePath(libPath, FolderPath));

            // New path on disk
            string newPath = null;

            // Original path in DB
            string origDBPath = MediaLibraryHelper.EnsurePath(FolderPath);

            // New path in DB
            string newDBPath = null;

            AddLog(NewPath);

            // Check if requested folder is in library root folder
            if (!origPath.StartsWith(libPath, StringComparison.CurrentCultureIgnoreCase))
            {
                CurrentError = GetString("media.folder.nolibrary");
                AddLog(CurrentError);
                return;
            }

            string origFolderName = Path.GetFileName(origPath);

            if ((String.IsNullOrEmpty(Files) && !mAllFiles) && string.IsNullOrEmpty(origFolderName))
            {
                NewPath = NewPath + "\\" + LibraryInfo.LibraryFolder;
                NewPath = NewPath.Trim('\\');
            }
            newPath = NewPath;

            // Process current folder copy/move action
            if (String.IsNullOrEmpty(Files) && !AllFiles)
            {
                newPath = newPath.TrimEnd('\\') + '\\' + origFolderName;
                newPath = newPath.Trim('\\');

                // Check if moving into same folder
                if ((Action.ToLower() == "move") && (newPath == FolderPath))
                {
                    CurrentError = GetString("media.move.foldermove");
                    AddLog(CurrentError);
                    return;
                }

                // Error if moving folder into itself
                string newRootPath = Path.GetDirectoryName(newPath).Trim();
                string newSubRootFolder = Path.GetFileName(newPath).ToLower().Trim();
                string originalSubRootFolder = Path.GetFileName(FolderPath).ToLower().Trim();
                if (String.IsNullOrEmpty(Files) && (Action.ToLower() == "move") && newPath.StartsWith(DirectoryHelper.EnsurePathBackSlash(FolderPath))
                    && (originalSubRootFolder == newSubRootFolder) && (newRootPath == FolderPath))
                {
                    CurrentError = GetString("media.move.movetoitself");
                    AddLog(CurrentError);
                    return;
                }

                // Get unique path for copy or move
                string path = Path.GetFullPath(DirectoryHelper.CombinePath(libPath, newPath));
                path = MediaLibraryHelper.EnsureUniqueDirectory(path);
                newPath = path.Remove(0, (libPath.Length + 1));

                // Get new DB path
                newDBPath = MediaLibraryHelper.EnsurePath(newPath.Replace(DirectoryHelper.EnsurePathBackSlash(libPath), ""));
            }
            else
            {
                origDBPath = MediaLibraryHelper.EnsurePath(FolderPath);
                newDBPath = MediaLibraryHelper.EnsurePath(newPath.Replace(libPath, "")).Trim('/');
            }

            // Error if moving folder into its subfolder
            if ((String.IsNullOrEmpty(Files) && !AllFiles) && (Action.ToLower() == "move") && newPath.StartsWith(DirectoryHelper.EnsurePathBackSlash(FolderPath)))
            {
                CurrentError = GetString("media.move.parenttochild");
                AddLog(CurrentError);
                return;
            }

            // Error if moving files into same directory
            if ((!String.IsNullOrEmpty(Files) || AllFiles) && (Action.ToLower() == "move") && (newPath.TrimEnd('\\') == FolderPath.TrimEnd('\\')))
            {
                CurrentError = GetString("media.move.fileserror");
                AddLog(CurrentError);
                return;
            }

            NewPath = newPath;
            refreshScript = "if ((typeof(window.top.opener) != 'undefined') && (typeof(window.top.opener.RefreshLibrary) != 'undefined')) {window.top.opener.RefreshLibrary(" + ScriptHelper.GetString(NewPath.Replace('\\', '|')) + ");} else if ((typeof(window.top.wopener) != 'undefined') && (typeof(window.top.wopener.RefreshLibrary) != 'undefined')) { window.top.wopener.RefreshLibrary(" + ScriptHelper.GetString(NewPath.Replace('\\', '|')) + "); } window.top.close();";

            // If mFiles is empty handle directory copy/move
            if (String.IsNullOrEmpty(Files) && !mAllFiles)
            {
                try
                {
                    switch (Action.ToLower())
                    {
                        case "move":
                            MediaLibraryInfoProvider.MoveMediaLibraryFolder(CMSContext.CurrentSiteName, MediaLibraryID, origDBPath, newDBPath, false);
                            break;

                        case "copy":
                            MediaLibraryInfoProvider.CopyMediaLibraryFolder(CMSContext.CurrentSiteName, MediaLibraryID, origDBPath, newDBPath, false, CurrentUser.UserID);
                            break;
                    }
                }
                catch (UnauthorizedAccessException ex)
                {
                    CurrentError = GetString("general.erroroccurred") + " " + GetString("media.security.accessdenied");
                    EventLogProvider ev = new EventLogProvider();
                    ev.LogEvent("MediaFolder", this.Action, ex);
                    AddLog(CurrentError);
                    return;
                }
                catch (ThreadAbortException ex)
                {
                    string state = ValidationHelper.GetString(ex.ExceptionState, string.Empty);
                    if (state == CMSThread.ABORT_REASON_STOP)
                    {
                        // When canceled
                        CurrentInfo = GetString("general.actioncanceled");
                        AddLog(CurrentInfo);
                    }
                    else
                    {
                        // Log error
                        CurrentError = GetString("general.erroroccurred") + " " + ex.Message;
                        EventLogProvider ev = new EventLogProvider();
                        ev.LogEvent("MediaFolder", this.Action, ex);
                        AddLog(CurrentError);
                        return;
                    }
                }
                catch (Exception ex)
                {
                    CurrentError = GetString("general.erroroccurred") + " " + ex.Message;
                    EventLogProvider ev = new EventLogProvider();
                    ev.LogEvent("MediaFolder", this.Action, ex);
                    AddLog(CurrentError);
                    return;
                }
            }
            else
            {
                string origDBFilePath = null;
                string newDBFilePath = null;

                if (!mAllFiles)
                {
                    try
                    {
                        string[] files = Files.Split('|');
                        foreach (string filename in files)
                        {
                            origDBFilePath = (string.IsNullOrEmpty(origDBPath)) ? filename : origDBPath + "/" + filename;
                            newDBFilePath = (string.IsNullOrEmpty(newDBPath)) ? filename : newDBPath + "/" + filename;
                            AddLog(filename);
                            CopyMove(origDBFilePath, newDBFilePath);
                        }
                    }
                    catch (UnauthorizedAccessException ex)
                    {
                        CurrentError = GetString("general.erroroccurred") + " " + ResHelper.GetString("media.security.accessdenied");
                        EventLogProvider ev = new EventLogProvider();
                        ev.LogEvent("MediaFile", this.Action, ex);
                        AddLog(CurrentError);
                        return;
                    }
                    catch (ThreadAbortException ex)
                    {
                        string state = ValidationHelper.GetString(ex.ExceptionState, string.Empty);
                        if (state == CMSThread.ABORT_REASON_STOP)
                        {
                            // When canceled
                            CurrentInfo = GetString("general.actioncanceled");
                            AddLog(CurrentInfo);
                        }
                        else
                        {
                            // Log error
                            CurrentError = GetString("general.erroroccurred") + " " + ex.Message;
                            EventLogProvider ev = new EventLogProvider();
                            ev.LogEvent("MediaFile", this.Action, ex);
                            AddLog(CurrentError);
                            return;
                        }
                    }
                    catch (Exception ex)
                    {
                        CurrentError = GetString("general.erroroccurred") + " " + ex.Message;
                        EventLogProvider ev = new EventLogProvider();
                        ev.LogEvent("MediaFile", this.Action, ex);
                        AddLog(CurrentError);
                        return;
                    }
                }
                else
                {
                    HttpContext context = (parameter as HttpContext);
                    if (context != null)
                    {
                        HttpContext.Current = context;

                        DataSet files = GetFileSystemDataSource();
                        if (!DataHelper.IsEmpty(files))
                        {
                            foreach (DataRow file in files.Tables[0].Rows)
                            {
                                string fileName = ValidationHelper.GetString(file["FileName"], "");

                                AddLog(fileName);

                                origDBFilePath = (string.IsNullOrEmpty(origDBPath)) ? fileName : origDBPath + "/" + fileName;
                                newDBFilePath = (string.IsNullOrEmpty(newDBPath)) ? fileName : newDBPath + "/" + fileName;

                                // Clear current httpcontext for CopyMove action in threat
                                HttpContext.Current = null;

                                try
                                {
                                    CopyMove(origDBFilePath, newDBFilePath);
                                }
                                catch (UnauthorizedAccessException ex)
                                {
                                    CurrentError = GetString("general.erroroccurred") + " " + ResHelper.GetString("media.security.accessdenied");
                                    EventLogProvider ev = new EventLogProvider();
                                    ev.LogEvent("MediaFile", this.Action, ex);
                                    AddLog(CurrentError);
                                    return;
                                }
                                catch (ThreadAbortException ex)
                                {
                                    string state = ValidationHelper.GetString(ex.ExceptionState, string.Empty);
                                    if (state == CMSThread.ABORT_REASON_STOP)
                                    {
                                        // When canceled
                                        CurrentInfo = GetString("general.actioncanceled");
                                        AddLog(CurrentInfo);
                                    }
                                    else
                                    {
                                        // Log error
                                        CurrentError = GetString("general.erroroccurred") + " " + ex.Message;
                                        EventLogProvider ev = new EventLogProvider();
                                        ev.LogEvent("MediaFile", this.Action, ex);
                                        AddLog(CurrentError);
                                        return;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    CurrentError = GetString("general.erroroccurred") + " " + ex.Message;
                                    EventLogProvider ev = new EventLogProvider();
                                    ev.LogEvent("MediaFile", this.Action, ex);
                                    AddLog(CurrentError);
                                    return;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    protected void btnOK_Click(object sender, EventArgs e)
    {
        string result = new Validator().NotEmpty(rfvDisplayName, rfvDisplayName.ErrorMessage).NotEmpty(rfvCodeName, rfvCodeName.ErrorMessage).NotEmpty(rfvURL, rfvURL.ErrorMessage)
            .IsCodeName(txtCodeName.Text, GetString("general.invalidcodename"))
            .Result;

        // Get the object
        WebFarmServerInfo wi = WebFarmServerInfoProvider.GetWebFarmServerInfo(serverid) ?? new WebFarmServerInfo();

        // Check license web farm server limit
        if (String.IsNullOrEmpty(result))
        {
            LicenseKeyInfo lki = LicenseHelper.CurrentLicenseInfo;
            if (lki == null)
            {
                return;
            }

            // Only if server is enabled
            if (chkEnabled.Checked)
            {
                // Enabling or new server as action insert
                VersionActionEnum action = ((wi.ServerID > 0) && wi.ServerEnabled) ? VersionActionEnum.Edit : VersionActionEnum.Insert;
                if (!lki.CheckServerCount(WebSyncHelperClass.ServerCount, action))
                {
                    result = GetString("licenselimitation.infopagemessage");
                }

                // Log the message
                if (!String.IsNullOrEmpty(result))
                {
                    EventLogProvider eventLog = new EventLogProvider();
                    string message = GetString("licenselimitation.serversexceeded");
                    eventLog.LogEvent(EventLogProvider.EVENT_TYPE_WARNING, DateTime.Now, "WebFarms", LicenseHelper.LICENSE_LIMITATION_EVENTCODE, URLHelper.CurrentURL, message);
                }
            }
        }

        if (result == "")
        {
            wi.ServerID = serverid;
            wi.ServerDisplayName = txtDisplayName.Text;
            wi.ServerName = txtCodeName.Text;
            wi.ServerURL = txtURL.Text;
            wi.ServerEnabled = chkEnabled.Checked;
            try
            {
                WebFarmServerInfoProvider.SetWebFarmServerInfo(wi);
                // Clear server list
                URLHelper.Redirect("WebFarm_Server_Edit.aspx?serverid=" + wi.ServerID + "&saved=1");
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message.Replace("%%name%%", wi.ServerName);
                lblError.Visible = true;
                lblInfo.Visible = false;
            }
        }
        else
        {
            lblError.Text = result;
            lblError.Visible = true;
            lblInfo.Visible = false;
        }
    }
    private void DisplayError(Exception ex)
    {
        pnlProgress.Visible = false;
        btnOk.Enabled = false;
        pnlDetails.Visible = false;

        string displayName = null;
        if (exportObj != null)
        {
            displayName = exportObj.ObjectDisplayName;
        }
        lblResult.Text = string.Format(GetString("RestoreObject.Error"), HTMLHelper.HTMLEncode(displayName), ex.Message);
        lblResult.ToolTip = EventLogProvider.GetExceptionLogMessage(ex);
        lblResult.CssClass = "ErrorLabel";

        // Log to the event log
        EventLogProvider ev = new EventLogProvider();
        ev.LogEvent("Export", "RestoreObject", ex);
    }
    /// <summary>
    /// Saves modified image data.
    /// </summary>
    /// <param name="name">Image name</param>
    /// <param name="extension">Image extension</param>
    /// <param name="mimetype">Image mimetype</param>
    /// <param name="title">Image title</param>
    /// <param name="description">Image description</param>
    /// <param name="binary">Image binary data</param>
    /// <param name="width">Image width</param>
    /// <param name="height">Image height</param>
    private void SaveImage(string name, string extension, string mimetype, string title, string description, byte[] binary, int width, int height)
    {
        // Process media file
        if (mfi == null)
        {
            mfi = MediaFileInfoProvider.GetMediaFileInfo(mediafileGuid, this.CurrentSiteName);
        }

        if (mfi != null)
        {
            MediaLibraryInfo mli = MediaLibraryInfoProvider.GetMediaLibraryInfo(mfi.FileLibraryID);
            if (mli != null)
            {
                string path = Path.GetDirectoryName(DirectoryHelper.CombinePath(MediaLibraryInfoProvider.GetMediaLibraryFolderPath(mli.LibraryID), mfi.FilePath));
                bool permissionsOK = DirectoryHelper.CheckPermissions(path, false, true, true, true);

                if (permissionsOK)
                {
                    MediaFileInfo originalMfi = mfi.Clone(true);

                    try
                    {
                        // Ensure object version
                        SynchronizationHelper.EnsureObjectVersion(mfi);

                        if (isPreview && !String.IsNullOrEmpty(PreviewPath))
                        {
                            SiteInfo si = SiteInfoProvider.GetSiteInfo(mfi.FileSiteID);
                            if (si != null)
                            {
                                string previewExt = (!String.IsNullOrEmpty(extension) && (extension != OldPreviewExt)) ? extension : OldPreviewExt;
                                string previewName = Path.GetFileNameWithoutExtension(PreviewPath);
                                string previewFolder = MediaLibraryHelper.EnsurePath(DirectoryHelper.CombinePath(Path.GetDirectoryName(mfi.FilePath).TrimEnd('/'), MediaLibraryHelper.GetMediaFileHiddenFolder(si.SiteName)));

                                // Delete old preview files with thumbnails
                                MediaFileInfoProvider.DeleteMediaFilePreview(CMSContext.CurrentSiteName, mli.LibraryID, mfi.FilePath, false);
                                MediaFileInfoProvider.DeleteMediaFilePreviewThumbnails(mfi);

                                // Save preview file
                                MediaFileInfoProvider.SaveFileToDisk(si.SiteName, mli.LibraryFolder, previewFolder, previewName, previewExt, mfi.FileGUID, binary, false, false);

                                // Log synchronization task
                                SynchronizationHelper.LogObjectChange(mfi, TaskTypeEnum.UpdateObject);
                            }
                        }
                        else
                        {
                            string newExt = null;
                            string newName = null;

                            if (!String.IsNullOrEmpty(extension))
                            {
                                newExt = extension;
                            }
                            if (!String.IsNullOrEmpty(mimetype))
                            {
                                mfi.FileMimeType = mimetype;
                            }

                            mfi.FileTitle = title;
                            mfi.FileDescription = description;

                            if (width > 0)
                            {
                                mfi.FileImageWidth = width;
                            }
                            if (height > 0)
                            {
                                mfi.FileImageHeight = height;
                            }
                            if (binary != null)
                            {
                                mfi.FileBinary = binary;
                                mfi.FileSize = binary.Length;
                            }
                            // Test all parameters to empty values and update new value if available
                            if (!String.IsNullOrEmpty(name))
                            {
                                newName = name;
                            }
                            // If filename changed move preview file and remove all ald thumbnails
                            if ((!String.IsNullOrEmpty(newName) && (mfi.FileName != newName)) || (!String.IsNullOrEmpty(newExt) && (mfi.FileExtension.ToLower() != newExt.ToLower())))
                            {
                                SiteInfo si = SiteInfoProvider.GetSiteInfo(mfi.FileSiteID);
                                if (si != null)
                                {
                                    string fileName = (newName != null ? newName : mfi.FileName);
                                    string fileExt = (newExt != null ? newExt : mfi.FileExtension);

                                    string newPath = MediaFileInfoProvider.GetMediaFilePath(mfi.FileLibraryID, DirectoryHelper.CombinePath(Path.GetDirectoryName(mfi.FilePath), fileName) + fileExt);
                                    string filePath = MediaFileInfoProvider.GetMediaFilePath(mfi.FileLibraryID, mfi.FilePath);

                                    // Rename file only if file with same name does not exsists
                                    if (!File.Exists(newPath))
                                    {
                                        // Ensure max length of file path
                                        if (newPath.Length < 260)
                                        {
                                            // Remove old thumbnails
                                            MediaFileInfoProvider.DeleteMediaFileThumbnails(mfi);
                                            MediaFileInfoProvider.DeleteMediaFilePreviewThumbnails(mfi);

                                            // Move media file
                                            MediaFileInfoProvider.MoveMediaFile(si.SiteName, mli.LibraryID, mfi.FilePath, DirectoryHelper.CombinePath(Path.GetDirectoryName(mfi.FilePath), fileName) + fileExt, false);

                                            // Set new file name or extension
                                            mfi.FileName = fileName;
                                            mfi.FileExtension = fileExt;

                                            // Ensure new binary
                                            if (binary != null)
                                            {
                                                mfi.FileBinary = binary;
                                                mfi.FileSize = binary.Length;
                                            }
                                        }
                                        else
                                        {
                                            throw new IOExceptions.PathTooLongException();
                                        }
                                    }
                                    else
                                    {
                                        baseImageEditor.LblLoadFailed.Visible = true;
                                        baseImageEditor.LblLoadFailed.ResourceString = "img.errors.fileexists";
                                        SavingFailed = true;
                                        return;
                                    }
                                }
                            }
                            else
                            {
                                // Remove old thumbnails
                                MediaFileInfoProvider.DeleteMediaFileThumbnails(mfi);

                                // Remove original media file before save
                                string filePath = MediaFileInfoProvider.GetMediaFilePath(mfi.FileLibraryID, mfi.FilePath);
                                if (File.Exists(filePath))
                                {
                                    File.Delete(filePath);
                                }
                            }

                            // Save new data
                            MediaFileInfoProvider.SetMediaFileInfo(mfi, false);
                        }
                    }
                    catch (Exception e)
                    {
                        // Log exception
                        EventLogProvider ev = new EventLogProvider();
                        ev.LogEvent("ImageEditor", "Save file", e);

                        baseImageEditor.LblLoadFailed.Visible = true;
                        baseImageEditor.LblLoadFailed.ResourceString = "img.errors.processing";
                        ScriptHelper.AppendTooltip(baseImageEditor.LblLoadFailed, e.Message, "help");
                        this.SavingFailed = true;
                        // Save original media file info
                        MediaFileInfoProvider.SetMediaFileInfo(originalMfi, false);
                    }
                }
            }
        }
    }
    /// <summary>
    /// Render override.
    /// </summary>
    protected override void Render(HtmlTextWriter writer)
    {
        // if everything ok, email should be send
        if (mSendEmail)
        {
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            Html32TextWriter mwriter = new Html32TextWriter(sw);
            repItems.RenderControl(mwriter);

            repItems.Visible = false;

            // Prepare the macro resolver
            ContextResolver resolver = ContextResolver.CreateContextChild();

            string[,] replacements = new string[2, 2];
            // Prepare macro replacements
            replacements[0, 0] = "message";
            replacements[0, 1] = txtMessageText.Text;
            replacements[1, 0] = "document";
            replacements[1, 1] = URLHelper.MakeLinksAbsolute(sb.ToString());

            resolver.SourceParameters = replacements;

            if (EmailTemplate != null)
            {
                EmailMessage message = new EmailMessage();
                message.EmailFormat = EmailFormatEnum.Html;

                message.From = EmailFrom;
                message.Recipients = txtEmailTo.Text;

                // Get current css stylesheet
                string styleSheet = URLHelper.MakeLinksAbsolute(GetCssFileLink());

                // resolve EmailSubject here
                message.Subject = resolver.ResolveMacros(EmailSubject);
                // resolve EmailTemplate, wrap to HTML code and add the CSS files
                message.Body = "<html><head>" + styleSheet + "</head><body class=\"EmailBody\">" + resolver.ResolveMacros(EmailTemplate) + "</body></html>";

                // check recipients
                if ((message.Recipients != null) && (message.Recipients.Trim() != ""))
                {
                    try
                    {
                        EmailSender.SendEmail(CMSContext.CurrentSiteName, message);

                        // Display message, email was sent successfully
                        lblInfo.Text = GetString("sendtofriend.emailsent");
                        txtEmailTo.Text = "";
                        txtMessageText.Text = "";
                    }
                    catch (Exception ex)
                    {
                        lblError.Text = GetString("SendToFriend.SendEmailError");
                        try
                        {
                            EventLogProvider eventLog = new EventLogProvider();
                            eventLog.LogEvent("Send email", "SendToFriend", ex);
                        }
                        catch
                        {
                            // Unable to log the event
                        }
                    }
                }
            }
        }

        base.Render(writer);
    }
    /// <summary>
    /// Restart webfarm.
    /// </summary>
    protected void btnRestartWebfarm_Click(object sender, EventArgs e)
    {
        if (StopProcessing)
        {
            return;
        }

        // Restart current server
        RestartApplication();

        // Log event
        EventLogProvider eventLog = new EventLogProvider();
        eventLog.LogEvent(EventLogProvider.EVENT_TYPE_INFORMATION, DateTime.Now, "System", "RESTARTWEBFARM", null, GetString("Administration-System.WebframRestarted"));

        string url = URLHelper.UpdateParameterInUrl(URLRewriter.CurrentURL, "lastaction", "WebfarmRestarted");
        url = URLHelper.UpdateParameterInUrl(url, "restartedhash", ValidationHelper.GetHashString("WebfarmRestarted"));
        URLHelper.Redirect(url);
    }
    /// <summary>
    /// Callback event handler.
    /// </summary>
    /// <param name="argument">Callback argument</param>
    public void RaiseCallbackEvent(string argument)
    {
        // Get arguments
        string[] args = argument.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
        bool cancel = ValidationHelper.GetBoolean(args[0], false);
        int messageLength = 0;
        int errorLength = 0;
        int warningLength = 0;
        string machineName = null;

        if (args.Length == 5)
        {
            messageLength = ValidationHelper.GetInteger(args[1], 0);
            errorLength = ValidationHelper.GetInteger(args[2], 0);
            warningLength = ValidationHelper.GetInteger(args[3], 0);
            machineName = ValidationHelper.GetString(args[4], null);
        }

        // Check if on same machine
        if (machineName == SqlHelperClass.MachineName.ToLowerCSafe())
        {
            try
            {
                // Cancel Import
                if (cancel)
                {
                    ImportManager.Settings.Cancel();
                }

                hdnState.Value = ImportManager.Settings.GetLimitedProgressLog(messageLength, errorLength, warningLength);
            }
            catch (Exception ex)
            {
                EventLogProvider ev = new EventLogProvider();
                ev.LogEvent("NewSiteWizard", "IMPORT", ex);

                hdnState.Value = ImportManager.Settings.GetLimitedProgressLog(messageLength, errorLength, warningLength);
            }
            finally
            {
                if (ImportManager.Settings.GetProgressState() != LogStatusEnum.Info)
                {
                    // Delete presistent data
                    PersistentStorageHelper.RemoveValue(PersistentSettingsKey);
                }
            }
        }
    }
    protected void ctrlImport_OnFinished(object sender, EventArgs e)
    {
        try
        {
            // Convert default culture
            if (!siteType.SelectTemplate)
            {
                TreeProvider tree = new TreeProvider(CMSContext.CurrentUser);
                tree.ChangeSiteDefaultCulture(SiteName, Culture, "en-US");

                // Change root GUID
                TreeNode root = DocumentHelper.GetDocument(SiteName, "/", Culture, false, "cms.root", null, null, 1, false, null, tree);
                if (root != null)
                {
                    root.NodeGUID = Guid.NewGuid();
                    DocumentHelper.UpdateDocument(root, tree);
                }
            }
        }
        catch (Exception ex)
        {
            EventLogProvider ev = new EventLogProvider();
            ev.LogEvent("NewSiteWizard", "FINISH", ex);
        }
        finally
        {
            if (ImportManager.Settings.ProcessCanceled)
            {
                NextButton.Enabled = CancelButton.Enabled = false;
                mImportCanceled = true;
                lblProgress.Text = "<strong>" + ResHelper.GetAPIString("ImportSite.ImportCanceled", "Import process has been cancelled.") + "</strong>";
            }
            else
            {
                if (!ImportManager.Settings.IsWarning() && !ImportManager.Settings.IsError())
                {
                    PreviousButton.Visible = false;
                    CultureHelper.SetPreferredCulture(Culture);
                    if (siteType.SelectTemplate)
                    {
                        // Done
                        finishSite.Domain = Domain;
                        wzdImport.ActiveStepIndex = 7;
                    }
                    else
                    {
                        selectMaster.SiteName = SiteName;
                        wzdImport.ActiveStepIndex += 1;
                        selectMaster.ReloadData();
                    }
                }
            }

            // Stop the timer
            string script = "StopSelectionTimer();";
            ltlScriptAfter.Text += ScriptHelper.GetScript(script);
        }
    }
Exemple #57
0
    /// <summary>
    /// Save selected field.
    /// </summary>
    private void SaveSelectedField()
    {
        // FormFieldInfo structure with data from updated form
        FormFieldInfo ffiUpdated = null;
        // FormCategoryInfo structure with data from updated form
        FormCategoryInfo fciUpdated = null;
        // Determines whether it is a new attribute (or attribute to update)
        bool isNewItem = false;
        string errorMessage = null;
        DataClassInfo dci = null;
        WebPartInfo wpi = null;

        // Variables for changes in DB tables
        string tableName = null;
        string oldColumnName = null;
        string newColumnName = null;
        string newColumnSize = null;
        string newColumnType = null;
        string newColumnDefaultValue = null;  // No default value
        bool newColumnAllowNull = true;

        if (!IsAlternativeForm)
        {
            switch (mMode)
            {
                case FieldEditorModeEnum.WebPartProperties:
                    // Fill WebPartInfo structure with data from database
                    wpi = WebPartInfoProvider.GetWebPartInfo(mWebPartId);
                    break;

                case FieldEditorModeEnum.ClassFormDefinition:
                case FieldEditorModeEnum.BizFormDefinition:
                case FieldEditorModeEnum.SystemTable:
                case FieldEditorModeEnum.CustomTable:
                    // Fill ClassInfo structure with data from database
                    dci = DataClassInfoProvider.GetDataClass(mClassName);
                    if (dci != null)
                    {
                        // Set table name
                        tableName = dci.ClassTableName;
                    }
                    else
                    {
                        lblError.Visible = true;
                        lblError.ResourceString = "fieldeditor.notablename";
                        return;
                    }
                    break;
            }
        }

        // Load current xml form definition
        LoadFormDefinition();

        if (SelectedItemType == FieldEditorSelectedItemEnum.Field)
        {
            // Fill FormFieldInfo structure with original data
            ffi = fi.GetFormField(SelectedItemName);

            // Fill FormFieldInfo structure with updated form data
            ffiUpdated = FillFormFieldInfoStructure(ffi);

            // Determine whether it is a new attribute or not
            isNewItem = (ffi == null);

            // Check if the attribute name already exists
            if (isNewItem || (ffi.Name.ToLower() != ffiUpdated.Name.ToLower()))
            {
                columnNames = fi.GetColumnNames();

                if (columnNames != null)
                {
                    foreach (string colName in columnNames)
                    {
                        // If name already exists
                        if (ffiUpdated.Name.ToLower() == colName.ToLower())
                        {
                            lblError.Visible = true;
                            lblError.ResourceString = "TemplateDesigner.ErrorExistingColumnName";
                            return;
                        }
                    }
                }

                // Check column name duplicity in JOINed tables
                if (!IsSystemFieldSelected)
                {
                    // Check whether current column already exists in 'View_CMS_Tree_Joined'
                    if (IsDocumentType && DocumentHelper.ColumnExistsInSystemTable(ffiUpdated.Name))
                    {
                        lblError.Visible = true;
                        lblError.ResourceString = "TemplateDesigner.ErrorExistingColumnInJoinedTable";
                        return;
                    }

                    // Check whether current column is uniquie in tables used to create views - applied only for system tables
                    if ((Mode == FieldEditorModeEnum.SystemTable) && FormHelper.ColumnExistsInView(mClassName, ffiUpdated.Name))
                    {
                        lblError.Visible = true;
                        lblError.ResourceString = "TemplateDesigner.ErrorExistingColumnInJoinedTable";
                        return;
                    }
                }
            }

            // New node
            if (isNewItem)
            {
                ffiUpdated.PrimaryKey = this.IsPrimaryField;
                newColumnName = ffiUpdated.Name;
                newColumnAllowNull = ffiUpdated.AllowEmpty;

                // Set implicit default value
                if (!(newColumnAllowNull) && (string.IsNullOrEmpty(ffiUpdated.DefaultValue)))
                {
                    if (!this.DevelopmentMode)
                    {
                        switch (ffiUpdated.DataType)
                        {
                            case FormFieldDataTypeEnum.Integer:
                            case FormFieldDataTypeEnum.LongInteger:
                            case FormFieldDataTypeEnum.Decimal:
                            case FormFieldDataTypeEnum.Boolean:
                                newColumnDefaultValue = "0";
                                break;

                            case FormFieldDataTypeEnum.Text:
                            case FormFieldDataTypeEnum.LongText:
                            case FormFieldDataTypeEnum.DocumentAttachments:
                                newColumnDefaultValue = "";
                                break;

                            case FormFieldDataTypeEnum.DateTime:
                                newColumnDefaultValue = new DateTime(1970, 1, 1, 0, 0, 0).ToString();
                                break;

                            case FormFieldDataTypeEnum.File:
                            case FormFieldDataTypeEnum.GUID:
                                // 32 digits, empty Guid
                                newColumnDefaultValue = Guid.Empty.ToString();
                                break;

                            case FormFieldDataTypeEnum.Binary:
                                newColumnDefaultValue = null;
                                break;
                        }
                    }
                }
                // Check if default value is in required format
                else if (!string.IsNullOrEmpty(ffiUpdated.DefaultValue))
                {
                    // If default value is macro, don't try to ensure the type
                    if (!ffiUpdated.IsMacro)
                    {
                        switch (ffiUpdated.DataType)
                        {
                            case FormFieldDataTypeEnum.Integer:
                                try
                                {
                                    int i = Int32.Parse(ffiUpdated.DefaultValue);
                                    newColumnDefaultValue = i.ToString();
                                }
                                catch
                                {
                                    newColumnDefaultValue = "0";
                                    errorMessage = GetString("TemplateDesigner.ErrorDefaultValueInteger");
                                }
                                break;

                            case FormFieldDataTypeEnum.LongInteger:
                                try
                                {
                                    long longInt = long.Parse(ffiUpdated.DefaultValue);
                                    newColumnDefaultValue = longInt.ToString();
                                }
                                catch
                                {
                                    newColumnDefaultValue = "0";
                                    errorMessage = GetString("TemplateDesigner.ErrorDefaultValueLongInteger");
                                }
                                break;

                            case FormFieldDataTypeEnum.Decimal:
                                if (ValidationHelper.IsDouble(ffiUpdated.DefaultValue))
                                {
                                    newColumnDefaultValue = FormHelper.GetDoubleValueInDBCulture(ffiUpdated.DefaultValue);
                                }
                                else
                                {
                                    newColumnDefaultValue = "0";
                                    errorMessage = GetString("TemplateDesigner.ErrorDefaultValueDouble");
                                }
                                break;

                            case FormFieldDataTypeEnum.DateTime:
                                if ((ffiUpdated.DefaultValue.ToLower() == DateTimePicker.DATE_TODAY.ToLower()) || (ffiUpdated.DefaultValue.ToLower() == DateTimePicker.TIME_NOW.ToLower()))
                                {
                                    newColumnDefaultValue = ffiUpdated.DefaultValue;
                                }
                                else
                                {
                                    try
                                    {
                                        DateTime dat = DateTime.Parse(ffiUpdated.DefaultValue);
                                        newColumnDefaultValue = dat.ToString();
                                    }
                                    catch
                                    {
                                        newColumnDefaultValue = DateTime.Now.ToString();
                                        errorMessage = GetString("TemplateDesigner.ErrorDefaultValueDateTime");
                                    }
                                }
                                break;

                            case FormFieldDataTypeEnum.File:
                            case FormFieldDataTypeEnum.GUID:
                                try
                                {
                                    Guid g = new Guid(ffiUpdated.DefaultValue);
                                    newColumnDefaultValue = g.ToString();
                                }
                                catch
                                {
                                    newColumnDefaultValue = Guid.Empty.ToString();
                                    errorMessage = GetString("TemplateDesigner.ErrorDefaultValueGuid");
                                }
                                break;

                            case FormFieldDataTypeEnum.LongText:
                            case FormFieldDataTypeEnum.Text:
                            case FormFieldDataTypeEnum.Boolean:

                                newColumnDefaultValue = ffiUpdated.DefaultValue;
                                break;
                        }
                    }
                }

                // Set column type and size
                LoadColumnTypeAndSize(ffiUpdated.DataType, ffiUpdated.Size, ref newColumnType, ref newColumnSize);

                if (string.IsNullOrEmpty(errorMessage))
                {
                    if (!IsAlternativeForm)
                    {
                        switch (mMode)
                        {
                            case FieldEditorModeEnum.ClassFormDefinition:
                            case FieldEditorModeEnum.BizFormDefinition:
                            case FieldEditorModeEnum.SystemTable:
                            case FieldEditorModeEnum.CustomTable:

                                // Add new column to specified table
                                try
                                {
                                    string newDBDefaultValue = null;

                                    // Check if it is not a macro
                                    if (ffiUpdated.IsMacro)
                                    {
                                        newDBDefaultValue = newColumnDefaultValue;
                                    }
                                    else
                                    {
                                        switch (ffiUpdated.DataType)
                                        {
                                            case FormFieldDataTypeEnum.Decimal:
                                                newDBDefaultValue = FormHelper.GetDoubleValueInDBCulture(newColumnDefaultValue);
                                                break;

                                            case FormFieldDataTypeEnum.DateTime:
                                                newDBDefaultValue = FormHelper.GetDateTimeValueInDBCulture(newColumnDefaultValue);
                                                break;
                                            default:
                                                newDBDefaultValue = newColumnDefaultValue;
                                                break;
                                        }
                                    }

                                    if (!ffiUpdated.External)
                                    {
                                        if (this.DevelopmentMode)
                                        {
                                            TableManager.AddTableColumn(tableName, newColumnName, newColumnType, newColumnAllowNull, newDBDefaultValue, false);
                                        }
                                        else
                                        {
                                            TableManager.AddTableColumn(tableName, newColumnName, newColumnType, newColumnAllowNull, newDBDefaultValue);
                                        }

                                        // Recreate the table PK constraint
                                        if (IsPrimaryField)
                                        {
                                            int pos = 0;
                                            FormFieldInfo[] pkFields = fi.GetFields(true, true, false, true);
                                            string[] primaryKeys = new string[pkFields.Length + 1];
                                            foreach (FormFieldInfo pk in pkFields)
                                            {
                                                if (pk != null)
                                                {
                                                    primaryKeys[pos++] = "[" + pk.Name + "]";
                                                }
                                            }
                                            primaryKeys[pos] = "[" + newColumnName + "]";
                                            TableManager.RecreatePKConstraint(tableName, primaryKeys, null);
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    lblError.Visible = true;
                                    lblError.Text = ex.Message;
                                    return;
                                }

                                break;
                        }
                    }
                }
                // Some error has occurred
                else
                {
                    lblError.Visible = true;
                    lblError.Text = errorMessage;
                    return;
                }
            }
            // Existing node
            else
            {
                // Get info whether it is a primary key or system fild
                ffiUpdated.PrimaryKey = ffi.PrimaryKey;

                // If attribute is a primary key
                if (ffi.PrimaryKey)
                {
                    // Check if the attribute type is integer number
                    if (ffiUpdated.DataType != FormFieldDataTypeEnum.Integer)
                    {
                        errorMessage += GetString("TemplateDesigner.ErrorPKNotInteger") + " ";
                    }

                    // Check if allow empty is disabled
                    if (ffiUpdated.AllowEmpty)
                    {
                        errorMessage += GetString("TemplateDesigner.ErrorPKAllowsNulls") + " ";
                    }

                    // Check that the field type is label
                    string labelControlName = Enum.GetName(typeof(FormFieldControlTypeEnum), FormFieldControlTypeEnum.LabelControl).ToLower();
                    if ((ffiUpdated.FieldType != FormFieldControlTypeEnum.LabelControl) && ((ffiUpdated.FieldType != FormFieldControlTypeEnum.CustomUserControl) && (ffiUpdated.Settings["controlname"].ToString().ToLower() != labelControlName)))
                    {
                        errorMessage += GetString("TemplateDesigner.ErrorPKisNotLabel") + " ";
                    }

                    // Some error has occurred
                    if (!string.IsNullOrEmpty(errorMessage))
                    {
                        lblError.Visible = true;
                        lblError.Text = GetString("TemplateDesigner.ErrorPKThisIsPK") + " " + errorMessage;
                        return;
                    }
                }

                // If table column update is needed
                if (((ffi.PrimaryKey) && (ffi.Name != ffiUpdated.Name)) ||
                     ((!ffi.PrimaryKey) &&
                        ((ffi.Name != ffiUpdated.Name) ||
                         (ffi.DataType != ffiUpdated.DataType) ||
                         (ffi.AllowEmpty != ffiUpdated.AllowEmpty) ||
                         (ffi.Size != ffiUpdated.Size) ||
                         ((ffi.DefaultValue != ffiUpdated.DefaultValue) || (ffiUpdated.DataType == FormFieldDataTypeEnum.Decimal)))
                     )
                   )
                {
                    // Set variables needed for changes in DB
                    oldColumnName = ffi.Name;
                    newColumnName = ffiUpdated.Name;
                    newColumnAllowNull = ffiUpdated.AllowEmpty;

                    // Set implicit default value
                    if (!(newColumnAllowNull) && (string.IsNullOrEmpty(ffiUpdated.DefaultValue)))
                    {
                        switch (ffiUpdated.DataType)
                        {
                            case FormFieldDataTypeEnum.Integer:
                            case FormFieldDataTypeEnum.LongInteger:
                            case FormFieldDataTypeEnum.Decimal:
                            case FormFieldDataTypeEnum.Boolean:
                                newColumnDefaultValue = "0";
                                break;

                            case FormFieldDataTypeEnum.Text:
                            case FormFieldDataTypeEnum.LongText:
                                newColumnDefaultValue = "";
                                break;

                            case FormFieldDataTypeEnum.DateTime:
                                newColumnDefaultValue = DateTime.Now.ToString();
                                break;

                            case FormFieldDataTypeEnum.File:
                            case FormFieldDataTypeEnum.GUID:
                                // 32 digits, empty Guid
                                newColumnDefaultValue = Guid.Empty.ToString();
                                break;

                            case FormFieldDataTypeEnum.Binary:
                                newColumnDefaultValue = null;
                                break;
                        }
                    }

                    // Check if default value is in required format
                    else if (!string.IsNullOrEmpty(ffiUpdated.DefaultValue))
                    {
                        // If default value is macro, don't try to ensure the type
                        if (!ffiUpdated.IsMacro)
                        {
                            switch (ffiUpdated.DataType)
                            {
                                case FormFieldDataTypeEnum.Integer:
                                    try
                                    {
                                        int i = Int32.Parse(ffiUpdated.DefaultValue);
                                        newColumnDefaultValue = i.ToString();
                                    }
                                    catch
                                    {
                                        newColumnDefaultValue = "0";
                                        errorMessage = GetString("TemplateDesigner.ErrorDefaultValueInteger");
                                    }
                                    break;

                                case FormFieldDataTypeEnum.LongInteger:
                                    try
                                    {
                                        long longInt = long.Parse(ffiUpdated.DefaultValue);
                                        newColumnDefaultValue = longInt.ToString();
                                    }
                                    catch
                                    {
                                        newColumnDefaultValue = "0";
                                        errorMessage = GetString("TemplateDesigner.ErrorDefaultValueLongInteger");
                                    }
                                    break;

                                case FormFieldDataTypeEnum.Decimal:
                                    if (ValidationHelper.IsDouble(ffiUpdated.DefaultValue))
                                    {
                                        newColumnDefaultValue = FormHelper.GetDoubleValueInDBCulture(ffiUpdated.DefaultValue);
                                    }
                                    else
                                    {
                                        newColumnDefaultValue = "0";
                                        errorMessage = GetString("TemplateDesigner.ErrorDefaultValueDouble");
                                    }
                                    break;

                                case FormFieldDataTypeEnum.DateTime:
                                    if ((ffiUpdated.DefaultValue.ToLower() == DateTimePicker.DATE_TODAY.ToLower()) || (ffiUpdated.DefaultValue.ToLower() == DateTimePicker.TIME_NOW.ToLower()))
                                    {
                                        newColumnDefaultValue = ffiUpdated.DefaultValue;
                                    }
                                    else
                                    {
                                        try
                                        {
                                            DateTime dat = DateTime.Parse(ffiUpdated.DefaultValue);
                                            newColumnDefaultValue = dat.ToString();
                                        }
                                        catch
                                        {
                                            newColumnDefaultValue = DateTime.Now.ToString();
                                            errorMessage = GetString("TemplateDesigner.ErrorDefaultValueDateTime");
                                        }
                                    }
                                    break;

                                case FormFieldDataTypeEnum.File:
                                case FormFieldDataTypeEnum.GUID:
                                    try
                                    {
                                        Guid g = new Guid(ffiUpdated.DefaultValue);
                                        newColumnDefaultValue = g.ToString();
                                    }
                                    catch
                                    {
                                        newColumnDefaultValue = Guid.Empty.ToString();
                                        errorMessage = GetString("TemplateDesigner.ErrorDefaultValueGuid");
                                    }
                                    break;

                                case FormFieldDataTypeEnum.LongText:
                                case FormFieldDataTypeEnum.Text:
                                case FormFieldDataTypeEnum.Boolean:

                                    newColumnDefaultValue = ffiUpdated.DefaultValue;
                                    break;
                            }
                        }
                    }

                    // Set column type and size
                    LoadColumnTypeAndSize(ffiUpdated.DataType, ffiUpdated.Size, ref newColumnType, ref newColumnSize);

                    if (string.IsNullOrEmpty(errorMessage))
                    {
                        if (!IsAlternativeForm)
                        {
                            switch (mMode)
                            {
                                case FieldEditorModeEnum.ClassFormDefinition:
                                case FieldEditorModeEnum.BizFormDefinition:
                                case FieldEditorModeEnum.SystemTable:
                                case FieldEditorModeEnum.CustomTable:

                                    try
                                    {
                                        string newDBDefaultValue = null;

                                        // Check if it is not a macro
                                        if (ffiUpdated.IsMacro)
                                        {
                                            newDBDefaultValue = newColumnDefaultValue;
                                        }
                                        else
                                        {
                                            switch (ffiUpdated.DataType)
                                            {
                                                case FormFieldDataTypeEnum.Decimal:
                                                    newDBDefaultValue = FormHelper.GetDoubleValueInDBCulture(newColumnDefaultValue);
                                                    break;

                                                case FormFieldDataTypeEnum.DateTime:
                                                    newDBDefaultValue = FormHelper.GetDateTimeValueInDBCulture(newColumnDefaultValue);
                                                    break;
                                                default:
                                                    newDBDefaultValue = newColumnDefaultValue;
                                                    break;
                                            }
                                        }

                                        if (ffiUpdated.External)
                                        {
                                            if (!ffi.External)
                                            {
                                                // Drop old column from table
                                                TableManager.DropTableColumn(tableName, ffi.Name);
                                            }
                                        }
                                        else
                                        {
                                            if (ffi.External)
                                            {
                                                // Add table column
                                                TableManager.AddTableColumn(tableName, newColumnName, newColumnType, newColumnAllowNull, newDBDefaultValue);
                                            }
                                            else
                                            {
                                                // Change table column
                                                TableManager.AlterTableColumn(tableName, oldColumnName, newColumnName, newColumnType, newColumnAllowNull, newDBDefaultValue);
                                                if (OnFieldNameChanged != null)
                                                {
                                                    OnFieldNameChanged(this, oldColumnName, newColumnName);
                                                }
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        // User friendly message for not null setting of column
                                        if (ffi.AllowEmpty && !newColumnAllowNull)
                                        {
                                            lblError.Visible = true;
                                            lblError.ResourceString = "FieldEditor.ColumnNotAcceptNull";
                                            lblError.ToolTip = ex.Message;
                                        }
                                        else
                                        {
                                            lblError.Visible = true;
                                            lblError.Text = ex.Message;
                                        }
                                        return;
                                    }

                                    break;
                            }
                        }
                    }
                    // Some error has occurred
                    else
                    {
                        lblError.Visible = true;
                        lblError.Text = errorMessage;
                        return;
                    }
                } // End update needed
            } // End existing node

            // Insert new field
            if (isNewItem)
            {
                InsertFormItem(ffiUpdated);
            }
            // Update current field
            else
            {
                fi.UpdateFormField(ffi.Name, ffiUpdated);
            }
        }
        else if (SelectedItemType == FieldEditorSelectedItemEnum.Category)
        {
            // Fill FormCategoryInfo structure with original data
            fci = fi.GetFormCategory(SelectedItemName);
            // Determine whether it is a new attribute or not
            isNewItem = (fci == null);

            // Fill FormCategoryInfo structure with updated form data
            fciUpdated = new FormCategoryInfo();
            fciUpdated.CategoryCaption = categoryEdit.Value.Replace("'", "");

            // Check if the category caption is empty
            if (string.IsNullOrEmpty(fciUpdated.CategoryCaption))
            {
                lblError.Visible = true;
                lblError.ResourceString = "TemplateDesigner.ErrorCategoryNameEmpty";
                return;
            }

            if (isNewItem)
            {
                // Use category caption for name attribut
                fciUpdated.CategoryName = fciUpdated.CategoryCaption;
            }
            else
            {
                fciUpdated.CategoryName = SelectedItemName;
            }

            if (isNewItem)
            {
                // Get form category names
                string[] categoryNames = fi.GetCategoryNames();

                if (categoryNames != null)
                {
                    // Check if the category name is unique
                    foreach (string name in categoryNames)
                    {
                        // If name already exists return error
                        if (fciUpdated.CategoryName == name)
                        {
                            lblError.Visible = true;
                            lblError.ResourceString = "TemplateDesigner.ErrorExistingCategoryName";
                            return;
                        }
                    }
                }

                // Insert new category
                InsertFormItem(fciUpdated);
            }
            else
            {
                // Update current
                fi.UpdateFormCategory(fci.CategoryName, fciUpdated);
            }
        }

        // Make changes in database
        if (SelectedItemType != 0)
        {
            // Get updated definition
            FormDefinition = fi.GetXmlDefinition();

            string error = null;

            if (!IsAlternativeForm)
            {
                switch (mMode)
                {
                    case FieldEditorModeEnum.WebPartProperties:
                        if (wpi != null)
                        {
                            // Update xml definition
                            wpi.WebPartProperties = FormDefinition;

                            try
                            {
                                WebPartInfoProvider.SetWebPartInfo(wpi);
                            }
                            catch (Exception ex)
                            {
                                error = ex.Message;
                            }
                        }
                        else
                        {
                            error = GetString("FieldEditor.WebpartNotFound");
                        }
                        break;

                    case FieldEditorModeEnum.ClassFormDefinition:
                    case FieldEditorModeEnum.BizFormDefinition:
                    case FieldEditorModeEnum.SystemTable:
                    case FieldEditorModeEnum.CustomTable:
                        if (dci != null)
                        {
                            // Update xml definition
                            dci.ClassFormDefinition = FormDefinition;

                            // Update xml schema
                            dci.ClassXmlSchema = TableManager.GetXmlSchema(dci.ClassTableName);

                            // When updating existing field
                            if (ffi != null)
                            {
                                // Update ClassNodeNameSource field
                                if (dci.ClassNodeNameSource == ffi.Name)
                                {
                                    dci.ClassNodeNameSource = ffiUpdated.Name;
                                }
                            }

                            bool fieldType = (SelectedItemType == FieldEditorSelectedItemEnum.Field);

                            // Update changes in DB
                            try
                            {
                                // Save the data class
                                DataClassInfoProvider.SetDataClass(dci);

                                // Generate the class code
                                GenerateCode();

                                // Update inherited classes with new fields
                                FormHelper.UpdateInheritedClasses(dci);
                            }
                            catch (Exception ex)
                            {
                                error = ex.Message;
                            }

                            if (fieldType)
                            {
                                // Generate default view
                                if (mMode == FieldEditorModeEnum.BizFormDefinition)
                                {
                                    SqlGenerator.GenerateDefaultView(dci, CMSContext.CurrentSiteName);
                                }
                                else
                                {
                                    SqlGenerator.GenerateDefaultView(dci, null);
                                }

                                // Regenerate queries
                                SqlGenerator.GenerateDefaultQueries(dci, true, true);
                            }

                            // Updates custom views
                            if ((mMode == FieldEditorModeEnum.SystemTable) || (mMode == FieldEditorModeEnum.ClassFormDefinition))
                            {
                                try
                                {
                                    TableManager.RefreshCustomViews(dci.ClassTableName);

                                    string lowClassName = dci.ClassName.ToLower();
                                    if (lowClassName == "cms.document" || lowClassName == "cms.tree")
                                    {
                                        TableManager.RefreshDocumentViews();
                                    }
                                }
                                catch (Exception ex)
                                {
                                    error = ResHelper.GetString("fieldeditor.refreshingviewsfailed");
                                    EventLogProvider ev = new EventLogProvider();
                                    ev.LogEvent("Field Editor", "EXCEPTION", ex);
                                }
                            }
                        }
                        else
                        {
                            error = GetString("FieldEditor.ClassNotFound");
                        }
                        break;
                }
            }

            if (!string.IsNullOrEmpty(error))
            {
                lblError.Visible = true;
                lblError.Text = "[FieldEditor.SaveSelectedField()]: " + error;
            }
            else
            {
                IsNewItemEdited = false;

                if (SelectedItemType == FieldEditorSelectedItemEnum.Category)
                {
                    Reload(categPreffix + fciUpdated.CategoryName);
                }
                else if (SelectedItemType == FieldEditorSelectedItemEnum.Field)
                {
                    Reload(fieldPreffix + ffiUpdated.Name);
                }

                lblError.Visible = false;
                lblInfo.Visible = true;
                lblInfo.ResourceString = "general.changessaved";
            }
        }

        // All done and new item, fire OnFieldCreated  event
        if (isNewItem && (ffiUpdated != null))
        {
            RaiseOnFieldCreated(ffiUpdated);
        }
    }
    protected void wzdImport_NextButtonClick(object sender, WizardNavigationEventArgs e)
    {
        switch (e.CurrentStepIndex)
        {
                // Import type
            case 0:
                {
                    if (!siteType.SelectTemplate)
                    {
                        try
                        {
                            // Get blank web template
                            WebTemplateInfo wi = WebTemplateInfoProvider.GetWebTemplateInfo("BlankSite");
                            if (wi == null)
                            {
                                e.Cancel = true;
                                return;
                            }

                            WebTemplateID = wi.WebTemplateId;

                            string path = Server.MapPath(wi.WebTemplateFileName);
                            if (File.Exists(path + "\\template.zip"))
                            {
                                // Template from zip file
                                path += "\\" + ZipStorageProvider.GetZipFileName("template.zip");

                                ImportSettings.TemporaryFilesPath = path;
                                ImportSettings.SourceFilePath = path;
                                ImportSettings.TemporaryFilesCreated = true;
                                ImportSettings.RefreshMacroSecurity = true;
                            }
                            else
                            {
                                // Init the settings
                                ImportSettings.TemporaryFilesCreated = false;
                                ImportSettings.SourceFilePath = Server.MapPath(wi.WebTemplateFileName);
                                ImportSettings.RefreshMacroSecurity = true;
                            }

                            if (!File.Exists(ImportSettings.SourceFilePath))
                            {
                                try
                                {
                                    ImportProvider.CreateTemporaryFiles(ImportSettings);
                                }
                                catch (Exception ex)
                                {
                                    lblError.Visible = true;
                                    lblError.Text = ex.Message;
                                    e.Cancel = true;
                                    return;
                                }
                            }

                            if (SiteInfoProvider.GetSitesCount() == 0)
                            {
                                // No site exists, overwrite all
                                ImportSettings.ImportType = ImportTypeEnum.All;
                                ImportSettings.CopyFiles = false;
                            }
                            else
                            {
                                // Some site exists, only new objects
                                ImportSettings.ImportType = ImportTypeEnum.New;
                            }

                            ltlScriptAfter.Text = ScriptHelper.GetScript(
                                "var actDiv = document.getElementById('actDiv'); \n" +
                                "if (actDiv != null) { actDiv.style.display='block'; } \n" +
                                "var buttonsDiv = document.getElementById('buttonsDiv'); if (buttonsDiv != null) { buttonsDiv.disabled=true; } \n" +
                                "BTN_Disable('" + NextButton.ClientID + "'); \n" +
                                "StartSelectionTimer();"
                                );

                            // Preselect objects asynchronously
                            ctrlAsync.Parameter = "N";
                            ctrlAsync.RunAsync(SelectObjects, WindowsIdentity.GetCurrent());

                            e.Cancel = true;
                        }
                        catch (Exception ex)
                        {
                            lblError.Text = ex.Message;
                            e.Cancel = true;
                            return;
                        }
                    }
                    else
                    {
                        siteDetails.SiteName = null;
                        siteDetails.SiteDisplayName = null;
                        selectTemplate.ReloadData();
                    }

                    wzdImport.ActiveStepIndex++;
                }
                break;

                // Template selection
            case 1:
                {
                    if (!selectTemplate.ApplySettings())
                    {
                        e.Cancel = true;
                        return;
                    }

                    // Init the settings
                    WebTemplateInfo wi = WebTemplateInfoProvider.GetWebTemplateInfo(selectTemplate.WebTemplateId);
                    if (wi == null)
                    {
                        throw new Exception("Web template not found.");
                    }

                    ImportSettings.IsWebTemplate = true;

                    string path = Server.MapPath(wi.WebTemplateFileName);
                    if (File.Exists(path + "\\template.zip"))
                    {
                        // Template from zip file
                        path += "\\" + ZipStorageProvider.GetZipFileName("template.zip");

                        ImportSettings.TemporaryFilesPath = path;
                        ImportSettings.SourceFilePath = path;
                        ImportSettings.TemporaryFilesCreated = true;
                        ImportSettings.RefreshMacroSecurity = true;
                    }
                    else
                    {
                        // Template from folder
                        ImportSettings.TemporaryFilesCreated = false;
                        ImportSettings.SourceFilePath = path;
                        ImportSettings.RefreshMacroSecurity = true;
                        try
                        {
                            ImportProvider.CreateTemporaryFiles(ImportSettings);
                        }
                        catch (Exception ex)
                        {
                            lblError.Visible = true;
                            lblError.Text = ex.Message;
                            e.Cancel = true;
                            return;
                        }
                    }

                    if (SiteInfoProvider.GetSitesCount() == 0)
                    {
                        // No site exists, overwrite all
                        ImportSettings.ImportType = ImportTypeEnum.All;
                    }
                    else
                    {
                        // Some site exists, only new objects
                        ImportSettings.ImportType = ImportTypeEnum.New;
                    }

                    ltlScriptAfter.Text = ScriptHelper.GetScript(
                        "var actDiv = document.getElementById('actDiv');\n" +
                        "if (actDiv != null) { actDiv.style.display='block'; }\n" +
                        "var buttonsDiv = document.getElementById('buttonsDiv');\n" +
                        "if (buttonsDiv != null) { buttonsDiv.disabled=true; }\n" +
                        "BTN_Disable('" + NextButton.ClientID + "');\n" +
                        "BTN_Disable('" + PreviousButton.ClientID + "');\n" +
                        "StartSelectionTimer();"
                        );

                    // Preselect objects asynchronously
                    ctrlAsync.Parameter = "T";
                    ctrlAsync.RunAsync(SelectObjects, WindowsIdentity.GetCurrent());

                    e.Cancel = true;
                }
                break;

                // Site details
            case 2:
                if (!siteDetails.ApplySettings())
                {
                    e.Cancel = true;
                    return;
                }

                // Update settings
                ImportSettings = siteDetails.Settings;

                Culture = siteDetails.Culture;

                pnlImport.ReloadData(true);
                wzdImport.ActiveStepIndex++;
                break;

                // Objects selection
            case 3:
                if (!pnlImport.ApplySettings())
                {
                    e.Cancel = true;
                    return;
                }

                // Check licences
                string error = ImportExportControl.CheckLicenses(ImportSettings);
                if (!string.IsNullOrEmpty(error))
                {
                    lblError.Text = error;

                    e.Cancel = true;
                    return;
                }

                ImportSettings = pnlImport.Settings;

                PreviousButton.Enabled = false;
                NextButton.Enabled = false;

                SiteName = ImportSettings.SiteName;
                Domain = ImportSettings.SiteDomain;

                // Init the Mimetype helper (required for the Import)
                MimeTypeHelper.LoadMimeTypes();

                // Start asynchronnous Import
                ImportSettings.SetSettings(ImportExportHelper.SETTINGS_DELETE_TEMPORARY_FILES, false);
                ImportSettings.DefaultProcessObjectType = ProcessObjectEnum.Selected;
                ImportManager.Settings = ImportSettings;

                // Import site asynchronously
                ctrlImport.RunAsync(ImportManager.Import, WindowsIdentity.GetCurrent());
                ctrlImport.PostbackOnError = false;

                ltlScript.Text = ScriptHelper.GetScript("StartImportStateTimer();");
                wzdImport.ActiveStepIndex++;
                break;

                // Import progress
            case 4:
                PreviousButton.Visible = false;

                CultureHelper.SetPreferredCulture(Culture);
                if (siteType.SelectTemplate)
                {
                    // Done
                    finishSite.Domain = Domain;
                    finishSite.SiteIsRunning = SiteIsRunning;
                    wzdImport.ActiveStepIndex = 7;
                }
                else
                {
                    if (ImportManager.Settings.IsWarning())
                    {
                        try
                        {
                            // Convert default culture
                            TreeProvider tree = new TreeProvider(CMSContext.CurrentUser);
                            tree.ChangeSiteDefaultCulture(SiteName, Culture, "en-US");

                            // Change root GUID
                            TreeNode root = DocumentHelper.GetDocument(SiteName, "/", Culture, false, "cms.root", null, null, 1, false, null, tree);
                            if (root != null)
                            {
                                root.NodeGUID = Guid.NewGuid();
                                DocumentHelper.UpdateDocument(root, tree);
                            }
                        }
                        catch (Exception ex)
                        {
                            EventLogProvider ev = new EventLogProvider();
                            ev.LogEvent("NewSiteWizard", "FINISH", ex);
                            lblError.Text = ex.Message;
                            e.Cancel = true;
                            return;
                        }
                    }
                    selectMaster.SiteName = SiteName;
                    selectMaster.ReloadData();
                }
                break;

                // Master template
            case 5:
                if (!selectMaster.ApplySettings())
                {
                    e.Cancel = true;
                    return;
                }

                siteStructure.SiteName = SiteName;
                break;

                // Define site structure
            case 6:
                finishSite.Domain = Domain;
                finishSite.SiteIsRunning = SiteIsRunning;
                break;

                // Other steps
            default:
                wzdImport.ActiveStepIndex = e.NextStepIndex;
                break;
        }
    }
    /// <summary>
    /// Reload data.
    /// </summary>
    public override void ReloadData(bool forceLoad)
    {
        if ((GraphImageWidth != 0) && (ComputedWidth == 0))
        {
            // Graph width is computed no need to create graph
            return;
        }

        this.Visible = true;

        // Indicaates whether exception was throw during data loading
        bool errorOccurred = false;
        ReportInfo ri = null;

        try
        {
            this.ReportTableName = this.Parameter;

            this.EnsureTableInfo();
            this.EnsureChildControls();

            //Test security
            if (TableInfo != null)
            {
                ri = ReportInfoProvider.GetReportInfo(TableInfo.TableReportID);
                if (ri != null)
                {
                    if (ri.ReportAccess != ReportAccessEnum.All)
                    {
                        if (!CMSContext.CurrentUser.IsAuthenticated())
                        {
                            this.Visible = false;
                            return;
                        }
                    }

                    //Set default parametrs directly if not set
                    if (this.ReportParameters == null)
                    {
                        FormInfo fi = new FormInfo(ri.ReportParameters);
                        // Get datarow with required columns
                        this.ReportParameters = fi.GetDataRow();
                        fi.LoadDefaultValues(this.ReportParameters);
                    }

                    ApplyTimeParameters();
                }
            }

            // Only use base parameters in case of stored procedure
            if (this.QueryIsStoredProcedure)
            {
                this.AllParameters = SpecialFunctions.ConvertDataRowToParams(this.ReportParameters, null);
            }

            // Load data
            DataSet ds = this.LoadData();

            // If no data load, set empty dataset
            if (DataHelper.DataSourceIsEmpty(ds))
            {
                string noRecordText = ValidationHelper.GetString(TableInfo.TableSettings["QueryNoRecordText"], String.Empty);
                if (noRecordText != String.Empty)
                {
                    GridViewObject.Visible = false;
                    lblInfo.Text = noRecordText;
                    lblInfo.Visible = true;
                    return;
                }

                this.Visible = false;
            }
            else
            {
                GridViewObject.Visible = true;
                // Resolve macros in column names
                int i = 0;
                foreach (DataColumn dc in ds.Tables[0].Columns)
                {
                    if (dc.ColumnName == "Column" + ((int)(i + 1)).ToString())
                    {
                        dc.ColumnName = ResolveMacros(ds.Tables[0].Rows[0][i].ToString());
                    }
                    else
                    {
                        dc.ColumnName = ResolveMacros(dc.ColumnName);
                    }
                    i++;
                }

                // Resolve macros in dataset
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    foreach (DataColumn dc in ds.Tables[0].Columns)
                    {
                        if (dc.DataType.FullName.ToLower() == "system.string")
                        {
                            dr[dc.ColumnName] = ResolveMacros(ValidationHelper.GetString(dr[dc.ColumnName], ""));
                        }
                    }
                }
            }

            ApplyStyles();

            // Databind to gridview control
            GridViewObject.DataSource = ds;
            this.EnsurePageIndex();
            GridViewObject.DataBind();

            if ((TableFirstColumnWidth != Unit.Empty) && (GridViewObject.Rows.Count > 0))
            {
                GridViewObject.Rows[0].Cells[0].Width = TableFirstColumnWidth;
            }

        }
        catch (Exception ex)
        {
            // Display error message, if data load fail
            lblError.Visible = true;
            lblError.Text = "[ReportTable.ascx] Error loading the data: " + ex.Message;
            EventLogProvider ev = new EventLogProvider();
            ev.LogEvent("Report table", "E", ex);
            errorOccurred = true;
        }

        // Export data
        if ((ri != null) && (!errorOccurred))
        {
            ProcessExport(ValidationHelper.GetCodeName(ri.ReportDisplayName));
        }
    }
    protected void btnClearCache_Click(object sender, EventArgs e)
    {
        if (StopProcessing)
        {
            return;
        }

        // Clear the cache
        CacheHelper.ClearCache(null, true);
        Functions.ClearHashtables();

        // Drop the routes
        CMSMvcHandler.DropAllRoutes();

        // Disposes all zip files
        ZipStorageProvider.DisposeAll();

        // Collect the memory
        GC.Collect();
        GC.WaitForPendingFinalizers();

        // Log event
        EventLogProvider eventLog = new EventLogProvider();
        eventLog.LogEvent(EventLogProvider.EVENT_TYPE_INFORMATION, DateTime.Now, "System", "CLEARCACHE", null, GetString("Administration-System.ClearCacheSuccess"));

        ShowConfirmation(GetString("Administration-System.ClearCacheSuccess"));

        LoadData();
    }