/// <summary>
    /// Gets current where condition.
    /// </summary>
    /// <returns>Where condition determining documents to process</returns>
    private string GetCurrentWhere()
    {
        var documentIds = docElem.UniGrid.SelectedItems;

        // Prepare the where condition
        var condition = new WhereCondition();

        if (mCurrentWhat == What.SelectedDocuments)
        {
            // Get where for selected documents
            condition.WhereIn("DocumentID", documentIds.ToList());
        }
        else
        {
            if (!string.IsNullOrEmpty(filterDocuments.WhereCondition))
            {
                // Add filter condition
                condition.Where(filterDocuments.WhereCondition);
            }

            // Select documents only under current workflow
            condition.WhereIn("DocumentWorkflowStepID", new IDQuery <WorkflowStepInfo>().WhereEquals("StepWorkflowID", WorkflowId));
        }
        return(condition.ToString(true));
    }
Ejemplo n.º 2
0
    /// <summary>
    /// Mass action 'ok' button clicked.
    /// </summary>
    protected void btnOk_Click(object sender, EventArgs e)
    {
        CheckModifyPermissions();

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

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

        switch (what)
        {
        // All items
        case What.All:
            var accountIds = AccountInfoProvider.GetAccounts()
                             .Where(gridElem.WhereCondition)
                             .Where(gridElem.WhereClause)
                             .AsIDQuery();

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

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

        default:
            return;
        }

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

        default:
            return;
        }

        // Reload unigrid
        gridElem.ClearSelectedItems();
        gridElem.ReloadData();
        pnlUpdate.Update();
    }
Ejemplo n.º 3
0
    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 = ContactInfo.Provider.Get()
                             .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);
            break;

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

        case Action.StartNewProcess:
        {
            var eventArgument = Request.Params.Get("__EVENTARGUMENT");

            if (eventArgument != START_PROCESS_CONFIRMED)
            {
                ShowStartProcessConfirmation(what);
                return;
            }

            StartNewProcess(what, where);
            break;
        }

        default:
            return;
        }

        // Reload unigrid
        gridElem.ResetSelection();
        gridElem.ReloadData();
        pnlUpdate.Update();
    }
    /// <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));
    }
Ejemplo n.º 5
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));
    }
Ejemplo n.º 6
0
    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();
    }
Ejemplo n.º 7
0
    private DataSet GetRecycleBinSeletedItems(BinSettingsContainer settings, string columns)
    {
        var where = new WhereCondition();

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

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

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

        return(ObjectVersionHistoryInfoProvider.GetRecycleBin(where.ToString(true), OrderBy, -1, columns));
    }
    /// <summary>
    /// Gets WHERE condition to retrieve available sites according specified type.
    /// </summary>
    private string GetSitesWhere()
    {
        WhereCondition condition = new WhereCondition().WhereEquals("SiteStatus", SiteStatusEnum.Running.ToStringRepresentation());

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

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

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

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

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

        string notTargetLanguage = null;

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

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

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

        selectTargetCultureElem.AdditionalWhereCondition = condition.ToString(true);
    }
Ejemplo n.º 10
0
    /// <summary>
    /// Reloads the data in the selector.
    /// </summary>
    /// <param name="reloadUniSelector">If true, UniSelector is also reloaded</param>
    public void ReloadData(bool reloadUniSelector = false)
    {
        uniSelector.IsLiveSite = IsLiveSite;
        var where = new WhereCondition();

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

        if (mSiteId != null)
        {
            where.WhereIn("ClassID", ClassSiteInfo.Provider.Get().Column("ClassID").WhereEquals("SiteID", mSiteId));
        }

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

        uniSelector.WhereCondition = where.ToString(true);

        if (reloadUniSelector)
        {
            uniSelector.Reload(true);
        }
    }
Ejemplo n.º 11
0
    /// <summary>
    /// Returns where condition filtering ShippingAddress, Country and State.
    /// </summary>
    private void AddCountryWhereCondition(WhereCondition where)
    {
        var addressWhere = new IDQuery <AddressInfo>();

        string[] split = ShippingCountry.Split(';');

        if ((split.Length >= 1) && (split.Length <= 2))
        {
            // Country filter
            var country = CountryInfoProvider.GetCountryInfo(split[0]);
            if (country != null)
            {
                addressWhere.WhereEquals("AddressCountryID", country.CountryID);

                if (split.Length == 2)
                {
                    // State filter
                    var state = StateInfoProvider.GetStateInfo(split[1]);
                    if (state != null)
                    {
                        addressWhere.WhereEquals("AddressStateID", state.StateID);
                    }
                }
            }
        }

        where.WhereIn("OrderShippingAddressID", addressWhere);
    }
Ejemplo n.º 12
0
    /// <summary>
    /// Initializes the selector.
    /// </summary>
    public void InitSelector()
    {
        uniSelector.IsLiveSite = IsLiveSite;

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

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

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

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

        where = new WhereCondition(where);

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

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

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

        uniSelector.WhereCondition = where.ToString(true);
    }
Ejemplo n.º 13
0
    /// <summary>
    /// Adds user condition to given <see paramref="whereCondition"/>.
    /// </summary>
    private void AddUserCondition(WhereCondition whereCondition, int siteID)
    {
        whereCondition.WhereGreaterThan("UserID", 0);

        if (siteID > 0)
        {
            whereCondition.WhereIn("UserID", UserSiteInfoProvider.GetUserSites()
                                   .Column("UserID")
                                   .WhereEquals("SiteID", siteID));
        }

        if (chkDisplayHidden.Visible && !chkDisplayHidden.Checked)
        {
            whereCondition.WhereIn("UserID", UserInfoProvider.GetUsers()
                                   .Column("UserID")
                                   .WhereEquals("UserIsHidden", 0)
                                   .Or()
                                   .WhereNull("UserIsHidden"));
        }
    }
Ejemplo n.º 14
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"));
     }
 }
        private WhereCondition GetProcessingTypesWhere()
        {
            var whereCondition = new WhereCondition();
            var selectedTypes  = GetSelectedTypes();

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

            return(whereCondition);
        }
Ejemplo n.º 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"));
    }
Ejemplo n.º 17
0
        private WhereCondition GetStatusWhereCondition()
        {
            var where = new WhereCondition();

            var selectedStatusIds = GetSelectedStatusIds();

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

            return(where);
        }
Ejemplo n.º 18
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"));
     }
 }
Ejemplo n.º 19
0
    /// <summary>
    /// Adds user condition to given <see paramref="whereCondition"/>.
    /// </summary>
    private void AddUserCondition(ref WhereCondition whereCondition, int siteID)
    {
        var userCondition = new WhereCondition().WhereGreaterThan("UserID", 0);

        if (siteID > 0 && IncludeSiteCondition())
        {
            userCondition.WhereIn("UserID", UserSiteInfoProvider.GetUserSites()
                                  .Column("UserID")
                                  .WhereEquals("SiteID", siteID));
        }

        if (chkDisplayHidden.Visible && !chkDisplayHidden.Checked)
        {
            userCondition.WhereIn("UserID", UserInfoProvider.GetUsers()
                                  .Column("UserID")
                                  .WhereEquals("UserIsHidden", 0)
                                  .Or()
                                  .WhereNull("UserIsHidden"));
        }

        whereCondition = new WhereCondition(whereCondition, userCondition);
    }
Ejemplo n.º 20
0
        private WhereCondition GetManufacturerWhereCondition()
        {
            var where = new WhereCondition();

            var selectedManufacturerIds = GetSelectedManufacturerIds();

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

            return(where);
        }
    /// <summary>
    /// Returns where condition.
    /// </summary>
    /// <param name="customWhere">Custom WHERE condition</param>
    private WhereCondition GetWhereCondition(string customWhere)
    {
        SiteInfo si;

        var where = new WhereCondition();

        // Get required site data
        if (!String.IsNullOrEmpty(SiteName))
        {
            si = SiteInfoProvider.GetSiteInfo(SiteName);
        }
        else
        {
            si = SiteContext.CurrentSite;
        }

        if (si != null)
        {
            // Build where condition
            var classWhere = new WhereCondition();

            // Get documents of the specified class only - without coupled data !!!
            if (!String.IsNullOrEmpty(ClassNames))
            {
                string[] classNames = ClassNames.Trim(';').Split(';');
                foreach (string className in classNames)
                {
                    classWhere.WhereEquals("ClassName", className).Or();
                }
            }

            where.WhereIn("NodeSKUID", new IDQuery <OrderItemInfo>("OrderItemSKUID").Source(s => s.Join <SKUInfo>("OrderItemSKUID", "SKUID")
                                                                                            .Join <OrderInfo>("COM_OrderItem.OrderItemOrderID", "OrderID"))
                          .WhereTrue("SKUEnabled")
                          .WhereNull("SKUOptionCategoryID")
                          .WhereEquals("OrderSiteID", si.SiteID)
                          .Where(classWhere));

            // Add custom WHERE condition
            if (!String.IsNullOrEmpty(customWhere))
            {
                where.Where(customWhere);
            }
        }

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

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

            where.WhereIn(JoinTableLeftFieldName, query);
            return(where.ToString());
        }
        else
        {
            return(base.GetWhereCondition());
        }
    }
Ejemplo n.º 23
0
    /// <summary>
    /// Returns <see cref="WhereCondition"/> for filtering site roles.
    /// </summary>
    /// <param name="roles">Role names</param>
    private WhereCondition GetSiteRolesCondition(string[] roles)
    {
        var siteRolesCondition = new WhereCondition();
        var siteRoles          = roles.Where(item => !item.StartsWith(".", StringComparison.OrdinalIgnoreCase)).ToArray();

        if (!siteRoles.Any())
        {
            return(siteRolesCondition);
        }

        if (SelectedSite > 0)
        {
            siteRolesCondition.WhereEquals("SiteID", SelectedSite);
        }

        return(siteRolesCondition.WhereIn("RoleName", siteRoles));
    }
Ejemplo n.º 24
0
        /// <summary>
        /// Returns a where condition to correctly retrieve which manufacturers are selected in the filter.
        /// </summary>
        /// <param name="model">Model specifying all foreign objects and all filtered products.</param>
        /// <returns>Manufacturers selected in the filter.</returns>
        private WhereCondition GetManufacturersWhereCondition(ProductFilterViewModel model)
        {
            //DocSection:ForeignPropertyWhere
            // Initializes a new where condition
            WhereCondition manufacturersWhere = new WhereCondition();

            // Gets a list of strings representing display names of selected manufacturers
            List <string> selectedManufacturersIds = GetSelectedManufacturersIds(model);

            // If any manufacturer is selected, sets the where condition
            if (selectedManufacturersIds.Any())
            {
                manufacturersWhere.WhereIn("SKUManufacturerID", selectedManufacturersIds);
            }
            //EndDocSection:ForeignPropertyWhere

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

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

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

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

        selectCultureElem.AdditionalWhereCondition = condition.ToString(true);
    }
        //EndDocSection:GetManufacturers


        //DocSection:ForeignPropertyWhere
        /// <summary>
        /// Returns a where condition to correctly retrieve which manufacturers are selected in the filter.
        /// </summary>
        /// <param name="model">Model specifying all foreign objects and all filtered products.</param>
        private WhereCondition GetManufacturersWhereCondition(ProductFilterViewModel model)
        {
            // Initializes a new where condition
            WhereCondition manufacturersWhere = new WhereCondition();

            // Gets a list of manufacturers that were selected on the live site
            List <string> selectedManufacturersIds = model.Manufacturers
                                                     .Where(manufacturer => manufacturer.IsChecked)
                                                     .Select(manufacturer => manufacturer.Id)
                                                     .ToList();

            // If any manufacturer is selected, sets the where condition
            if (selectedManufacturersIds.Any())
            {
                manufacturersWhere.WhereIn("SKUManufacturerID", selectedManufacturersIds);
            }

            // Returns the where condition
            return(manufacturersWhere);
        }
    /// <summary>
    /// Builds a SQL condition for filtering the variant list, and returns it.
    /// </summary>
    /// <returns>A SQL condition for filtering the variant list.</returns>
    private WhereCondition GetFilterWhereCondition()
    {
        var condition = new WhereCondition();

        bool   allChecked          = AllCheckboxesChecked();
        string variantNameOrNumber = txtVariantNameNumber.Text;

        // If there are no options/categories in filter or all options are selected and Name-or-Number search box is empty, empty condition is returned
        if (((optionToCheckBoxMap.Keys.Count == 0) || allChecked) && (string.IsNullOrEmpty(variantNameOrNumber)))
        {
            return(condition);
        }

        foreach (KeyValuePair <int, List <int> > pair in SelectedOptionIDs)
        {
            // Option ids for current category (pair.Key = current category id)
            List <int> optionIds = pair.Value;

            // If there are no selected options in category, whole category is ignored
            if (optionIds.Count > 0)
            {
                // Where condition for selected options from current category
                condition.WhereIn("SKUID", new IDQuery <VariantOptionInfo>("VariantSKUID").WhereIn("OptionSKUID", optionIds));
            }
        }

        // Variants with SKUName or Number like text in textbox field
        if (!string.IsNullOrEmpty(variantNameOrNumber))
        {
            condition.Where(w => w.WhereContains("SKUNumber", variantNameOrNumber).Or().WhereContains("SKUName", variantNameOrNumber));
        }

        // Condition is empty -> not a single option is checked -> grid will be empty
        if (condition.WhereCondition == null)
        {
            condition.NoResults();
        }

        return(condition);
    }
Ejemplo n.º 28
0
        public override string GetWhereCondition()
        {
            var whereCondition = new WhereCondition();
            var originalQuery  = fltCountry.WhereCondition;

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

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

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

            return(whereCondition.ToString(true));
        }
        /// <summary>
        /// Returns an enumerable collection of products ordered by the date of publication.
        /// If no recommendation provided, top <paramref name="count"/> products is returned.
        /// </summary>
        /// <param name="filter">Instance of a product filter.</param>
        /// <param name="count">The number of products to return. Use 0 as value to return all records.</param>
        /// <returns>An enumerable collection that contains the specified number of products.</returns>
        public IEnumerable <SKUTreeNode> GetRecommendedProducts(IList <Guid> recommendations, int count = 4)
        {
            AddMissingRecommendations(recommendations, count);

            var recommendationWhere = new WhereCondition();

            if (recommendations.Any())
            {
                recommendationWhere.WhereIn("DocumentGuid", recommendations);
            }

            return(DocumentHelper.GetDocuments()
                   .Published()
                   .OnSite(SiteContext.CurrentSiteName)
                   .Culture("en-us")
                   .CombineWithDefaultCulture()
                   .TopN(count)
                   .WhereTrue("SKUEnabled")
                   .Where(recommendationWhere)
                   .OrderByDescending("SKUInStoreFrom")
                   .OfType <SKUTreeNode>()
                   .ToList());
        }
    /// <summary>
    /// Builds a SQL condition for filtering the order list, and returns it.
    /// </summary>
    /// <returns>A SQL condition for filtering the order list.</returns>
    private WhereCondition GetFilterWhereCondition()
    {
        var condition = new WhereCondition();

        // Order status
        if (statusSelector.SelectedID > 0)
        {
            condition.WhereEquals("OrderStatusID", statusSelector.SelectedID);
        }

        // Order site
        if (FilterSiteID > 0)
        {
            condition.WhereEquals("OrderSiteID", FilterSiteID);
        }

        // Order identifier
        string filterOrderId = txtOrderId.Text.Trim().Truncate(txtOrderId.MaxLength);
        if (filterOrderId != String.Empty)
        {
            int orderId = ValidationHelper.GetInteger(filterOrderId, 0);
            // Include also an invoice number
            condition.Where(w => w.WhereEquals("OrderID", orderId).Or().WhereContains("OrderInvoiceNumber", filterOrderId));
        }

        // Customer's properties, applicable only if a valid customer is not specified
        if (CustomerFilterEnabled)
        {
            // First, Last name and Company search
            string customerNameOrCompany = txtCustomerNameOrCompany.Text.Trim().Truncate(txtCustomerNameOrCompany.MaxLength);
            if (customerNameOrCompany != String.Empty)
            {
                condition.WhereIn("OrderCustomerID", new IDQuery<CustomerInfo>("CustomerID").WhereContains("CustomerFirstName", customerNameOrCompany)
                                                                                .Or()
                                                                                .WhereContains("CustomerLastName", customerNameOrCompany)
                                                                                .Or()
                                                                                .WhereContains("CustomerCompany", customerNameOrCompany));
            }
        }

        // Order is paid
        switch (drpOrderIsPaid.SelectedValue)
        {
            case "0":
                condition.Where("ISNULL(OrderIsPaid, 0) = 0");
                break;
            case "1":
                condition.Where("ISNULL(OrderIsPaid, 0) = 1");
                break;
        }

        // Advanced Filter
        if (AdvancedFilterEnabled)
        {
            // Specific currency was selected
            if (CurrencySelector.SelectedID > 0)
            {
                condition.WhereEquals("OrderCurrencyID", CurrencySelector.SelectedID);
            }

            // Specific payment method was selected
            if (PaymentSelector.SelectedID > 0)
            {
                condition.WhereEquals("OrderPaymentOptionID", PaymentSelector.SelectedID);
            }

            // Specific shipping option was selected
            if (ShippingSelector.SelectedID > 0)
            {
                condition.WhereEquals("OrderShippingOptionID", ShippingSelector.SelectedID);
            }

            // Specific tracking number was provided
            var trackingNumber = txtTrackingNumber.Text.Truncate(txtTrackingNumber.MaxLength);
            if (trackingNumber != string.Empty)
            {
                condition.WhereContains("OrderTrackingNumber", trackingNumber);
            }

            // Specific created date was selected
            if ((dtpCreatedTo.SelectedDateTime < dtpCreatedTo.MaxDate) && (dtpCreatedTo.SelectedDateTime > dtpCreatedTo.MinDate))
            {
                condition.WhereLessOrEquals("OrderDate", dtpCreatedTo.SelectedDateTime);
            }

            // Specific from date was selected
            if ((dtpFrom.SelectedDateTime < dtpFrom.MaxDate) && (dtpFrom.SelectedDateTime > dtpFrom.MinDate))
            {
                condition.WhereGreaterOrEquals("OrderDate", dtpFrom.SelectedDateTime);
            }
        }

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

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

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

                WhereCondition condition = new WhereCondition();

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

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

                UniGridRelationship.WhereCondition = condition.ToString(true);

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

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

                    if (!string.IsNullOrEmpty(action))
                    {
                        switch (action.ToLowerCSafe())
                        {
                            // Insert from 'Select document' dialog
                            case "insertfromselectdocument":
                                SaveRelationship();
                                break;
                        }
                    }
                }
            }
            else
            {
                bool inserted = QueryHelper.GetBoolean("inserted", false);
                if (inserted)
                {
                    ShowConfirmation(GetString("relationship.wasadded"));
                }
            }
        }
    }
    /// <summary>
    /// Gets current where condition.
    /// </summary>
    /// <returns>Where condition determining documents to process</returns>
    private string GetCurrentWhere()
    {
        List<string> documentIds = docElem.UniGrid.SelectedItems;

        // Prepare the where condition
        WhereCondition condition = new WhereCondition();
        if (currentWhat == What.SelectedDocuments)
        {
            // Get where for selected documents
            condition.WhereIn("DocumentID", documentIds);
        }
        else
        {
            if (!string.IsNullOrEmpty(filterDocuments.WhereCondition))
            {
                // Add filter condition
                condition.Where(filterDocuments.WhereCondition);
            }

            // Select documents only under current workflow
            condition.WhereIn("DocumentWorkflowStepID", new IDQuery<WorkflowStepInfo>().WhereEquals("StepWorkflowID", WorkflowId));
        }
        return condition.ToString(true);
    }
    /// <summary>
    /// Builds a SQL condition for filtering the variant list, and returns it.
    /// </summary>
    /// <returns>A SQL condition for filtering the variant list.</returns>
    private WhereCondition GetFilterWhereCondition()
    {
        var condition = new WhereCondition();

        bool allChecked = AllCheckboxesChecked();
        string variantNameOrNumber = txtVariantNameNumber.Text;

        // If there are no options/categories in filter or all options are selected and Name-or-Number search box is empty, empty condition is returned
        if (((optionToCheckBoxMap.Keys.Count == 0) || allChecked) && (string.IsNullOrEmpty(variantNameOrNumber)))
        {
            return condition;
        }

        foreach (KeyValuePair<int, List<int>> pair in SelectedOptionIDs)
        {
            // Option ids for current category (pair.Key = current category id)
            List<int> optionIds = pair.Value;

            // If there are no selected options in category, whole category is ignored
            if (optionIds.Count > 0)
            {
                // Where condition for selected options from current category
                condition.WhereIn("SKUID", new IDQuery<VariantOptionInfo>("VariantSKUID").WhereIn("OptionSKUID", optionIds));
            }
        }

        // Variants with SKUName or Number like text in textbox field
        if (!string.IsNullOrEmpty(variantNameOrNumber))
        {
            condition.Where(w => w.WhereContains("SKUNumber", variantNameOrNumber).Or().WhereContains("SKUName", variantNameOrNumber));
        }

        // Condition is empty -> not a single option is checked -> grid will be empty
        if (condition.WhereCondition == null)
        {
            condition.NoResults();
        }

        return condition;
    }
Ejemplo n.º 34
0
    /// <summary>
    /// Generates complete filter where condition.
    /// </summary>    
    private string GenerateWhereCondition()
    {
        var whereCondition = new WhereCondition();

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

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

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

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

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

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

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

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

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

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

        return whereCondition.ToString(true);
    }
    /// <summary>
    /// Gets WHERE condition for available sites according field configuration.
    /// </summary>
    private string GetSiteWhere()
    {
        // First check configuration
        WhereCondition condition = new WhereCondition();

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

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

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

        // Get only current user's sites
        if (!MembershipContext.AuthenticatedUser.IsGlobalAdministrator)
        {
            condition.WhereIn("SiteID", new IDQuery<UserSiteInfo>(UserSiteInfo.TYPEINFO.SiteIDColumn)
                                                    .WhereEquals("UserID", MembershipContext.AuthenticatedUser.UserID));
        }
        return condition.ToString(true);
    }
    /// <summary>
    /// Setups target language selector control.
    /// </summary>
    private void SetupTargetLanguageDropDownWhereCondition()
    {
        WhereCondition condition = new WhereCondition();

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

        string notTargetLanguage = null;

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

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

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

        selectTargetCultureElem.AdditionalWhereCondition = condition.ToString(true);
    }
    /// <summary>
    /// Returns where condition filtering ShippingAddress, Country and State.
    /// </summary>
    private void AddCountryWhereCondition(WhereCondition where)
    {
        var addressWhere = new IDQuery<AddressInfo>();

        string[] split = ShippingCountry.Split(';');

        if ((split.Length >= 1) && (split.Length <= 2))
        {
            // Country filter
            var country = CountryInfoProvider.GetCountryInfo(split[0]);
            if (country != null)
            {
                addressWhere.WhereEquals("AddressCountryID", country.CountryID);

                if (split.Length == 2)
                {
                    // State filter
                    var state = StateInfoProvider.GetStateInfo(split[1]);
                    if (state != null)
                    {
                        addressWhere.WhereEquals("AddressStateID", state.StateID);
                    }
                }
            }
        }

        where.WhereIn("OrderShippingAddressID", addressWhere);
    }
    /// <summary>
    /// Gets WHERE condition to retrieve available sites according specified type.
    /// </summary>
    private string GetSitesWhere()
    {
        WhereCondition condition = new WhereCondition().WhereEquals("SiteStatus", "RUNNING");

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

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

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

        return condition.ToString(true);
    }
Ejemplo n.º 39
0
    /// <summary>
    /// Returns where condition.
    /// </summary>
    /// <param name="customWhere">Custom WHERE condition</param>
    private WhereCondition GetWhereCondition(string customWhere)
    {
        SiteInfo si;
        var where = new WhereCondition();

        // Get required site data
        if (!String.IsNullOrEmpty(SiteName))
        {
            si = SiteInfoProvider.GetSiteInfo(SiteName);
        }
        else
        {
            si = SiteContext.CurrentSite;
        }

        if (si != null)
        {
            // Build where condition
            var classWhere = new WhereCondition();

            // Get documents of the specified class only - without coupled data !!!
            if (!String.IsNullOrEmpty(ClassNames))
            {
                string[] classNames = ClassNames.Trim(';').Split(';');
                foreach (string className in classNames)
                {
                    classWhere.WhereEquals("ClassName", className).Or();
                }
            }

            where.WhereIn("NodeSKUID", new IDQuery<OrderItemInfo>("OrderItemSKUID").Source(s => s.Join<SKUInfo>("OrderItemSKUID", "SKUID")
                                                                                   .Join<OrderInfo>("COM_OrderItem.OrderItemOrderID", "OrderID"))
                                                                                   .WhereTrue("SKUEnabled")
                                                                                   .WhereNull("SKUOptionCategoryID")
                                                                                   .WhereEquals("OrderSiteID", si.SiteID)
                                                                                   .Where(classWhere));

            // Add custom WHERE condition
            if (!String.IsNullOrEmpty(customWhere))
            {
                where.Where(customWhere);
            }
        }

        return where;
    }
    private void ReloadData()
    {
        if (StopProcessing)
        {
            // Do nothing
            gridDocs.StopProcessing = true;
            editDoc.StopProcessing  = true;
        }
        else
        {
            if (((AllowUsers == UserContributionAllowUserEnum.Authenticated) || (AllowUsers == UserContributionAllowUserEnum.DocumentOwner)) &&
                !AuthenticationHelper.IsAuthenticated())
            {
                // Not authenticated, do not display anything
                pnlList.Visible = false;
                pnlEdit.Visible = false;

                StopProcessing = true;
            }
            else
            {
                SetContext();

                // Hide document list
                gridDocs.Visible = false;

                // If the list of documents should be displayed ...
                if (DisplayList)
                {
                    // Get all documents of the current user
                    TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser);

                    // Generate additional where condition
                    WhereCondition condition = new WhereCondition(WhereCondition);

                    if (!String.IsNullOrEmpty(ClassNames))
                    {
                        condition.WhereIn("ClassName", ClassNames.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries));
                    }

                    // Add user condition
                    if (AllowUsers == UserContributionAllowUserEnum.DocumentOwner)
                    {
                        condition.WhereEquals("NodeOwner", MembershipContext.AuthenticatedUser.UserID);
                    }

                    // Get the documents
                    var query =
                        DocumentHelper.GetDocuments()
                        .OnSite(SiteName)
                        .Path(MacroResolver.ResolveCurrentPath(Path))
                        .Where(condition)
                        .OrderBy(OrderBy)
                        .Published(SelectOnlyPublished)
                        .NestingLevel(MaxRelativeLevel)
                        .CheckPermissions(CheckPermissions);

                    TreeProvider.SetQueryCultures(query, CultureCode, CombineWithDefaultCulture);

                    // Do not apply published from / to columns to make sure the published information is correctly evaluated
                    query.Properties.ExcludedVersionedColumns = new[] { "DocumentPublishFrom", "DocumentPublishTo" };

                    var ds = query.Result;

                    if (!DataHelper.DataSourceIsEmpty(ds))
                    {
                        // Display and initialize grid if datasource is not empty
                        gridDocs.Visible            = true;
                        gridDocs.DataSource         = ds;
                        gridDocs.OrderBy            = OrderBy;
                        editDoc.AlternativeFormName = AlternativeFormName;
                    }
                }

                bool isAuthorizedToCreateDoc = false;
                if (ParentNode != null)
                {
                    // Check if single class name is set
                    string className = (!string.IsNullOrEmpty(AllowedChildClasses) && !AllowedChildClasses.Contains(";")) ? AllowedChildClasses : null;

                    // Check user's permission to create new document if allowed
                    isAuthorizedToCreateDoc = !CheckPermissions || MembershipContext.AuthenticatedUser.IsAuthorizedToCreateNewDocument(ParentNodeID, className);
                    // Check group's permission to create new document if allowed
                    isAuthorizedToCreateDoc &= CheckGroupPermission("createpages");

                    if (!CheckDocPermissionsForInsert && CheckPermissions)
                    {
                        // If document permissions are not required check create permission on parent document
                        isAuthorizedToCreateDoc = MembershipContext.AuthenticatedUser.IsAuthorizedPerDocument(ParentNode, NodePermissionsEnum.Create) == AuthorizationResultEnum.Allowed;
                    }

                    if (AllowUsers == UserContributionAllowUserEnum.DocumentOwner)
                    {
                        if (VirtualContext.ReadonlyMode)
                        {
                            isAuthorizedToCreateDoc = false;
                        }
                        else
                        {
                            // Check if user is document owner (or global admin)
                            isAuthorizedToCreateDoc = isAuthorizedToCreateDoc &&
                                                      ((ParentNode.NodeOwner == MembershipContext.AuthenticatedUser.UserID) ||
                                                       MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin));
                        }
                    }
                }

                // Enable/disable inserting new document
                pnlNewDoc.Visible = (isAuthorizedToCreateDoc && AllowInsert);

                if (!gridDocs.Visible && !pnlNewDoc.Visible && pnlList.Visible)
                {
                    // Not authenticated to create new docs and grid is hidden
                    StopProcessing = true;
                }

                ReleaseContext();
            }
        }
    }
    /// <summary>
    /// Mass action 'ok' button clicked.
    /// </summary>
    protected void btnOk_Click(object sender, EventArgs e)
    {
        CheckModifyPermissions();

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

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

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

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

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

        // Reload unigrid
        gridElem.ResetSelection();
        gridElem.ReloadData();
        pnlUpdate.Update();
    }
    /// <summary>
    /// Setups target language drop down list control.
    /// </summary>
    private void SetupTargetLanguageDropDownWhereCondition()
    {
        WhereCondition condition = new WhereCondition().WhereNotEquals("CultureCode", DataHelper.GetNotEmpty(selectCultureElem.DropDownCultures.SelectedValue, defaultCulture));

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

        selectTargetCultureElem.AdditionalWhereCondition = condition.ToString(true);
    }
 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"));
     }
 }
 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>
    /// Translates document(s).
    /// </summary>
    private void Translate(object parameter)
    {
        if (parameter == null || nodeIds.Count < 1)
        {
            return;
        }

        int refreshId = 0;

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

        try
        {
            // Begin log
            AddLog(ResHelper.GetString("contentrequest.starttranslate", currentCulture));

            bool oneSubmission = chkSeparateSubmissions.Checked;

            // Prepare translation settings
            TranslationSettings settings = new TranslationSettings();
            settings.TargetLanguage = targetCulture;
            settings.TranslateWebpartProperties = SettingsKeyInfoProvider.GetBoolValue(SiteContext.CurrentSiteName + ".CMSTranslateWebpartProperties");
            settings.SourceLanguage = translationElem.FromLanguage;
            settings.Instructions = translationElem.Instructions;
            settings.Priority = translationElem.Priority;
            settings.TranslateAttachments = translationElem.ProcessBinary;
            settings.ProcessBinary = translationElem.ProcessBinary;
            settings.TranslationDeadline = translationElem.Deadline;
            settings.TranslationServiceName = translationElem.SelectedService;

            using (var tr = new CMSTransactionScope())
            {
                // Get the translation provider
                AbstractMachineTranslationService machineService = null;
                AbstractHumanTranslationService humanService = null;
                TranslationSubmissionInfo submission = null;
                TranslationServiceInfo ti = TranslationServiceInfoProvider.GetTranslationServiceInfo(translationElem.SelectedService);
                if (ti != null)
                {
                    // Set if we need target tag (Translations.com workaround)
                    settings.GenerateTargetTag = ti.TranslationServiceGenerateTargetTag;

                    if (oneSubmission)
                    {
                        if (ti.TranslationServiceIsMachine)
                        {
                            machineService = AbstractMachineTranslationService.GetTranslationService(ti, CurrentSiteName);
                        }
                        else
                        {
                            humanService = AbstractHumanTranslationService.GetTranslationService(ti, CurrentSiteName);
                        }
                    }

                    bool langSupported = true;
                    if (humanService != null)
                    {
                        if (!humanService.IsLanguageSupported(settings.TargetLanguage))
                        {
                            AddError(ResHelper.GetString("translationservice.targetlanguagenotsupported"));
                            langSupported = false;
                        }
                        else
                        {
                            submission = TranslationServiceHelper.CreateSubmissionInfo(settings, ti, MembershipContext.AuthenticatedUser.UserID, SiteContext.CurrentSiteID, "Page submission " + DateTime.Now);
                        }
                    }

                    if (langSupported)
                    {
                        if (!oneSubmission || (machineService != null) || (humanService != null))
                        {
                            const string columns = "NodeID, NodeAliasPath, DocumentCulture, NodeParentID";
                            string submissionFileName = "";
                            string submissionName = "";
                            int charCount = 0;
                            int wordCount = 0;
                            int docCount = 0;

                            // Prepare the where condition
                            var where = new WhereCondition().WhereIn("NodeID", nodeIds);

                            // Get the documents in target culture to be able to check if "Skip already translated" option is on
                            // Combine both, source and target culture (at least one hit has to be found - to find the source of translation)
                            where.WhereIn("DocumentCulture", new[] { settings.SourceLanguage, settings.TargetLanguage });

                            DataSet ds = tree.SelectNodes(SiteContext.CurrentSiteName, "/%", TreeProvider.ALL_CULTURES, true, null, where.ToString(true), "NodeAliasPath DESC", TreeProvider.ALL_LEVELS, false, 0, columns);
                            if (!DataHelper.DataSourceIsEmpty(ds))
                            {
                                List<int> processedNodes = new List<int>();

                                // Translate the documents
                                foreach (DataRow dr in ds.Tables[0].Rows)
                                {
                                    refreshId = ValidationHelper.GetInteger(dr["NodeParentID"], 0);
                                    int nodeId = ValidationHelper.GetInteger(dr["NodeID"], 0);

                                    if (!processedNodes.Contains(nodeId))
                                    {
                                        processedNodes.Add(nodeId);

                                        string aliasPath = ValidationHelper.GetString(dr["NodeAliasPath"], "");
                                        string culture = ValidationHelper.GetString(dr["DocumentCulture"], "");

                                        if (chkSkipTranslated.Checked)
                                        {
                                            if (culture == settings.TargetLanguage)
                                            {
                                                // Document already exists in requested culture, skip it
                                                AddLog(string.Format(ResHelper.GetString("content.translatedalready"), HTMLHelper.HTMLEncode(aliasPath + " (" + culture + ")")));
                                                continue;
                                            }
                                        }

                                        // Get document in source language
                                        TreeNode node = DocumentHelper.GetDocument(nodeId, settings.SourceLanguage, true, null);
                                        if (node == null)
                                        {
                                            // Document doesn't exist in source culture, skip it
                                            continue;
                                        }

                                        AddLog(string.Format(ResHelper.GetString("content.translating"), HTMLHelper.HTMLEncode(aliasPath + " (" + culture + ")")));

                                        // Save the first document as a base for submission name
                                        if (string.IsNullOrEmpty(submissionName))
                                        {
                                            submissionName = node.GetDocumentName();
                                        }
                                        if (string.IsNullOrEmpty(submissionFileName))
                                        {
                                            submissionFileName = node.NodeAlias;
                                        }

                                        docCount++;

                                        // Submit the document
                                        if (machineService != null)
                                        {
                                            TranslationServiceHelper.Translate(machineService, settings, node);
                                        }
                                        else
                                        {
                                            if (oneSubmission)
                                            {
                                                TreeNode targetNode = TranslationServiceHelper.CreateTargetCultureNode(node, settings.TargetLanguage, true, false, !settings.TranslateAttachments);
                                                TranslationSubmissionItemInfo submissionItem = TranslationServiceHelper.CreateSubmissionItemInfo(settings, submission, node, targetNode.DocumentID);

                                                charCount += submissionItem.SubmissionItemCharCount;
                                                wordCount += submissionItem.SubmissionItemWordCount;
                                            }
                                            else
                                            {
                                                TranslationServiceHelper.SubmitToTranslation(settings, node, out submission);
                                            }
                                        }
                                    }
                                }

                                if (docCount > 0)
                                {
                                    if (oneSubmission && (humanService != null))
                                    {
                                        AddLog(ResHelper.GetString("content.submitingtranslation"));

                                        // Set submission name
                                        int itemCount = docCount;
                                        if (itemCount > 1)
                                        {
                                            submissionName += " " + string.Format(GetString("translationservices.submissionnamesuffix"), itemCount - 1);
                                        }
                                        submission.SubmissionName = submissionName;
                                        submission.SubmissionCharCount = charCount;
                                        submission.SubmissionWordCount = wordCount;
                                        submission.SubmissionItemCount = itemCount;
                                        submission.SubmissionParameter = submissionFileName;

                                        string err = humanService.CreateSubmission(submission);
                                        if (!string.IsNullOrEmpty(err))
                                        {
                                            AddError(LocalizationHelper.GetString("ContentRequest.TranslationFailed") + " \"" + err + "\"");
                                        }

                                        // Save submission with ticket
                                        TranslationSubmissionInfoProvider.SetTranslationSubmissionInfo(submission);
                                    }
                                }
                                else
                                {
                                    TranslationSubmissionInfoProvider.DeleteTranslationSubmissionInfo(submission);
                                    AddError(ResHelper.GetString("TranslateDocument.DocumentsAlreadyTranslated", currentCulture));
                                }
                            }
                            else
                            {
                                TranslationSubmissionInfoProvider.DeleteTranslationSubmissionInfo(submission);
                                AddError(ResHelper.GetString("TranslateDocument.NoSourceDocuments", currentCulture));
                            }
                        }
                        else
                        {
                            AddError(ResHelper.GetString("TranslateDocument.TranslationServiceNotFound", currentCulture));
                        }
                    }
                }

                tr.Commit();
            }
        }
        catch (ThreadAbortException ex)
        {
            string state = ValidationHelper.GetString(ex.ExceptionState, string.Empty);
            if (state == CMSThread.ABORT_REASON_STOP)
            {
                // When canceled
                AddError(ResHelper.GetString("TranslateDocument.TranslationCanceled", currentCulture));
            }
            else
            {
                // Log error
                LogExceptionToEventLog(ex);
            }
        }
        catch (Exception ex)
        {
            // Log error
            LogExceptionToEventLog(ex);
        }
        finally
        {
            if (IsDialog)
            {
                ctlAsync.Parameter = "wopener.location.replace(wopener.location); CloseDialog(); wopener.RefreshTree(null, null);";
            }
            else
            {
                if (string.IsNullOrEmpty(CurrentError))
                {
                    // Overwrite refreshId variable if sub-levels are visible
                    if (ValidationHelper.GetBoolean(parameter, false) && Parameters.ContainsKey("refreshnodeid"))
                    {
                        refreshId = ValidationHelper.GetInteger(Parameters["refreshnodeid"], 0);
                    }

                    // Refresh tree
                    ctlAsync.Parameter = "RefreshTree(" + refreshId + ", " + refreshId + "); \n" + "SelectNode(" + refreshId + ");";
                }
                else
                {
                    ctlAsync.Parameter = "RefreshTree(null, null);";
                }
            }
        }
    }
    /// <summary>
    /// Reloads the data in the selector.
    /// </summary>
    /// <param name="reloadUniSelector">If true, UniSelector is also reloaded</param>
    public void ReloadData(bool reloadUniSelector = false)
    {
        uniSelector.IsLiveSite = IsLiveSite;
        var where = new WhereCondition();

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

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

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

        uniSelector.WhereCondition = where.ToString(true);

        if (reloadUniSelector)
        {
            uniSelector.Reload(true);
        }
    }
    /// <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>
    /// Returns where condition based on webpart fields.
    /// </summary>
    private WhereCondition GetWhereCondition()
    {
        // Orders from current site
        var where = new WhereCondition()
            .WhereEquals("OrderSiteID", SiteContext.CurrentSiteID);

        // Order status filter
        var status = OrderStatusInfoProvider.GetOrderStatusInfo(OrderStatus, SiteContext.CurrentSiteName);
        if (status != null)
        {
            where.WhereEquals("OrderStatusID", status.StatusID);
        }

        // Customer or company like filter
        if (!string.IsNullOrEmpty(CustomerOrCompany))
        {
            where.WhereIn("OrderCustomerID", new IDQuery<CustomerInfo>()
                .Where("CustomerFirstName + ' ' + CustomerLastName + ' ' + CustomerFirstName LIKE N'%"+ SqlHelper.EscapeLikeText(SqlHelper.EscapeQuotes(CustomerOrCompany)) + "%'")
                .Or()
                .WhereContains("CustomerCompany", CustomerOrCompany));
        }

        // Filter for orders with note
        if (HasNote)
        {
            where.WhereNotEmpty("OrderNote");
        }

        // Payment method filter
        var payment = PaymentOptionInfoProvider.GetPaymentOptionInfo(PaymentMethod, SiteContext.CurrentSiteName);
        if (payment != null)
        {
            where.WhereEquals("OrderPaymentOptionID", payment.PaymentOptionID);
        }

        // Payment status filter
        switch (PaymentStatus.ToLowerCSafe())
        {
            case PAY_STATUS_NOT_PAID:
                where.Where(new WhereCondition().WhereFalse("OrderIsPaid").Or().WhereNull("OrderIsPaid"));
                break;

            case PAY_STATUS_PAID:
                where.WhereTrue("OrderIsPaid");
                break;
        }

        // Currency filter
        var currencyObj = CurrencyInfoProvider.GetCurrencyInfo(Currency, SiteContext.CurrentSiteName);
        if (currencyObj != null)
        {
            where.WhereEquals("OrderCurrencyID", currencyObj.CurrencyID);
        }

        // Min price in main currency filter
        if (MinPriceInMainCurrency > 0)
        {
            where.Where("OrderTotalPriceInMainCurrency", QueryOperator.LargerOrEquals, MinPriceInMainCurrency);
        }

        // Max price in main currency filter
        if (MaxPriceInMainCurrency > 0)
        {
            where.Where("OrderTotalPriceInMainCurrency", QueryOperator.LessOrEquals, MaxPriceInMainCurrency);
        }

        // Shipping option filter
        var shipping = ShippingOptionInfoProvider.GetShippingOptionInfo(ShippingOption, SiteContext.CurrentSiteName);
        if (shipping != null)
        {
            where.WhereEquals("OrderShippingOptionID", shipping.ShippingOptionID);
        }

        // Shipping country filter
        if (!string.IsNullOrEmpty(ShippingCountry) && ShippingCountry != "0")
        {
            AddCountryWhereCondition(where);
        }

        // Date filter
        AddDateWhereCondition(where);

        return where;
    }
    private DataSet GetRecycleBinSeletedItems(BinSettingsContainer settings, string columns)
    {
        var where = new WhereCondition();

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

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

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

        return ObjectVersionHistoryInfoProvider.GetRecycleBin(where.ToString(true), OrderBy, -1, columns);
    }
    /// <summary>
    /// Initializes the selector.
    /// </summary>
    public void InitSelector()
    {
        uniSelector.IsLiveSite = IsLiveSite;

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

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

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

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

        where = new WhereCondition(where);

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

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

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

        uniSelector.WhereCondition = where.ToString(true);
    }
    /// <summary>
    /// OnPreRender.
    /// </summary>
    protected override void OnPreRender(EventArgs e)
    {
        gridDocuments.StopProcessing = StopProcessing;
        if (StopProcessing)
        {
            return;
        }

        // Get actual filter where condition
        string filterWhere = gridDocuments.FilterForm.GetWhereCondition();

        // Filter selected document type only
        if ((ClassID > 0) && !RequestHelper.IsCallback())
        {
            CurrentWhereCondition = SqlHelper.AddWhereCondition(filterWhere, "NodeClassID = " + ClassID);
        }
        else
        {
            CurrentWhereCondition = filterWhere;
        }

        if (!dataLoaded)
        {
            if ((gridDocuments.FilterForm.FieldControls != null) && (gridDocuments.FilterForm.FieldControls.Count > 0))
            {
                // Set actual where condition from basic filter if exists
                gridDocuments.WhereClause = filterWhere;
            }

            gridDocuments.ReloadData();
        }

        // Hide column with languages if only one culture is assigned to the site
        if (DataHelper.DataSourceIsEmpty(SiteCultures) || (SiteCultures.Tables[0].Rows.Count <= 1))
        {
            // Hide column with flags
            if (gridDocuments.NamedColumns.ContainsKey("documentculture"))
            {
                gridDocuments.NamedColumns["documentculture"].Visible = false;
            }

            // Hide language filter
            gridDocuments.FilterForm.FieldsToHide.Add("DocumentCulture");
        }
        else
        {
            if (FlagsControls.Count != 0)
            {
                // Get all document node IDs
                HashSet<int> nodeIds = new HashSet<int>();
                foreach (DocumentFlagsControl ucDocFlags in FlagsControls)
                {
                    nodeIds.Add(ucDocFlags.NodeID);
                }

                var condition = new WhereCondition();
                condition.WhereIn("NodeID", nodeIds);

                // Get all culture documents
                DataSet docs = Tree.SelectNodes(currentSiteName, "/%", TreeProvider.ALL_CULTURES, false, null, condition.ToString(true), null, -1, false, 0, "NodeID, DocumentLastVersionNumber, DocumentCulture, DocumentModifiedWhen, DocumentLastPublished");

                if (!DataHelper.DataSourceIsEmpty(docs))
                {
                    var groupedDocs = new GroupedDataSource(docs, "NodeID");

                    // Initialize the document flags controls
                    foreach (var docFlagCtrl in FlagsControls)
                    {
                        docFlagCtrl.DataSource = groupedDocs;
                        docFlagCtrl.ReloadData();
                    }
                }
            }
        }

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

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

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

        selectCultureElem.AdditionalWhereCondition = condition.ToString(true);
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (StopProcessing)
        {
            return;
        }

        // Set visibility of the target language selector
        plcTargetLang.Visible = DisplayTargetlanguage;
        if (DisplayTargetlanguage)
        {
            SetupTargetLanguageDropDownWhereCondition();
        }

        if (TranslationSettings != null)
        {
            var condition = new WhereCondition();

            var targetCultures = TranslationSettings.TargetLanguages;
            if (targetCultures.Count > 0)
            {
                condition.WhereNotIn("CultureCode", targetCultures);
            }

            if (NodeID > 0)
            {
                condition.WhereIn("CultureCode", new IDQuery("cms.document", "DocumentCulture").WhereEquals("DocumentNodeID", NodeID));
            }

            selectCultureElem.AdditionalWhereCondition = condition.ToString(true);
        }

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

        StringBuilder sb = new StringBuilder();
        sb.Append(@"
        function SelectService(serviceName, displaySeparateSubmission, supportsInstructions, supportsPriority, supportsAttachments, supportsDeadline) {
        var nameElem = document.getElementById('", hdnSelectedName.ClientID, @"');
        if (nameElem != null) {
        nameElem.value = serviceName;
        }

        document.getElementById('pnlSeparateSubmissions').style.display = (displaySeparateSubmission ? '' : 'none');
        document.getElementById('pnlInstructions').style.display = (supportsInstructions ? '' : 'none');
        document.getElementById('pnlPriority').style.display = (supportsPriority ? '' : 'none');
        document.getElementById('pnlDeadline').style.display = (supportsDeadline ? '' : 'none');
        document.getElementById('pnlProcessBinary').style.display = (supportsAttachments ? '' : 'none');
        var selectButton = document.getElementById('rad' + serviceName);
        if (selectButton != null) {
        selectButton.checked = 'checked';
        }
        }");

        ScriptHelper.RegisterClientScriptBlock(Page, typeof(string), "TranslationServiceSelector", sb.ToString(), true);

        string format = "{% CultureName %}{% if (CultureCode == \"" + defaultCulture + "\") { \" \" +\"" + GetString("general.defaultchoice") + "\" } %}";
        selectCultureElem.DropDownCultures.AutoPostBack = DisplayTargetlanguage;
        selectCultureElem.UniSelector.DisplayNameFormat = format;
        selectTargetCultureElem.UniSelector.DisplayNameFormat = format;

        // Preselect 'Normal' priority
        if (!URLHelper.IsPostback())
        {
            drpPriority.Value = 1;
        }

        ReloadData();
    }
    protected void btnOk_Click(object sender, EventArgs e)
    {
        What what = (What)ValidationHelper.GetInteger(drpWhat.SelectedValue, 0);
        Action action = (Action)ValidationHelper.GetInteger(drpAction.SelectedValue, 0);

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

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

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

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

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

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

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

            default:
                return;
        }

        // Reload unigrid
        gridElem.ResetSelection();
        gridElem.ReloadData();
        pnlUpdate.Update();
    }