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;
    }
    /// <summary>
    /// Generates WHERE condition.
    /// </summary>
    private WhereCondition GenerateWhereCondition()
    {
        var where = new WhereCondition();
        string name = txtName.Text;

        if (String.IsNullOrEmpty(name))
        {
            return where;
        }

        // Get filter operator (LIKE, NOT LIKE, =, !=)
        switch (filter.SelectedValue)
        {
            default:
                where.Where(w => w.WhereContains("CategoryDisplayName", name).Or().WhereContains("CategoryLiveSiteDisplayName", name));
                break;
            case WhereBuilder.EQUAL:
                where.Where(w => w.WhereEquals("CategoryDisplayName", name).Or().WhereEquals("CategoryLiveSiteDisplayName", name));
                break;
            case WhereBuilder.NOT_LIKE:
                where.Where(w => w.WhereNotContains("CategoryDisplayName", name).Or().WhereNull("CategoryDisplayName"))
                     .And()
                     .Where(w => w.WhereNotContains("CategoryLiveSiteDisplayName", name).Or().WhereNull("CategoryLiveSiteDisplayName"));
                break;
            case WhereBuilder.NOT_EQUAL:
                where.Where(w => w.WhereNotEquals("CategoryDisplayName", name).Or().WhereNull("CategoryDisplayName"))
                     .And()
                     .Where(w => w.WhereNotEquals("CategoryLiveSiteDisplayName", name).Or().WhereNull("CategoryLiveSiteDisplayName"));
                break;
        }

        return where;
    }
    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");
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        PageTitle.TitleText = GetString("newsletter_issue_subscribersclicks.title");
        linkId = QueryHelper.GetInteger("linkid", 0);
        if (linkId == 0)
        {
            RequestHelper.EndResponse();
        }

        LinkInfo link = LinkInfoProvider.GetLinkInfo(linkId);
        EditedObject = link;

        IssueInfo issue = IssueInfoProvider.GetIssueInfo(link.LinkIssueID);
        EditedObject = issue;

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

        var where = new WhereCondition().Where("LinkID", QueryOperator.Equals, linkId);

        // Link's issue is the main A/B test issue
        if (issue.IssueIsABTest && !issue.IssueIsVariant)
        {
            // Get A/B test and its winner issue ID
            ABTestInfo test = ABTestInfoProvider.GetABTestInfoForIssue(issue.IssueID);
            if (test != null)
            {
                // Get ID of the same link from winner issue
                var winnerLink = LinkInfoProvider.GetLinks()
                                                 .WhereEquals("LinkIssueID", test.TestWinnerIssueID)
                                                 .WhereEquals("LinkTarget", link.LinkTarget)
                                                 .WhereEquals("LinkDescription", link.LinkDescription)
                                                 .TopN(1)
                                                 .Column("LinkID")
                                                 .FirstOrDefault();

                if (winnerLink != null)
                {
                    if (winnerLink.LinkID > 0)
                    {
                        // Add link ID of winner issue link
                        where.Or(new WhereCondition().Where("LinkID", QueryOperator.Equals, winnerLink.LinkID));
                    }
                }
            }
        }
        where.And(new WhereCondition(fltOpenedBy.WhereCondition));

        UniGrid.WhereCondition = where.WhereCondition;
        UniGrid.QueryParameters = where.Parameters;
        UniGrid.Pager.DefaultPageSize = PAGESIZE;
        UniGrid.Pager.ShowPageSize = false;
        UniGrid.FilterLimit = 1;
        UniGrid.OnExternalDataBound += UniGrid_OnExternalDataBound;
    }
Example #5
0
        public void Where_TwoConditionsWithOr()
        {
            const string expectedResult  = "SELECT\t*\r\nFROM [ec].[OrderDetails] AS o\r\nWHERE (o.[ProductName] = 'Value1' OR o.[ProductName] = 'Value2')\r\n";
            var          condition1      = new WhereCondition <OrderDetailAttr>(w => w.ProductName, ComparisonOperator.Equal, "Value1");
            var          condition2      = new WhereCondition <OrderDetailAttr>(w => w.ProductName, ComparisonOperator.Equal, "Value2");
            var          congiditonGroup = new WhereConditionGroup(condition1, GroupOperator.Or, condition2);

            var sql = _builderAttr.Where(congiditonGroup).ToSql();

            Assert.AreEqual(expectedResult, sql);
        }
        private WhereCondition GetPriceWhereCondition()
        {
            var where = new WhereCondition();

            foreach (var range in GetSelectedRanges())
            {
                where.Or(GetWhereConditionForPriceRange(range));
            }

            return(where);
        }
Example #7
0
    protected DataSet gridTasks_OnDataReload(string completeWhere, string currentOrder, int currentTopN, string columns, int currentOffset, int currentPageSize, ref int totalRecords)
    {
        // Get the tasks
        string where = GetSiteWhere();
        WhereCondition mergedWhere = new WhereCondition(completeWhere).And().Where(where);

        DataSet ds = StagingTaskInfoProvider.SelectObjectTaskList(CurrentSiteID, SelectedServerID, objectType, mergedWhere.ToString(true), currentOrder, currentTopN, columns, currentOffset, currentPageSize, ref totalRecords);

        pnlFooter.Visible = (totalRecords > 0);
        return(ds);
    }
Example #8
0
        private WhereCondition GetInStockWhereCondition()
        {
            var where = new WhereCondition();

            if (mBrewerFilterViewModel.OnlyInStock)
            {
                where.WhereGreaterThan("SKUAvailableItems", 0).Or().WhereNull("SKUAvailableItems");
            }

            return(where);
        }
Example #9
0
        public void WhereCondition_AB()
        {
            WhereCondition wc = new WhereCondition()
            {
                Left  = "A",
                Right = "B"
            };
            string correctValue = "[A] = 'B'";
            string testValue    = wc.Build();

            MyAssert.Equals(correctValue, testValue);
        }
Example #10
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");
    }
Example #11
0
 private void GetStagingTasksByTaskGroup(WhereCondition where, int taskGroupSelected)
 {
     if (taskGroupSelected > 0)
     {
         // Get tasks for given task group
         where.WhereIn("TaskID", TaskGroupTaskInfoProvider.GetTaskGroupTasks().WhereEquals("TaskGroupID", taskGroupSelected).Column("TaskID"));
     }
     else if (taskGroupSelected == UniSelector.US_NONE_RECORD)
     {
         where.WhereNotIn("TaskID", TaskGroupTaskInfoProvider.GetTaskGroupTasks().Column("TaskID"));
     }
 }
    /// <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));
    }
        /// <summary>
        /// 解析数据
        /// </summary>
        /// <param name="whereConditionArguments"></param>
        /// <returns></returns>
        public virtual WhereConditionArguments Parse(WhereConditionArguments whereConditionArguments)
        {
            if (whereConditionArguments == null)
            {
                throw new ArgumentNullException(nameof(whereConditionArguments));
            }


            List <WhereCondition> removeList = new List <WhereCondition>();

            foreach (WhereCondition item in whereConditionArguments.WhereConditions.Where(item => !(item is null)))
            {
                WhereCondition whereCondition = item;
                if ((whereCondition.MatchMode & (EnumMatchMode.Between | EnumMatchMode.NotBetween | EnumMatchMode.In |
                                                 EnumMatchMode.NotIn)) == whereCondition.MatchMode)
                {
                    IEnumerable <object> targetList;
                    Type type = whereCondition.Value?.GetType();
                    if (type is null)
                    {
                        continue;
                    }

                    targetList = type == typeof(string)
                        ? JsonConvert.DeserializeObject <List <object> >(((string)whereCondition.Value)?.Trim())
                        : whereCondition.Value is IEnumerable array?array.Cast <object>() : null;

                    if (targetList == null ||
                        ((whereCondition.MatchMode & (EnumMatchMode.Between | EnumMatchMode.NotBetween)) ==
                         whereCondition.MatchMode && targetList.Count() != 2))
                    {
                        removeList.Add(item);
                    }

                    whereCondition.Value = targetList;
                }
                else if ((whereCondition.MatchMode & EnumMatchMode.Like) == EnumMatchMode.Like)
                {
                    //No conversion required
                }
            }

            foreach (WhereConditionArguments item in whereConditionArguments.InnerWhereConditionArguments)
            {
                if (item is WhereConditionArguments innerWhereConditionArguments)
                {
                    innerWhereConditionArguments = Parse(innerWhereConditionArguments);
                }
            }

            removeList.ForEach(item => whereConditionArguments.WhereConditions.Remove(item));
            return(whereConditionArguments);
        }
    /// <summary>
    /// Publishes document(s).
    /// </summary>
    private void PublishAll(object parameter)
    {
        if (parameter == null)
        {
            return;
        }

        TreeProvider tree = new TreeProvider(currentUser);

        tree.AllowAsyncActions = false;

        try
        {
            AddLog(GetString("content.publishingdocuments", currentCulture));

            string[] parameters = ((string)parameter).Split(';');
            string   siteName   = parameters[1];
            int[]    workNodes  = nodeIds.ToArray();
            string where = new WhereCondition().WhereIn("NodeID", workNodes).ToString(true);
            string columns     = SqlHelper.MergeColumns(DocumentColumnLists.SELECTNODES_REQUIRED_COLUMNS, "NodeAliasPath, ClassName, DocumentCulture");
            string cultureCode = chkAllCultures.Checked ? TreeProvider.ALL_CULTURES : parameters[0];

            // Get the documents
            var documents = tree.SelectNodes(siteName, "/%", cultureCode, false, null, where, "NodeAliasPath DESC", TreeProvider.ALL_LEVELS, false, 0, columns);
            if (!DataHelper.DataSourceIsEmpty(documents))
            {
                foreach (DataRow nodeRow in documents.Tables[0].Rows)
                {
                    if (PerformPublish(tree, nodeRow, cultureCode))
                    {
                        return;
                    }
                }
            }
            else
            {
                AddError(GetString("content.nothingtopublish", currentCulture));
            }
        }
        catch (ThreadAbortException ex)
        {
            if (!CMSThread.Stopped(ex))
            {
                // Log error
                LogExceptionToEventLog(GetString("content.publishfailed", currentCulture), ex);
            }
        }
        catch (Exception ex)
        {
            // Log error
            LogExceptionToEventLog(GetString("content.publishfailed", currentCulture), ex);
        }
    }
        private WhereCondition GetProcessingTypesWhere()
        {
            var whereCondition = new WhereCondition();
            var selectedTypes  = GetSelectedTypes();

            if (selectedTypes.Any())
            {
                whereCondition.WhereIn("CoffeeProcessing", selectedTypes);
            }

            return(whereCondition);
        }
Example #16
0
    /// <summary>
    /// Returns <see cref="WhereCondition"/> for filtering global roles.
    /// </summary>
    /// <param name="roles">Role names</param>
    private WhereCondition GetGlobalRolesCondition(string[] roles)
    {
        var globalRolesCondition = new WhereCondition();
        var globalRoles          = roles.Where(item => item.StartsWith(".", StringComparison.OrdinalIgnoreCase)).Select(item => item.TrimStart('.')).ToArray();

        if (!globalRoles.Any())
        {
            return(globalRolesCondition);
        }

        return(globalRolesCondition.WhereIn("RoleName", globalRoles).WhereNull("SiteID"));
    }
Example #17
0
    /// <summary>
    /// Restores documents selected in UniGrid.
    /// </summary>
    private void Restore(object parameter)
    {
        try
        {
            // Begin log
            AddLog(ResHelper.GetString("Recyclebin.RestoringDocuments", mCurrentCulture));
            BinSettingsContainer settings = (BinSettingsContainer)parameter;
            DataSet recycleBin            = null;
            switch (settings.CurrentWhat)
            {
            case What.AllDocuments:
                DateTime modifiedFrom = DateTimeHelper.ZERO_TIME;
                DateTime modifiedTo   = DateTimeHelper.ZERO_TIME;
                SetDocumentAge(ref modifiedFrom, ref modifiedTo);
                recycleBin = VersionHistoryInfoProvider.GetRecycleBin((mSelectedSite != null) ? mSelectedSite.SiteID : 0, 0, GetWhereCondition(filter.WhereCondition), "CMS_VersionHistory.DocumentNamePath ASC", -1, "VersionHistoryID, CMS_VersionHistory.DocumentNamePath, CMS_VersionHistory.VersionDocumentName", modifiedFrom, modifiedTo);
                break;

            case What.SelectedDocuments:
                // Restore selected documents
                var toRestore = settings.SelectedItems;
                if ((toRestore != null) && (toRestore.Count > 0))
                {
                    string where = new WhereCondition().WhereIn("VersionHistoryID", toRestore).ToString(true);
                    recycleBin   = VersionHistoryInfoProvider.GetRecycleBin(0, 0, where, "CMS_VersionHistory.DocumentNamePath ASC", -1, "VersionHistoryID, CMS_VersionHistory.DocumentNamePath, CMS_VersionHistory.VersionDocumentName");
                }
                break;
            }

            if (!DataHelper.DataSourceIsEmpty(recycleBin))
            {
                RestoreDataSet(settings.User, recycleBin);
            }
        }
        catch (ThreadAbortException ex)
        {
            if (CMSThread.Stopped(ex))
            {
                // When canceled
                CurrentInfo = ResHelper.GetString("Recyclebin.RestorationCanceled", mCurrentCulture);
                AddLog(CurrentInfo);
            }
            else
            {
                // Log error
                LogException("RESTOREDOC", ex);
            }
        }
        catch (Exception ex)
        {
            // Log error
            LogException("RESTOREDOC", ex);
        }
    }
Example #18
0
    private DataSet gridTasks_OnDataReload(string completeWhere, string currentOrder, int currentTopN, string columns, int currentOffset, int currentPageSize, ref int totalRecords)
    {
        completeWhere = new WhereCondition(completeWhere).And().WhereIn("TaskID", TaskGroupTaskInfoProvider.GetTaskGroupTasks().WhereEquals("TaskGroupID", CurrentTaskGroup.TaskGroupID).Column("TaskID")).ToString(true);

        // Get the tasks
        var tasksQuery = StagingTaskInfoProvider.SelectTaskList(CurrentSiteID, SelectedServerID, completeWhere, currentOrder, currentTopN, columns, currentOffset, currentPageSize);
        var result     = tasksQuery.Result;

        totalRecords = tasksQuery.TotalRecords;

        return(result);
    }
Example #19
0
    /// <summary>
    /// Adds role condition to given <paramref name="whereCondition"/>.
    /// </summary>
    private void AddRoleCondition(WhereCondition whereCondition)
    {
        var assignedRolesSelectionMode   = drpTypeSelectInRoles.SelectedValue;
        var unassignedRolesSelectionMode = drpTypeSelectNotInRoles.SelectedValue;

        var assignedRoles   = selectRoleElem.Value.ToString();
        var unassignedRoles = selectNotInRole.Value.ToString();

        whereCondition
        .Where(GetRolesSelectorCondition(assignedRolesSelectionMode, assignedRoles))
        .WhereNot(GetRolesSelectorCondition(unassignedRolesSelectionMode, unassignedRoles));
    }
Example #20
0
    /// <summary>
    /// Returns complete WHERE condition.
    /// </summary>
    protected WhereCondition GetCompleteWhereCondition()
    {
        var allRecords = UniSelector.US_ALL_RECORDS.ToString();

        var customWhere = ValidationHelper.GetString(GetValue("WhereCondition"), "");

        var where = new WhereCondition();

        // Do not select product options and select only enabled products
        where.WhereNull("SKUOptionCategoryID")
        .WhereTrue("SKUEnabled");

        // Get products only with specified public status
        if (!String.IsNullOrEmpty(ProductPublicStatusName) && (ProductPublicStatusName != allRecords))
        {
            var pStatusSiteID = ECommerceSettings.UseGlobalPublicStatus(SiteName) ? 0 : SiteInfoProvider.GetSiteID(SiteName);
            where.WhereEquals("SKUPublicStatusID",
                              new IDQuery <PublicStatusInfo>("PublicStatusID")
                              .WhereEquals("PublicStatusSiteID".AsColumn().IsNull(0), pStatusSiteID)
                              .WhereEquals("PublicStatusName", ProductPublicStatusName)
                              .TopN(1)
                              );
        }

        // Get products only with specified internal status
        if (!String.IsNullOrEmpty(ProductInternalStatusName) && (ProductInternalStatusName != allRecords))
        {
            var iStatusSiteID = ECommerceSettings.UseGlobalInternalStatus(SiteName) ? 0 : SiteInfoProvider.GetSiteID(SiteName);
            where.WhereEquals("SKUInternalStatusID",
                              new IDQuery <InternalStatusInfo>("InternalStatusID")
                              .WhereEquals("InternalStatusSiteID".AsColumn().IsNull(0), iStatusSiteID)
                              .WhereEquals("InternalStatusName", ProductInternalStatusName)
                              .TopN(1)
                              );
        }

        // Get products only from specified department
        if (!String.IsNullOrEmpty(ProductDepartmentName) && (ProductDepartmentName != allRecords))
        {
            var dept = DepartmentInfoProvider.GetDepartmentInfo(ProductDepartmentName, SiteName);

            var departmentID = (dept != null) ? dept.DepartmentID : 0;
            where.WhereEquals("SKUDepartmentID", departmentID);
        }

        // Include user custom WHERE condition
        if (customWhere.Trim() != "")
        {
            where.Where(customWhere);
        }

        return(where);
    }
Example #21
0
        /// <summary>
        /// Update
        /// </summary>
        /// <param name="updated"></param>
        /// <param name="wheres"></param>
        /// <returns></returns>
        public override BaseHelper Set(Dictionary <string, object> updated, Dictionary <string, object> wheres)
        {
            Dictionary <string, Column> cols = CurrentTable.Columns;

            StringBuffer        _valueNames = string.Empty;
            List <SqlParameter> _parameters = new List <SqlParameter>();

            foreach (KeyValuePair <string, Column> kv in cols)
            {
                string colName = kv.Key;
                Column col     = kv.Value;

                //在传入obj中存在数据
                if (updated.ContainsKey(colName))
                {
                    SqlParameter param = makeParam(col, updated[colName]);
                    _parameters.Add(param);

                    _valueNames += colName + "=" + param.ParameterName + ",";
                }
            }


            WhereCondition whereObj = MakeWhere(wheres);

            //合并2个params
            int n = _parameters.Count;
            int m = whereObj.Params.Length;

            SqlParameter[] paramx = new SqlParameter[n + m];
            _parameters.CopyTo(paramx);
            whereObj.Params.CopyTo(paramx, n);

            StringBuffer sql = new StringBuffer();            //"Update " + Schema + CurrentTable.Name + " Set " + _valueNames.ToString(0, _valueNames.Length - 1) + " " + whereObj.WhereSql + " ; ";

            sql.AppendFormat("UPDATE {0}{1} SET {2} {3} ;", Schema, CurrentTable.Name, _valueNames.ToString(0, _valueNames.Length - 1), whereObj.WhereSql);

//			HttpContext.Current.Response.Write("<hr>"+sql +  "<hr>"+paramx.Length+"<hr>");
//			for (int i = 0; i < paramx.Length ; i++){
//				HttpContext.Current.Response.Write("<hr>"+paramx[i].ParameterName +  "<hr>"+paramx[i].Value+"<hr>");
//			}
//			return this;

            if (inTrans)
            {
                return(SetTrans(sql, paramx));
            }
            else
            {
                int v = dac.ExecuteNonQuery(sql, paramx);
                return(End(v, sql));
            }
        }
Example #22
0
        private WhereBuilder AddCondition(WhereCondition condition)
        {
            condition.IsNot = _not;
            condition.IsOr  = _or;

            _or  = false;
            _not = false;

            _whereConditions.Add(condition);

            return(this);
        }
        public void VerifyNotAllowedTrailingOperatorsThrowsException()
        {
            // Arrange
            var condition = new WhereCondition();

            condition.AddSegment(new WhereCondition.Condition("Entity", WhereCondition.ComparisonType.Equal, 42));
            condition.AddSegment(WhereCondition.Operator.And);


            // Act & Assert
            Should.Throw <InvalidSqlStatementException>(() => condition.GenerateQuery());
        }
Example #24
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));
    }
    /// <summary>
    /// Gets where condition.
    /// </summary>
    public override string GetWhereCondition()
    {
        EnsureChildControls();

        DateTime dateFrom  = dtmTimeFrom.SelectedDateTime;
        DateTime dateTo    = dtmTimeTo.SelectedDateTime;
        string   fieldName = (FieldInfo != null) ? FieldInfo.Name : Field;

        string where = null;

        if (String.IsNullOrEmpty(WhereConditionFormat))
        {
            // Get default where condition
            WhereCondition condition = null;

            if (dateFrom != DateTimeHelper.ZERO_TIME)
            {
                condition = new WhereCondition(fieldName, QueryOperator.GreaterOrEquals, dateFrom);
            }

            if (dateTo != DateTimeHelper.ZERO_TIME)
            {
                if (condition == null)
                {
                    condition = new WhereCondition();
                }

                condition.And().WhereLessOrEquals(fieldName, dateTo);
            }

            if (condition != null)
            {
                where = condition.ToString(true);
            }
        }
        else
        {
            if (dateFrom != DateTimeHelper.ZERO_TIME)
            {
                // Add "from date" where condition
                where = String.Format(WhereConditionFormat, fieldName, dateFrom.ToString(CultureHelper.EnglishCulture), ">=");
            }

            if (dateTo != DateTimeHelper.ZERO_TIME)
            {
                // Add "to date" where condition
                where = SqlHelper.AddWhereCondition(where, String.Format(WhereConditionFormat, fieldName, dateTo.ToString(CultureHelper.EnglishCulture), "<="));
            }
        }

        return(where);
    }
Example #26
0
    protected DataSet gridTasks_OnDataReload(string completeWhere, string currentOrder, int currentTopN, string columns, int currentOffset, int currentPageSize, ref int totalRecords)
    {
        // Get the tasks
        string where = GetSiteWhere();
        WhereCondition mergedWhere = new WhereCondition(completeWhere).And().Where(where);

        var tasksQuery = StagingTaskInfoProvider.SelectObjectTaskList(CurrentSiteID, SelectedServerID, objectType, mergedWhere.ToString(true), currentOrder, currentTopN, columns, currentOffset, currentPageSize);
        var result     = tasksQuery.Result;

        totalRecords = tasksQuery.TotalRecords;

        return(result);
    }
Example #27
0
        private WhereCondition GetStatusWhereCondition()
        {
            var where = new WhereCondition();

            var selectedStatusIds = GetSelectedStatusIds();

            if (selectedStatusIds.Any())
            {
                where.WhereIn("SKUPublicStatusID", selectedStatusIds);
            }

            return(where);
        }
Example #28
0
 private void GetStagingTasksByUser(WhereCondition where, int selected)
 {
     if (selected > 0)
     {
         // Get tasks for current user
         where.WhereIn("TaskID", StagingTaskUserInfoProvider.GetTaskUsers().WhereEquals("UserID", selected).Column("TaskID"));
     }
     else if (selected == UniSelector.US_NONE_RECORD)
     {
         // Get all tasks without any assigned user
         where.WhereNotIn("TaskID", StagingTaskUserInfoProvider.GetTaskUsers().Column("TaskID"));
     }
 }
Example #29
0
        public void WhereCondition_AisnotNULL()
        {
            WhereCondition wc = new WhereCondition()
            {
                Left     = "A",
                Operator = "IS NOT",
                Right    = "NULL"
            };
            string correctValue = "[A] IS NOT NULL";
            string testValue    = wc.Build();

            MyAssert.Equals(correctValue, testValue);
        }
Example #30
0
        public static IEnumerable <Guid> GetUuidsByCriteria(PartDataContext dataContext, SoegObjektType soegObject, int startIndex, int maxCount)
        {
            var elements = PersonRegistration.CreateXQueryElements(soegObject);

#if Mono
            var byCriteriaStr = WhereCondition.GetMatchingObjects <object>(dataContext, elements, "PersonRegistration", true, new string[] { "UUID" }, startIndex, maxCount, "UUID");
            var byCriteria    = byCriteriaStr.Select(o => new Guid(o.ToString()));
#else
            var byCriteria = WhereCondition.GetMatchingObjects <Guid>(dataContext, elements, "PersonRegistration", true, new string[] { "UUID" }, startIndex, maxCount, "UUID");
#endif

            return(byCriteria);
        }
    /// <summary>
    /// Gets where condition for selecting relationship names
    /// </summary>
    private WhereCondition GetRelationshipNameCondition()
    {
        var relationshipNameCondition = new WhereCondition();

        if (!UseAdHocRelationshipName)
        {
            relationshipNameCondition.Where(new WhereCondition().WhereFalse("RelationshipNameIsAdHoc").Or().WhereNull("RelationshipNameIsAdHoc"));
        }

        relationshipNameCondition.WhereEquals("RelationshipName", RelationshipName);

        return(relationshipNameCondition);
    }
Example #32
0
        private WhereCondition GetManufacturerWhereCondition()
        {
            var where = new WhereCondition();

            var selectedManufacturerIds = GetSelectedManufacturerIds();

            if (selectedManufacturerIds.Any())
            {
                where.WhereIn("SKUManufacturerID", selectedManufacturerIds);
            }

            return(where);
        }
Example #33
0
    /// <summary>
    /// Adds condition based on privilege level dropdown to given <paramref name="whereCondition"/>.
    /// </summary>
    /// <remarks>Logic in this method mirrors <see cref="UserInfo.SiteIndependentPrivilegeLevel"/> behavior to get correct condition.</remarks>
    private void AddPrivilegeLevelCondition(WhereCondition whereCondition)
    {
        string drpPrivilegeSelectedItemValue = drpPrivilege.SelectedItem.Value;

        if (drpPrivilegeSelectedItemValue == UniGrid.ALL)
        {
            return;
        }

        var privilegeLevel = drpPrivilegeSelectedItemValue.ToInteger(0);

        whereCondition.WhereEquals("UserPrivilegeLevel", privilegeLevel);
    }
    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(gridElem.WhereCondition)
                             .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.ClearSelectedItems();
        gridElem.ReloadData();
        pnlUpdate.Update();
    }
    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}");
    }
    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>
    /// Applies filter on associated UniGrid control.
    /// </summary>
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        string text = txtSearch.Text.Trim();
        if (!string.IsNullOrEmpty(text))
        {
            WhereCondition = new WhereCondition()
                .WhereContains("CompanyName", text)
                .ToString(true);
        }
        else
        {
            WhereCondition = null;
        }

        //Raise OnFilterChange event
        RaiseOnFilterChanged();
    }
    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;
    }
    private WhereCondition GetContactWhereCondition()
    {
        var contactWhere = new WhereCondition();
        ContactInfo contact;

        // Get primary contact WHERE condition
        if (CurrentAccount.AccountPrimaryContactID != 0)
        {
            contact = ContactInfoProvider.GetContactInfo(CurrentAccount.AccountPrimaryContactID);
            if (contact != null)
            {
                if (!String.IsNullOrEmpty(contact.ContactFirstName))
                {
                    contactWhere.Or().WhereContains("PrimaryContactFirstName", contact.ContactFirstName);
                }
                if (!String.IsNullOrEmpty(contact.ContactMiddleName))
                {
                    contactWhere.Or().WhereContains("PrimaryContactMiddleName", contact.ContactMiddleName);
                }
                if (!String.IsNullOrEmpty(contact.ContactLastName))
                {
                    contactWhere.Or().WhereContains("PrimaryContactLastName", contact.ContactLastName);
                }
            }
        }

        // Get secondary contact WHERE condition
        if (CurrentAccount.AccountSecondaryContactID != 0)
        {
            contact = ContactInfoProvider.GetContactInfo(CurrentAccount.AccountSecondaryContactID);
            if (contact != null)
            {
                if (!String.IsNullOrEmpty(contact.ContactFirstName))
                {
                    contactWhere.Or().WhereContains("SecondaryContactFirstName", contact.ContactFirstName);
                }
                if (!String.IsNullOrEmpty(contact.ContactMiddleName))
                {
                    contactWhere.Or().WhereContains("SecondaryContactMiddleName", contact.ContactMiddleName);
                }
                if (!String.IsNullOrEmpty(contact.ContactLastName))
                {
                    contactWhere.Or().WhereContains("SecondaryContactLastName", contact.ContactLastName);
                }
            }
        }
        return contactWhere;
    }
    /// <summary>
    /// Deletes document(s).
    /// </summary>
    private void Delete(object parameter)
    {
        if (parameter == null || nodeIds.Count < 1)
        {
            return;
        }

        if (!LicenseHelper.LicenseVersionCheck(RequestContext.CurrentDomain, FeatureEnum.Blogs, ObjectActionEnum.Edit))
        {
            AddError(ResHelper.GetString("cmsdesk.blogdeletelicenselimitations", currentCulture));
            return;
        }

        if (!LicenseHelper.LicenseVersionCheck(RequestContext.CurrentDomain, FeatureEnum.Documents, ObjectActionEnum.Edit))
        {
            AddError(ResHelper.GetString("cmsdesk.documentdeletelicenselimitations", currentCulture));
            return;
        }
        int refreshId = 0;

        TreeProvider tree = new TreeProvider(currentUser);
        tree.AllowAsyncActions = false;

        string[] parameters = ((string)parameter).Split(';');

        bool allLevelsSelected = ValidationHelper.GetBoolean(parameters[3], false);

        try
        {
            string siteName = parameters[1];
            bool isMultipleDelete = ValidationHelper.GetBoolean(parameters[2], false);

            // Prepare the where condition
            string where = new WhereCondition().WhereIn("NodeID", nodeIds).ToString(true);
            string columns = SqlHelper.MergeColumns(DocumentColumnLists.SELECTNODES_REQUIRED_COLUMNS, "NodeAliasPath, ClassName, DocumentCulture, NodeParentID");

            bool combineWithDefaultCulture = false;
            string cultureCode = parameters[0];

            switch (parameters[4])
            {
                // Standard page deletion
                case "documentoptions":
                    combineWithDefaultCulture = chkAllCultures.Checked;
                    cultureCode = combineWithDefaultCulture ? TreeProvider.ALL_CULTURES : parameters[0];
                    break;

                // Root page deletion
                case "rootoptions":
                    cultureCode = rblRoot.SelectedValue == "allpages" ? TreeProvider.ALL_CULTURES : parameters[0];
                    where = rblRoot.SelectedValue == "allculturepages" ? String.Empty : where;
                    break;
            }

            // Begin log
            AddLog(ResHelper.GetString("ContentDelete.DeletingDocuments", currentCulture));

            string orderBy = "NodeAliasPath DESC";
            if (cultureCode == TreeProvider.ALL_CULTURES)
            {
                // Default culture has to be selected on last position
                string defaultCulture = CultureHelper.GetDefaultCultureCode(siteName);
                orderBy += ", CASE WHEN DocumentCulture = '" + SqlHelper.EscapeQuotes(defaultCulture) + "' THEN 1 ELSE 0 END";
            }

            // Get the documents
            DataSet ds = tree.SelectNodes(siteName, "/%", cultureCode, combineWithDefaultCulture, null, where, orderBy, TreeProvider.ALL_LEVELS, false, 0, columns);
            if (!DataHelper.DataSourceIsEmpty(ds))
            {
                string altPath = Convert.ToString(selAltPath.Value);
                TreeNode altNode = null;
                if (chkUseDeletedPath.Checked && !String.IsNullOrEmpty(altPath))
                {
                    NodeSelectionParameters nsp = new NodeSelectionParameters();
                    nsp.AliasPath = altPath;
                    nsp.CultureCode = TreeProvider.ALL_CULTURES;
                    nsp.ClassNames = TreeProvider.ALL_CLASSNAMES;
                    nsp.CombineWithDefaultCulture = true;
                    nsp.SiteName = siteName;
                    nsp.MaxRelativeLevel = TreeProvider.ALL_LEVELS;
                    nsp.TopN = 1;

                    altNode = DocumentHelper.GetDocument(nsp, tree);

                    // Check whether user is authorized to use alternating document
                    if (altNode != null)
                    {
                        if (currentUser.IsAuthorizedPerDocument(altNode, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Denied)
                        {
                            throw new Exception(GetString("contentdelete.notallowedalternating"));
                        }
                    }
                    else
                    {
                        // Do not allow to delete a page with specified redirection URL which is not valid
                        throw new Exception(GetString("contentdelete.redirectionurlisnotvalid"));
                    }
                }

                // Delete the documents
                foreach (DataRow nodeRow in ds.Tables[0].Rows)
                {
                    // Get the current document
                    string className = nodeRow["ClassName"].ToString();
                    string aliasPath = nodeRow["NodeAliasPath"].ToString();
                    string docCulture = nodeRow["DocumentCulture"].ToString();
                    refreshId = ValidationHelper.GetInteger(nodeRow["NodeParentID"], 0);
                    if (refreshId == 0)
                    {
                        refreshId = ValidationHelper.GetInteger(nodeRow["NodeID"], 0);
                    }
                    TreeNode node = DocumentHelper.GetDocument(siteName, aliasPath, docCulture, false, className, null, null, TreeProvider.ALL_LEVELS, false, null, tree);

                    if (node == null)
                    {
                        AddLog(string.Format(ResHelper.GetString("ContentRequest.DocumentNoLongerExists", currentCulture), HTMLHelper.HTMLEncode(aliasPath)));
                        continue;
                    }

                    // Ensure current parent ID
                    int parentId = node.NodeParentID;

                    // Check if bound SKU can be deleted (if any)
                    bool authorizedToDeleteSKU = !node.HasSKU || IsUserAuthorizedToModifySKU(node);

                    // Check delete permissions
                    if (IsUserAuthorizedToDeleteDocument(node) && (CanDestroy(node) || !chkDestroy.Checked) && authorizedToDeleteSKU)
                    {
                        // Delete the document
                        if (parentId <= 0)
                        {
                            parentId = node.NodeID;
                        }

                        // Prepare settings for delete
                        var settings = new DeleteDocumentSettings(node, chkAllCultures.Checked, chkDestroy.Checked, tree);
                        bool skip = false;

                        // Add additional settings if alternating document is specified
                        if (altNode != null)
                        {
                            var nodeAliasPath = node.NodeAliasPath;
                            var altNodeAliasPath = altNode.NodeAliasPath;

                            // Skip deletion for pages which have alternative node as their child or itself
                            if (altNodeAliasPath.EqualsCSafe(nodeAliasPath, true) || altNodeAliasPath.StartsWithCSafe(nodeAliasPath.TrimEnd('/') + "/", true))
                            {
                                AddError(String.Format(GetString("contentdelete.redirectionurltosamepage"), HTMLHelper.HTMLEncode(node.NodeAliasPath)));
                                skip = true;
                            }
                            else
                            {
                                settings.AlternatingDocument = altNode;
                                settings.AlternatingDocumentCopyAllPaths = chkAltAliases.Checked;
                                settings.AlternatingDocumentMaxLevel = chkAltSubNodes.Checked ? -1 : node.NodeLevel;
                            }
                        }

                        // Delete document
                        refreshId = !skip && DocumentHelper.DeleteDocument(settings) || isMultipleDelete ? parentId : node.NodeID;
                    }
                    // Access denied - not authorized to delete the document
                    else
                    {
                        AddError(string.Format(ResHelper.GetString("cmsdesk.notauthorizedtodeletedocument", currentCulture), HTMLHelper.HTMLEncode(node.NodeAliasPath)));
                    }
                }
            }
            else
            {
                AddError(ResHelper.GetString("DeleteDocument.CultureNotExists", currentCulture));
            }
        }
        catch (ThreadAbortException ex)
        {
            if (CMSThread.Stopped(ex))
            {
                // When canceled
                ShowError(ResHelper.GetString("DeleteDocument.DeletionCanceled", currentCulture));
            }
            else
            {
                // Log error
                LogExceptionToEventLog(ex);
            }
        }
        catch (Exception ex)
        {
            // Log error
            LogExceptionToEventLog(ex);
        }
        finally
        {
            if (string.IsNullOrEmpty(CurrentError))
            {
                // Overwrite refreshId variable if sub-levels are visible
                if (allLevelsSelected && Parameters.ContainsKey("refreshnodeid"))
                {
                    refreshId = ValidationHelper.GetInteger(Parameters["refreshnodeid"], 0);
                }

                // Refresh tree or page (on-site editing)
                if (!RequiresDialog)
                {
                    ctlAsyncLog.Parameter = "RefreshTree(" + refreshId + ", " + refreshId + "); \n" + "SelectNode(" + refreshId + ");";
                }
                else
                {
                    // Go to the root by default
                    string url = URLHelper.ResolveUrl("~/");

                    // Update the refresh node id when set in the parent dialog
                    if (Parameters != null)
                    {
                        int refreshNodeId = ValidationHelper.GetInteger(Parameters["refreshnodeid"], 0);
                        if (refreshNodeId > 0)
                        {
                            refreshId = refreshNodeId;
                        }
                    }

                    // Try go to the parent document
                    if (refreshId > 0)
                    {
                        TreeProvider tp = new TreeProvider(MembershipContext.AuthenticatedUser);
                        TreeNode tn = DocumentHelper.GetDocument(refreshId, TreeProvider.ALL_CULTURES, tp);
                        if (tn != null)
                        {
                            url = URLHelper.ResolveUrl(DocumentURLProvider.GetUrl(tn));
                        }
                    }

                    ctlAsyncLog.Parameter = "window.refreshPageOnClose = true; window.reloadPageUrl = " + ScriptHelper.GetString(url) + "; CloseDialog();";
                }
            }
            else
            {
                ctlAsyncLog.Parameter = "RefreshTree(null, null);";
            }
        }
    }
    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>
    /// 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>
    /// Checks if page is not already assigned.
    /// </summary>
    /// <param name="filledVariantPath">Variant path filled in form</param>
    private void CheckDoublePageAssignment(string filledVariantPath)
    {
        string originalVariantPath = ValidationHelper.GetString(ABVariant.GetOriginalValue("ABVariantPath"), "");

        //Check if variantPath is changed
        if (originalVariantPath != filledVariantPath)
        {
            var condition = new WhereCondition()
                .WhereEquals("ABVariantTestID", ABTest.ABTestID)
                .WhereEquals("ABVariantPath", filledVariantPath);

            if (ABVariant.ABVariantID > 0)
            {
                condition.Where("ABVariantID", QueryOperator.NotEquals, ABVariant.ABVariantID);
            }

            var variants = ABVariantInfoProvider.GetVariants().Where(condition).TopN(1);
            if (variants.Any())
            {
                ShowError(GetString("abtesting.variantpath.alreadyassigned"));
                form.StopProcessing = true;
            }
        }
    }
Example #44
0
 /// <summary>
 /// Returns where condition based on parent product for variants.
 /// </summary>
 /// <param name="condition">Condition to restrict parent product.</param>
 private WhereCondition GetParentProductWhereCondition(WhereCondition condition)
 {
     return new WhereCondition().WhereNotNull("SKUParentSKUID").And().WhereIn("SKUParentSKUID", new IDQuery<SKUInfo>("SKUID").Where(condition));
 }
 /// <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);
 }
Example #46
0
 public Query AddWhere(WhereCondition condition, IPhrase phrase)
 {
     return Where(new Where(condition, phrase, ValueObjectType.Value, WhereComparision.None, null, ValueObjectType.Literal), false);
 }
Example #47
0
 public Query AddWhere(WhereCondition condition, object thisObject, ValueObjectType thisObjectType, WhereComparision comparison, object thatObject, ValueObjectType thatObjectType)
 {
     return Where(new Where(condition, thisObject, thisObjectType, comparison, thatObject, thatObjectType), false);
 }
 private WhereCondition GetAddressWhereCondition()
 {
     var addressWhere = new WhereCondition();
     if (!String.IsNullOrEmpty(CurrentAccount.AccountAddress1))
     {
         addressWhere.Or().WhereContains("AccountAddress1", CurrentAccount.AccountAddress1);
     }
     if (!String.IsNullOrEmpty(CurrentAccount.AccountAddress2))
     {
         addressWhere.Or().WhereContains("AccountAddress2", CurrentAccount.AccountAddress2);
     }
     if (!String.IsNullOrEmpty(CurrentAccount.AccountCity))
     {
         addressWhere.Or().WhereContains("AccountCity", CurrentAccount.AccountCity);
     }
     if (!String.IsNullOrEmpty(CurrentAccount.AccountZIP))
     {
         addressWhere.Or().WhereContains("AccountZIP", CurrentAccount.AccountZIP);
     }
     return addressWhere;
 }
    /// <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);
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        PageTitle.TitleText = GetString("newsletter_issue_openedby.title");
        issueId = QueryHelper.GetInteger("objectid", 0);
        if (issueId == 0)
        {
            RequestHelper.EndResponse();
        }

        IssueInfo issue = IssueInfoProvider.GetIssueInfo(issueId);
        EditedObject = issue;

        // 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 where = new WhereCondition();
        if (issueId > 0)
        {
            where.Where("IssueID", QueryOperator.Equals, issueId);
        }
        where.And(new WhereCondition(fltOpenedBy.WhereCondition));

        UniGrid.QueryParameters = where.Parameters;
        UniGrid.WhereCondition = where.WhereCondition;
        UniGrid.Pager.DefaultPageSize = PAGESIZE;
        UniGrid.Pager.ShowPageSize = false;
        UniGrid.FilterLimit = 1;
        UniGrid.OnExternalDataBound += UniGrid_OnExternalDataBound;
        UniGrid.OnBeforeDataReload += UniGrid_OnBeforeDataReload;
    }
Example #51
0
 public Query AddWhere(WhereCondition condition, string literalExpression)
 {
     return Where(new Where(condition, literalExpression, ValueObjectType.Literal, WhereComparision.None, null, ValueObjectType.Literal), false);
 }
 private WhereCondition GetPhoneWhereCondition()
 {
     var phoneWhere = new WhereCondition();
     if (!String.IsNullOrEmpty(CurrentAccount.AccountPhone))
     {
         phoneWhere.WhereContains("AccountPhone", CurrentAccount.AccountPhone);
     }
     if (!String.IsNullOrEmpty(CurrentAccount.AccountFax))
     {
         phoneWhere.Or().WhereContains("AccountFax", CurrentAccount.AccountFax);
     }
     return phoneWhere;
 }
Example #53
0
 public Query AddWhere(WhereCondition condition, WhereList whereList)
 {
     return Where(new Where(condition, whereList), false);
 }
    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);
    }
Example #55
0
 /// <summary>
 /// Returns where condition for a single column. It consider parent product for variants.
 /// </summary>
 /// <param name="column">Column to filter for.</param>
 /// <param name="condition">Condition to restrict.</param>
 private WhereCondition GetColumnWhereCondition(string column, WhereCondition condition)
 {
     return new WhereCondition().Where(condition.Or().WhereNull(column).And().Where(GetParentProductWhereCondition(condition)));
 }
    /// <summary>
    /// Creates WHERE condition for VersionObjectSiteID column.
    /// </summary>
    private WhereCondition GetVersionObjectSiteIDWhereCondition()
    {
        var where = new WhereCondition();
        if (IsSingleSite || (SiteName == "##global##"))
        {
            where.Where("VersionObjectSiteID", QueryUnaryOperator.IsNull);
        }

        if (CurrentSite != null)
        {
            where.Or().Where("VersionObjectSiteID", QueryOperator.Equals, CurrentSite.SiteID);
        }

        return where;
    }
Example #57
0
    /// <summary>
    /// Returns where condition based on webpart fields.
    /// </summary>
    private WhereCondition GetWhereCondition()
    {
        var where = new WhereCondition().WhereEquals("SKUSiteID", SiteContext.CurrentSiteID);

        // Show products only from current site or global too, based on setting
        if (ECommerceSettings.AllowGlobalProducts(SiteContext.CurrentSiteName))
        {
            where.Where(w => w.WhereEquals("SKUSiteID", SiteContext.CurrentSiteID).Or().WhereNull("SKUSiteID"));
        }

        // Show/hide product variants - it is based on type of inventory tracking for parent product
        string trackByVariants = TrackInventoryTypeEnum.ByVariants.ToStringRepresentation();
        where.Where(v => v.Where(w => w.WhereNull("SKUParentSKUID").And().WhereNotEquals("SKUTrackInventory", trackByVariants))
                          .Or()
                          .Where(GetParentProductWhereCondition(new WhereCondition().WhereEquals("SKUTrackInventory", trackByVariants))));

        // Product type filter
        if (!string.IsNullOrEmpty(ProductType) && (ProductType != FILTER_ALL))
        {
            if (ProductType == PRODUCT_TYPE_PRODUCTS)
            {
                where.WhereNull("SKUOptionCategoryID");
            }
            else if (ProductType == PRODUCT_TYPE_PRODUCT_OPTIONS)
            {
                where.WhereNotNull("SKUOptionCategoryID");
            }
        }

        // Representing filter
        if (!string.IsNullOrEmpty(Representing) && (Representing != FILTER_ALL))
        {
            SKUProductTypeEnum productTypeEnum = Representing.ToEnum<SKUProductTypeEnum>();
            string productTypeString = productTypeEnum.ToStringRepresentation();

            where.WhereEquals("SKUProductType", productTypeString);
        }

        // Product number filter
        if (!string.IsNullOrEmpty(ProductNumber))
        {
            where.WhereContains("SKUNumber", ProductNumber);
        }

        // Department filter
        DepartmentInfo di = DepartmentInfoProvider.GetDepartmentInfo(Department, CurrentSiteName);
        di = di ?? DepartmentInfoProvider.GetDepartmentInfo(Department, null);

        if (di != null)
        {
            where.Where(GetColumnWhereCondition("SKUDepartmentID", new WhereCondition().WhereEquals("SKUDepartmentID", di.DepartmentID)));
        }

        // Manufacturer filter
        ManufacturerInfo mi = ManufacturerInfoProvider.GetManufacturerInfo(Manufacturer, CurrentSiteName);
        mi = mi ?? ManufacturerInfoProvider.GetManufacturerInfo(Manufacturer, null);
        if (mi != null)
        {
            where.Where(GetColumnWhereCondition("SKUManufacturerID", new WhereCondition().WhereEquals("SKUManufacturerID", mi.ManufacturerID)));
        }

        // Supplier filter
        SupplierInfo si = SupplierInfoProvider.GetSupplierInfo(Supplier, CurrentSiteName);
        si = si ?? SupplierInfoProvider.GetSupplierInfo(Supplier, null);
        if (si != null)
        {
            where.Where(GetColumnWhereCondition("SKUSupplierID", new WhereCondition().WhereEquals("SKUSupplierID", si.SupplierID)));
        }

        // Needs shipping filter
        if (!string.IsNullOrEmpty(NeedsShipping) && (NeedsShipping != FILTER_ALL))
        {
            if (NeedsShipping == NEEDS_SHIPPING_YES)
            {
                where.Where(GetColumnWhereCondition("SKUNeedsShipping", new WhereCondition().WhereTrue("SKUNeedsShipping")));
            }
            else if (NeedsShipping == NEEDS_SHIPPING_NO)
            {
                where.Where(GetColumnWhereCondition("SKUNeedsShipping", new WhereCondition().WhereFalse("SKUNeedsShipping").Or().WhereNull("SKUNeedsShipping")));
            }
        }

        // Price from filter
        if (PriceFrom > 0)
        {
            where.WhereGreaterOrEquals("SKUPrice", PriceFrom);
        }

        // Price to filter
        if (PriceTo > 0)
        {
            where.WhereLessOrEquals("SKUPrice", PriceTo);
        }

        // Public status filter
        PublicStatusInfo psi = PublicStatusInfoProvider.GetPublicStatusInfo(PublicStatus, CurrentSiteName);
        if (psi != null)
        {
            where.Where(GetColumnWhereCondition("SKUPublicStatusID", new WhereCondition().WhereEquals("SKUPublicStatusID", psi.PublicStatusID)));
        }

        // Internal status filter
        InternalStatusInfo isi = InternalStatusInfoProvider.GetInternalStatusInfo(InternalStatus, CurrentSiteName);
        if (isi != null)
        {
            where.Where(GetColumnWhereCondition("SKUInternalStatusID", new WhereCondition().WhereEquals("SKUInternalStatusID", isi.InternalStatusID)));
        }

        // Allow for sale filter
        if (!string.IsNullOrEmpty(AllowForSale) && (AllowForSale != FILTER_ALL))
        {
            if (AllowForSale == ALLOW_FOR_SALE_YES)
            {
                where.WhereTrue("SKUEnabled");
            }
            else if (AllowForSale == ALLOW_FOR_SALE_NO)
            {
                where.WhereEqualsOrNull("SKUEnabled", false);
            }
        }

        // Available items filter
        if (!string.IsNullOrEmpty(AvailableItems))
        {
            int value = ValidationHelper.GetInteger(AvailableItems, int.MaxValue);
            where.WhereLessOrEquals("SKUAvailableItems", value);
        }

        // Needs to be reordered filter
        if (NeedsToBeReordered)
        {
            where.Where(w => w.Where(v => v.WhereNull("SKUReorderAt").And().WhereLessOrEquals("SKUAvailableItems", 0))
                              .Or()
                              .Where(z => z.WhereNotNull("SKUReorderAt").And().WhereLessOrEquals("SKUAvailableItems".AsColumn(), "SKUReorderAt".AsColumn())));
        }

        return where;
    }
    /// <summary>
    /// Merges given where condition with additional settings.
    /// </summary>
    /// <param name="where">Original where condition</param>
    /// <returns>New where condition</returns>
    private WhereCondition GetWhereCondition(WhereCondition where)
    {
        // Create version condition
        var condition = new WhereCondition().WhereNotNull("VersionDeletedWhen");

        // Add recycle bin condition (ensure correct parentheses wrapping)
        condition.Where(where);

        // 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;
    }
    /// <summary>
    /// Returns site condition for given site id.
    /// </summary>
    /// <param name="siteID">Site id</param>
    private static WhereCondition GetSiteCondition(int siteID)
    {
        var condition = new WhereCondition();

        switch (siteID)
        {
            case UniSelector.US_GLOBAL_RECORD:
                condition.WhereNull("StateSiteID");
                break;

            case UniSelector.US_ALL_RECORDS:
            case UniSelector.US_NONE_RECORD:
                break;

            default:
                condition.WhereEquals("StateSiteID", siteID);
                break;
        }

        return condition;
    }
    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();
    }