protected void Page_Load(object sender, EventArgs e)
    {
        mNewsletter = EditedObject as NewsletterInfo;
        if (mNewsletter == null)
        {
            pnlAvailability.Visible = false;
            return;
        }

        if (!mNewsletter.CheckPermissions(PermissionsEnum.Read, CurrentSiteName, CurrentUser))
        {
            RedirectToAccessDenied(mNewsletter.TypeInfo.ModuleName, "ManageTemplates");
        }

        if (!RequestHelper.IsPostBack())
        {
            LoadBindings();
        }

        // Show all issue templates from current site
        var where = new WhereCondition()
            .WhereEquals("TemplateType", EmailTemplateType.Issue)
            .WhereEquals("TemplateSiteID", mNewsletter.NewsletterSiteID)
            .WhereNotEquals("TemplateID", mNewsletter.NewsletterTemplateID);
        usTemplates.WhereCondition = where.ToString(expand: true);
        usTemplates.OnSelectionChanged += usTemplates_OnSelectionChanged;
    }
示例#2
0
    /// <summary>
    /// Gets WHERE condition to retrieve available sites according specified type.
    /// </summary>
    private string GetSitesWhere()
    {
        WhereCondition condition = new WhereCondition().WhereEquals("SiteStatus", SiteStatusEnum.Running.ToStringRepresentation());

        // If not global admin display only related sites
        if (!MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin))
        {
            condition.WhereIn("SiteID", new IDQuery <UserSiteInfo>(UserSiteInfo.TYPEINFO.SiteIDColumn)
                              .WhereEquals("UserID", MembershipContext.AuthenticatedUser.UserID));
        }

        switch (Sites)
        {
        case AvailableSitesEnum.OnlySingleSite:
            if (!string.IsNullOrEmpty(SelectedSiteName))
            {
                condition.WhereEquals("SiteName", SelectedSiteName);
            }
            break;

        case AvailableSitesEnum.OnlyCurrentSite:
            condition.WhereEquals("SiteName", SiteContext.CurrentSiteName);
            break;
        }

        return(condition.ToString(true));
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        PageTitle.TitleText = GetString("newsletter_issue_openedby.title");

        var issue = (IssueInfo)EditedObject;

        issueID = issue.IssueID;

        // Do not show page if reports are not available
        if (issue.IssueSentEmails <= 0)
        {
            ShowInformation(GetString("newsletter.issue.overviewnotsentyet"));
            UniGrid.Visible     = false;
            fltOpenedBy.Visible = false;
            return;
        }

        // Prevent accessing issues from sites other than current site
        if (issue.IssueSiteID != SiteContext.CurrentSiteID)
        {
            RedirectToResourceNotAvailableOnSite("Issue with ID " + issueID);
        }

        // Issue is the main A/B test issue
        isMainABTestIssue = issue.IssueIsABTest && !issue.IssueIsVariant;
        if (isMainABTestIssue)
        {
            // Initialize variant selector in the filter
            fltOpenedBy.IssueId = issue.IssueID;

            if (RequestHelper.IsPostBack())
            {
                // Get issue ID from variant selector
                issueID = fltOpenedBy.IssueId;
            }

            // Reset ID for main issue, grid will show data from main and winner variant issues
            if (issueID == issue.IssueID)
            {
                issueID = 0;
            }
        }

        var whereCondition = new WhereCondition(fltOpenedBy.WhereCondition);

        if (issueID > 0)
        {
            whereCondition.And(w => w.WhereEquals("OpenedEmailIssueID", issueID));
        }

        UniGrid.WhereCondition        = whereCondition.ToString(true);
        UniGrid.Pager.DefaultPageSize = PAGESIZE;
        UniGrid.Pager.ShowPageSize    = false;
        UniGrid.FilterLimit           = 1;
        UniGrid.OnExternalDataBound  += UniGrid_OnExternalDataBound;
        UniGrid.OnBeforeDataReload   += UniGrid_OnBeforeDataReload;

        UniGrid.ZeroRowsText = GetString("newsletter.issue.noopenmails");
    }
    private string CreateWhereCondition(string originalWhere)
    {
        var where = new WhereCondition();
        where.Where(new WhereCondition(originalWhere)
        {
            WhereIsComplex = true
        });

        // Add where conditions from filters
        where.Where(new WhereCondition(nameFilter.WhereCondition)
        {
            WhereIsComplex = true
        });

        string objType = ValidationHelper.GetString(objTypeSelector.Value, "");

        if (!String.IsNullOrEmpty(objType))
        {
#pragma warning disable BH2000 // Method 'WhereLike()' or 'WhereNotLike()' should not be used used.
            where.WhereLike("VersionObjectType", objType);
#pragma warning restore BH2000 // Method 'WhereLike()' or 'WhereNotLike()' should not be used used.
        }

        int userId = ValidationHelper.GetInteger(userSelector.Value, 0);
        if (userId > 0)
        {
            where.WhereEquals("VersionDeletedByUserID", userId);
        }

        // Get older than value
        if (DisplayDateTimeFilter)
        {
            DateTime olderThan     = DateTime.Now.Date.AddDays(1);
            int      dateTimeValue = ValidationHelper.GetInteger(txtFilter.Text, 0);

            switch (drpFilter.SelectedIndex)
            {
            case 0:
                olderThan = olderThan.AddDays(-dateTimeValue);
                break;

            case 1:
                olderThan = olderThan.AddDays(-dateTimeValue * 7);
                break;

            case 2:
                olderThan = olderThan.AddMonths(-dateTimeValue);
                break;

            case 3:
                olderThan = olderThan.AddYears(-dateTimeValue);
                break;
            }

            where.WhereLessOrEquals("VersionDeletedWhen", olderThan);
        }

        return(where.ToString(true));
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        PageTitle.TitleText = GetString("newsletter_issue_openedby.title");

        var issue = (IssueInfo)EditedObject;
        issueID = issue.IssueID;

        // Do not show page if reports are not available
        if (issue.IssueSentEmails <= 0)
        {
            ShowInformation(GetString("newsletter.issue.overviewnotsentyet"));
            UniGrid.Visible = false;
            fltOpenedBy.Visible = false;
            return;
        }

        // Prevent accessing issues from sites other than current site
        if (issue.IssueSiteID != SiteContext.CurrentSiteID)
        {
            RedirectToResourceNotAvailableOnSite("Issue with ID " + issueID);
        }

        // Issue is the main A/B test issue
        isMainABTestIssue = issue.IssueIsABTest && !issue.IssueIsVariant;
        if (isMainABTestIssue)
        {
            // Initialize variant selector in the filter
            fltOpenedBy.IssueId = issue.IssueID;

            if (RequestHelper.IsPostBack())
            {
                // Get issue ID from variant selector
                issueID = fltOpenedBy.IssueId;
            }

            // Reset ID for main issue, grid will show data from main and winner variant issues
            if (issueID == issue.IssueID)
            {
                issueID = 0;
            }
        }

        var whereCondition = new WhereCondition(fltOpenedBy.WhereCondition);

        if (issueID > 0)
        {
            whereCondition.And(w => w.WhereEquals("OpenedEmailIssueID", issueID));
        }

        UniGrid.WhereCondition = whereCondition.ToString(true);
        UniGrid.Pager.DefaultPageSize = PAGESIZE;
        UniGrid.Pager.ShowPageSize = false;
        UniGrid.FilterLimit = 1;
        UniGrid.OnExternalDataBound += UniGrid_OnExternalDataBound;
        UniGrid.OnBeforeDataReload += UniGrid_OnBeforeDataReload;

        UniGrid.ZeroRowsText = GetString("newsletter.issue.noopenmails");
    }
示例#6
0
    /// <summary>
    /// Mass action 'ok' button clicked.
    /// </summary>
    protected void btnOk_Click(object sender, EventArgs e)
    {
        CheckModifyPermissions();

        Action action = (Action)ValidationHelper.GetInteger(drpAction.SelectedItem.Value, 0);
        What   what   = (What)ValidationHelper.GetInteger(drpWhat.SelectedItem.Value, 0);

        var where = new WhereCondition()
                    .WhereEquals("ContactGroupMemberContactGroupID", cgi.ContactGroupID)
                    // Set constraint for account relations only
                    .WhereEquals("ContactGroupMemberType", 1);

        switch (what)
        {
        // All items
        case What.All:
            var accountIds = GetFilteredAccountsFromView().Column("AccountID");

            where.WhereIn("ContactGroupMemberRelatedID", accountIds);
            break;

        // Selected items
        case What.Selected:
            // Convert array to integer values to make sure no sql injection is possible (via string values)
            where.WhereIn("ContactGroupMemberRelatedID", gridElem.SelectedItems);
            break;

        default:
            return;
        }

        switch (action)
        {
        // Action 'Remove'
        case Action.Remove:
            // Delete the relations between contact group and accounts
            ContactGroupMemberInfoProvider.DeleteContactGroupMembers(where.ToString(true), cgi.ContactGroupID, true, true);
            // Show result message
            if (what == What.Selected)
            {
                ShowConfirmation(GetString("om.account.massaction.removed"));
            }
            else
            {
                ShowConfirmation(GetString("om.account.massaction.removedall"));
            }
            break;

        default:
            return;
        }

        // Reload unigrid
        gridElem.ResetSelection();
        gridElem.ReloadData();
        pnlUpdate.Update();
    }
    /// <summary>
    /// Creates filter condition and raise filter change event.
    /// </summary>
    private void FilterData()
    {
        WhereCondition where = new WhereCondition();
        int    paging = 0;
        string order  = string.Empty;

        // Build where condition according to drop-downs settings
        if (statusSelector.SelectedID > 0)
        {
            where.WhereEquals("SKUPublicStatusID", statusSelector.SelectedID);
        }

        if (manufacturerSelector.SelectedID > 0)
        {
            where.WhereEquals("SKUManufacturerID", manufacturerSelector.SelectedID);
        }

        if (chkStock.Checked)
        {
            where.Where(w => w.WhereNull("SKUTrackInventory")
                        .Or()
                        .WhereGreaterThan("SKUAvailableItems", 0)
                        .Or()
                        .WhereIn("SKUID", new IDQuery <SKUInfo>("SKUParentSKUID").WhereGreaterThan("SKUAvailableItems", 0)));
        }

        if (!string.IsNullOrEmpty(txtSearch.Text))
        {
            where.WhereContains("SKUName", txtSearch.Text);
        }

        // Process drpSort drop-down
        if (ValidationHelper.GetInteger(drpPaging.SelectedValue, 0) > 0)
        {
            paging = ValidationHelper.GetInteger(drpPaging.SelectedValue, 0);
        }

        if (!string.IsNullOrEmpty(drpSort.SelectedValue))
        {
            order = drpSort.SelectedValue;
        }

        // Set where condition
        WhereCondition = where.ToString(true);

        if (paging > 0)
        {
            // Set paging
            PageSize = paging;
        }

        if (!string.IsNullOrEmpty(order))
        {
            // Set sorting
            OrderBy = GetOrderBy(order);
        }
    }
    /// <summary>
    /// Initializes the selector.
    /// </summary>
    public void InitSelector()
    {
        uniSelector.IsLiveSite = IsLiveSite;

        // Set resource prefix if specified
        if (ResourcePrefix != null)
        {
            uniSelector.ResourcePrefix = ResourcePrefix;
        }

        // Initialize selector for on-line marketing
        if (ValidationHelper.GetString(GetValue("mode"), "").ToLowerCSafe() == "onlinemarketing")
        {
            UniSelector.SelectionMode    = SelectionModeEnum.MultipleButton;
            UniSelector.OnItemsSelected += UniSelector_OnItemsSelected;
            UniSelector.ReturnColumnName = "CustomerID";
            IsLiveSite = false;
            SiteID     = ValidationHelper.GetInteger(GetValue("SiteID"), 0);
            UniSelector.ResourcePrefix = "om.customerselector";
        }

        var where = new WhereCondition();
        // Add registered customers
        if (DisplayRegisteredCustomers)
        {
            where.WhereIn("CustomerUserID", new IDQuery <UserSiteInfo>("UserID").WhereEquals("SiteID", SiteID));
        }

        // Add anonymous customers
        if (DisplayAnonymousCustomers)
        {
            where.Or().Where(w => w.WhereEquals("CustomerSiteID", SiteID).And().WhereNull("CustomerUserID"));
        }

        where = new WhereCondition(where);

        // Filter out only enabled items
        if (DisplayOnlyEnabled)
        {
            where.WhereTrue("CustomerEnabled");
        }

        // Add items which have to be on the list
        if (!string.IsNullOrEmpty(AdditionalItems))
        {
            where.Or().WhereIn("CustomerID", AdditionalItems.Split(','));
        }

        // Selected value must be on the list
        if (CustomerID > 0)
        {
            where.Or().WhereEquals("CustomerID", CustomerID);
        }

        uniSelector.WhereCondition = where.ToString(true);
    }
示例#9
0
 protected void gridElem_OnBeforeDataReload()
 {
     // Filter records by tag group ID
     var where = new WhereCondition().WhereEquals("TagGroupID", groupId);
     if (!String.IsNullOrEmpty(gridElem.CompleteWhereCondition))
     {
         where.Where(gridElem.CompleteWhereCondition);
     }
     gridElem.WhereCondition = where.ToString(true);
 }
示例#10
0
        /// <summary>
        ///     Removes all previously logged data related to the Dancing Goat default A/B test and Campaign.
        /// </summary>
        private void ClearStatisticsData()
        {
            var whereCondition = new WhereCondition().WhereContains("StatisticsCode", AbTest.ABTestName).Or()
                                 .WhereEquals("StatisticsObjectName", Campaign.CampaignUTMCode).Or()
                                 .WhereEquals("StatisticsObjectName", Conversion.ConversionName);

            StatisticsInfoProvider.RemoveAnalyticsData(DateTimeHelper.ZERO_TIME, DateTimeHelper.ZERO_TIME,
                                                       _mSite.SiteID,
                                                       whereCondition.ToString(true));
        }
    /// <summary>
    /// Reloads grid.
    /// </summary>
    public void ReloadData()
    {
        WhereCondition where = new WhereCondition();

        if (!String.IsNullOrEmpty(drpCustom.SelectedValue))
        {
            string columnName = Views ? "TABLE_NAME" : "ROUTINE_NAME";
            string prefix     = Views ? "View_Custom_" : "Proc_Custom_";

            switch (drpCustom.SelectedValue)
            {
            case "1":
                where.WhereStartsWith(columnName, prefix);
                break;

            case "0":
                where.WhereNotStartsWith(columnName, prefix);
                break;
            }
        }

        // Filter system views
        if (Views)
        {
            where.WhereNotEquals("TABLE_SCHEMA", "sys");
        }

        where.Where(fltViews.GetCondition());

        TableManager tm = new TableManager(null);

        if (Views)
        {
            gridViews.DataSource = tm.GetList(where.ToString(true), "TABLE_NAME, TABLE_SCHEMA, IsCustom=CASE SUBSTRING(TABLE_NAME,0,13) WHEN 'View_Custom_' THEN 1 ELSE 0 END", true);
        }
        else
        {
            where.WhereEquals("ROUTINE_TYPE", "PROCEDURE");
            gridViews.DataSource = tm.GetList(where.ToString(true), "ROUTINE_NAME, ROUTINE_SCHEMA, IsCustom=CASE SUBSTRING(ROUTINE_NAME,0,13) WHEN 'Proc_Custom_' THEN 1 ELSE 0 END", false);
        }
    }
示例#12
0
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        PageTitle.TitleText = GetString("newsletter_issue_openedby.title");

        issueID = Issue.IssueID;

        // Do not show page if reports are not available
        if (Issue.IssueSentEmails <= 0)
        {
            ShowInformation(GetString("newsletter.issue.overviewnotsentyet"));
            UniGrid.Visible     = false;
            fltOpenedBy.Visible = false;
            return;
        }

        // Issue is the main A/B test issue
        isMainABTestIssue = Issue.IssueIsABTest && !Issue.IssueIsVariant;
        if (isMainABTestIssue)
        {
            // Initialize variant selector in the filter
            fltOpenedBy.IssueId = Issue.IssueID;

            if (RequestHelper.IsPostBack())
            {
                // Get issue ID from variant selector
                issueID = fltOpenedBy.IssueId;
            }

            // Reset ID for main issue, grid will show data from main and winner variant issues
            if (issueID == Issue.IssueID)
            {
                issueID = 0;
            }
        }

        var whereCondition = new WhereCondition(fltOpenedBy.WhereCondition);

        if (issueID > 0)
        {
            whereCondition.And(w => w.WhereEquals("OpenedEmailIssueID", issueID));
        }

        UniGrid.WhereCondition        = whereCondition.ToString(true);
        UniGrid.Pager.DefaultPageSize = PAGESIZE;
        UniGrid.Pager.ShowPageSize    = false;
        UniGrid.FilterLimit           = 1;
        UniGrid.OnExternalDataBound  += UniGrid_OnExternalDataBound;
        UniGrid.OnBeforeDataReload   += UniGrid_OnBeforeDataReload;

        UniGrid.ZeroRowsText = GetString("newsletter.issue.noopenmails");
    }
    /// <summary>
    /// Creates where condition according to values selected in filter.
    /// </summary>
    public override string GetWhereCondition()
    {
        var where = new WhereCondition();
        var oper = drpLanguage.SelectedValue.ToEnum <QueryOperator>();
        var val  = ValidationHelper.GetString(cultureElem.Value, null);

        if (String.IsNullOrEmpty(val))
        {
            val = "##ANY##";
        }

        if (val != "##ANY##")
        {
            // Create base query
            var tree  = new TreeProvider();
            var query = tree.SelectNodes()
                        .All()
                        .Column("NodeID");

            switch (val)
            {
            case "##ALL##":
            {
                var cultureCount = SiteCultures.Tables[0].Rows.Count;
                query.GroupBy("NodeID").Having(string.Format("(COUNT(NodeID) {0} {1})", oper.ToStringRepresentation(), cultureCount));

                where.WhereIn("NodeID", query);
            }
            break;

            default:
            {
                query.WhereEquals("DocumentCulture", val);

                if (oper == QueryOperator.NotEquals)
                {
                    where.WhereNotIn("NodeID", query);
                }
                else
                {
                    where.WhereIn("NodeID", query);
                }
            }
            break;
            }
        }
        else if (oper == QueryOperator.NotEquals)
        {
            where.NoResults();
        }

        return(where.ToString(true));
    }
示例#14
0
    /// <summary>
    /// Sets WHERE condition.
    /// </summary>
    private string GetWhere()
    {
        var where = new WhereCondition();
        var oper = EnumStringRepresentationExtensions.ToEnum <QueryOperator>(QueryHelper.GetString("searchlanguage", null));
        var val  = QueryHelper.GetString("searchculture", "##ANY##");

        if (String.IsNullOrEmpty(val))
        {
            val = "##ANY##";
        }

        if (val != "##ANY##")
        {
            // Create base query
            var tree  = new TreeProvider();
            var query = tree.SelectNodes()
                        .All()
                        .Column("NodeID");

            switch (val)
            {
            case "##ALL##":
            {
                query.GroupBy("NodeID").Having(string.Format("(COUNT(NodeID) {0} {1})", oper.ToStringRepresentation(), SiteCulturesCount));

                where.WhereIn("NodeID", query);
            }
            break;

            default:
            {
                query.WhereEquals("DocumentCulture", val);

                if (oper == QueryOperator.NotEquals)
                {
                    where.WhereNotIn("NodeID", query);
                }
                else
                {
                    where.WhereIn("NodeID", query);
                }
            }
            break;
            }
        }
        else if (oper == QueryOperator.NotEquals)
        {
            where.NoResults();
        }

        return(where.ToString(true));
    }
示例#15
0
    /// <summary>
    /// Add site default currency according selector settings.
    /// </summary>
    /// <param name="whereCondition">Where condition.</param>
    /// <returns></returns>
    protected override string AppendInclusiveWhere(string whereCondition)
    {
        // Prepare where condition
        var where = new WhereCondition(whereCondition);

        // Add site main currency when required
        if (AddSiteDefaultCurrency && (MainCurrencyID > 0))
        {
            where.Or().WhereEquals("CurrencyID", MainCurrencyID);
        }

        // Append additional items
        return(base.AppendInclusiveWhere(where.ToString(true)));
    }
示例#16
0
    /// <summary>
    /// Exclude main currency and currencies without exchange rate according selector settings.
    /// </summary>
    /// <param name="whereCondition">Where condition.</param>
    protected override string AppendExclusiveWhere(string whereCondition)
    {
        // Prepare where condition
        var where = new WhereCondition(whereCondition);

        // Exclude site main currency when required
        if (ExcludeSiteDefaultCurrency && (MainCurrencyID > 0))
        {
            where.WhereNotEquals("CurrencyID", MainCurrencyID);
        }

        // Restrict disabled or site not related currencies
        return(base.AppendExclusiveWhere(where.ToString(true)));
    }
示例#17
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!CheckPermissions("cms.scoring", "Read"))
        {
            return;
        }

        var whereCondition = new WhereCondition(gridElem.WhereCondition);

        gridElem.OnExternalDataBound += gridElem_OnExternalDataBound;
        gridElem.WhereCondition       = whereCondition.ToString(true);

        gridElem.ZeroRowsText  = GetString("om.score.notfound");
        gridElem.EditActionUrl = URLHelper.AppendQuery(UIContextHelper.GetElementUrl("CMS.Scoring", "ScoringProperties"), "displayTitle=0&objectid={0}");
    }
示例#18
0
        public override string ToPlainQuery()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendFormat("DELETE {0} FROM {1}{2}", Table, FromTableOrQuery(), FromQuery == null ? "" : $" AS {FromQuery.Item2}");

            sb.Append(JoinString);

            if (WhereCondition != null)
            {
                sb.AppendFormat(" WHERE {0}", WhereCondition.ToString());
            }

            return(sb.ToString().Trim());
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!CheckPermissions("cms.scoring", "Read"))
        {
            return;
        }

        var whereCondition = new WhereCondition(gridElem.WhereCondition)
            .WhereEquals("ScoreSiteID", SiteContext.CurrentSiteID);

        gridElem.OnExternalDataBound += gridElem_OnExternalDataBound;
        gridElem.WhereCondition = whereCondition.ToString(true);

        gridElem.ZeroRowsText = GetString("om.score.notfound");
        gridElem.EditActionUrl = URLHelper.AppendQuery(UIContextHelper.GetElementUrl("CMS.Scoring", "ScoringProperties"), "displayTitle=0&objectid={0}");
    }
示例#20
0
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        currentSite = SiteContext.CurrentSite;
        currentUser = MembershipContext.AuthenticatedUser;

        // Check 'Manage' permission
        var manageBlogs = currentUser.IsAuthorizedPerResource("cms.blog", "Manage");

        // There is no sense to display (ALL) in blogs DDL when
        // user does not have manage blogs permission
        if (!manageBlogs)
        {
            DisplayAllRecord = false;
        }

        var condition = new WhereCondition().WhereEquals("NodeSiteID", currentSite.SiteID);

        if (!currentUser.IsGlobalAdministrator && !manageBlogs)
        {
            condition.Where(BlogHelper.GetBlogsWhere(currentUser.UserID, currentUser.UserName, null));
        }

        // Culture priority column to handle duplicities
        var culturePriority = new RowNumberColumn("CulturePriority", "BlogID");

        culturePriority.PartitionBy = "NodeID";

        // Init Blog selector
        uniSelector.DisplayNameFormat    = "{%BlogName%}";
        uniSelector.SelectionMode        = SelectionModeEnum.SingleDropDownList;
        uniSelector.WhereCondition       = condition.ToString(true);
        uniSelector.ReturnColumnName     = "BlogID";
        uniSelector.AdditionalColumns    = culturePriority.ToString();
        uniSelector.ObjectType           = "cms.blog";
        uniSelector.ResourcePrefix       = "unisiteselector";
        uniSelector.AllowEmpty           = false;
        uniSelector.AllowAll             = false;
        uniSelector.OnAfterRetrieveData += uniSelector_OnAfterRetrieveData;

        // Preselect my blogs
        if (IsInMydesk && !RequestHelper.IsPostBack())
        {
            uniSelector.Value = "##MYBLOGS##";
        }
    }
示例#21
0
        public override string ToPlainQuery()
        {
            StringBuilder sb = new StringBuilder();

            if (FromTableOrQuery() == null)
            {
                sb.AppendFormat("CREATE TABLE {0} (", Table);

                foreach (var column in ListColumns)
                {
                    sb.AppendFormat("{0} {1}", column.Item1, String.Format(column.Item2.GetStringValue(), column.Item3));

                    Tuple <int, int> idParam;

                    if (IdentityColumns.TryGetValue(column.Item1, out idParam))
                    {
                        sb.AppendFormat(" IDENTITY({0}, {1})", idParam.Item1, idParam.Item2);
                    }

                    sb.Append(", ");
                }

                if (ListConstraints.Count > 0)
                {
                    sb.Append($" {GetConstraintString()}");
                }

                sb.Append(");");
            }
            else
            {
                sb.AppendFormat("SELECT * INTO {0} FROM {1}{2}",
                                Table,
                                FromTableOrQuery(),
                                FromQuery == null ? "" : $" AS {FromQuery.Item2}");

                sb.Append(JoinString);

                if (WhereCondition != null)
                {
                    sb.AppendFormat(" WHERE {0}", WhereCondition.ToString());
                }
            }

            return(sb.ToString().Trim());
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        var whereCondition = new WhereCondition(gridElem.WhereCondition);

        if (ContactID != null)
        {
            whereCondition.WhereEquals("ContactID", ContactID);
        }
        if (SiteID != null)
        {
            whereCondition.WhereEquals("ScoreSiteID", SiteID);
        }

        gridElem.WhereCondition = whereCondition.ToString(true);

        gridElem.OnExternalDataBound += gridElem_OnExternalDataBound;
    }
    /// <summary>
    /// Sets the where condition for filter on custom table filtering.
    /// </summary>
    public override string GetWhereCondition()
    {
        List <string> SelectedObjectRefIDs = GetSelectedObjects();

        if (SelectedObjectRefIDs.Count > 0)
        {
            var query = new DataQuery(JoinTableName + ".selectall").Column(JoinTableLeftFieldName).WhereIn(JoinTableRightFieldName, SelectedObjectRefIDs).Distinct();
            WhereCondition where = new WhereCondition();

            where.WhereIn(JoinTableLeftFieldName, query);
            return(where.ToString());
        }
        else
        {
            return(base.GetWhereCondition());
        }
    }
示例#24
0
    protected void Page_Load(object sender, EventArgs e)
    {
        var whereCondition = new WhereCondition(gridElem.WhereCondition);

        if (ContactID != null)
        {
            whereCondition.WhereEquals("ContactID", ContactID);
        }
        if (SiteID != null)
        {
            whereCondition.WhereEquals("ScoreSiteID", SiteID);
        }

        gridElem.WhereCondition = whereCondition.ToString(true);

        gridElem.OnExternalDataBound += gridElem_OnExternalDataBound;
    }
示例#25
0
    /// <summary>
    /// Reloads control.
    /// </summary>
    public void ReloadData()
    {
        var where            = new WhereCondition(WhereCondition);
        uniselector.AllowAll = AllowAllItem;

        // Do not add condition to empty condition which allows everything
        if (!String.IsNullOrEmpty(where.WhereCondition))
        {
            string status = ValidationHelper.GetString(Value, "");
            if (!String.IsNullOrEmpty(status))
            {
                where.Or().WhereEquals(uniselector.ReturnColumnName, status);
            }
        }

        uniselector.WhereCondition = where.ToString(true);
        uniselector.Reload(true);
    }
    /// <summary>
    /// Generates complete filter where condition.
    /// </summary>
    private string GenerateWhereCondition()
    {
        var whereCondition = new WhereCondition();

        whereCondition = whereCondition
                         .Where(fltFormerUrlPath.GetCondition());

        // Create WHERE condition for advanced filter
        if (IsAdvancedMode)
        {
            whereCondition = whereCondition
                             .Where(fltModified.GetCondition())
                             .Where(fltPageName.GetCondition())
                             .Where(fltType.GetCondition());
        }

        return(whereCondition.ToString(true));
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        // Check hash
        if (!QueryHelper.ValidateHash("hash"))
        {
            URLHelper.Redirect(AdministrationUrlHelper.GetErrorPageUrl("dialogs.badhashtitle", "dialogs.badhashtext", true));
        }
        else
        {
            string element = QueryHelper.GetString("tasktype", null);

            // Check UI permissions for Staging
            var user = MembershipContext.AuthenticatedUser;
            if (!user.IsAuthorizedPerUIElement("cms.staging", element))
            {
                RedirectToUIElementAccessDenied("cms.staging", element);
            }

            // Check 'Manage XXX tasks' permission
            if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("cms.staging", "Manage" + element + "Tasks"))
            {
                RedirectToAccessDenied("cms.staging", "Manage" + element + "Tasks");
            }

            // Register modal dialog scripts
            RegisterModalPageScripts();
            PageTitle.TitleText = GetString("Task.LogHeader");

            serverId = QueryHelper.GetInteger("serverid", 0);
            int taskId = QueryHelper.GetInteger("taskid", 0);

            var condition = new WhereCondition().WhereEquals("SynchronizationTaskID", taskId);

            if (serverId > 0)
            {
                condition.WhereEquals("SynchronizationServerID", serverId);
            }

            gridLog.WhereCondition      = condition.ToString(true);
            gridLog.ZeroRowsText        = GetString("Task.LogNoEvents");
            gridLog.OnBeforeDataReload += gridLog_OnBeforeDataReload;
        }
    }
示例#28
0
    /// <summary>
    /// Initializes the selector.
    /// </summary>
    public void InitSelector()
    {
        uniSelector.IsLiveSite = IsLiveSite;
        uniSelector.AdditionalSearchColumns = "CustomerFirstName,CustomerCompany,CustomerEmail";

        // Set resource prefix if specified
        if (!string.IsNullOrEmpty(ResourcePrefix))
        {
            uniSelector.ResourcePrefix = ResourcePrefix;
        }

        var where = new WhereCondition();

        // Do not filter customer by UserID if both Anonymous and Registered are requested
        if (!DisplayRegisteredCustomers || !DisplayAnonymousCustomers)
        {
            // Add registered customers
            if (DisplayRegisteredCustomers)
            {
                where.WhereNotNull("CustomerUserID");
            }

            // Add anonymous customers
            if (DisplayAnonymousCustomers)
            {
                where.WhereNull("CustomerUserID");
            }
        }

        // Add items which have to be on the list
        if (!string.IsNullOrEmpty(AdditionalItems) && !where.WhereIsEmpty)
        {
            where.Or().WhereIn("CustomerID", AdditionalItems.Split(','));
        }

        // Selected value must be on the list
        if ((CustomerID > 0) && !where.WhereIsEmpty)
        {
            where.Or().WhereEquals("CustomerID", CustomerID);
        }

        uniSelector.WhereCondition = where.ToString(true);
    }
    /// <summary>
    /// Setups source language drop down list control.
    /// </summary>
    /// <param name="targetCultures">List of target cultures which should not be in te source selector</param>
    private void SetupSourceLanguageDropDownWhereCondition(HashSet <string> targetCultures)
    {
        var condition = new WhereCondition();

        if (targetCultures.Count > 0)
        {
            condition.WhereNotIn("CultureCode", targetCultures.ToList());
        }

        if (NodeID > 0)
        {
            // Get source culture list from original node if current node is linked
            var node         = TreeProvider.SelectSingleNode(NodeID, TreeProvider.ALL_CULTURES, true, false);
            var sourceNodeID = node.OriginalNodeID;

            condition.WhereIn("CultureCode", new IDQuery("cms.document", "DocumentCulture").WhereEquals("DocumentNodeID", sourceNodeID));
        }

        selectCultureElem.AdditionalWhereCondition = condition.ToString(true);
    }
示例#30
0
        public override string ToPlainQuery()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendFormat("UPDATE {0} SET {1}", UpdateTable, UpdateColumns.ToString());

            if (FromTableOrQuery() != null)
            {
                sb.AppendFormat(" FROM {0}{1}", FromTableOrQuery(), FromQuery == null ? "" : $" AS {FromQuery.Item2}");
            }

            sb.Append(JoinString);

            if (WhereCondition != null)
            {
                sb.AppendFormat(" WHERE {0}", WhereCondition.ToString());
            }

            return(sb.ToString().Trim());
        }
示例#31
0
    /// <summary>
    /// Merges given where condition with additional settings.
    /// </summary>
    /// <param name="where">Original where condition</param>
    /// <returns>New where condition</returns>
    private string GetWhereCondition(string where)
    {
        // Add recycle bin condition
        var condition = new WhereCondition(where)
                        .WhereNotNull("VersionDeletedWhen");

        // Filter by object name
        if (!string.IsNullOrEmpty(ObjectDisplayName))
        {
            condition.WhereContains("VersionObjectDisplayName", ObjectDisplayName);
        }

        // Filter by object type
        if (!String.IsNullOrEmpty(ObjectType))
        {
            condition.WhereContains("VersionObjectType", ObjectType);
        }

        return(condition.ToString(true));
    }
示例#32
0
    /// <summary>
    /// Builds a SQL condition for filtering the discount list, and returns it.
    /// </summary>
    /// <returns>A SQL condition for filtering the discount list.</returns>
    private string GetFilterWhereCondition()
    {
        string discountStatus = drpStatus.SelectedValue;
        var    condition      = new WhereCondition();


        /* Active discounts */
        if (discountStatus == "0")
        {
            condition.Where(GetActiveQuery());
        }
        /* Disabled discounts */
        else if (discountStatus == "1")
        {
            condition.WhereNot(GetEnabledDiscounts());
        }
        /* Finished discounts */
        else if (discountStatus == "2")
        {
            condition.Where(GetEnabledDiscounts())
            .WhereLessThan(GetColumn("DiscountValidTo"), DateTime.Now)
            .WhereNot(GetIncompleteDiscounts())
            .Or(GetDiscountsWithCouponsExceeded());
        }
        /* Scheduled discounts */
        else if (discountStatus == "3")
        {
            condition.Where(GetEnabledDiscounts())
            .WhereGreaterThan(GetColumn("DiscountValidFrom"), DateTime.Now)
            .WhereNot(GetIncompleteDiscounts());
        }
        /* Incomplete discounts */
        else if (discountStatus == "4")
        {
            condition.Where(GetEnabledDiscounts())
            .Where(GetIncompleteDiscounts());
        }

        return(condition.ToString(true));
    }
    /// <summary>
    /// Generates where condition.
    /// </summary>
    private string GenerateWhereCondition()
    {
        // Get older than value
        DateTime olderThan     = DateTime.Now.Date.AddDays(1);
        int      dateTimeValue = ValidationHelper.GetInteger(txtFilter.Text, 0);

        switch (drpFilter.SelectedIndex)
        {
        case 0:
            olderThan = olderThan.AddDays(-dateTimeValue);
            break;

        case 1:
            olderThan = olderThan.AddDays(-dateTimeValue * 7);
            break;

        case 2:
            olderThan = olderThan.AddMonths(-dateTimeValue);
            break;

        case 3:
            olderThan = olderThan.AddYears(-dateTimeValue);
            break;
        }

        var where = new WhereCondition().WhereLessOrEquals(SOURCE_MODIFIEDWHEN, olderThan);

        // Add where condition
        if (!string.IsNullOrEmpty(txtDocumentName.Text))
        {
            AddOutdatedWhereCondition(where, SOURCE_DOCUMENTNAME, drpDocumentName, txtDocumentName);
        }

        if (!string.IsNullOrEmpty(txtDocumentType.Text))
        {
            AddOutdatedWhereCondition(where, SOURCE_CLASSDISPLAYNAME, drpDocumentType, txtDocumentType);
        }

        return(where.ToString(true));
    }
示例#34
0
        public override string GetWhereCondition()
        {
            var whereCondition = new WhereCondition();
            var originalQuery  = fltCountry.WhereCondition;

            if (string.IsNullOrEmpty(originalQuery) || string.IsNullOrEmpty(CountryIDColumnName))
            {
                return(string.Empty);
            }

            var countryIDs = CountryInfo.Provider.Get()
                             .Where(originalQuery)
                             .AsMaterializedList("CountryID");

            whereCondition.WhereIn(CountryIDColumnName, countryIDs);
            if (fltCountry.FilterOperator == WhereBuilder.NOT_LIKE || fltCountry.FilterOperator == WhereBuilder.NOT_EQUAL)
            {
                whereCondition.Or().WhereNull(CountryIDColumnName);
            }

            return(whereCondition.ToString(true));
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        emailTemplateInfo = EditedObject as EmailTemplateInfo;

        if (emailTemplateInfo == null)
        {
            pnlAvailability.Visible = false;
            return;
        }

        // Initialize newsletter selector
        var where = new WhereCondition()
            .WhereEquals("NewsletterType", NewsletterType.TemplateBased)
            .WhereEquals("NewsletterSiteID", SiteContext.CurrentSiteID)
            .WhereNotEquals("NewsletterTemplateID", emailTemplateInfo.TemplateID);
        usNewsletters.WhereCondition = where.ToString(expand: true);

        if (!RequestHelper.IsPostBack())
        {
            LoadSiteBindings();
        }

        usNewsletters.OnSelectionChanged += usSites_OnSelectionChanged;
    }
    /// <summary>
    /// PageLoad event handler.
    /// </summary>
    protected void Page_Load(object sender, EventArgs e)
    {
        if (StopProcessing)
        {
            UniGridRelationship.StopProcessing = StopProcessing;
        }
        else
        {
            // Set tree node from Form object
            if ((TreeNode == null) && (Form != null) && (Form.EditedObject != null))
            {
                TreeNode node = Form.EditedObject as TreeNode;
                if ((node != null) && (Form.Mode == FormModeEnum.Update))
                {
                    TreeNode = node;
                }
                else
                {
                    ShowError(GetString("relationship.editdocumenterror"));
                }
            }

            if (TreeNode != null)
            {
                // Set unigrid
                UniGridRelationship.OnExternalDataBound += UniGridRelationship_OnExternalDataBound;
                UniGridRelationship.OnBeforeDataReload += UniGridRelationship_OnBeforeDataReload;
                UniGridRelationship.OnAction += UniGridRelationship_OnAction;
                UniGridRelationship.ZeroRowsText = GetString("relationship.nodatafound");
                UniGridRelationship.ShowActionsMenu = !IsLiveSite;

                int nodeId = TreeNode.NodeID;
                bool oneRelationshipName = !string.IsNullOrEmpty(RelationshipName);

                WhereCondition condition = new WhereCondition();

                if (oneRelationshipName)
                {
                    condition.WhereIn("RelationshipNameID", new IDQuery<RelationshipNameInfo>().WhereEquals("RelationshipName", RelationshipName));
                }

                // Switch sides is disabled
                if (!AllowSwitchSides)
                {
                    condition.WhereEquals(DefaultSide ? "RightNodeID" : "LeftNodeID", nodeId);
                }
                else
                {
                    condition.Where(new WhereCondition().WhereEquals("RightNodeID", nodeId).Or().WhereEquals("LeftNodeID", nodeId));
                }

                UniGridRelationship.WhereCondition = condition.ToString(true);

                if (ShowAddRelation)
                {
                    btnNewRelationship.OnClientClick = GetAddRelatedDocumentScript() + " return false;";
                }
                else
                {
                    pnlNewLink.Visible = false;
                }
            }
            else
            {
                UniGridRelationship.StopProcessing = true;
                UniGridRelationship.Visible = false;
                pnlNewLink.Visible = false;
            }

            if (RequestHelper.IsPostBack())
            {
                string target = Request[Page.postEventSourceID];
                if ((target == pnlUpdate.ClientID) || (target == pnlUpdate.UniqueID))
                {
                    string action = Request[Page.postEventArgumentID];

                    if (!string.IsNullOrEmpty(action))
                    {
                        switch (action.ToLowerCSafe())
                        {
                            // Insert from 'Select document' dialog
                            case "insertfromselectdocument":
                                SaveRelationship();
                                break;
                        }
                    }
                }
            }
            else
            {
                bool inserted = QueryHelper.GetBoolean("inserted", false);
                if (inserted)
                {
                    ShowConfirmation(GetString("relationship.wasadded"));
                }
            }
        }
    }
    protected void btnOk_Click(object sender, EventArgs e)
    {
        What what = (What)ValidationHelper.GetInteger(drpWhat.SelectedValue, 0);
        Action action = (Action)ValidationHelper.GetInteger(drpAction.SelectedValue, 0);

        // Check permissions for specified action
        CheckActionPermissions(action);

        // Set constraint for contact relations only
        var where = new WhereCondition()
            .WhereEquals("ContactGroupMemberType", 0)
            .WhereEquals("ContactGroupMemberContactGroupID", cgi.ContactGroupID);

        switch (what)
        {
            case What.All:
                var contactIds = ContactInfoProvider.GetContacts()
                    .Where(GetWhereCondition())
                    .Where(gridElem.WhereClause)
                    .AsIDQuery();
                where.WhereIn("ContactGroupMemberRelatedID", contactIds);
                break;

            case What.Selected:
                where.WhereIn("ContactGroupMemberRelatedID", gridElem.SelectedItems);
                break;
        }

        switch (action)
        {
            case Action.Remove:
                RemoveContacts(what, where.ToString(true));
                break;

            case Action.ChangeStatus:
                ChangeStatus(what);
                break;

            case Action.StartNewProcess:
                StartNewProcess(what, where.ToString(true));
                break;

            default:
                return;
        }

        // Reload unigrid
        gridElem.ResetSelection();
        gridElem.ReloadData();
        pnlUpdate.Update();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        // Register script files
        ScriptHelper.RegisterCMS(this);
        ScriptHelper.RegisterScriptFile(this, "~/CMSModules/Content/CMSDesk/Operation.js");

        if (!QueryHelper.ValidateHash("hash"))
        {
            pnlContent.Visible = false;
            ShowError(GetString("dialogs.badhashtext"));
            return;
        }

        // Setup page title text and image
        PageTitle.TitleText = GetString("Content.TranslateTitle");
        EnsureDocumentBreadcrumbs(PageBreadcrumbs, action: PageTitle.TitleText);

        if (IsDialog)
        {
            RegisterModalPageScripts();
            RegisterEscScript();

            plcInfo.Visible = false;

            pnlButtons.Visible = false;
        }

        if (!TranslationServiceHelper.IsTranslationAllowed(CurrentSiteName))
        {
            pnlContent.Visible = false;
            ShowError(GetString("translations.translationnotallowed"));
            return;
        }

        // Initialize current user
        currentUser = MembershipContext.AuthenticatedUser;
        // Initialize current site
        currentSite = SiteContext.CurrentSite;

        // Initialize events
        ctlAsyncLog.OnFinished += ctlAsyncLog_OnFinished;
        ctlAsyncLog.OnError += ctlAsyncLog_OnError;
        ctlAsyncLog.OnCancel += ctlAsyncLog_OnCancel;

        isSelect = QueryHelper.GetBoolean("select", false);
        if (isSelect)
        {
            pnlDocList.Visible = false;
            pnlDocSelector.Visible = true;
            translationElem.DisplayMachineServices = false;
        }

        var displayTargetLanguage = !IsDialog || isSelect;
        translationElem.DisplayTargetlanguage = displayTargetLanguage;

        // Get target culture(s)
        targetCultures = displayTargetLanguage ? translationElem.TargetLanguages : new HashSet<string>(new[] { QueryHelper.GetString("targetculture", currentCulture) });

        // Set the target settings
        var settings = new TranslationSettings();
        settings.TargetLanguages.AddRange(targetCultures);

        var useCurrentAsDefault = QueryHelper.GetBoolean("currentastargetdefault", false);
        if (!currentUser.IsGlobalAdministrator && currentUser.UserHasAllowedCultures && !currentUser.IsCultureAllowed(currentCulture, SiteContext.CurrentSiteName))
        {
            // Do not use current culture as default if user has no permissions to edit it
            useCurrentAsDefault = false;
        }

        translationElem.UseCurrentCultureAsDefaultTarget = useCurrentAsDefault;

        // Do not include default culture if it is current one
        if (useCurrentAsDefault && !currentCulture.EqualsCSafe(defaultCulture, true) && !RequestHelper.IsPostBack())
        {
            settings.TargetLanguages.Add(currentCulture);
        }

        translationElem.TranslationSettings = settings;
        allowTranslate = true;

        if (RequestHelper.IsCallback())
        {
            return;
        }

        // If not in select mode, load all the document IDs and check permissions
        // In select mode, documents are checked when the button is clicked
        if (!isSelect)
        {
            DataSet allDocs = null;
            TreeProvider tree = new TreeProvider();

            // Current Node ID to translate
            string parentAliasPath = string.Empty;
            if (Parameters != null)
            {
                parentAliasPath = ValidationHelper.GetString(Parameters["parentaliaspath"], string.Empty);
                nodeIdsArr = ValidationHelper.GetString(Parameters["nodeids"], string.Empty).Trim('|').Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
            }

            if (string.IsNullOrEmpty(parentAliasPath))
            {
                if (nodeIdsArr == null)
                {
                    // One document translation is requested
                    string nodeIdQuery = QueryHelper.GetString("nodeid", "");
                    if (nodeIdQuery != "")
                    {
                        // Mode of single node translation
                        pnlList.Visible = false;
                        chkSkipTranslated.Checked = false;

                        translationElem.NodeID = ValidationHelper.GetInteger(nodeIdQuery, 0);

                        nodeIdsArr = new[] { nodeIdQuery };
                    }
                    else
                    {
                        nodeIdsArr = new string[] { };
                    }
                }

                foreach (string nodeId in nodeIdsArr)
                {
                    int id = ValidationHelper.GetInteger(nodeId, 0);
                    if (id != 0)
                    {
                        nodeIds.Add(id);
                    }
                }
            }
            else
            {
                // Exclude root of the website from multiple translation requested by document listing bulk action
                var where = new WhereCondition(WhereCondition)
                    .WhereNotEquals("ClassName", SystemDocumentTypes.Root);

                allDocs = tree.SelectNodes(currentSite.SiteName, parentAliasPath.TrimEnd(new[] { '/' }) + "/%",
                    TreeProvider.ALL_CULTURES, true, ClassID > 0 ? DataClassInfoProvider.GetClassName(ClassID) : TreeProvider.ALL_CLASSNAMES, where.ToString(true),
                    "DocumentName", AllLevels ? TreeProvider.ALL_LEVELS : 1, false, 0,
                    DocumentColumnLists.SELECTNODES_REQUIRED_COLUMNS + ",DocumentName,NodeParentID,NodeSiteID,NodeAliasPath");

                if (!DataHelper.DataSourceIsEmpty(allDocs))
                {
                    foreach (DataTable table in allDocs.Tables)
                    {
                        foreach (DataRow row in table.Rows)
                        {
                            nodeIds.Add(ValidationHelper.GetInteger(row["NodeID"], 0));
                        }
                    }
                }
            }

            if (nodeIds.Count > 0)
            {
                var where = new WhereCondition().WhereIn("NodeID", nodeIds).ToString(true);
                DataSet ds = allDocs ?? tree.SelectNodes(currentSite.SiteName, "/%", TreeProvider.ALL_CULTURES, true, null, where, "DocumentName", TreeProvider.ALL_LEVELS, false);

                if (!DataHelper.DataSourceIsEmpty(ds))
                {
                    string docList = null;

                    cancelNodeId = string.IsNullOrEmpty(parentAliasPath)
                        ? DataHelper.GetIntValue(ds.Tables[0].Rows[0], "NodeParentID")
                        : TreePathUtils.GetNodeIdByAliasPath(currentSite.SiteName, parentAliasPath);

                    foreach (DataTable table in ds.Tables)
                    {
                        foreach (DataRow dr in table.Rows)
                        {
                            bool isLink = (dr["NodeLinkedNodeID"] != DBNull.Value);
                            string name = (string)dr["DocumentName"];
                            docList += HTMLHelper.HTMLEncode(name);
                            if (isLink)
                            {
                                docList += DocumentUIHelper.GetDocumentMarkImage(Page, DocumentMarkEnum.Link);
                            }
                            docList += "<br />";
                            lblDocuments.Text = docList;

                            // Set visibility of checkboxes
                            TreeNode node = TreeNode.New(ValidationHelper.GetString(dr["ClassName"], string.Empty), dr);

                            if (!TranslationServiceHelper.IsAuthorizedToTranslateDocument(node, currentUser, targetCultures))
                            {
                                allowTranslate = false;

                                plcMessages.AddError(String.Format(GetString("cmsdesk.notauthorizedtotranslatedocument"), HTMLHelper.HTMLEncode(node.NodeAliasPath)));
                            }
                        }
                    }

                    if (!allowTranslate && !RequestHelper.IsPostBack())
                    {
                        // Hide UI only when security check is performed within first load, if postback used user may loose some setting
                        HideUI();
                    }
                }

                // Display check box for separate submissions for each document if there is more than one document
                translationElem.DisplaySeparateSubmissionOption = (nodeIds.Count > 1);
            }
            else
            {
                // Hide everything
                pnlContent.Visible = false;
            }
        }

        // Register the dialog script
        ScriptHelper.RegisterDialogScript(this);

        ctlAsyncLog.TitleText = GetString("contentrequest.starttranslate");
        // Set visibility of panels
        pnlContent.Visible = true;
        pnlLog.Visible = false;
    }
    /// <summary>
    /// Reloads control.
    /// </summary>
    public void ReloadData()
    {
        var where = new WhereCondition(WhereCondition);

        var siteName = SiteID > 0 ? SiteInfoProvider.GetSiteName(SiteID) : SiteContext.CurrentSiteName;
        var allowGlobal = SettingsKeyInfoProvider.GetBoolValue(siteName + ".cmscmglobalconfiguration");

        uniselector.AllowAll = AllowAllItem;

        if (DisplayAll || DisplaySiteOrGlobal)
        {
            // Display all site and global statuses
            if (DisplayAll && allowGlobal)
            {
                // No WHERE condition required
            }
            // Display current site and global statuses
            else if (DisplaySiteOrGlobal && allowGlobal && (SiteID > 0))
            {
                where.WhereEqualsOrNull("AccountStatusSiteID", SiteID);
            }
            // Current site
            else if (SiteID > 0)
            {
                where.WhereEquals("AccountStatusSiteID", SiteID);
            }
            // Display global statuses
            else if (allowGlobal)
            {
                where.WhereNull("AccountStatusSiteID");
            }

            // Don't display anything
            if (String.IsNullOrEmpty(where.WhereCondition) && !DisplayAll)
            {
                where.NoResults();
            }
        }
        // Display either global or current site statuses
        else
        {
            // Current site
            if (SiteID > 0)
            {
                where.WhereEquals("AccountStatusSiteID", SiteID);
            }
            // Display global statuses
            else if (((SiteID == UniSelector.US_GLOBAL_RECORD) || (SiteID == UniSelector.US_NONE_RECORD)) && allowGlobal)
            {
                where.WhereNull("AccountStatusSiteID");
            }
            // Don't display anything
            if (String.IsNullOrEmpty(where.WhereCondition))
            {
                where.NoResults();
            }
        }

        // Do not add condition to empty condition which allows everything
        if (!String.IsNullOrEmpty(where.WhereCondition))
        {
            string status = ValidationHelper.GetString(Value, "");
            if (!String.IsNullOrEmpty(status))
            {
                where.Or().WhereEquals(uniselector.ReturnColumnName, status);
            }
        }

        uniselector.WhereCondition = where.ToString(expand: true);
        uniselector.Reload(true);
    }
    /// <summary>
    /// Setups target language selector control.
    /// </summary>
    private void SetupTargetLanguageDropDownWhereCondition()
    {
        WhereCondition condition = new WhereCondition();

        var culturesAreEqual = currentCulture.EqualsCSafe(defaultCulture, true);
        var selectedSourceCulture = selectCultureElem.DropDownCultures.SelectedValue;

        string notTargetLanguage = null;

        if (!String.IsNullOrEmpty(selectedSourceCulture))
        {
            // Use source language if selected
            notTargetLanguage = selectedSourceCulture;
        }
        else if (!culturesAreEqual || !UseCurrentCultureAsDefaultTarget)
        {
            // Use default culture if source and target languages are equal
            notTargetLanguage = defaultCulture;
        }

        if (!String.IsNullOrEmpty(selectedSourceCulture))
        {
            condition.WhereNotEquals("CultureCode", notTargetLanguage);
        }

        if (!CurrentUser.IsGlobalAdministrator && CurrentUser.UserHasAllowedCultures)
        {
            condition.WhereIn("CultureID", new IDQuery(UserCultureInfo.OBJECT_TYPE, "CultureID").WhereEquals("UserID", CurrentUser.UserID).WhereEquals("SiteID", CurrentSite.SiteID));
        }

        selectTargetCultureElem.AdditionalWhereCondition = condition.ToString(true);
    }
    /// <summary>
    /// Generates complete filter where condition.
    /// </summary>    
    private string GenerateWhereCondition()
    {
        var whereCondition = new WhereCondition();

        // Create WHERE condition for basic filter
        int contactStatus = ValidationHelper.GetInteger(fltContactStatus.Value, -1);
        if (fltContactStatus.Value == null)
        {
            whereCondition = whereCondition.WhereNull("ContactStatusID");
        }
        else if (contactStatus > 0)
        {
            whereCondition = whereCondition.WhereEquals("ContactStatusID", contactStatus);
        }

        whereCondition = whereCondition
            .Where(fltFirstName.GetCondition())
            .Where(fltLastName.GetCondition())
            .Where(fltEmail.GetCondition());

        // Only monitored contacts
        if (radMonitored.SelectedIndex == 1)
        {
            whereCondition = whereCondition.WhereTrue("ContactMonitored");
        }
        // Only not monitored contacts
        else if (radMonitored.SelectedIndex == 2)
        {
            whereCondition = whereCondition.WhereEqualsOrNull("ContactMonitored", 0);
        }

        // Only contacts that were replicated to SalesForce leads
        if (radSalesForceLeadReplicationStatus.SelectedIndex == 1)
        {
            whereCondition = whereCondition.WhereNotNull("ContactSalesForceLeadID");
        }
        // Only contacts that were not replicated to SalesForce leads
        else if (radSalesForceLeadReplicationStatus.SelectedIndex == 2)
        {
            whereCondition = whereCondition.WhereNull("ContactSalesForceLeadID");
        }

        // Create WHERE condition for advanced filter (id needed)
        if (IsAdvancedMode)
        {
            whereCondition = whereCondition
               .Where(fltMiddleName.GetCondition())
               .Where(fltCity.GetCondition())
               .Where(fltPhone.GetCondition())
               .Where(fltCreated.GetCondition())
               .Where(GetOwnerCondition(fltOwner))
               .Where(GetCountryCondition(fltCountry))
               .Where(GetStateCondition(fltState));

            if (!String.IsNullOrEmpty(txtIP.Text))
            {
                var nestedIpQuery = IPInfoProvider.GetIps().WhereLike("IPAddress", SqlHelper.EscapeLikeText(SqlHelper.EscapeQuotes(txtIP.Text)));

                whereCondition = whereCondition.WhereIn("ContactID", nestedIpQuery.Column("IPOriginalContactID")).Or().WhereIn("ContactID", nestedIpQuery.Column("IPActiveContactID"));
            }
        }

        // When "merged/not merged" filter is hidden or in advanced mode display contacts according to filter or in basic mode don't display merged contacts
        if ((HideMergedFilter && NotMerged) ||
            (IsAdvancedMode && !HideMergedFilter && !chkMerged.Checked) ||
            (!HideMergedFilter && !NotMerged && !IsAdvancedMode))
        {
            whereCondition = whereCondition
                .Where(
                    new WhereCondition(
                        new WhereCondition()
                            .WhereNull("ContactMergedWithContactID")
                            .WhereGreaterOrEquals("ContactSiteID", 0)
                        )
                        .Or(
                            new WhereCondition()
                                .WhereNull("ContactGlobalContactID")
                                .WhereNull("ContactSiteID")
                        ));
        }

        // Hide contacts merged into global contact when displaying list of available contacts for global contact
        if (HideMergedIntoGlobal)
        {
            whereCondition = whereCondition.WhereNull("ContactGlobalContactID");
        }

        if (!DisableGeneratingSiteClause)
        {
            // Filter by site
            if (!plcSite.Visible)
            {
                // Filter site objects
                if (SiteID > 0)
                {
                    whereCondition = whereCondition.WhereEquals("ContactSiteID", SiteID);
                }
                // Filter only global objects
                else if (SiteID == UniSelector.US_GLOBAL_RECORD)
                {
                    whereCondition = whereCondition.WhereNull("ContactSiteID");
                }
            }
            // Filter by site filter
            else
            {
                // Only global objects
                if (SelectedSiteID == UniSelector.US_GLOBAL_RECORD)
                {
                    whereCondition = whereCondition.WhereNull("ContactSiteID");
                }
                // Global and site objects
                else if (SelectedSiteID == UniSelector.US_GLOBAL_AND_SITE_RECORD)
                {
                    whereCondition = whereCondition.WhereEqualsOrNull("ContactSiteID", SiteContext.CurrentSiteID);
                }
                // Site objects
                else if (SelectedSiteID != UniSelector.US_ALL_RECORDS)
                {
                    whereCondition = whereCondition.WhereEquals("ContactSiteID", mSelectedSiteID);
                }
            }
        }

        return whereCondition.ToString(true);
    }
    protected override void OnInit(EventArgs e)
    {
        currentUser = MembershipContext.AuthenticatedUser;
        prefferedUICultureCode = currentUser.PreferredUICultureCode;

        var categoryWhere = new WhereCondition();

        if (IsUITemplate())
        {
            categorySelector.RootPath = CATEGORY_UIWEBPARTS;
            COOKIE_SELECTED_CATEGORY += "UI";
        }
        else
        {
            categoryWhere.WhereNotEquals("ObjectPath", CATEGORY_UIWEBPARTS).WhereNotStartsWith("ObjectPath", CATEGORY_UIWEBPARTS + "/");
        }

        // Display only top level categories
        categoryWhere.WhereLessThan("ObjectLevel", 2);
        categorySelector.WhereCondition = categoryWhere.ToString(true);

        base.OnInit(e);
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        // Register script files
        ScriptHelper.RegisterCMS(this);
        ScriptHelper.RegisterScriptFile(this, "~/CMSModules/Content/CMSDesk/Operation.js");

        // Set current UI culture
        currentCulture = CultureHelper.PreferredUICultureCode;
        // Initialize current user
        currentUser = MembershipContext.AuthenticatedUser;
        // Initialize current site
        currentSite = SiteContext.CurrentSite;

        // Initialize events
        ctlAsyncLog.OnFinished += ctlAsyncLog_OnFinished;
        ctlAsyncLog.OnError += ctlAsyncLog_OnError;
        ctlAsyncLog.OnCancel += ctlAsyncLog_OnCancel;

        if (!RequestHelper.IsCallback())
        {
            DataSet allDocs = null;
            TreeProvider tree = new TreeProvider(currentUser);

            // Current Node ID to delete
            string parentAliasPath = string.Empty;
            if (Parameters != null)
            {
                parentAliasPath = ValidationHelper.GetString(Parameters["parentaliaspath"], string.Empty);
            }
            if (string.IsNullOrEmpty(parentAliasPath))
            {
                nodeIdsArr = QueryHelper.GetString("nodeid", string.Empty).Trim('|').Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string nodeId in nodeIdsArr)
                {
                    int id = ValidationHelper.GetInteger(nodeId, 0);
                    if (id != 0)
                    {
                        nodeIds.Add(id);
                    }
                }
            }
            else
            {
                var where = new WhereCondition(WhereCondition)
                    .WhereNotEquals("ClassName", SystemDocumentTypes.Root);
                allDocs = tree.SelectNodes(currentSite.SiteName, parentAliasPath.TrimEnd(new[] { '/' }) + "/%",
                    TreeProvider.ALL_CULTURES, true, ClassID > 0 ? DataClassInfoProvider.GetClassName(ClassID) : TreeProvider.ALL_CLASSNAMES, where.ToString(true),
                                           "DocumentName", TreeProvider.ALL_LEVELS, false, 0,
                                           DocumentColumnLists.SELECTNODES_REQUIRED_COLUMNS + ",DocumentName,NodeParentID,NodeSiteID,NodeAliasPath,NodeSKUID");

                if (!DataHelper.DataSourceIsEmpty(allDocs))
                {
                    foreach (DataTable table in allDocs.Tables)
                    {
                        foreach (DataRow row in table.Rows)
                        {
                            nodeIds.Add(ValidationHelper.GetInteger(row["NodeID"], 0));
                        }
                    }
                }
            }

            // Setup page title text and image
            PageTitle.TitleText = GetString("Content.DeleteTitle");
            EnsureDocumentBreadcrumbs(PageBreadcrumbs, action: PageTitle.TitleText);

            // Register the dialog script
            ScriptHelper.RegisterDialogScript(this);

            ctlAsyncLog.TitleText = GetString("ContentDelete.DeletingDocuments");
            // Set visibility of panels
            pnlContent.Visible = true;
            pnlLog.Visible = false;

            bool isMultilingual = CultureSiteInfoProvider.IsSiteMultilingual(currentSite.SiteName);
            if (!isMultilingual)
            {
                // Set all cultures checkbox
                chkAllCultures.Checked = true;
                pnlAllCultures.Visible = false;
            }

            if (nodeIds.Count > 0)
            {
                if (nodeIds.Count == 1)
                {
                    // Single document deletion
                    int nodeId = ValidationHelper.GetInteger(nodeIds[0], 0);
                    TreeNode node = null;

                    if (string.IsNullOrEmpty(parentAliasPath))
                    {
                        // Get any culture if current not found
                        node = tree.SelectSingleNode(nodeId, CultureCode) ?? tree.SelectSingleNode(nodeId, TreeProvider.ALL_CULTURES);
                    }
                    else
                    {
                        if (allDocs != null)
                        {
                            DataRow dr = allDocs.Tables[0].Rows[0];
                            node = TreeNode.New(ValidationHelper.GetString(dr["ClassName"], string.Empty), dr, tree);
                        }
                    }

                    if (node != null)
                    {
                        bool rootDeleteDisabled = false;

                        if (IsProductsMode)
                        {
                            string startingPath = SettingsKeyInfoProvider.GetValue(CurrentSiteName + ".CMSStoreProductsStartingPath");
                            if (node.NodeAliasPath.CompareToCSafe(startingPath) == 0)
                            {
                                string closeLink = "<a href=\"#\"><span style=\"cursor: pointer;\" " +
                                       "onclick=\"SelectNode(" + node.NodeID + "); return false;\">" + GetString("general.back") +
                                       "</span></a>";

                                ShowError(string.Format(GetString("com.productsection.deleteroot"), closeLink, ""));
                                pnlDelete.Visible = false;
                                rootDeleteDisabled = true;
                            }
                        }

                        if (node.IsRoot() && isMultilingual)
                        {
                            // Hide 'Delete all cultures' checkbox
                            pnlAllCultures.Visible = false;

                            if (!URLHelper.IsPostback())
                            {
                                // Check if there are any documents in another culture or current culture has some documents
                                pnlDeleteRoot.Visible = IsAnyDocumentInAnotherCulture(node) && (tree.SelectNodesCount(SiteContext.CurrentSiteName, "/%", LocalizationContext.PreferredCultureCode, false, null, null, null, TreeProvider.ALL_LEVELS, false) > 0);

                                if (pnlDeleteRoot.Visible)
                                {
                                    // Insert 'Delete current root' option if current root node is translated to current culture
                                    if (node.DocumentCulture == LocalizationContext.PreferredCultureCode)
                                    {
                                        rblRoot.Items.Add(new ListItem(GetString("rootdeletion.currentroot"), "current"));
                                    }

                                    rblRoot.Items.Add(new ListItem(GetString("rootdeletion.currentculture"), "allculturepages"));
                                    rblRoot.Items.Add(new ListItem(GetString("rootdeletion.allpages"), "allpages"));
                                }
                                else
                                {
                                    rblRoot.Items.Add(new ListItem(GetString("rootdeletion.allpages"), "allpages"));
                                }

                                if (rblRoot.SelectedIndex < 0)
                                {
                                    rblRoot.SelectedIndex = 0;
                                }
                            }
                        }

                        // Display warning for root node
                        if (!rootDeleteDisabled && node.IsRoot())
                        {
                            if (!currentUser.IsGlobalAdministrator)
                            {
                                pnlDelete.Visible = false;

                                ShowInformation(GetString("delete.rootonlyglobaladmin"));
                            }
                            else
                            {
                                if ((rblRoot.SelectedValue == "allpages") || !isMultilingual || ((rblRoot.SelectedValue == "allculturepages") && !IsAnyDocumentInAnotherCulture(node)))
                                {
                                    messagesPlaceholder.ShowWarning(GetString("Delete.RootWarning"));

                                    plcDeleteRoot.Visible = true;
                                }
                                else
                                {
                                    plcDeleteRoot.Visible = false;
                                }
                            }
                        }

                        hasChildren = node.NodeHasChildren;

                        bool authorizedToDeleteSKU = !node.HasSKU || IsUserAuthorizedToModifySKU(node);
                        if (!RequestHelper.IsPostBack())
                        {
                            bool authorizedToDeleteDocument = IsUserAuthorizedToDeleteDocument(node);
                            if (!authorizedToDeleteDocument || !authorizedToDeleteSKU)
                            {
                                pnlDelete.Visible = false;
                                RedirectToAccessDenied(String.Format(GetString("cmsdesk.notauthorizedtodeletedocument"), HTMLHelper.HTMLEncode(node.NodeAliasPath)));
                            }
                        }

                        if (node.IsLink)
                        {
                            PageTitle.TitleText = GetString("Content.DeleteTitleLink") + " \"" + HTMLHelper.HTMLEncode(ResHelper.LocalizeString(node.GetDocumentName())) + "\"";
                            headQuestion.Text = GetString("ContentDelete.QuestionLink");
                            chkAllCultures.Checked = true;
                            plcCheck.Visible = false;
                        }
                        else
                        {
                            string nodeName = HTMLHelper.HTMLEncode(node.GetDocumentName());
                            // Get name for root document
                            if (node.IsRoot())
                            {
                                nodeName = HTMLHelper.HTMLEncode(currentSite.DisplayName);
                            }
                            PageTitle.TitleText = GetString("Content.DeleteTitle") + " \"" + HTMLHelper.HTMLEncode(ResHelper.LocalizeString(nodeName)) + "\"";

                        }

                        // Show or hide checkbox
                        pnlDestroy.Visible = CanDestroy(node);

                        cancelNodeId = IsMultipleAction ? node.NodeParentID : node.NodeID;

                        lblDocuments.Text = HTMLHelper.HTMLEncode(node.GetDocumentName());

                        if (node.IsRoot())
                        {
                            // Change SEO panel if root is selected
                            pnlSeo.Visible = false;
                        }
                    }
                    else
                    {
                        if (!RequestHelper.IsPostBack())
                        {
                            URLHelper.Redirect(UIHelper.GetInformationUrl("editeddocument.notexists"));
                        }
                        else
                        {
                            // Hide everything
                            pnlContent.Visible = false;
                        }
                    }

                    headQuestion.Text = GetString("ContentDelete.Question");
                    lblAllCultures.Text = GetString("ContentDelete.AllCultures");
                    lblDestroy.Text = GetString("ContentDelete.Destroy");
                    headDeleteDocument.Text = GetString("ContentDelete.Document");
                }
                else if (nodeIds.Count > 1)
                {
                    string where = "NodeID IN (";
                    foreach (int nodeID in nodeIds)
                    {
                        where += nodeID + ",";
                    }

                    where = where.TrimEnd(',') + ")";
                    DataSet ds = allDocs ?? tree.SelectNodes(currentSite.SiteName, "/%", TreeProvider.ALL_CULTURES, true, null, where, "DocumentName", -1, false);

                    if (!DataHelper.DataSourceIsEmpty(ds))
                    {
                        string docList = null;

                        if (string.IsNullOrEmpty(parentAliasPath))
                        {
                            cancelNodeId = DataHelper.GetIntValue(ds.Tables[0].Rows[0], "NodeParentID");
                        }
                        else
                        {
                            cancelNodeId = TreePathUtils.GetNodeIdByAliasPath(currentSite.SiteName, parentAliasPath);
                        }

                        bool canDestroy = true;
                        bool permissions = true;

                        foreach (DataTable table in ds.Tables)
                        {
                            foreach (DataRow dr in table.Rows)
                            {
                                bool isLink = (dr["NodeLinkedNodeID"] != DBNull.Value);
                                string name = (string)dr["DocumentName"];
                                docList += HTMLHelper.HTMLEncode(name);
                                if (isLink)
                                {
                                    docList += DocumentUIHelper.GetDocumentMarkImage(Page, DocumentMarkEnum.Link);
                                }
                                docList += "<br />";
                                lblDocuments.Text = docList;

                                // Set visibility of checkboxes
                                TreeNode node = TreeNode.New(ValidationHelper.GetString(dr["ClassName"], string.Empty), dr);

                                if (!IsUserAuthorizedToDeleteDocument(node))
                                {
                                    permissions = false;
                                    AddError(String.Format(
                                        GetString("cmsdesk.notauthorizedtodeletedocument"),
                                        HTMLHelper.HTMLEncode(node.NodeAliasPath)), null);
                                }

                                // Can destroy if "can destroy all previous AND current"
                                canDestroy = CanDestroy(node) && canDestroy;

                                if (!hasChildren)
                                {
                                    hasChildren = node.NodeHasChildren;
                                }
                            }
                        }

                        pnlDelete.Visible = permissions;
                        pnlDestroy.Visible = canDestroy;
                    }
                    else
                    {
                        if (!RequestHelper.IsPostBack())
                        {
                            URLHelper.Redirect(UIHelper.GetInformationUrl("editeddocument.notexists"));
                        }
                        else
                        {
                            // Hide everything
                            pnlContent.Visible = false;
                        }
                    }

                    headQuestion.Text = GetString("ContentDelete.QuestionMultiple");
                    PageTitle.TitleText = GetString("Content.DeleteTitleMultiple");
                    lblAllCultures.Text = GetString("ContentDelete.AllCulturesMultiple");
                    lblDestroy.Text = GetString("ContentDelete.DestroyMultiple");
                    headDeleteDocument.Text = GetString("global.pages");
                }

                lblAltPath.AssociatedControlClientID = selAltPath.PathTextBox.ClientID;

                selAltPath.SiteID = currentSite.SiteID;

                chkUseDeletedPath.CheckedChanged += chkUseDeletedPath_CheckedChanged;
                if (!RequestHelper.IsPostBack())
                {
                    selAltPath.Enabled = false;
                    chkAltSubNodes.Enabled = false;
                    chkAltAliases.Enabled = false;

                    // Set default path if is defined
                    selAltPath.Value = SettingsKeyInfoProvider.GetValue(CurrentSiteName + ".CMSDefaultDeletedNodePath");

                    if (!hasChildren)
                    {
                        chkAltSubNodes.Checked = false;
                        chkAltSubNodes.Enabled = false;
                    }
                }

                // If user has allowed cultures specified
                if (currentUser.UserHasAllowedCultures)
                {
                    // Get all site cultures
                    DataSet siteCultures = CultureSiteInfoProvider.GetSiteCultures(currentSite.SiteName);
                    bool denyAllCulturesDeletion = false;
                    // Check that user can edit all site cultures
                    foreach (DataRow culture in siteCultures.Tables[0].Rows)
                    {
                        string cultureCode = DataHelper.GetStringValue(culture, "CultureCode");
                        if (!currentUser.IsCultureAllowed(cultureCode, currentSite.SiteName))
                        {
                            denyAllCulturesDeletion = true;
                        }
                    }
                    // If user can't edit all site cultures
                    if (denyAllCulturesDeletion)
                    {
                        // Hide all cultures selector
                        pnlAllCultures.Visible = false;
                        chkAllCultures.Checked = false;
                    }
                }
                pnlDeleteDocument.Visible = pnlAllCultures.Visible || pnlDestroy.Visible;
            }
            else
            {
                // Hide everything
                pnlContent.Visible = false;
            }
        }

        // Initialize header action
        InitializeActionMenu();
    }
    /// <summary>
    /// Returns SQL WHERE condition depending on selected checkboxes.
    /// </summary>
    /// <returns>Returns SQL WHERE condition</returns>
    public string GetWhereCondition()
    {
        var where = new WhereCondition();

        // Contacts checked
        if (chkContacts.Checked)
        {
            where.Where(GetContactWhereCondition());
        }

        // Address checked
        if (chkAddress.Checked)
        {
            where.Where(GetAddressWhereCondition());
        }

        // Email address checked
        if (chkEmail.Checked)
        {
            string domain = ContactHelper.GetEmailDomain(CurrentAccount.AccountEmail);
            if (!String.IsNullOrEmpty(domain))
            {
                var emailWhere = new WhereCondition().WhereEndsWith("AccountEmail", "@" + domain);
                where.Where(emailWhere);
            }
        }

        // URL checked
        if (chkURL.Checked && !String.IsNullOrEmpty(CurrentAccount.AccountWebSite))
        {
            var urlWhere = new WhereCondition().WhereContains("AccountWebSite", URLHelper.CorrectDomainName(CurrentAccount.AccountWebSite));
            where.Where(urlWhere);
        }

        // Phone & fax checked
        if (chkPhone.Checked && (!String.IsNullOrEmpty(CurrentAccount.AccountPhone) || !String.IsNullOrEmpty(CurrentAccount.AccountFax)))
        {
            where.Where(GetPhoneWhereCondition());
        }

        if ((!chkContacts.Checked && !chkAddress.Checked && !chkEmail.Checked && !chkURL.Checked && !chkPhone.Checked) || (String.IsNullOrEmpty(where.WhereCondition)))
        {
            return "(1 = 0)";
        }

        // Filter out current account
        where.WhereNotEquals("AccountID", CurrentAccount.AccountID);

        // Filter out merged records
        where.Where(w => w.Where(x => x.WhereNull("AccountMergedWithAccountID")
                                       .WhereNull("AccountGlobalAccountID")
                                       .WhereGreaterThan("AccountSiteID", 0))
                          .Or(y => y.WhereNull("AccountGlobalAccountID")
                                    .WhereNull("AccountSiteID")));

        // For global object use siteselector's value
        if (plcSite.Visible)
        {
            mSelectedSiteID = UniSelector.US_ALL_RECORDS;
            if (siteSelector.Visible)
            {
                mSelectedSiteID = siteSelector.SiteID;
            }
            else if (siteOrGlobalSelector.Visible)
            {
                mSelectedSiteID = siteOrGlobalSelector.SiteID;
            }

            // Only global objects
            if (mSelectedSiteID == UniSelector.US_GLOBAL_RECORD)
            {
                where.WhereNull("AccountSiteID");
            }
            // Global and site objects
            else if (mSelectedSiteID == UniSelector.US_GLOBAL_AND_SITE_RECORD)
            {
                where.Where(w => w.WhereNull("AccountSiteID").Or().WhereEquals("AccountSiteID", SiteContext.CurrentSiteID));
            }
            // Site objects
            else if (mSelectedSiteID != UniSelector.US_ALL_RECORDS)
            {
                where.WhereEquals("AccountSiteID", mSelectedSiteID);
            }
        }
        // Filter out accounts from different sites
        else
        {
            // Site accounts only
            if (CurrentAccount.AccountSiteID > 0)
            {
                where.WhereEquals("AccountSiteID", CurrentAccount.AccountSiteID);
            }
            // Global accounts only
            else
            {
                where.WhereNull("AccountSiteID");
            }
        }

        return where.ToString(expand: true);
    }
    /// <summary>
    /// Reloads the data.
    /// </summary>
    /// <param name="forceReload">If true, the data is reloaded even when already loaded</param>
    public void ReloadData(bool forceReload)
    {
        if (!dataLoaded || forceReload)
        {
            drpWebpart.Items.Clear();

            if (DisplayNone)
            {
                drpWebpart.Items.Add(new ListItem(ResHelper.GetString("General.SelectNone"), ""));
            }

            // Do not retrieve webparts
            WhereCondition condition = new WhereCondition(WhereCondition);
            if (!ShowWebparts)
            {
                condition.WhereEquals("ObjectType", "webpartcategory");
            }

            if (!ShowInheritedWebparts)
            {
                condition.WhereNull("WebPartParentID");
            }

            if (!String.IsNullOrEmpty(RootPath))
            {
                string rootPath = RootPath.TrimEnd('/');
                condition.Where(new WhereCondition().WhereEquals("ObjectPath", rootPath).Or().WhereStartsWith("ObjectPath", rootPath + "/"));
            }

            ds = WebPartCategoryInfoProvider.GetCategoriesAndWebparts(condition.ToString(true), "DisplayName", 0, "ObjectID, DisplayName, ParentID, ObjectType");

            if (!DataHelper.DataSourceIsEmpty(ds))
            {
                int counter = 0;

                // Make special collection for "tree mapping"
                Dictionary<int, SortedList<string, object[]>> categories = new Dictionary<int, SortedList<string, object[]>>();

                // Fill collection from dataset
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    int parentId = ValidationHelper.GetInteger(dr["ParentID"], 0);
                    int id = ValidationHelper.GetInteger(dr["ObjectID"], 0);
                    string name = ResHelper.LocalizeString(ValidationHelper.GetString(dr["DisplayName"], String.Empty));
                    string type = ValidationHelper.GetString(dr["ObjectType"], String.Empty);

                    // Skip webpart, take only WebpartCategory
                    if (type == "webpart")
                    {
                        continue;
                    }

                    SortedList<string, object[]> list;
                    categories.TryGetValue(parentId, out list);

                    // Sub categories list not created yet
                    if (list == null)
                    {
                        list = new SortedList<string, object[]>();
                        categories.Add(parentId, list);
                    }

                    list.Add(name + "_" + counter, new object[] { id, name });

                    counter++;
                }

                // Start filling the dropdown from the root(parentId = 0)
                int level = 0;

                // Root is not shown, start indentation later
                if (!ShowRoot)
                {
                    level = -1;
                }

                AddSubCategories(categories, 0, level);
            }

            dataLoaded = true;
        }
    }
    /// <summary>
    /// Reloads the data in the selector.
    /// </summary>
    /// <param name="reloadUniSelector">If true, UniSelector is also reloaded</param>
    public void ReloadData(bool reloadUniSelector = false)
    {
        uniSelector.IsLiveSite = IsLiveSite;
        var where = new WhereCondition();

        if (OnlyDocumentTypes)
        {
            where.WhereEquals("ClassIsDocumentType", 1);
        }
        else if (OnlyCustomTables)
        {
            where.WhereEquals("ClassIsCustomTable", 1);
        }

        if (mSiteId != null)
        {
            where.WhereIn("ClassID", ClassSiteInfoProvider.GetClassSites().Column("ClassID").WhereEquals("SiteID", mSiteId));
        }

        // Combine default where condition with external
        if (!String.IsNullOrEmpty(WhereCondition))
        {
            where.Where(WhereCondition);
        }

        uniSelector.WhereCondition = where.ToString(true);

        if (reloadUniSelector)
        {
            uniSelector.Reload(true);
        }
    }
    protected void LoadAvailableTables()
    {
        var tm = new TableManager(null);

        var where = new WhereCondition()
            .WhereNotIn("TABLE_NAME", new ObjectQuery<DataClassInfo>().Column("ClassTableName").WhereNotNull("ClassTableName"))
            .WhereNotIn("TABLE_NAME", new List<string> { "Analytics_Index", "sysdiagrams", "Temp_WebPart" });

        drpExistingTables.DataSource = tm.GetTables(where.ToString());
        drpExistingTables.DataBind();
    }
    /// <summary>
    /// PageLoad event handler.
    /// </summary>
    protected void Page_Load(object sender, EventArgs e)
    {
        // Object type cannot be defined in xml definition -> it would ignore code behind configuration
        UniGridRelationship.ObjectType = (IsAdHocRelationship) ? RelationshipInfo.OBJECT_TYPE_ADHOC : RelationshipInfo.OBJECT_TYPE;

        if (StopProcessing)
        {
            UniGridRelationship.StopProcessing = StopProcessing;
            return;
        }

        // Set tree node from Form object
        if ((TreeNode == null) && (Form != null) && (Form.EditedObject != null))
        {
            var node = Form.EditedObject as TreeNode;
            if ((node != null) && (Form.Mode == FormModeEnum.Update))
            {
                TreeNode = node;
            }
            else
            {
                ShowInformation(GetString("relationship.editdocumenterror"));
            }
        }

        if (TreeNode != null)
        {
            InitUniGrid();

            int nodeId = TreeNode.NodeID;

            // Add relationship name condition
            var condition = new WhereCondition().WhereIn("RelationshipNameID", new IDQuery<RelationshipNameInfo>().Where(GetRelationshipNameCondition()));

            // Switch sides is disabled
            if (!AllowSwitchSides)
            {
                condition.WhereEquals(DefaultSide ? "RightNodeID" : "LeftNodeID", nodeId);
            }
            else
            {
                condition.Where(new WhereCondition().WhereEquals("RightNodeID", nodeId).Or().WhereEquals("LeftNodeID", nodeId));
            }

            InitFilterVisibility();

            UniGridRelationship.WhereCondition = condition.ToString(true);

            if (ShowAddRelation)
            {
                btnNewRelationship.OnClientClick = GetAddRelatedDocumentScript() + " return false;";
            }
            else
            {
                pnlNewLink.Visible = false;
            }
        }
        else
        {
            UniGridRelationship.StopProcessing = true;
            UniGridRelationship.Visible = false;

            btnNewRelationship.Enabled = false;
        }

        if (RequestHelper.IsPostBack())
        {
            string target = Request[Page.postEventSourceID];
            if ((target != pnlUpdate.ClientID) && (target != pnlUpdate.UniqueID))
            {
                return;
            }

            string action = Request[Page.postEventArgumentID];
            if (string.IsNullOrEmpty(action))
            {
                return;
            }

            switch (action.ToLowerCSafe())
            {
                // Insert from 'Select document' dialog
                case "insertfromselectdocument":
                    SaveRelationship();
                    break;
            }
        }
        else
        {
            bool inserted = QueryHelper.GetBoolean("inserted", false);
            if (inserted)
            {
                ShowConfirmation(GetString("relationship.wasadded"));
            }
        }
    }
 /// <summary>
 /// Creates where condition for UniGrid and reloads it.
 /// </summary>
 private void InitWhereCondition()
 {
     var where = new WhereCondition().WhereEquals("ShippingOptionSiteID", SiteContext.CurrentSiteID);
     UniGrid.WhereCondition = where.ToString(true);
 }
    /// <summary>
    /// Mass action 'ok' button clicked.
    /// </summary>
    protected void btnOk_Click(object sender, EventArgs e)
    {
        CheckModifyPermissions();

        Action action = (Action)ValidationHelper.GetInteger(drpAction.SelectedItem.Value, 0);
        What what = (What)ValidationHelper.GetInteger(drpWhat.SelectedItem.Value, 0);

        var where = new WhereCondition()
            .WhereEquals("ContactGroupMemberContactGroupID", cgi.ContactGroupID)
            // Set constraint for account relations only
            .WhereEquals("ContactGroupMemberType", 1);

        switch (what)
        {
            // All items
            case What.All:
                var accountIds = new ObjectQuery("om.contactgroupaccountlist")
                    .Column("AccountID")
                    .Where(gridElem.WhereCondition)
                    .Where(gridElem.WhereClause);

                where.WhereIn("ContactGroupMemberRelatedID", accountIds);
                break;
            // Selected items
            case What.Selected:
                // Convert array to integer values to make sure no sql injection is possible (via string values)
                where.WhereIn("ContactGroupMemberRelatedID", gridElem.SelectedItems);
                break;
            default:
                return;
        }

        switch (action)
        {
            // Action 'Remove'
            case Action.Remove:
                // Delete the relations between contact group and accounts
                ContactGroupMemberInfoProvider.DeleteContactGroupMembers(where.ToString(true), cgi.ContactGroupID, true, true);
                // Show result message
                if (what == What.Selected)
                {
                    ShowConfirmation(GetString("om.account.massaction.removed"));
                }
                else
                {
                    ShowConfirmation(GetString("om.account.massaction.removedall"));
                }
                break;
            default:
                return;
        }

        // Reload unigrid
        gridElem.ResetSelection();
        gridElem.ReloadData();
        pnlUpdate.Update();
    }
    /// <summary>
    /// Gets WHERE condition for available sites according field configuration.
    /// </summary>
    private string GetSiteWhere()
    {
        // First check configuration
        WhereCondition condition = new WhereCondition();

        if (!IsCopyMoveLinkDialog)
        {
            condition.WhereEquals("SiteStatus", "RUNNING");
        }

        switch (Config.ContentSites)
        {
            case AvailableSitesEnum.OnlySingleSite:
                condition.WhereEquals("SiteName", Config.ContentSelectedSite);
                break;

            case AvailableSitesEnum.OnlyCurrentSite:
                condition.WhereEquals("SiteName", SiteContext.CurrentSiteName);
                break;
        }

        // Get only current user's sites
        if (!MembershipContext.AuthenticatedUser.IsGlobalAdministrator)
        {
            condition.WhereIn("SiteID", new IDQuery<UserSiteInfo>(UserSiteInfo.TYPEINFO.SiteIDColumn)
                                                    .WhereEquals("UserID", MembershipContext.AuthenticatedUser.UserID));
        }
        return condition.ToString(true);
    }
    /// <summary>
    /// Builds a SQL condition for filtering the discount list, and returns it.
    /// </summary>
    /// <returns>A SQL condition for filtering the discount list.</returns>
    private string GetFilterWhereCondition()
    {
        string discountStatus = drpStatus.SelectedValue;
        var condition = new WhereCondition();

        /* Active discounts */
        if (discountStatus == "0")
        {
            condition.Where(GetActiveQuery());
        }
        /* Disabled discounts */
        else if (discountStatus == "1")
        {
            condition.WhereNot(GetEnabledDiscounts());
        }
        /* Finished discounts */
        else if (discountStatus == "2")
        {
            condition.Where(GetEnabledDiscounts())
                     .WhereLessThan(GetColumn("DiscountValidTo"), DateTime.Now)
                     .WhereNot(GetIncompleteDiscounts())
                     .Or(GetDiscountsWithCouponsExceeded());
        }
        /* Scheduled discounts */
        else if (discountStatus == "3")
        {
            condition.Where(GetEnabledDiscounts())
                     .WhereGreaterThan(GetColumn("DiscountValidFrom"), DateTime.Now)
                     .WhereNot(GetIncompleteDiscounts());
        }
        /* Incomplete discounts */
        else if (discountStatus == "4")
        {
            condition.Where(GetEnabledDiscounts())
                     .Where(GetIncompleteDiscounts());
        }

        return condition.ToString(true);
    }
    /// <summary>
    /// Generates where condition.
    /// </summary>
    private string GenerateWhereCondition()
    {
        // Get older than value
        DateTime olderThan = DateTime.Now.Date.AddDays(1);
        int dateTimeValue = ValidationHelper.GetInteger(txtFilter.Text, 0);

        switch (drpFilter.SelectedIndex)
        {
            case 0:
                olderThan = olderThan.AddDays(-dateTimeValue);
                break;

            case 1:
                olderThan = olderThan.AddDays(-dateTimeValue * 7);
                break;

            case 2:
                olderThan = olderThan.AddMonths(-dateTimeValue);
                break;

            case 3:
                olderThan = olderThan.AddYears(-dateTimeValue);
                break;
        }

        var where = new WhereCondition().WhereLessOrEquals(SOURCE_MODIFIEDWHEN, olderThan);

        // Add where condition
        if (!string.IsNullOrEmpty(txtDocumentName.Text))
        {
            AddOutdatedWhereCondition(where, SOURCE_DOCUMENTNAME, drpDocumentName, txtDocumentName);
        }

        if (!string.IsNullOrEmpty(txtDocumentType.Text))
        {
            AddOutdatedWhereCondition(where, SOURCE_CLASSDISPLAYNAME, drpDocumentType, txtDocumentType);
        }

        return where.ToString(true);
    }
 /// <summary>
 /// Prepares IDs of nodes when action is performed for all documents under specified parent.
 /// </summary>
 private void PrepareNodeIdsForAllDocuments(string siteName)
 {
     if (!string.IsNullOrEmpty(parentAlias))
     {
         var where = new WhereCondition(whereCondition)
             .WhereNotEquals("ClassName", SystemDocumentTypes.Root);
         string columns = SqlHelper.MergeColumns(DocumentColumnLists.SELECTNODES_REQUIRED_COLUMNS, "NodeParentID, DocumentName, NodeAliasPath, NodeLinkedNodeID");
         documentsToProcess = TreeProvider.SelectNodes(siteName, parentAlias.TrimEnd('/') + "/%", TreeProvider.ALL_CULTURES, true, DataClassInfoProvider.GetClassName(ClassID), where.ToString(true), AllLevels ? "NodeLevel DESC, NodeAliasPath" : null, AllLevels ? -1 : 1, false, 0, columns);
         nodeIds.Clear();
         if (!DataHelper.DataSourceIsEmpty(documentsToProcess))
         {
             foreach (DataRow row in documentsToProcess.Tables[0].Rows)
             {
                 nodeIds.Add(ValidationHelper.GetInteger(row["NodeID"], 0));
             }
         }
     }
 }
    private DataSet GetRecycleBinSeletedItems(BinSettingsContainer settings, string columns)
    {
        var where = new WhereCondition();

        switch (settings.CurrentWhat)
        {
            case What.AllObjects:
                if (IsSingleSite)
                {
                    where.WhereNull("VersionObjectSiteID");
                }
                if (settings.Site != null)
                {
                    where.Or().WhereEquals("VersionObjectSiteID", settings.Site.SiteID);
                }

                // Wrap filter condition with brackets
                where.Where(new WhereCondition(filter.WhereCondition) { WhereIsComplex = true });
                where = GetWhereCondition(where);
                break;

            case What.SelectedObjects:
                // Restore selected objects
                var toRestore = settings.SelectedItems;
                where.WhereIn("VersionID", toRestore);
                break;
        }

        return ObjectVersionHistoryInfoProvider.GetRecycleBin(where.ToString(true), OrderBy, -1, columns);
    }
    /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    protected void Page_Load(object sender, EventArgs e)
    {
        gridElem.EditActionUrl = "Edit.aspx?variantid={0}&nodeid=" + NodeID;
        gridElem.ZeroRowsText = GetString("contentvariant.nodata");

        // Grid initialization
        gridElem.OnAction += new OnActionEventHandler(gridElem_OnAction);

        // If not set, get the page template id for the current node and its document template
        if ((PageTemplateID <= 0) && (Node != null))
        {
            PageTemplateID = Node.GetUsedPageTemplateId();
        }

        // Build where condition
        var where = new WhereCondition().WhereEquals("VariantPageTemplateID", PageTemplateID);

        // Display only variants for the current document
        if (Node != null)
        {
            where.WhereEqualsOrNull("VariantDocumentID", Node.DocumentID);
        }

        // Display variants just for a specific zone/webpart/widget
        if (!string.IsNullOrEmpty(ZoneID))
        {
            where.WhereEquals("VariantZoneID", ZoneID);

            if (InstanceGUID != Guid.Empty)
            {
                // Web part/widget condition
                where.WhereEquals("VariantInstanceGUID", InstanceGUID );
            }
        }

        gridElem.WhereCondition = where.ToString(expand: true);
    }
    /// <summary>
    /// Initializes the selector.
    /// </summary>
    public void InitSelector()
    {
        uniSelector.IsLiveSite = IsLiveSite;

        // Set resource prefix if specified
        if (ResourcePrefix != null)
        {
            uniSelector.ResourcePrefix = ResourcePrefix;
        }

        // Initialize selector for on-line marketing
        if (ValidationHelper.GetString(GetValue("mode"), "").ToLowerCSafe() == "onlinemarketing")
        {
            UniSelector.SelectionMode = SelectionModeEnum.MultipleButton;
            UniSelector.OnItemsSelected += UniSelector_OnItemsSelected;
            UniSelector.ReturnColumnName = "CustomerID";
            IsLiveSite = false;
            SiteID = ValidationHelper.GetInteger(GetValue("SiteID"), 0);
            UniSelector.ResourcePrefix = "om.customerselector";
        }

        var where = new WhereCondition();
        // Add registered customers
        if (DisplayRegisteredCustomers)
        {
            where.WhereIn("CustomerUserID", new IDQuery<UserSiteInfo>("UserID").WhereEquals("SiteID", SiteID));
        }

        // Add anonymous customers
        if (DisplayAnonymousCustomers)
        {
            where.Or().Where(w => w.WhereEquals("CustomerSiteID", SiteID).And().WhereNull("CustomerUserID"));
        }

        where = new WhereCondition(where);

        // Filter out only enabled items
        if (DisplayOnlyEnabled)
        {
            where.WhereTrue("CustomerEnabled");
        }

        // Add items which have to be on the list
        if (!string.IsNullOrEmpty(AdditionalItems))
        {
            where.Or().WhereIn("CustomerID", AdditionalItems.Split(','));
        }

        // Selected value must be on the list
        if (CustomerID > 0)
        {
            where.Or().WhereEquals("CustomerID", CustomerID);
        }

        uniSelector.WhereCondition = where.ToString(true);
    }
    /// <summary>
    /// Setups source language drop down list control.
    /// </summary>
    /// <param name="targetCultures">List of target cultures which should not be in te source selector</param>
    private void SetupSourceLanguageDropDownWhereCondition(HashSet<string> targetCultures)
    {
        var condition = new WhereCondition();
        if (targetCultures.Count > 0)
        {
            condition.WhereNotIn("CultureCode", targetCultures.ToList());
        }

        if (NodeID > 0)
        {
            // Get source culture list from original node if current node is linked
            var node = TreeProvider.SelectSingleNode(NodeID, TreeProvider.ALL_CULTURES, true, false);
            var sourceNodeID = node.OriginalNodeID;

            condition.WhereIn("CultureCode", new IDQuery("cms.document", "DocumentCulture").WhereEquals("DocumentNodeID", sourceNodeID));
        }

        selectCultureElem.AdditionalWhereCondition = condition.ToString(true);
    }
    /// <summary>
    /// Removes global shipping options from recycle bin.
    /// </summary>
    private static void RemoveGlobalShippingOptionsFromRecycleBin()
    {
        const string shippingObjectType = "ecommerce.shippingoption";
        var shippingOption = ModuleManager.GetObject(shippingObjectType);

        // Nothing to remove when shipping option type not present
        if (shippingOption == null)
        {
            return;
        }

        // Get histories for all objects of shipping option type
        var histories = ObjectVersionHistoryInfoProvider.GetVersionHistories().WhereEquals("VersionObjectType", shippingObjectType);

        // Fill ids list with IDs of global shipping options present in histories
        var ids = new List<int>();
        foreach (var history in histories)
        {
            if (!String.IsNullOrEmpty(history.VersionXML))
            {
                HierarchyHelper.LoadObjectFromXML(OperationTypeEnum.Export, shippingOption, history.VersionXML);

                if (shippingOption.IsGlobal)
                {
                    ids.Add(shippingOption.Generalized.ObjectID);
                }
            }
        }

        // Remove version histories for selected shipping options
        if (ids.Count != 0)
        {
            var where = new WhereCondition().WhereIn("VersionObjectID", ids);
            ObjectVersionHistoryInfoProvider.DeleteVersionHistories(where.ToString(true));
        }
    }
    /// <summary>
    /// Creates where condition according to values selected in filter.
    /// </summary>
    public override string GetWhereCondition()
    {
        var where = new WhereCondition();
        var oper = drpLanguage.SelectedValue.ToEnum<QueryOperator>();
        var val = ValidationHelper.GetString(cultureElem.Value, null);
        if (String.IsNullOrEmpty(val))
        {
            val = "##ANY##";
        }

        if (val != "##ANY##")
        {
            // Create base query
            var tree = new TreeProvider();
            var query = tree.SelectNodes()
                            .All()
                            .Column("NodeID");

            switch (val)
            {
                case "##ALL##":
                    {
                        var cultureCount = SiteCultures.Tables[0].Rows.Count;
                        query.GroupBy("NodeID").Having(string.Format("(COUNT(NodeID) {0} {1})", oper.ToStringRepresentation(), cultureCount));

                        where.WhereIn("NodeID", query);
                    }
                    break;

                default:
                    {
                        query.WhereEquals("DocumentCulture", val);

                        if (oper == QueryOperator.NotEquals)
                        {
                            where.WhereNotIn("NodeID", query);
                        }
                        else
                        {
                            where.WhereIn("NodeID", query);
                        }
                    }
                    break;
            }
        }
        else if (oper == QueryOperator.NotEquals)
        {
            where.NoResults();
        }

        return where.ToString(true);
    }