Exemple #1
0
	protected override void OnPreRender(EventArgs e)
	{
		bSearch.Attributes["onclick"] = String.Format(
			"jsUtils.OpenWindow('{0}?iblock_id={1}&n={2}&k={3}', 600, 500);",
			BXJSUtility.Encode(VirtualPathUtility.ToAbsolute("~/bitrix/admin/IBlockElementSearch.aspx")),
			iblockId,
			tbValue.ClientID,
			lbName.ClientID
		);

		//Настраиваем внешний вид
		int elementId;
		if (int.TryParse(tbValue.Text, out elementId) && elementId > 0)
		{
			BXFilter f = new BXFilter();
            f.Add(new BXFilterItem(BXIBlockElement.Fields.ID, BXSqlFilterOperators.Equal, elementId));
            if (iblockId > 0)
                f.Add(new BXFilterItem(BXIBlockElement.Fields.IBlock.ID, BXSqlFilterOperators.Equal, iblockId));
            BXIBlockElementCollection element = BXIBlockElement.GetList(f, null);

			if (element.Count != 0)
			{
				tbValue.Text = element[0].Id.ToString();
				lbName.Text = element[0].Name;
			}
			else
			{
				tbValue.Text = string.Empty;
				lbName.Text = string.Empty;
			}
		}


		base.OnPreRender(e);
	}
    protected override void OnPreRender(EventArgs e)
    {
        bSearch.Attributes["onclick"] = String.Format(
            "jsUtils.OpenWindow('{0}?editor_id={1}&label_id={2}', 800, 500);",
            BXJSUtility.Encode(VirtualPathUtility.ToAbsolute("~/bitrix/admin/UserSearch.aspx")),
            tbValue.ClientID,
            lbName.ClientID
        );

        //Настраиваем внешний вид
        int id;
        if (int.TryParse(_userId.ToString(), out id) && id > 0)
        {
            BXFilter f = new BXFilter();
            if (id > 0)
            {
                f.Add(new BXFilterItem(BXUser.Fields.UserId, BXSqlFilterOperators.Equal, id));
                _userId = id;
            }
            BXUserCollection user = BXUser.GetList(f, null);

            if (user.Count == 1)
            {
                tbValue.Text = user[0].UserId.ToString();
                lbName.Text = string.Format("[{0}] ({1}) {2}", user[0].UserId.ToString(), user[0].UserName, user[0].FirstName + " " + user[0].LastName);
            }
            else
            {
                tbValue.Text = string.Empty;
                lbName.Text = string.Empty;
            }
        }


        base.OnPreRender(e);
    }
		public override void ProcessMessage(BXCommand cmd, bool executionContext, string executionVirtualPath)
		{
			#region Search
			if (cmd.Action == "Bitrix.Search.ProvideUrl")
			{
                string moduleId = cmd.Parameters.Get("moduleId", string.Empty);
                if (string.Equals(moduleId, "forum", StringComparison.OrdinalIgnoreCase)
                    && AboutCommentsShow()
                    && BXModuleManager.IsModuleInstalled("Forum"))
                {
                    //Поиск по комментариям к эл-там каталога
                    int blockId = IBlockId;
                    int forumId = cmd.Parameters.GetInt("itemGroup", 0);
                    int postId = cmd.Parameters.GetInt("itemId", 0);
                    int topicId = cmd.Parameters.GetInt("param1");


                    if (blockId == 0 || !string.Equals(moduleId, "forum", StringComparison.OrdinalIgnoreCase) || forumId <= 0 || postId <= 0)
                        return;

                    BXSchemeFieldBase commentCpField =  BXIBlockElement.Fields.CustomFields[blockId].GetFieldByKey(CommentCustomPropertyName);
                    if (commentCpField == null)
                        return;

                    BXFilter f = new BXFilter(
                            new BXFilterItem(BXIBlockElement.Fields.Active, BXSqlFilterOperators.Equal, "Y"),
                            new BXFilterItem(BXIBlockElement.Fields.ActiveDate, BXSqlFilterOperators.Equal, "Y"),
                            new BXFilterItem(BXIBlockElement.Fields.IBlock.ID, BXSqlFilterOperators.Equal, blockId),
                            new BXFilterItem(commentCpField, BXSqlFilterOperators.Equal, topicId)
                            );

                    string siteId = DesignerSite;
                    if (!string.IsNullOrEmpty(siteId))
                        f.Add(new BXFilterItem(BXIBlockElement.Fields.IBlock.Sites.SiteId, BXSqlFilterOperators.Equal, siteId));

                    BXIBlockElementCollection c = BXIBlockElement.GetList(f, null);
                    if (c.Count == 0)
                        return;

                    BXIBlockElement el = c[0];
                    //формируем постоянную ссылку на комментарий
                    string commentUrl = string.Empty;
                    if (!EnableSef)
                        commentUrl = string.Format("{0}?{1}={2}&{3}={4}#comment{4}", BXSite.GetUrlForPath(executionVirtualPath, null), ElementIdVariable, el.Id.ToString(), CommentVariable, postId.ToString());
                    else
                    {
                        BXParamsBag<object> commentSefParams = new BXParamsBag<object>();
                        commentSefParams["SectionId"] = string.Empty;
                        commentSefParams["ElementId"] = el.Id.ToString();
                        commentSefParams["CommentId"] = postId.ToString();
                        string t = ElementDetailCommentReadTemplate;
                        if (t.IndexOf("##") < 0)
                            t = string.Concat(t, "##comment#CommentId#");
                        commentUrl = BXSefUrlUtility.MakeLink(CombineLink(SefFolder, t), commentSefParams).Replace("//", "/");
                    }
                    cmd.AddCommandResult(string.Concat("bitrix:forum@", executionVirtualPath), new BXCommandResult(BXCommandResultType.Ok, commentUrl));
                    return;
                }

				if (cmd.Parameters.Get<string>("moduleId") != "iblock")
					return;

				if (IBlockId < 0 || cmd.Parameters.Get<int>("itemGroup") != IBlockId)
					return;

				int elementId = cmd.Parameters.Get("itemId", -1);
				if (elementId < 0)
					return;

				BXFilter elementFilter = new BXFilter(
					new BXFilterItem(BXIBlockElement.Fields.Active, BXSqlFilterOperators.Equal, "Y"),
					new BXFilterItem(BXIBlockElement.Fields.IBlock.ID, BXSqlFilterOperators.Equal, IBlockId),
					new BXFilterItem(BXIBlockElement.Fields.ID, BXSqlFilterOperators.Equal, elementId)
				);

				BXIBlockElementCollection element = BXIBlockElement.GetList(elementFilter, null);
				if (element != null && element.Count < 1)
					return;

				BXIBlockElement iblockElement = element[0];
				int replaceSectionId = 0;
				if (iblockElement.Sections.Count != 0)
					replaceSectionId = iblockElement.Sections[0].SectionId;

				string url;
				if (EnableSef)
				{
					string replaceSectionCode = String.Empty;
					if (ElementDetailTemplate.Contains("#SECTION_CODE#") || ElementDetailTemplate.Contains("#SectionCode#"))
					{
						BXIBlockSection elementSection = BXIBlockSection.GetById(replaceSectionId);
						if (elementSection != null)
							replaceSectionCode = elementSection.Code;
					}

					BXParamsBag<object> replaceItems = new BXParamsBag<object>();
					replaceItems.Add("IblockId", iblockElement.IBlockId);
					replaceItems.Add("IBLOCK_ID", iblockElement.IBlockId);
					replaceItems.Add("ELEMENT_ID", iblockElement.Id);
					replaceItems.Add("ElementId", iblockElement.Id);
					replaceItems.Add("ElementCode", iblockElement.Code);
					replaceItems.Add("ELEMENT_CODE", iblockElement.Code);
					replaceItems.Add("SectionId", replaceSectionId);
					replaceItems.Add("SECTION_ID", replaceSectionId);
					replaceItems.Add("SectionCode", replaceSectionCode);
					replaceItems.Add("SECTION_CODE", replaceSectionCode);

					//url = MakeLink(SefFolder, ElementDetailTemplate, replaceItems);
					url = CombineLink(SefFolder, BXSefUrlUtility.MakeLink(ElementDetailTemplate, replaceItems));
				}
				else
				{
					url = String.Format("{0}?{1}={2}&{3}={4}", BXSite.GetUrlForPath(executionVirtualPath, null), SectionIdVariable, replaceSectionId, ElementIdVariable, elementId);
				}

				cmd.AddCommandResult("bitrix:catalogue@" + executionVirtualPath, new BXCommandResult(BXCommandResultType.Ok, url));
			}
			#endregion

			if (cmd.Action == "Bitrix.Main.GeneratePublicMenu")
			{
				//return;
				//Совпадает ли тип меню в параметрах компонента с типом, который запрашивает система.
				if (!Parameters.Get("GenerateMenuType", "left").Equals(cmd.Parameters.Get<string>("menuType"), StringComparison.InvariantCultureIgnoreCase))
					return;

				//Генерируем меню только для тех адресов, которые выводит сам компонент.
				if (!EnableSef && !BXSiteRemapUtility.UnmapVirtualPath(executionVirtualPath).Equals(cmd.Parameters.Get<string>("uriPath"), StringComparison.InvariantCultureIgnoreCase))
					return;
				else if (EnableSef && !cmd.Parameters.Get<string>("uriPath").StartsWith(Bitrix.IO.BXPath.ToVirtualRelativePath(SefFolder.TrimStart('\\', '/')) + "/", StringComparison.InvariantCultureIgnoreCase))
					return;

				if (IBlockId < 0)
					return;

				BXParamsBag<object> request = new BXParamsBag<object>();
				if (EnableSef)
				{
					BXParamsBag<string> urlToPage = new BXParamsBag<string>();
					urlToPage["index.page"] = CommonListPageTemplate;
					urlToPage["index.all"] = CommonListShowAllTemplate;
					urlToPage["list"] = ElementListTemplate;
					urlToPage["list.page"] = SectionListPageTemplate;
					urlToPage["list.all"] = SectionListShowAllTemplate;
					urlToPage["detail"] = ElementDetailTemplate;

					//MapVariable(SefFolder, urlToPage, request, "index", BXUri.ToRelativeUri(cmd.Parameters.Get<string>("uri")));
					Uri url = new Uri(BXUri.ToAbsoluteUri(cmd.Parameters.Get<string>("uri")));
					BXSefUrlUtility.MapVariable(SefFolder, urlToPage, request, "index", url, null);

					ParseVariableAliases(request);
				}
				else
				{
					BXParamsBag<string> variableAlias = new BXParamsBag<string>();
					variableAlias["SectionId"] = SectionIdVariable;
					variableAlias["ElementId"] = ElementIdVariable;
					variableAlias["PageId"] = PageIdVariable;
					variableAlias["ShowAll"] = ShowAllVariable;

					MapVariable(variableAlias, request, BXUri.ToRelativeUri(cmd.Parameters.Get<string>("uri")));
				}

				#region Menu Item Permission
				string permissionCacheKey = "catalogue-" + IBlockId.ToString() + "-menu-permission";
				if ((menuItemPermisson = (string)BXCacheManager.MemoryCache.Get(permissionCacheKey)) == null)
				{
					menuItemPermisson = String.Empty;
					StringBuilder menuItemRoles = new StringBuilder();

					BXRoleCollection iblockRoles = BXRoleManager.GetAllRolesForOperation("IBlockRead", "iblock", IBlockId.ToString());
					foreach (BXRole role in iblockRoles)
					{
						//Если доступно всем
						if (role.RoleName == "Guest")
						{
							menuItemRoles = null;
							break;
						}
						//Если доступно группе User, значит достаточно проверить только для этой группы
						else if (role.RoleName == "User")
						{
							menuItemRoles = null;
							menuItemPermisson = "User";
							break;
						}
						else
						{
							menuItemRoles.Append(role.RoleName);
							menuItemRoles.Append(";");
						}
					}

					if (menuItemRoles != null && menuItemRoles.Length > 0)
						menuItemPermisson = menuItemRoles.ToString();

					BXCacheManager.MemoryCache.Insert(permissionCacheKey, menuItemPermisson);
				}
				#endregion

				int elementId = 0, sectionId = 0;
				string elementCode = String.Empty, sectionCode = String.Empty;

				elementId = request.Get<int>("ElementId", elementId);
				sectionId = request.Get<int>("SectionId", sectionId);
				elementCode = request.Get<string>("ElementCode", elementCode);
				sectionCode = request.Get<string>("SectionCode", sectionCode);

				string parentLevelUri = null;
				List<BXPublicMenuItem> menuList = null;

				//Указан идентификатор или символьный код
				if (elementId > 0 || !String.IsNullOrEmpty(elementCode))
				{
					BXFilter elementFilter = new BXFilter(
						new BXFilterItem(BXIBlockElement.Fields.IBlock.ID, BXSqlFilterOperators.Equal, IBlockId),
						new BXFilterItem(BXIBlockElement.Fields.Active, BXSqlFilterOperators.Equal, "Y")
					);

					if (elementId > 0)
						elementFilter.Add(new BXFilterItem(BXIBlockElement.Fields.ID, BXSqlFilterOperators.Equal, elementId));
					if (!String.IsNullOrEmpty(elementCode))
						elementFilter.Add(new BXFilterItem(BXIBlockElement.Fields.Code, BXSqlFilterOperators.Equal, elementCode));
					if (sectionId > 0)
						elementFilter.Add(new BXFilterItem(BXIBlockElement.Fields.Sections.Section.ID, BXSqlFilterOperators.Equal, sectionId));
					if (!String.IsNullOrEmpty(sectionCode))
						elementFilter.Add(new BXFilterItem(BXIBlockElement.Fields.Sections.Section.Code, BXSqlFilterOperators.Equal, sectionCode));

					BXIBlockElementCollection element = BXIBlockElement.GetList(elementFilter, null);
					if (element != null && element.Count > 0)
					{
						BXIBlockElement.BXInfoBlockElementSectionCollection sections = element[0].Sections;
						if (sections != null && sections.Count > 0)
						{
							BXParamsBag<object> replaceItems = new BXParamsBag<object>();
							replaceItems["SECTION_ID"] = sections[0].SectionId;
							replaceItems["SectionId"] = replaceItems["SECTION_ID"];
							replaceItems["SECTION_CODE"] = GetSectionCode(sections[0].SectionId);
							replaceItems["SectionCode"] = replaceItems["SECTION_CODE"];

							parentLevelUri = MakeMenuUri(executionVirtualPath, replaceItems); //Меню строится для раздела, к которому привязан элемент
						}
					}
				}

				//Если ничего не указано выводим все дерево
				Dictionary<string, BXPublicMenu.BXLoadMenuCommandParameter> menuTree = new Dictionary<string, BXPublicMenu.BXLoadMenuCommandParameter>();
				if (parentLevelUri == null && menuList == null)
				{
					BXIBlockSectionCollection sectionsList = BXIBlockSection.GetList(
						new BXFilter(
							new BXFilterItem(BXIBlockSection.Fields.Active, BXSqlFilterOperators.Equal, "Y"),
							new BXFilterItem(BXIBlockSection.Fields.ActiveGlobal, BXSqlFilterOperators.Equal, "Y"),
							new BXFilterItem(BXIBlockSection.Fields.IBlock.ID, BXSqlFilterOperators.Equal, IBlockId)
						),
						new BXOrderBy(
							new BXOrderByPair(BXIBlockSection.Fields.LeftMargin, BXOrderByDirection.Asc)
						),
						null,
						null,
						BXTextEncoder.EmptyTextEncoder
					);

					int previousDepthLevel = 1;
					int previousSectionId = 0;
					Dictionary<int, MenuSectionTree> sectionTree = new Dictionary<int, MenuSectionTree>();
					foreach (BXIBlockSection section in sectionsList)
					{
						BXParamsBag<object> replaceItems = new BXParamsBag<object>();
						replaceItems["SECTION_ID"] = section.Id;
						replaceItems["SECTION_CODE"] = section.Code ?? String.Empty;
						replaceItems["SectionId"] = replaceItems["SECTION_ID"];
						replaceItems["SectionCode"] = replaceItems["SECTION_CODE"];

						sectionTree[section.Id] = new MenuSectionTree();
						string url = MakeMenuUri(executionVirtualPath, replaceItems);
						sectionTree[section.Id].url = url;
						sectionTree[section.Id].sectionId = section.SectionId;

						//Если предыдущий раздел не имеет дочерних разделов, то устанавливаем у него parentLevelUrl
						if (previousSectionId > 0 && section.DepthLevel <= previousDepthLevel)
							sectionTree[previousSectionId].parentLevelUrl = sectionTree[sectionTree[previousSectionId].sectionId].url;
						previousDepthLevel = section.DepthLevel;
						previousSectionId = section.Id;

						BXPublicMenuItem menuItem = new BXPublicMenuItem();
						menuItem.Title = section.Name;
						menuItem.Links.Add(url);
						menuItem.Sort = section.LeftMargin;

						menuItem.ConditionType = ConditionType.Group;
						menuItem.Condition = menuItemPermisson;

						if (!sectionTree.ContainsKey(section.SectionId))
						{
							sectionTree[section.SectionId] = new MenuSectionTree();
							sectionTree[section.SectionId].menuItems = new List<BXPublicMenuItem>();

							if (section.SectionId < 1)
								sectionTree[section.SectionId].url = EnableSef ? BXPath.ToVirtualRelativePath(BXPath.TrimStart(SefFolder)) : BXSiteRemapUtility.UnmapVirtualPath(executionVirtualPath);
						}

						if (sectionTree[section.SectionId].menuItems == null)
							sectionTree[section.SectionId].menuItems = new List<BXPublicMenuItem>();

						sectionTree[section.SectionId].menuItems.Add(menuItem);
					}

					//Последний элемент не может иметь дочерних элементов, поэтому указываем parentLevelUrl
					if (sectionTree.ContainsKey(previousSectionId) && sectionTree.ContainsKey(sectionTree[previousSectionId].sectionId))
						sectionTree[previousSectionId].parentLevelUrl = sectionTree[sectionTree[previousSectionId].sectionId].url;

					foreach (KeyValuePair<int, MenuSectionTree> sectionItem in sectionTree)
					{
						if (!menuTree.ContainsKey(sectionItem.Value.url))
						{
							menuTree.Add(
								sectionItem.Value.url,
								new BXPublicMenu.BXLoadMenuCommandParameter(sectionItem.Value.menuItems, true, sectionItem.Value.parentLevelUrl)
							);
						}
					}
				}

				if (menuTree.Count > 0)
					cmd.AddCommandResult("bitrix:catalogue@" + executionVirtualPath, new BXCommandResult(BXCommandResultType.Ok, menuTree));
				else if (menuList != null || parentLevelUri != null)
				{
					BXPublicMenu.BXLoadMenuCommandParameter menuResult = new BXPublicMenu.BXLoadMenuCommandParameter(menuList, true, parentLevelUri);
					cmd.AddCommandResult("bitrix:catalogue@" + executionVirtualPath, new BXCommandResult(BXCommandResultType.Ok, menuResult));
				}
			}
		}
	protected void BXForumGrid_Select(object sender, BXSelectEventArgs e)
	{
		BXFilter filter = new BXFilter(new BXFilterItem(BXForum.Fields.CheckPermissions, BXSqlFilterOperators.Equal, new string[] { BXForum.Operations.ForumAdminManage }));
		filter.Add(new BXFilter(BXForumFilter.CurrentFilter, BXForum.Fields));

		BXOrderBy orderBy;

		if (String.IsNullOrEmpty(e.SortExpression))
			orderBy = new BXOrderBy(
				new BXOrderByPair(BXForum.Fields.Category.Sort, BXOrderByDirection.Asc),
				new BXOrderByPair(BXForum.Fields.Category.Id, BXOrderByDirection.Asc),
				new BXOrderByPair(BXForum.Fields.Sort, BXOrderByDirection.Asc),
				new BXOrderByPair(BXForum.Fields.Name, BXOrderByDirection.Asc)
			);
		else
			orderBy = new BXOrderBy(BXForum.Fields, e.SortExpression);

		e.Data = BXForum.GetList(
			filter,
			orderBy,
			null, 
			new BXQueryParams(e.PagingOptions),
			BXTextEncoder.EmptyTextEncoder
		);
	}
    protected void BXSubscriptionsGrid_Select(object sender, BXSelectEventArgs e)
    {
        if (UserId <= 0)
        {
            e.Data = new List<BXSubscriptionsSelect>();
            return;
        }
        currentFilter = new BXFilter(new BXFilterItem(BXForumSubscription.Fields.Subscriber.Id,BXSqlFilterOperators.Equal,UserId));
        currentFilter.Add(new BXFilter(BXSubscriptionsFilter.CurrentFilter, BXForumSubscription.Fields));
        //BXSubscriptionsFilter.CurrentFilter.con
        BXOrderBy orderBy;

        if (String.IsNullOrEmpty(e.SortExpression))
            orderBy = new BXOrderBy(new BXOrderByPair(BXForumSubscription.Fields.Id, BXOrderByDirection.Asc));
        else
            orderBy = new BXOrderBy(BXForumSubscription.Fields, e.SortExpression);

        BXForumSubscriptionCollection subs = BXForumSubscription.GetList(
                                                            currentFilter,
                                                            orderBy,
                                                            new BXSelectAdd(BXForumSubscription.Fields.Topic,BXForumSubscription.Fields.Forum),
                                                            new BXQueryParams(e.PagingOptions),
                                                            BXTextEncoder.EmptyTextEncoder
                                                        );
        List<BXSubscriptionsSelect> list = subs.ConvertAll<BXSubscriptionsSelect>(delegate(BXForumSubscription input)
            {
                string siteName = String.Empty;
                if (sites.ContainsKey(input.SiteId)) siteName = sites[input.SiteId];
                else throw new KeyNotFoundException("site is not found");
            return new BXSubscriptionsSelect(   
                                                input.Id, input.Forum!=null ? input.Forum.Name:"", 
                                                input.Topic!=null? input.Topic.Name:"", input.OnlyTopic, 
                                                input.DateStart, siteName,
                                                GetMessageRaw(input.TopicId>0? "ColumnText.Topic" : input.OnlyTopic ? "ColumnText.OnlyTopic" : "ColumnText.FullForum")
                                            );

            }
        );

        e.Data = list;

    }
    protected override void LoadComponentDefinition()
    {
        #region MainGroup
        List<BXParamValue> types = new List<BXParamValue>();
        types.Add(new BXParamValue("-", ""));
        BXIBlockTypeCollection typeCollection = BXIBlockType.GetList(null, new BXOrderBy(new BXOrderByPair(BXIBlockType.Fields.Sort, BXOrderByDirection.Asc)));
        foreach (BXIBlockType t in typeCollection)
            types.Add(new BXParamValue(t.Translations[BXLoc.CurrentLocale].Name, t.Id.ToString()));

        ParamsDefinition["IBlockTypeId"].Values = types;

		BXFilter iblockFilter = new BXFilter();
		if (Parameters.ContainsKey("IBlockTypeId"))
		{
			int typeId;
			int.TryParse(Parameters["IBlockTypeId"], out typeId);
			if (typeId > 0)
				iblockFilter.Add(new BXFilterItem(BXIBlock.Fields.Type.ID, BXSqlFilterOperators.Equal, typeId));
		}
		if (!string.IsNullOrEmpty(DesignerSite))
			iblockFilter.Add(new BXFilterItem(BXIBlock.Fields.Sites.SiteId, BXSqlFilterOperators.Equal, DesignerSite));

        List<BXParamValue> iblocks = new List<BXParamValue>();
        BXIBlockCollection iblockCollection = BXIBlock.GetList(iblockFilter, new BXOrderBy(new BXOrderByPair(BXIBlock.Fields.Sort, BXOrderByDirection.Asc)));
        foreach (BXIBlock b in iblockCollection)
            iblocks.Add(new BXParamValue(b.Name, b.Id.ToString()));

        ParamsDefinition["IBlockId"].Values = iblocks;
        #endregion

        #region TOPElements
        List<BXParamValue> properties = new List<BXParamValue>();
        if (Parameters.ContainsKey("IBlockId"))
        {
            int iblockId;
            int.TryParse(Parameters["IBlockId"], out iblockId);
            if (iblockId > 0)
            {
                BXCustomFieldCollection cfCollection = BXCustomEntityManager.GetFields("IBlock_" + iblockId);
                foreach (BXCustomField f in cfCollection)
                    properties.Add(new BXParamValue(f.EditFormLabel, f.Name));
            }
        }

        ParamsDefinition["TOPProperties"].Values = properties;
        #endregion

        #region ELProperties
        ParamsDefinition["ELProperties"].Values = properties;
        #endregion

        #region DetailView
        ParamsDefinition["DTProperties"].Values = properties;
        #endregion

        ParamsDefinition.Add(BXParametersDefinition.Paging);
        ParamsDefinition.Add(BXParametersDefinition.Search);

        foreach (string parDefKey in ParamsDefinition.Keys)
            ParamsDefinition[parDefKey].AdjustPresentation(this);
	}
		private void BuildElements()
		{
			if (this.elements != null)
				return;

			this.elements = new Dictionary<int, BXIBlockElement>();

			List<object> vals = property.Values;
			if (vals.Count == 0) //нет элементов
				return;
			if (vals.Count == 1) //элемент один, значение не int или не является идентификатором
			{
				try
				{
					if (((int)vals[0]) < 1)
						return;
				}
				catch (InvalidCastException)
				{
					return;
				}
			}

			BXFilter filter = new BXFilter();
			if (property.IsMultiple)
				filter.Add(new BXFilterItem(BXIBlockElement.Fields.ID, BXSqlFilterOperators.In, vals));
			else
				filter.Add(new BXFilterItem(BXIBlockElement.Fields.ID, BXSqlFilterOperators.Equal, vals[0]));

			if (field != null)
			{
				int iblockId = field.Settings.GetInt("IBlockId");
				if (iblockId > 0)
					filter.Add(new BXFilterItem(BXIBlockElement.Fields.IBlock.ID, BXSqlFilterOperators.Equal, iblockId));
			}

			foreach (BXIBlockElement e in BXIBlockElement.GetList(filter, new BXOrderBy(new BXOrderByPair(BXIBlockElement.Fields.ID, BXOrderByDirection.Asc)), new BXSelect(BXSelectFieldPreparationMode.Normal, BXIBlockElement.Fields.ID, BXIBlockElement.Fields.Name), null, BXTextEncoder.EmptyTextEncoder))
				this.elements[e.Id] = e;
		}
    protected override void LoadComponentDefinition()
    {
        #region MainGroup

        List<BXParamValue> types = new List<BXParamValue>();
        types.Add(new BXParamValue("-", ""));
		BXIBlockTypeCollection typeCollection = BXIBlockType.GetList(null, new BXOrderBy(new BXOrderByPair(BXIBlockType.Fields.Sort, BXOrderByDirection.Asc)));
		foreach (BXIBlockType t in typeCollection)
			types.Add(new BXParamValue(t.Translations[BXLoc.CurrentLocale].Name, t.Id.ToString()));

        ParamsDefinition["IBlockTypeId"].Values = types;
        ParamsDefinition["IBlockTypeId"].RefreshOnDirty = true;

        BXFilter iblockFilter = new BXFilter();
        if (Parameters.ContainsKey("IBlockTypeId"))
        {
            int typeId;
            int.TryParse(Parameters["IBlockTypeId"], out typeId);
            if (typeId > 0)
				iblockFilter.Add(new BXFilterItem(BXIBlock.Fields.Type.ID, BXSqlFilterOperators.Equal, typeId));
        }
        if (!string.IsNullOrEmpty(DesignerSite))
			iblockFilter.Add(new BXFilterItem(BXIBlock.Fields.Sites.SiteId, BXSqlFilterOperators.Equal, DesignerSite));

        List<BXParamValue> iblocks = new List<BXParamValue>();
		BXIBlockCollection iblockCollection = BXIBlock.GetList(iblockFilter, new BXOrderBy(new BXOrderByPair(BXIBlock.Fields.Sort, BXOrderByDirection.Asc)));
		foreach (BXIBlock b in iblockCollection)
			iblocks.Add(new BXParamValue(b.Name, b.Id.ToString()));

        ParamsDefinition["IBlockId"].Values = iblocks;
        ParamsDefinition["IBlockId"].RefreshOnDirty = true;

        #endregion
    }
	protected void BXUsersGrid_SelectCount(object sender, BXSelectCountEventArgs e)
	{
        BXFilter countFilter = new BXFilter();
            countFilter.Add(new BXFilter(BXUsersFilter.CurrentFilter, BXForumUser.Fields));
		    e.Count = BXForumUser.Count(countFilter);
	}
	protected void BXUsersGrid_Select(object sender, BXSelectEventArgs e)
	{
        BXFilter filter = new BXFilter();
        filter.Add(new BXFilter(BXUsersFilter.CurrentFilter, BXForumUser.Fields));

        BXOrderBy orderBy;

        if (String.IsNullOrEmpty(e.SortExpression))
            orderBy = new BXOrderBy(new BXOrderByPair(BXForumUser.Fields.Id, BXOrderByDirection.Asc));
        else
            orderBy = new BXOrderBy(BXForumUser.Fields, e.SortExpression);

        BXForumUserCollection subs = BXForumUser.GetList(   filter, 
                                                            orderBy,
                                                            new BXSelectAdd(BXForumUser.Fields.User,BXForumUser.Fields.SubscriptionsCount),
                                                            new BXQueryParams(e.PagingOptions),
                                                            BXTextEncoder.EmptyTextEncoder
                                                        );
        List<SubscriptionsGridSelect> list = new List<SubscriptionsGridSelect>();
        string msg = GetMessage("GridText.ToolTip.EditUser");
        foreach (BXForumUser u in subs)
            list.Add(new SubscriptionsGridSelect(u.User,u,msg));
        e.Data = list;
 
	}
    private BXFilter CreateSelectFilter()
    {
        BXFilter r = new BXFilter(BXAdminFilter1.CurrentFilter, BXCustomField.Fields);
        r.Add(
            new BXFilterOr(
                new BXFilterItem(BXCustomField.Fields.OwnerEntityId, BXSqlFilterOperators.Equal, BXBlogModuleConfiguration.PostCustomFieldEntityId),
                new BXFilterItem(BXCustomField.Fields.OwnerEntityId, BXSqlFilterOperators.Equal, BXBlogModuleConfiguration.BlogCustomFieldEntityId)
            )
        );

        return r;
    }
		private Dictionary<int, BXIBlockSection> BuildSections()
		{
			Dictionary<int, BXIBlockSection> sections = new Dictionary<int, BXIBlockSection>();
			BXFilter filter = new BXFilter();

			if (property.IsMultiple)
				filter.Add(new BXFilterItem(BXIBlockSection.Fields.ID, BXSqlFilterOperators.In, property.Values));
			else
				filter.Add(new BXFilterItem(BXIBlockSection.Fields.ID, BXSqlFilterOperators.Equal, property.Value));

			if (field != null)
			{
				int iblockId = field.Settings.GetInt("IBlockId");
				if (iblockId > 0)
					filter.Add(new BXFilterItem(BXIBlockSection.Fields.IBlock.ID, BXSqlFilterOperators.Equal, iblockId));
			}

			BXIBlockSectionCollection sectionCollection = BXIBlockSection.GetList(
				filter,
				new BXOrderBy(new BXOrderByPair(BXIBlockSection.Fields.ID, BXOrderByDirection.Asc)),
				null,
				null,
				BXTextEncoder.EmptyTextEncoder
			);

			foreach (BXIBlockSection s in sectionCollection)
				sections[s.Id] = s;

			return sections;
		}
    protected override void LoadComponentDefinition()
    {
        #region MainGroup

        List<BXParamValue> types = new List<BXParamValue>();
        types.Add(new BXParamValue("-", ""));
        BXIBlockTypeCollection typeCollection = BXIBlockType.GetList(null, new BXOrderBy(new BXOrderByPair(BXIBlockType.Fields.Sort, BXOrderByDirection.Asc)));
        foreach (BXIBlockType t in typeCollection)
            types.Add(new BXParamValue(t.Translations[BXLoc.CurrentLocale].Name, t.Id.ToString()));

        ParamsDefinition["IBlockTypeId"].Values = types;
        ParamsDefinition["IBlockTypeId"].RefreshOnDirty = true;

        BXFilter iblockFilter = new BXFilter();
        if (Parameters.ContainsKey("IBlockTypeId"))
        {
            int typeId;
            int.TryParse(Parameters["IBlockTypeId"], out typeId);
            if (typeId > 0)
				iblockFilter.Add(new BXFilterItem(BXIBlock.Fields.Type.ID, BXSqlFilterOperators.Equal, typeId));
        }
        if (!string.IsNullOrEmpty(DesignerSite))
			iblockFilter.Add(new BXFilterItem(BXIBlock.Fields.Sites.SiteId, BXSqlFilterOperators.Equal, DesignerSite));

        List<BXParamValue> iblocks = new List<BXParamValue>();
        BXIBlockCollection iblockCollection = BXIBlock.GetList(iblockFilter, new BXOrderBy(new BXOrderByPair(BXIBlock.Fields.Sort, BXOrderByDirection.Asc)));
        foreach (BXIBlock b in iblockCollection)
            iblocks.Add(new BXParamValue(b.Name, b.Id.ToString()));

        ParamsDefinition["IBlockId"].Values = iblocks;
        ParamsDefinition["IBlockId"].RefreshOnDirty = true;
        #endregion

        #region DataSource
        List<BXParamValue> sortFields = new List<BXParamValue>();
        sortFields.Add(new BXParamValue("ID", "ID"));
        sortFields.Add(new BXParamValue(GetMessageRaw("Title"), "name"));
        sortFields.Add(new BXParamValue(GetMessageRaw("DateOfModification"), "updatedate"));
        sortFields.Add(new BXParamValue(GetMessageRaw("SortIndex"), "sort"));
        sortFields.Add(new BXParamValue(GetMessageRaw("QuantityOfViewsAvg"), "sort")); /// ?
        sortFields.Add(new BXParamValue(GetMessageRaw("ActiveFromDate"), "activefromdate"));
        sortFields.Add(new BXParamValue(GetMessageRaw("ActiveUntilDate"), "activetodate"));

        ParamsDefinition["SortBy1"].Values = sortFields;
        #endregion

        #region View
        

        List<BXParamValue> properties = new List<BXParamValue>();
        if (Parameters.ContainsKey("IBlockId"))
        {
            int iblockId;
            int.TryParse(Parameters["IBlockId"], out iblockId);
            if (iblockId > 0)
            {
                BXCustomFieldCollection cfCollection = BXCustomEntityManager.GetFields("IBlock_" + iblockId);
                foreach (BXCustomField f in cfCollection)
                    properties.Add(new BXParamValue(f.EditFormLabel, f.Name));
            }
        }

        ParamsDefinition["Properties"].Values = properties;
        #endregion

        #region Additional
        ParamsDefinition["PropertyKeywords"].Values = properties;
        ParamsDefinition["PropertyDescription"].Values = properties;
        #endregion
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        #region SetupParameters
        SectionId = Parameters.Get("SectionId", 0);

        ShowSubelements = Parameters.Get("ShowSubelements", true);

        SortBy1 = Parameters.Get("SortBy1", "sort");
        SortOrder1 = Parameters.Get("SortOrder1", "Desc");

        PerPageCount = Parameters.Get("PerPageCount", 30);
        PerLineCount = Parameters.Get("PerLineCount", 3);
        Properties = Parameters.GetListString("Properties");

        string PropertyKeywords = Parameters.Get("PropertyKeywords", "-");
        string PropertyDescription = Parameters.Get("PropertyDescription", "-");
        bool AddAdminPanelButtons = Parameters.Get("AddAdminPanelButtons", false);
        bool ShowCompareButton = Parameters.Get("ShowCompareButton", false);
        bool SetPageTitle = Parameters.Get("SetPageTitle", true);
        bool CacheOnFilter = Parameters.Get("CacheOnFilter", false);

		Parameters["PagingAllowAll"] = false.ToString();
        /*bool PagerOverList = Parameters.GetBool("PagerOverList", false);
        bool PagerUnderList = Parameters.GetBool("PagerUnderList", false);
        string CategoryTitle = Parameters.GetString("CategoryTitle", "");
        bool PagerAlways = Parameters.GetBool("PagerAlways", true);
        string TemplateTitle = Parameters.GetString("TemplateTitle", "");
        bool UseInvertedNavigation = Parameters.GetBool("UseInvertedNavigation", false);
        int CacheTimeOnInvertedNavigation = Parameters.GetInt("CacheTimeOnInvertedNavigation", 36000);*/
        #endregion
        
        #region HackUnSef
        string PageKey = String.Empty;

        BXParamsBag<object> request = new BXParamsBag<object>();
        BXParamsBag<string> urlToPage = new BXParamsBag<string>();
        urlToPage.Add("SectionPage", SectionPageURL);
        urlToPage.Add("Section", SectionURL);
        
        if (EnableSef)
        {
            PageKey = MapVariable(SEFFolder, urlToPage, request, String.Empty);

            Results["ParamSectionId"] = ParamSectionId;
            Results["ParamElementId"] = ParamElementId;
            Results["ParamPageId"] = ParamPageId;
            Results["ParamElementCode"] = ParamElementCode;
            Results["ParamSectionCode"] = ParamSectionCode;
        }
        else
        {
            BXParamsBag<string> variableAliases = new BXParamsBag<string>();
			variableAliases.Add(ParamSectionId, AliasSectionId);
			variableAliases.Add(ParamElementId, AliasElementId);
			variableAliases.Add(ParamPageId, AliasPageId);
			variableAliases.Add(ParamSectionCode, AliasSectionCode);
			variableAliases.Add(ParamElementCode, AliasElementCode);
            MapVariable(variableAliases, request);

            Results["ParamSectionId"] = AliasSectionId;
            Results["ParamElementId"] = AliasElementId;
            Results["ParamPageId"] = AliasPageId;
            Results["ParamElementCode"] = AliasElementCode;
            Results["ParamSectionCode"] = AliasSectionCode;
        }

        SectionId = request.Get(ParamSectionId, SectionId);
        //ElementId = request.Get(ParamElementId, ElementId);
        PageId = request.Get(ParamPageId, PageId);
        ElementCode = request.Get<string>(ParamElementCode, ElementCode);
        SectionCode = request.Get<string>(ParamSectionCode, SectionCode);

        // Rewrite default variables
        request.Add(ParamSectionId, SectionId);
        //request.Add(ParamElementId, ElementId);
        request.Add(ParamElementCode, ElementCode);
        request.Add(ParamSectionCode, SectionCode);

        if (!EnableSef)
        {
            if (PageId > 0) PageKey = "SectionPage";
            //else if (ElementId > 0 || !String.IsNullOrEmpty(ElementCode)) PageKey = "Element";
            else if (SectionId > 0 || !String.IsNullOrEmpty(SectionCode)) PageKey = "Section";
        }

        Results["SectionURL"] = SectionURL;
        Results["SectionPageURL"] = SectionPageURL;
        Results["ElementURL"] = ElementURL;

        Results["SectionId"] = SectionId;
        //Results["ElementId"] = ElementId;
        Results["PageId"] = PageId;
        Results["ElementCode"] = ElementCode;
        Results["SectionCode"] = SectionCode;

        Results["PageKey"] = PageKey;
        #endregion

        if (!IsCached(IBlockTypeId, IBlockId, SectionId, PageId, SectionCode))
        {
			if (IBlockId > 0)
			{
				#region MakeComponentDataFilter
				BXIBlockElementCollection es = null;

				BXFilter esf = new BXFilter();
				BXOrderBy eso = new BXOrderBy();

				esf.Add(new BXFilterItem(BXIBlockElement.Fields.Active, BXSqlFilterOperators.Equal, "Y"));

				eso.Add(BXIBlockElement.Fields, String.Format("{0} {1}", SortBy1, SortOrder1));

				if (IBlockId > 0)
				{
					esf.Add(new BXFilterItem(BXIBlockElement.Fields.IBlock.ID, BXSqlFilterOperators.Equal, IBlockId));
				}
				if (!String.IsNullOrEmpty(SectionCode))
				{
					esf.Add(new BXFilterItem(BXIBlockElement.Fields.Sections.Section.Code, BXSqlFilterOperators.Equal, SectionCode));
					if (ShowSubelements)
					{
						esf.Add(new BXFilterItem(BXIBlockElement.Fields.IncludeParentSections, BXSqlFilterOperators.Equal, "Y"));
					}
				}
				else if (SectionId > 0)
				{
					esf.Add(new BXFilterItem(BXIBlockElement.Fields.Sections.Section.ID, BXSqlFilterOperators.Equal, SectionId));
					if (ShowSubelements)
					{
						esf.Add(new BXFilterItem(BXIBlockElement.Fields.IncludeParentSections, BXSqlFilterOperators.Equal, "Y"));
					}
				}
				else
				{
					if (ShowSubelements)
					{
						esf.Add(new BXFilterItem(BXIBlockElement.Fields.IncludeParentSections, BXSqlFilterOperators.Equal, "Y"));
					}
					else
						esf.Add(new BXFilterItem(BXIBlockElement.Fields.Sections.Section.ID, BXSqlFilterOperators.Equal, "0"));
				}
				#endregion

				#region Paging Operations
				string PageUrlTemplate = String.Empty;
				string DefaultPageUrl = String.Empty;
				if (EnableSef)
				{
					DefaultPageUrl = BXComponentManager.MakeLink(SEFFolder, SectionURL);
					PageUrlTemplate = BXComponentManager.MakeLink(SEFFolder, SectionPageURL);
				}
				else
				{
					DefaultPageUrl = SectionURL;
					PageUrlTemplate = SectionPageURL;
				}

				BXQueryParams queryParams = PreparePaging(
					delegate
					{
						return BXIBlockElement.Count(esf);
					},
					request,
					Results.Get<string>("ParamPageId"),
					false,
					DefaultPageUrl,
					PageUrlTemplate,
					string.Empty
				);
				es = BXIBlockElement.GetList(esf, eso, null, queryParams);

				#endregion

				#region SetPageTitle
				if (SetPageTitle)
				{
					string PageTitle = Parameters.Get<string>("SectionTitle", String.Empty);
					if (String.IsNullOrEmpty(PageTitle))
					{
						BXIBlockSection rootSection = null;
						if (!String.IsNullOrEmpty(SectionCode))
						{
							BXFilter sParentFilter = new BXFilter(
									new BXFilterItem(BXIBlockSection.Fields.Code, BXSqlFilterOperators.Equal, SectionCode),
									new BXFilterItem(BXIBlockSection.Fields.Active, BXSqlFilterOperators.Equal, "Y")
									);

							BXIBlockSectionCollection sCol = BXIBlockSection.GetList(sParentFilter, null);
							if (sCol != null && sCol.Count > 0)
								rootSection = sCol[0];
						}
						else if (SectionId > 0)
							rootSection = BXIBlockSection.GetById(SectionId);

						if (rootSection != null)
							PageTitle = rootSection.Name;
						else
						{
							BXIBlock iblock = BXIBlock.GetById(IBlockId);
							if (iblock != null)
								PageTitle = iblock.Name;
						}
					}

					Results["SectionName"] = PageTitle;
				}
				#endregion

				if (es != null)
				{
					Results["DataVolume"] = es.Count;
				}

				if (es != null && es.Count > 0)
				{
					List<Dictionary<string, string>> data = new List<Dictionary<string, string>>();
					foreach (BXIBlockElement el in es)
					{
						Dictionary<string, string> v = new Dictionary<string, string>();

						string imageUrl = String.Empty;
						BXFile image = el.DetailImageId > 0 ? el.DetailImage : el.PreviewImage;

						if (image != null)
							imageUrl = String.Format(
							"{0}ImageResizer.ashx?path={1}&width={2}&height={3}&fit={4}",
							BXUri.ToAbsoluteUri("~/bitrix/handlers/Main/"),
							UrlEncode(image.FileVirtualPath),
							Parameters.Get("PreviewWidth", 150),
							Parameters.Get("PreviewHeight", 150),
							!Parameters.Get<bool>("FlickrMode", false));

						v.Add("Id", el.Id.ToString());
						v.Add("Title", el.Name);
						v.Add("PreviewText", el.PreviewText);
						v.Add("PreviewTextType", el.PreviewTextType.ToString());
						v.Add("PreviewImage", imageUrl);

						request.Add(ParamElementId, el.Id);
						request.Add(ParamElementCode, String.IsNullOrEmpty(el.Code) ? String.Empty : el.Code);
						if (EnableSef)
							v.Add("ElementLink", BXStringUtility.HtmlEncodeEx(MakeLink(SEFFolder, ElementURL, request)));
						else
							v.Add("ElementLink", BXStringUtility.HtmlEncodeEx(MakeLink(ElementURL, request)));

						data.Add(v);

						Dictionary<string, BXCustomProperty> v2 = new Dictionary<string, BXCustomProperty>();
						BXCustomPropertyCollection props = el.Properties;
						if (props != null)
							foreach (KeyValuePair<string, BXCustomProperty> kcs in props)
								if (Properties.Exists(delegate(string x)
								{
									return x.Equals(kcs.Key, StringComparison.InvariantCultureIgnoreCase);
								}))
									v2[kcs.Key] = kcs.Value;

						Results["DataProperties_" + el.Id] = v2;
					}

					Results["Data"] = data;
				}

				Results["EnableAjaxA"] = Parameters.Get<bool>("EnableAjax", false) ? "EnableAjax=\"True\"" : "";
			}
			IncludeComponentTemplate();
        }

		if (SetPageTitle && Results.ContainsKey("SectionName") && Results["SectionName"] != null)
		{
			string PageTitle = Results.Get<string>("SectionName");

			if (Page is BXPublicPage)
				(Page as BXPublicPage).BXTitle = PageTitle;
		}
	}
	//METHODS
	protected void Page_Load(object sender, EventArgs e)
	{
		if (IBlockId > 0)
		{
			//if (EnableSef)
			//{
			//	MapVariable(Parameters.Get<string>("SEFFolder", "/photogallery"), Parameters.Get<string>("SEF_Album"), Results);
			//}
			//else
			//{
			//    BXParamsBag<string> variableAlias = new BXParamsBag<string>();
			//    variableAlias["AlbumID"] = Parameters.Get<string>("ParamAlbum", "Album");
			//    variableAlias["PageID"] = Parameters.Get<string>("ParamAlbumPage", "Album");
			//    variableAlias["PageShowAll"] = Parameters.Get<string>("ParamAlbumShowAll", "Album");
			//    MapVariable(variableAlias, Results);

			//    if (AlbumId > 0)
			//    {
			//        Results["AlbumParentID"] = BXInfoBlockSectionManagerOld.GetById(AlbumId).ParentSectionId;
			//    }
			//}

			int albumParent = 0;


			if (BXIBlock.IsUserCanOperate(IBlockId, BXIBlock.Operations.IBlockModifySections))
				CanModify = true;

			if (AlbumId > 0)
			{
				//load album
				AlbumItem = BXIBlockSection.GetById(AlbumId, Bitrix.Services.Text.BXTextEncoder.EmptyTextEncoder);

				if (AlbumItem != null)
				{
					albumParent = AlbumItem.SectionId;



					if (Page is BXPublicPage)
						((BXPublicPage)Page).MasterTitle = Server.HtmlDecode(AlbumItem.Name);
					Page.Title = AlbumItem.Name;
					IsNested = true;

					BXFile image = AlbumItem.Image;

					if (image != null)
					{
						Bitrix.Services.Image.BXImageInfo imageInfo = Bitrix.Services.Image.
							   BXImageUtility.GetResizedImage(image, Parameters.Get("PreviewWidth", 75),
							   Parameters.Get("PreviewHeight", 75));

						AlbumCoverUrl = imageInfo.GetUri();
					}

					FillNavChain();
				}
			}

			BackUrl = GetAlbumUrl(albumParent);

			UploadUrl = MakeLink(Parameters.Get<string>("UrlTemplateUpload", BXConfigurationUtility.Constants.ErrorHref), AlbumId);
			EditUrl = MakeLink(Parameters.Get<string>("UrlTemplateAlbumEdit", BXConfigurationUtility.Constants.ErrorHref), AlbumId);
			AddUrl = MakeLink(Parameters.Get<string>("UrlTemplateAlbumAdd", BXConfigurationUtility.Constants.ErrorHref), AlbumId);

			BXFilter filter = new BXFilter();
			BXPagingParams pagingParams = new BXPagingParams();
			if (AlbumItem != null)
			{

				filter.Add(new BXFilterItem(BXIBlockSection.Fields.IBlock.ID, BXSqlFilterOperators.Equal, Parameters.Get("IBlockId", 0)));
				filter.Add(new BXFilterItem(BXIBlockSection.Fields.SectionId, BXSqlFilterOperators.Equal, AlbumItem.Id));
				filter.Add(new BXFilterItem(BXIBlockSection.Fields.DepthLevel, BXSqlFilterOperators.Less, Album.DepthLevel + 2));

				BXFilter photoFilter = new BXFilter();
				photoFilter.Add(new BXFilterItem(BXIBlockElement.Fields.IBlock.ID, BXSqlFilterOperators.Equal, Parameters.Get("IBlockId", 0)));
				photoFilter.Add(new BXFilterItem(BXIBlockElement.Fields.Sections.Section.ID, BXSqlFilterOperators.Equal, Album.SectionId));

				BXParamsBag<object> mapParams = new BXParamsBag<object>();
		
				mapParams["AlbumID"] = AlbumId;
				
				
				pagingParams.AllowPaging = true;
				string pageId = Request.QueryString["page"];
				int photoId = Parameters.Get<int>("PhotoId",0);// если шаблон фото детально передал параметр, 
				//значит нужно показать элемент вместе с текущей страницей для вывода в слайдер
				pagingParams = PreparePagingParams();
				if (photoId > 0 && pageId==null)
				{
					//Determine page
					
					BXIBlockElement currentPhoto = BXIBlockElement.GetById(photoId);

					int count = BXIBlockElement.Count(new BXFilter(new BXFilterItem(BXIBlockElement.Fields.Sections.Section.ID, BXSqlFilterOperators.Equal, AlbumItem.Id),
																	new BXFilterItem(BXIBlockElement.Fields.IBlock.ID, BXSqlFilterOperators.Equal, currentPhoto.IBlockId)));


					if (currentPhoto != null)
					{
						BXFilter countFilter = new BXFilter();
						countFilter.Add(new BXFilterItem(BXIBlockElement.Fields.ID, BXSqlFilterOperators.Less, currentPhoto.Id));
						countFilter.Add(new BXFilterItem(BXIBlockElement.Fields.IBlock.ID, BXSqlFilterOperators.Equal, currentPhoto.IBlockId));
						countFilter.Add(new BXFilterItem(BXIBlockElement.Fields.Sections.Section.ID, BXSqlFilterOperators.Equal, AlbumItem.Id));

						int index = BXIBlockElement.Count(countFilter);

						BXPagingHelper helper = ResolvePagingHelper(count, pagingParams);
						pagingParams.Page = helper.GetOuterIndex(helper.GetPageIndexForItem(index));
						Component.Parameters["PagingPageId"] = (pagingParams.Page ?? 1).ToString();
						Component.Parameters["PageId"] = (pagingParams.Page ?? 1).ToString();
					}
				}




				BXQueryParams queryParams = PreparePaging(
					pagingParams,
										delegate
										{
											return BXIBlockElement.Count(photoFilter);
										},
					mapParams,
					"PageID",
					Parameters.Get<string>("UrlTemplateAlbum"),
					Parameters.Get<string>("UrlTemplateAlbumPage"),
					Parameters.Get<string>("UrlTemplateAlbumShowAll")
					);
				var photoOrderBy = new BXOrderBy();
				photoOrderBy.Add(BXIBlockElement.Fields, String.Format("{0} {1}", this.PhotoSortBy, this.PhotoSortOrder));
				PhotoItems = BXIBlockElement.GetList(photoFilter, photoOrderBy, null, queryParams, Bitrix.Services.Text.BXTextEncoder.EmptyTextEncoder);
				PhotoDescriptionDictionary = new Dictionary<BXIBlockElement, PhotoDescription>();
				//Component.Parameters["PageId"] = (pagingParams.Page ?? 1).ToString();
				ComponentCache["PageId"] = (pagingParams.Page ?? 1).ToString();
				if (Photos.Count > 0)
				{
					foreach (BXIBlockElement photo in PhotoItems)
					{
						PhotoDescription photoDesc = new PhotoDescription();

						photoDesc.Preview = string.Empty;

						BXFile image = photo.DetailImageId > 0 ? photo.DetailImage : photo.PreviewImage;

						if (image == null)
							continue;

						Bitrix.Services.Image.BXImageInfo imageInfo = Bitrix.Services.Image.
						BXImageUtility.GetResizedImage(image, Parameters.Get("PreviewWidth", 75),
						Parameters.Get("PreviewHeight", 75));
						photoDesc.Preview = imageInfo.GetUri();
						photoDesc.DetailUrl = image.GetUri();
						BXParamsBag<object> replace = new BXParamsBag<object>();
						replace.Add("PHOTOID", photo.Id);
						replace.Add("ALBUMID", AlbumId);
						if (!EnableSef)
						{
							photoDesc.PhotoUrl =
								string.Format("?{0}={1}", Parameters.Get<string>("ParamPhoto", "photo"), photo.Id);
						}
						else
						{
							photoDesc.PhotoUrl =
								MakeLink(Parameters.Get<string>("SEFFolder"), Parameters.Get<string>("SEF_Photo"), replace);
						}

						photoDesc.ActualCoverHeight = imageInfo.Height;
						photoDesc.ActualCoverWidth = imageInfo.Width;
						photoDesc.CurUserId = CurrentUserId;
						photoDesc.DetailHeight = image.Height;
						photoDesc.DetailWidth = image.Width;
						photoDesc.Element = photo;
						PhotoDescriptionDictionary[photo] = photoDesc;
						

					}
				}

				ParentAlbumId = Album.ParentSectionId;
			}
			else
			{
				filter.Add(new BXFilterItem(BXIBlockSection.Fields.IBlock.ID, BXSqlFilterOperators.Equal, Parameters.Get("IBlockId", 0)));
				filter.Add(new BXFilterItem(BXIBlockSection.Fields.DepthLevel, BXSqlFilterOperators.Less, 2));
				if (Page is BXPublicPage)
					((BXPublicPage)Page).MasterTitle = GetMessageRaw("Photogallery");
				Page.Title = GetMessageRaw("Photogallery");
				ParentAlbumId = 0;
			}
			var albumOrderBy = new BXOrderBy();
			albumOrderBy.Add(BXIBlockSection.Fields, String.Format("{0} {1}", this.AlbumSortBy, this.AlbumSortOrder));
			SectionItems = BXIBlockSection.GetList(filter, albumOrderBy, null, null, Bitrix.Services.Text.BXTextEncoder.EmptyTextEncoder);
			AlbumDescriptionDictionary = new Dictionary<BXIBlockSection, AlbumDescription>();

			if ((Sections.Count != 0) && (AlbumId > 0))
				IsParent = true;

			foreach (BXIBlockSection section in SectionItems)
			{
				AlbumDescription albumDesc = new AlbumDescription();

				filter = new BXFilter();
				filter.Add(new BXFilterItem(BXIBlockElement.Fields.IBlock.ID, BXSqlFilterOperators.Equal, Parameters.Get("IBlockId", 0)));
				filter.Add(new BXFilterItem(BXIBlockElement.Fields.Sections.Section.ID, BXSqlFilterOperators.Equal, section.Id));

				BXIBlockElementCollection elements = BXIBlockElement.GetList(filter, null);

				albumDesc.CoverImageUrl =
					BXUri.ToRelativeUri(
						"~/bitrix/components/bitrix/photogallery.album/templates/.default/images/no_image.png");

				albumDesc.Count = elements.Count;

				albumDesc.Url = GetAlbumUrl(section.Id);
				albumDesc.EditUrl = MakeLink(Parameters.Get<string>("UrlTemplateAlbumEdit", BXConfigurationUtility.Constants.ErrorHref), section.Id);

				BXFile image = section.Image;

				if (image == null)
					foreach (BXIBlockElement element in elements)
					{
						image = element.PreviewImage;
						if (image != null)
							break;
					}

				albumDesc.IsCoverEmpty = true;
				if (image != null)
				{
				    Bitrix.Services.Image.BXImageInfo imageInfo = Bitrix.Services.Image.
					    BXImageUtility.GetResizedImage(
                        image, Parameters.Get("CoverWidth", 75),
					    Parameters.Get("CoverHeight", 75));

				    albumDesc.CoverImageUrl = imageInfo.GetUri();
				    albumDesc.IsCoverEmpty = false;
				}

				AlbumDescriptionDictionary[section] = albumDesc;

			}

		}

		IncludeComponentTemplate();
	}
    public override void ProcessMessage(BXCommand cmd, bool executionContext, string executionVirtualPath)
    {
        #region Search
        if (cmd.Action == "Bitrix.Search.ProvideUrl")
        {
            string moduleId = cmd.Parameters.Get("moduleId", string.Empty);
            if (string.Equals(moduleId, "forum", StringComparison.OrdinalIgnoreCase) 
                && AllowComments 
                && BXModuleManager.IsModuleInstalled("Forum"))
            {
                //Поиск по комментариям к новостям
                int blockId = IBlockId;
                int forumId = cmd.Parameters.GetInt("itemGroup", 0);
                int postId = cmd.Parameters.GetInt("itemId", 0);
                int topicId = cmd.Parameters.GetInt("param1");


                if (blockId == 0 || !string.Equals(moduleId, "forum", StringComparison.OrdinalIgnoreCase) || forumId <= 0 || postId <= 0)
                    return;

                BXFilter f = new BXFilter(
                        new BXFilterItem(BXIBlockElement.Fields.Active, BXSqlFilterOperators.Equal, "Y"),
                        new BXFilterItem(BXIBlockElement.Fields.ActiveDate, BXSqlFilterOperators.Equal, "Y"),
                        new BXFilterItem(BXIBlockElement.Fields.IBlock.ID, BXSqlFilterOperators.Equal, blockId),
                        new BXFilterItem(BXIBlockElement.Fields.CustomFields[blockId].GetFieldByKey(CommentCustomPropertyName), BXSqlFilterOperators.Equal, topicId)
                        );

                string siteId = DesignerSite;
                if (!string.IsNullOrEmpty(siteId))
                    f.Add(new BXFilterItem(BXIBlockElement.Fields.IBlock.Sites.SiteId, BXSqlFilterOperators.Equal, siteId));

                BXIBlockElementCollection c = BXIBlockElement.GetList(f, null);
                if (c.Count == 0)
                    return;

                BXIBlockElement el = c[0];
                //формируем постоянную ссылку на комментарий
                string commentUrl = string.Empty;
                if (!EnableSef)
                    commentUrl = string.Format("{0}?{1}={2}&{3}={4}#comment{4}", BXSite.GetUrlForPath(executionVirtualPath, null, cmd.SiteId), ParamNews, el.Id.ToString(), ParamComment, postId.ToString());
                else
                {
                    BXParamsBag<object> commentSefParams = new BXParamsBag<object>();
                    commentSefParams["SectionId"] = string.Empty;
                    commentSefParams["ElementId"] = el.Id.ToString();
                    commentSefParams["CommentId"] = postId.ToString();
                    string t = SefDetailCommentRead;
                    if (t.IndexOf("##") < 0)
                        t = string.Concat(t, "##comment#CommentId#");
                    commentUrl = BXSefUrlUtility.MakeLink(CombineLink(SefFolder, t), commentSefParams).Replace("//", "/");
                }
                cmd.AddCommandResult(string.Concat("bitrix:forum@", executionVirtualPath), new BXCommandResult(BXCommandResultType.Ok, commentUrl));                    
                return;
            }

            if (!string.Equals(moduleId, "iblock", StringComparison.OrdinalIgnoreCase))
                return;

            if (IBlockId < 0 || cmd.Parameters.Get<int>("itemGroup") != IBlockId)
                return;

            int elementId = cmd.Parameters.Get("itemId", -1);
            if (elementId < 0)
                return;

            BXIBlockElement elm = BXIBlockElement.GetById(elementId);
            if (elm == null) return;
            BXParamsBag<object> p = new BXParamsBag<object>();
            p.Add("ElementId", elementId);
            p.Add("SectionId", elm.Sections.Count > 0 ? elm.Sections[0].SectionId.ToString() : String.Empty);
            string url;
            if (EnableSef)
            {
                url = MakeLink(SefFolder, SefNews, p);
                if (elm.Sections.Count == 0)
                    url = url.Replace("//", "/");
            }
            else
                url = MakeLink(string.Format("{0}?{1}=#ElementId#", BXSite.GetUrlForPath(executionVirtualPath, null, cmd.SiteId), ParamNews), p);
            cmd.AddCommandResult("bitrix:news@" + executionVirtualPath, new BXCommandResult(BXCommandResultType.Ok, url));
        }
        #endregion

        if (cmd.Action == "Bitrix.Main.GeneratePublicMenu")
        {
            //Совпадает ли тип меню в параметрах компонента с типом, который запрашивает система.
            if (!Parameters.Get("GenerateMenuType", "left").Equals(cmd.Parameters.Get<string>("menuType"), StringComparison.InvariantCultureIgnoreCase))
                return;

            //Генерируем меню только для тех адресов, которые выводит сам компонент.
            if (!Parameters.Get<bool>("EnableSEF") && !BXSiteRemapUtility.UnmapVirtualPath(executionVirtualPath).Equals(cmd.Parameters.Get<string>("uriPath"), StringComparison.InvariantCultureIgnoreCase))
                return;
            else if (Parameters.Get<bool>("EnableSEF") && !cmd.Parameters.Get<string>("uriPath").StartsWith(Bitrix.IO.BXPath.ToVirtualRelativePath(SefFolder.TrimStart('\\', '/')) + "/", StringComparison.InvariantCultureIgnoreCase))
                return;

            if (IBlockId < 0)
                return;

            BXParamsBag<object> request = new BXParamsBag<object>();
            BXParamsBag<string> urlToPage = new BXParamsBag<string>();

            if (EnableSef)
            {
                urlToPage["detail"] = SefNews;
                urlToPage["section"] = SefSection;
                urlToPage["news.page"] = SefPage;
                urlToPage["news.showall"] = SefShowAll;
                urlToPage["rss"] = Parameters.Get("Sef_Rss", String.Empty);
                urlToPage["sectionrss"] = Parameters.Get("Sef_Rss_Section", String.Empty);

                MapVariable(SefFolder, urlToPage, request, String.Empty, BXUri.ToRelativeUri(cmd.Parameters.Get<string>("uri")));
            }
            else
            {
                BXParamsBag<string> variableAlias = new BXParamsBag<string>();
                variableAlias["ElementId"] = ParamNews;
                variableAlias["SectionId"] = ParamSection;

                MapVariable(variableAlias, request, BXUri.ToRelativeUri(cmd.Parameters.Get<string>("uri")));
            }

            //Определим уровень доступа пунктов
            if ((menuItemPermisson = (string)BXCacheManager.MemoryCache.Get(PermissionCacheKey)) == null)
            {
                menuItemPermisson = String.Empty;
                StringBuilder menuItemRoles = new StringBuilder();
                if (Parameters.Get<bool>("UsePermissions"))
                {
                    foreach (string permission in Parameters.GetList("GroupPermissions", new List<object>()))
                    {
                        menuItemRoles.Append(permission);
                        menuItemRoles.Append(";");
                    }

                    if (menuItemRoles.Length > 0)
                        menuItemRoles.Append("Admin");
                }
                else
                {
                    BXRoleCollection iblockRoles = BXRoleManager.GetAllRolesForOperation("IBlockRead", "iblock", IBlockId.ToString());
                    foreach (BXRole role in iblockRoles)
                    {
                        //Если доступно всем
                        if (role.RoleName == "Guest")
                        {
                            menuItemRoles = null;
                            break;
                        }
                        //Если доступно группе User, значит достаточно проверить только для этой группы
                        else if (role.RoleName == "User")
                        {
                            menuItemRoles = null;
                            menuItemPermisson = "User";
                            break;
                        }
                        else
                        {
                            menuItemRoles.Append(role.RoleName);
                            menuItemRoles.Append(";");
                        }
                    }
                }

                if (menuItemRoles != null && menuItemRoles.Length > 0)
                    menuItemPermisson = menuItemRoles.ToString();

                BXCacheManager.MemoryCache.Insert(PermissionCacheKey, menuItemPermisson);
            }

            int elementId = 0, sectionId = 0;
            elementId = request.Get<int>("ElementId", elementId);
            sectionId = request.Get<int>("SectionId", sectionId);

            string parentLevelUri = null;
            List<BXPublicMenuItem> menuList = null;

            if (elementId > 0 && sectionId > 0)
            {
                parentLevelUri = MakeMenuUri(executionVirtualPath, sectionId);
            }
            //Если указан только элемент
            else if (elementId > 0)
            {
                BXFilter elementFilter = new BXFilter(
                    new BXFilterItem(BXIBlockElement.Fields.ID, BXSqlFilterOperators.Equal, elementId),
                    new BXFilterItem(BXIBlockElement.Fields.IBlock.ID, BXSqlFilterOperators.Equal, IBlockId)
                );

                if (Parameters.Get<bool>("ShowActiveElements", true))
                {
                    elementFilter.Add(new BXFilterItem(BXIBlockElement.Fields.Active, BXSqlFilterOperators.Equal, "Y"));
                    elementFilter.Add(new BXFilterItem(BXIBlockElement.Fields.ActiveDate, BXSqlFilterOperators.Equal, "Y"));
                }

                BXIBlockElementCollection element = BXIBlockElement.GetList(elementFilter, null);
                if (element != null && element.Count > 0)
                {
                    BXIBlockElement.BXInfoBlockElementSectionCollection sections = element[0].Sections;
                    if (sections != null && sections.Count > 0)
                    {
                        sectionId = sections[0].SectionId;
                        parentLevelUri = MakeMenuUri(executionVirtualPath, sectionId); //Меню строится для раздела, к которому привязан элемент
                    }
                }
            }

            //Если указан раздел выводим его дочерние разделы
            if (parentLevelUri == null && sectionId > 0)
            {
                BXIBlockSectionCollection sectionList = BXIBlockSection.GetList(
                    new BXFilter(
                        new BXFilterItem(BXIBlockSection.Fields.Active, BXSqlFilterOperators.Equal, "Y"),
                        new BXFilterItem(BXIBlockSection.Fields.ActiveGlobal, BXSqlFilterOperators.Equal, "Y"),
                        new BXFilterItem(BXIBlockSection.Fields.IBlock.ID, BXSqlFilterOperators.Equal, IBlockId),
                        new BXFilterItem(BXIBlockSection.Fields.SectionId, BXSqlFilterOperators.Equal, sectionId)
                    ),
                    new BXOrderBy(
                        new BXOrderByPair(BXIBlockSection.Fields.Sort, BXOrderByDirection.Asc),
                        new BXOrderByPair(BXIBlockSection.Fields.Name, BXOrderByDirection.Asc)
                    )
                );

                menuList = ExtractMenuItemsFromCollection(sectionList, executionVirtualPath);

                //Если нет дочерних разделов, то меню строится для родителя указанного раздела 
                if (menuList == null)
                {
                    sectionList = BXIBlockSection.GetList(
                        new BXFilter(
                            new BXFilterItem(BXIBlockSection.Fields.Active, BXSqlFilterOperators.Equal, "Y"),
                            new BXFilterItem(BXIBlockSection.Fields.ActiveGlobal, BXSqlFilterOperators.Equal, "Y"),
                            new BXFilterItem(BXIBlockSection.Fields.IBlock.ID, BXSqlFilterOperators.Equal, IBlockId),
                            new BXFilterItem(BXIBlockSection.Fields.ID, BXSqlFilterOperators.Equal, sectionId)
                        ),
                        new BXOrderBy(
                            new BXOrderByPair(BXIBlockSection.Fields.Sort, BXOrderByDirection.Asc),
                            new BXOrderByPair(BXIBlockSection.Fields.Name, BXOrderByDirection.Asc)
                        )
                    );

                    if (sectionList != null && sectionList.Count > 0 && sectionList[0].SectionId > 0)
                    {
                        parentLevelUri = MakeMenuUri(executionVirtualPath, sectionList[0].SectionId);
                    }
                    else
                    {
                        //Если такой раздел не существует или это раздел корневой (нет родителя)
                        if (Parameters.Get<bool>("EnableSEF"))
                            parentLevelUri = SefFolder;
                        else
                            parentLevelUri = BXSiteRemapUtility.UnmapVirtualPath(executionVirtualPath);
                    }
                }
            }

            //Если ничего не указано выводим корневые разделы
            Dictionary<string, BXPublicMenu.BXLoadMenuCommandParameter> menuTree = new Dictionary<string, BXPublicMenu.BXLoadMenuCommandParameter>();
            if (parentLevelUri == null && menuList == null)
            {

                /*BXIBlockSectionCollection sectionList = BXIBlockSection.GetList(
                    new BXFilter(
                        new BXFilterItem(BXIBlockSection.Fields.Active, BXSqlFilterOperators.Equal, "Y"),
                        new BXFilterItem(BXIBlockSection.Fields.ActiveGlobal, BXSqlFilterOperators.Equal, "Y"),
                        new BXFilterItem(BXIBlockSection.Fields.IBlock.ID, BXSqlFilterOperators.Equal, IBlockId),
                        new BXFilterItem(BXIBlockSection.Fields.SectionId, BXSqlFilterOperators.Equal, null)
                    ),

                    new BXOrderBy(
                        new BXOrderByPair(BXIBlockSection.Fields.Sort, BXOrderByDirection.Asc),
                        new BXOrderByPair(BXIBlockSection.Fields.Name, BXOrderByDirection.Asc)
                    )
                );

                            menuList = ExtractMenuItemsFromCollection(sectionList, executionVirtualPath);
            */
                BXIBlockSectionCollection sectionsList = BXIBlockSection.GetList(
                    new BXFilter(
                        new BXFilterItem(BXIBlockSection.Fields.Active, BXSqlFilterOperators.Equal, "Y"),
                        new BXFilterItem(BXIBlockSection.Fields.ActiveGlobal, BXSqlFilterOperators.Equal, "Y"),
                        new BXFilterItem(BXIBlockSection.Fields.IBlock.ID, BXSqlFilterOperators.Equal, IBlockId)
                    ),
                    new BXOrderBy(
                        new BXOrderByPair(BXIBlockSection.Fields.LeftMargin, BXOrderByDirection.Asc),
                        new BXOrderByPair(BXIBlockSection.Fields.Sort, BXOrderByDirection.Asc),
                        new BXOrderByPair(BXIBlockSection.Fields.Name, BXOrderByDirection.Asc)
                    )
                );

                Dictionary<int, List<BXPublicMenuItem>> sectionTree = new Dictionary<int, List<BXPublicMenuItem>>();
                foreach (BXIBlockSection section in sectionsList)
                {
                    if (!sectionTree.ContainsKey(section.SectionId))
                        sectionTree.Add(section.SectionId, new List<BXPublicMenuItem>());

                    BXPublicMenuItem menuItem = new BXPublicMenuItem();
                    menuItem.Title = section.Name;
                    menuItem.Links.Add(MakeMenuUri(executionVirtualPath, section.Id));
                    menuItem.Sort = section.Sort;
                    if (!String.IsNullOrEmpty(menuItemPermisson))
                    {
                        menuItem.ConditionType = ConditionType.Group;
                        menuItem.Condition = menuItemPermisson;
                    }
                    sectionTree[section.SectionId].Add(menuItem);
                }

                foreach (KeyValuePair<int, List<BXPublicMenuItem>> submenuList in sectionTree)
                {
                    string url = null;
                    if (submenuList.Key > 0)
                    {
                        url = MakeMenuUri(executionVirtualPath, submenuList.Key);
                    }
                    else
                    {
                        if (Parameters.Get<bool>("EnableSEF"))
                            url = SefFolder;
                        else
                            url = BXSiteRemapUtility.UnmapVirtualPath(executionVirtualPath);
                    }

                    menuTree.Add(url, new BXPublicMenu.BXLoadMenuCommandParameter(submenuList.Value, true, null));
                }
            }

            if (menuTree.Count > 0)
                cmd.AddCommandResult("bitrix:news@" + executionVirtualPath, new BXCommandResult(BXCommandResultType.Ok, menuTree));
            else
            {
                BXPublicMenu.BXLoadMenuCommandParameter menuResult = new BXPublicMenu.BXLoadMenuCommandParameter(menuList, true, parentLevelUri);
                cmd.AddCommandResult("bitrix:news@" + executionVirtualPath, new BXCommandResult(BXCommandResultType.Ok, menuResult));
            }


        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        #region InitializeStartup
        SectionId = Parameters.Get("SectionId", 0);

        bool COUNT_ELEMENTS = Parameters.Get<bool>("COUNT_ELEMENTS", false);
        string SortByWhat = Parameters.Get<string>("SortBy", "sort");
        string OrderByWhat = Parameters.Get<string>("OrderBy", "asc");
        #endregion

        BXParamsBag<object> request = new BXParamsBag<object>();

        if (EnableSef)
        {
            BXParamsBag<string> urlToPage = new BXParamsBag<string>();
            urlToPage.Add("Catalog.List0", SectionURL);
            urlToPage.Add("Catalog.List1", SectionPageURL);

            MapVariable(SEFFolder, urlToPage, request);

            Results["ParamSectionId"] = ParamSectionId;
            Results["ParamSectionCode"] = ParamSectionCode;
        }
        else
        {
            BXParamsBag<string> variableAlias = new BXParamsBag<string>();
            variableAlias[ParamSectionId] = AliasSectionId;
            variableAlias[ParamSectionCode] = AliasSectionCode;

            MapVariable(variableAlias, request);

            Results["ParamSectionId"] = AliasSectionId;
            Results["ParamSectionCode"] = AliasSectionCode;
        }

        //IBlockId = request.Get("iblock_id", IBlockId);
        SectionId = request.Get(ParamSectionId, SectionId);
        SectionCode = request.Get<string>(ParamSectionCode, SectionCode);

        // Rewrite default variables
        request.Add(ParamSectionId, SectionId);
        request.Add(ParamSectionCode, SectionCode);        

        Results["SectionURL"] = SectionURL;

        Results["SectionId"] = SectionId;
        Results["SectionCode"] = SectionCode;

        if (EnableSef)
            Results["CatalogRoot"] = BXPath.ToVirtualAbsolutePath(SEFFolder);
        else
            Results["CatalogRoot"] = Parameters.Get<string>("CatalogRoot", BXSefUrlManager.CurrentUrl.AbsolutePath);

        if (!IsCached(IBlockId, SectionId, SectionCode))
        {
            if (IBlockId > 0)
            {
                List<Dictionary<string, string>> sList = new List<Dictionary<string, string>>();
                                        
                int i = 0, baseDepth = 0;
                BXIBlockSectionCollection sections = null;


                if (SectionId <= 0 && String.IsNullOrEmpty(SectionCode))
                {
                    sections = BXIBlockSection.GetTree(IBlockId, Depth + 1);
                }
                else
                {
                    #region SectionList
                    BXOrderBy sOrder = new BXOrderBy();
					sOrder.Add(BXIBlockSection.Fields, String.Format("{0} {1}", SortByWhat, OrderByWhat));
					//sOrder.Add(BXIBlockSection.Fields, String.Format("{0} {1}", "id", "asc"));
                    BXIBlockSection parentSection = null;

                    if (String.IsNullOrEmpty(SectionCode))
                    {
                        if (SectionId > 0)
                            parentSection = BXIBlockSection.GetById(SectionId);
                    }
                    else
                    {
                        BXFilter sParentFilter = new BXFilter(
							new BXFilterItem(BXIBlockSection.Fields.Code, BXSqlFilterOperators.Equal, SectionCode),
							new BXFilterItem(BXIBlockSection.Fields.Active, BXSqlFilterOperators.Equal, "Y")
                            );

                        BXIBlockSectionCollection sCol = BXIBlockSection.GetList(sParentFilter, null);
                        if (sCol != null && sCol.Count > 0)
                            parentSection = sCol[0];
                    }

                    BXFilter sFilter = new BXFilter(
							new BXFilterItem(BXIBlockSection.Fields.IBlock.ID, BXSqlFilterOperators.Equal, IBlockId),
							new BXFilterItem(BXIBlockSection.Fields.Active, BXSqlFilterOperators.Equal, "Y")
                        );

                    if (parentSection != null)
                    {
                        ParentSectionId = parentSection.Id;                        
                        baseDepth = parentSection.DepthLevel;

						sFilter.Add(new BXFilterItem(BXIBlockSection.Fields.LeftMargin, BXSqlFilterOperators.GreaterOrEqual, parentSection.LeftMargin));
						sFilter.Add(new BXFilterItem(BXIBlockSection.Fields.RightMargin, BXSqlFilterOperators.Less, parentSection.RightMargin));
						sFilter.Add(new BXFilterItem(BXIBlockSection.Fields.DepthLevel, BXSqlFilterOperators.LessOrEqual, parentSection.DepthLevel + Depth));

                        sections = BXIBlockSection.GetList(sFilter, sOrder);
                    }
                    #endregion
                    #region NavChain
                    BXIBlockSectionCollection navChain = null;

                    if (SectionId > 0)
                    {
                        navChain = BXIBlockSection.GetNavChain(SectionId);
                    }
                    else if (ParentSectionId > 0)
                    {
                        navChain = BXIBlockSection.GetNavChain(ParentSectionId);                        
                    }

                    Results["NavChain"] = navChain;
                    SetupNavchain(navChain, request);  
                    #endregion
                }
                Results["DataVolume"] = (sections != null) ? sections.Count : 0;
				if (sections != null)
				{
					string str = String.Empty;
					if (EnableSef)
						str = String.Concat(SEFFolder, "/", SectionURL);
					else
						str = SectionURL;

					foreach (BXIBlockSection s in sections)
					{
						Dictionary<string, string> v = new Dictionary<string, string>();
						if (s.DepthLevel == 1)
						{
							i++;
							v.Add("I", (i < 10) ? "0" + i : i.ToString());
						}
						v.Add("SectionId", s.Id.ToString());
						v.Add("Depth", (s.DepthLevel - baseDepth).ToString());
						v.Add("Name", s.Name);
						if (COUNT_ELEMENTS)
							v.Add("ElementsCount", s.ElementsCount.ToString());
						if (!String.IsNullOrEmpty(SectionURL))
						{
							request["iblock_id"] = s.IBlockId;
							request["section_id"] = s.Id;
							request["section_code"] = String.IsNullOrEmpty(s.Code) ? String.Empty : s.Code;
							v.Add("Path", BXUri.ToRelativeUri(MakeLink(str, request)));
						}
						sList.Add(v);
					}
				}

                Results["Section"] = sList;

                Results["EnableAjaxA"] = Parameters.Get<bool>("EnableAjax", false)?
                    "EnableAjax=\"True\"": "";
            }

            IncludeComponentTemplate();
        }
        else
        {
             // 1. NavChain
            if (Results.ContainsKey("NavChain")) SetupNavchain((BXIBlockSectionCollection)Results["NavChain"], request);
        }
	}
	protected void AuthUserGridView_Select(object sender, Bitrix.UI.BXSelectEventArgs e)
	{
		var filter = new BXFilter(BXAdminFilter1.CurrentFilter, Bitrix.Security.BXUser.Fields);
		var self = currentUserCanModifySelfUser ? new BXFilterItem(Bitrix.Security.BXUser.Fields.UserId, BXSqlFilterOperators.Equal, BXIdentity.Current.Id) : null;
		var roles = (userViewRoles.Length > 1 || userViewRoles[0] != 0) ? new BXFilterItem(Bitrix.Security.BXUser.Fields.GetFieldByKey("CheckRoles"), BXSqlFilterOperators.LessOrEqual, userViewRoles) : null;

		if (self != null && roles != null)
			filter.Add(new BXFilterOr(self, roles));
		else if (roles != null)
			filter.Add(roles);

		e.Data = Bitrix.Security.BXUser.GetList(
			filter,
			new BXOrderBy(Bitrix.Security.BXUser.Fields, e.SortExpression),
			new BXSelectAdd(Bitrix.Security.BXUser.Fields.CustomFields.DefaultFields),
			new BXQueryParams(e.PagingOptions),
			BXTextEncoder.EmptyTextEncoder
		);
	}
		protected override void OnPreRender(EventArgs e)
		{
			base.OnPreRender(e);
			button.Attributes["onclick"] = string.Format(
				"jsUtils.OpenWindow('{0}?iblock_id={1}&n={2}&k={3}', 600, 500);",
				BXJSUtility.Encode(VirtualPathUtility.ToAbsolute("~/bitrix/admin/IBlockElementSearch.aspx")),
				IBlockId,
				text.ClientID,
				label.ClientID
			);

			int id;
			if (string.IsNullOrEmpty(text.Text) || !int.TryParse(text.Text.Trim(), out id) || id <= 0)
			{
				label.Text = "";
				return;
			}
			

			var filter = new BXFilter();
            filter.Add(new BXFilterItem(BXIBlockElement.Fields.ID, BXSqlFilterOperators.Equal, id));
            if (IBlockId > 0)
                filter.Add(new BXFilterItem(BXIBlockElement.Fields.IBlock.ID, BXSqlFilterOperators.Equal, IBlockId));
            
			var elements = BXIBlockElement.GetList(
				filter,
				null,
				new BXSelect(BXIBlockElement.Fields.Name),
				new BXQueryParams(new BXPagingOptions(0, 1))
			);
			label.Text = elements.Count == 0 ? "" : elements[0].Name;
		}
	protected void AuthUserGridView_SelectCount(object sender, BXSelectCountEventArgs e)
	{
		var filter = new BXFilter(BXAdminFilter1.CurrentFilter, Bitrix.Security.BXUser.Fields);
		var self = currentUserCanModifySelfUser ? new BXFilterItem(Bitrix.Security.BXUser.Fields.UserId, BXSqlFilterOperators.Equal, BXIdentity.Current.Id) : null;
		var roles = (userViewRoles.Length > 1 || userViewRoles[0] != 0) ? new BXFilterItem(Bitrix.Security.BXUser.Fields.GetFieldByKey("CheckRoles"), BXSqlFilterOperators.LessOrEqual, userViewRoles) : null;

		if (self != null && roles != null)
			filter.Add(new BXFilterOr(self, roles));
		else if (roles != null)
			filter.Add(roles);

		e.Count = Bitrix.Security.BXUser.Count(filter);
	}
    protected void Page_Load(object sender, EventArgs e)
    {
        Size = Parameters.Get("Size", 2);

        if (EnableSef)
        {
            MapVariable(Parameters.Get<string>("SEFFolder", "/photogallery"), Parameters.Get<string>("SEF_Photo"), Results);
        }
        else
        {
            BXParamsBag<string> variableAlias = new BXParamsBag<string>();

            variableAlias["PhotoId"] = Parameters.Get<string>("ParamPhoto", "photo");

            MapVariable(variableAlias, Results);
        }

        if (PhotoId > 0)
        {
            BXIBlockElement photoItem = BXIBlockElement.GetById(PhotoId);

            if (photoItem != null)
            {
                if (photoItem.Sections.Count > 0)
                {
                    int albumId = photoItem.Sections[0].SectionId;

                    BXFilter photoFilter = new BXFilter();
                    photoFilter.Add(new BXFilterItem(BXIBlockElement.Fields.Sections.Section.ID, BXSqlFilterOperators.Equal, albumId));
                    PhotoItems = BXIBlockElement.GetList(photoFilter,null,new BXSelectAdd(BXIBlockElement.Fields.DetailImage,BXIBlockElement.Fields.PreviewImage),null);
                }
                else
                {
                    PhotoItems = new BXIBlockElementCollection();
                    PhotoItems.Add(photoItem);
                }
                    foreach (BXIBlockElement photo in PhotoItems)
                    {

                        if (PhotoId == photo.Id)
                            SelectedIndex = PhotoItems.IndexOf(photo);

                        Results["Preview" + photo.Id.ToString()] = string.Empty;

                        BXFile image = photo.DetailImageId > 0 ? photo.DetailImage : photo.PreviewImage;

                        if (image == null)
                            continue;
                        BXParamsBag<object> vars = new BXParamsBag<object>();
                        vars["PhotoId"] = photo.Id;
                        Results["PHOTO_LINK_" + photo.Id.ToString()] = MakeLink(Parameters.Get<string>("UrlTemplatePhoto", BXConfigurationUtility.Constants.ErrorHref), vars);
                        // if we've found preview file with needed dimensions stored in cash folder, we return it

                        Bitrix.Services.Image.BXImageInfo imageInfo = Bitrix.Services.Image.
                            BXImageUtility.GetResizedImage(image, PreviewWidth, PreviewHeight);

                        Results["Preview" + photo.Id.ToString()] = imageInfo.GetUri();
                        Results["PreviewWidth" + photo.Id.ToString()] = imageInfo.Width;
                        Results["PreviewHeight" + photo.Id.ToString()] = imageInfo.Height;


                    }
                


            }
            if (Size > PhotoItems.Count)
                Size = PhotoItems.Count;
            IncludeComponentTemplate();
        }
    }
	protected void GridView1_SelectCount(object sender, BXSelectCountEventArgs e)
	{
		BXFilter filter = new BXFilter();
        if ( _userId > 0)
            filter.Add(new BXFilterItem(Bitrix.Security.BXUser.Fields.UserId, BXSqlFilterOperators.Equal, _userId));
        e.Count = Bitrix.Security.BXUser.Count(filter);
	}
    public override void ProcessMessage(BXCommand cmd, bool executionContext, string executionVirtualPath)
    {
        if (cmd.Action == "Bitrix.Search.ProvideUrl")
        {
            if (cmd.Parameters.Get<string>("moduleId") != "iblock")
                return;
            int iblockId = Parameters.Get("IBlockId", -1);
            if (iblockId < 0 || cmd.Parameters.Get<int>("itemGroup") != iblockId)
                return;
            int elementId = cmd.Parameters.Get("itemId", -1);
            if (elementId < 0)
                return;

            BXIBlockElement ibe = BXIBlockElement.GetById(elementId);
            BXIBlockSection ibs = null;
            if (ibe != null)
                foreach (int sid in ibe.Sections.ToList())
                {
                    ibs = BXIBlockSection.GetById(sid);
                    if (ibs != null)
                        break;
                }
            if (ibe == null || ibs == null)
                return;

            Results["SECTION_ID"] = ibs.Id;
            Results["ELEMENT_ID"] = ibe.Id;
            Results["SECTION_CODE"] = ibs.Code ?? string.Empty;
            Results["ELEMENT_CODE"] = ibe.Code ?? string.Empty;

            string url;
            if (Parameters.Get<bool>("EnableSEF"))
                url =
                    MakeLink(Parameters.Get<string>("SEFFolder"),
                             Parameters.Get<string>("SEF_URL_TEMPLATES_element", "#SECTION_ID#/#ELEMENT_ID#/"));
            else
                url = MakeLink(string.Format(
                                   "{0}?{1}=#SECTION_ID#&{2}=#ELEMENT_ID#",
                                   VirtualPathUtility.ToAbsolute(executionVirtualPath),
                                   Parameters.Get<string>("VARIABLE_ALIASES_SECTION_ID", "SECTION_ID"),
                                   Parameters.Get<string>("VARIABLE_ALIASES_ELEMENT_ID", "ELEMENT_ID")
                                   ));
            cmd.AddCommandResult("bitrix:catalog@" + executionVirtualPath,
                                 new BXCommandResult(BXCommandResultType.Ok, url));
        }

		if (cmd.Action == "Bitrix.Main.GeneratePublicMenu")
		{
			//Bitrix.Diagnostics.BXDump.ToFile(
			//    String.Format(
			//        "executionVirtualPath={0}, uriPath={1}, uri={2}, SefFolder={3}, GenerateMenuType={4}, menuType={5}", 
			//        executionVirtualPath, 
			//        cmd.Parameters.Get<string>("uriPath"), 
			//        cmd.Parameters.Get<string>("uri"), 
			//        Bitrix.IO.BXPath.ToVirtualRelativePath(SEFFolder.TrimStart('\\', '/')),
			//        Parameters.Get("GenerateMenuType", "left"),
			//        cmd.Parameters.Get<string>("menuType")
			//    )
			//);

			//if (!cmd.Parameters.Get<string>("uriPath").StartsWith(Bitrix.IO.BXPath.ToVirtualRelativePath(SEFFolder.TrimStart('\\', '/')) + "/", StringComparison.InvariantCultureIgnoreCase))
				//return;

			//Генерируем меню только для тех адресов, которые выводит сам компонент.
			if (!Parameters.Get<bool>("EnableSEF") && !executionVirtualPath.Equals(cmd.Parameters.Get<string>("uriPath"), StringComparison.InvariantCultureIgnoreCase))
				return;
			else if (Parameters.Get<bool>("EnableSEF") && !cmd.Parameters.Get<string>("uriPath").StartsWith(Bitrix.IO.BXPath.ToVirtualRelativePath(SEFFolder.TrimStart('\\', '/')) + "/", StringComparison.InvariantCultureIgnoreCase))
				return;

			if (!Parameters.Get("GenerateMenuType", "left").Equals(cmd.Parameters.Get<string>("menuType"), StringComparison.InvariantCultureIgnoreCase))
				return;

			int iblockId = Parameters.Get("IBlockId", -1);
			if (iblockId < 0)
			    return;

			BXParamsBag<string> urlToPage = new BXParamsBag<string>();
			BXParamsBag<object> request = new BXParamsBag<object>();
			string PageKey = String.Empty;

			urlToPage.Add("ElementTOP", TOPElementURL.TrimEnd('/', '\\'));
			urlToPage.Add("SectionPage", SectionPageURL.TrimEnd('/', '\\'));
			urlToPage.Add("Element", ElementURL.TrimEnd('/', '\\'));
			urlToPage.Add("Section", SectionURL.TrimEnd('/', '\\'));

			if (EnableSef)
			{
				PageKey = MapVariable(SEFFolder, urlToPage, request, String.Empty, BXUri.ToRelativeUri(cmd.Parameters.Get<string>("uri")));
			}
			else
			{
				BXParamsBag<string> variableAliases = new BXParamsBag<string>();
				variableAliases.Add(ParamSectionId, AliasSectionId);
				variableAliases.Add(ParamElementId, AliasElementId);
				variableAliases.Add(ParamPageId, AliasPageId);
				variableAliases.Add(ParamSectionCode, AliasSectionCode);
				variableAliases.Add(ParamElementCode, AliasElementCode);

				MapVariable(variableAliases, request, BXUri.ToRelativeUri(cmd.Parameters.Get<string>("uri")));
			}

			SectionId = request.Get(ParamSectionId, SectionId);
			ElementId = request.Get(ParamElementId, ElementId);
			PageId = request.Get(ParamPageId, PageId);
			ElementCode = request.Get(ParamElementCode, ElementCode);
			SectionCode = request.Get(ParamSectionCode, SectionCode);

			List<BXPublicMenuItem> resultList = null;
			string parentLevelUri = null;

			if (ElementId > 0 || !String.IsNullOrEmpty(ElementCode))
			{
				if (SectionId > 0 || !String.IsNullOrEmpty(SectionCode))
				{
					BXParamsBag<object> p = new BXParamsBag<object>();
					p["SECTION_ID"] = SectionId;
					p["SECTION_CODE"] = SectionCode;
					parentLevelUri = MakeMenuUri(executionVirtualPath, p);
				}
				else
				{
					BXFilter elFilter = new BXFilter(
						new BXFilterItem(BXIBlockElement.Fields.Active, BXSqlFilterOperators.Equal, "Y"),
						new BXFilterItem(BXIBlockElement.Fields.ActiveDate, BXSqlFilterOperators.Equal, "Y")
					);
					if (ElementId > 0)
						elFilter.Add(new BXFilterItem(BXIBlockElement.Fields.ID, BXSqlFilterOperators.Equal, ElementId));
					else
						elFilter.Add(new BXFilterItem(BXIBlockElement.Fields.Code, BXSqlFilterOperators.Equal, ElementCode));

					BXIBlockElementCollection collElement = BXIBlockElement.GetList(elFilter, null);
					if (collElement != null)
					{
						if (collElement.Count > 0)
						{
							BXIBlockElement.BXInfoBlockElementSectionCollection es = collElement[0].Sections;
							if (es != null)
							{
								if (es.Count > 0)
								{
									SectionId = es[0].SectionId;

									BXParamsBag<object> p = new BXParamsBag<object>();
									p["SECTION_ID"] = SectionId;

									if (Parameters.Get<bool>("EnableSEF") && SectionURL.Contains("#SECTION_CODE#"))
									{
										BXIBlockSectionCollection collSection = BXIBlockSection.GetList(
											new BXFilter(
												new BXFilterItem(BXIBlockSection.Fields.ActiveGlobal, BXSqlFilterOperators.Equal, "Y"),
												new BXFilterItem(BXIBlockSection.Fields.Active, BXSqlFilterOperators.Equal, "Y"),
												new BXFilterItem(BXIBlockSection.Fields.ID, BXSqlFilterOperators.Equal, SectionId),
												new BXFilterItem(BXIBlockSection.Fields.IBlock.ID, BXSqlFilterOperators.Equal, iblockId)
											),
											null
										);
										if (collSection != null)
										{
											if (collSection.Count > 0)
											{
												SectionCode = collSection[0].Code;
												p["SECTION_CODE"] = SectionCode;
											}
										}
									}

									parentLevelUri = MakeMenuUri(executionVirtualPath, p);
								}
							}
						}
					}
				}
			}

			if (parentLevelUri == null)
			{
				if (SectionId > 0 || !String.IsNullOrEmpty(SectionCode))
				{
					int parentSectionId = 0;
					bool parentSectionFound = false;

					if (SectionId <= 0)
					{
						BXIBlockSectionCollection coll = BXIBlockSection.GetList(
							new BXFilter(
								new BXFilterItem(BXIBlockSection.Fields.ActiveGlobal, BXSqlFilterOperators.Equal, "Y"),
								new BXFilterItem(BXIBlockSection.Fields.Active, BXSqlFilterOperators.Equal, "Y"),
								new BXFilterItem(BXIBlockSection.Fields.Code, BXSqlFilterOperators.Equal, SectionCode),
								new BXFilterItem(BXIBlockSection.Fields.IBlock.ID, BXSqlFilterOperators.Equal, iblockId)
							),
							null
						);
						if (coll != null)
						{
							if (coll.Count > 0)
							{
								SectionId = coll[0].Id;
								parentSectionId = coll[0].SectionId;
								parentSectionFound = true;
							}
						}
					}

					if (SectionId > 0)
					{
						BXIBlockSectionCollection coll = BXIBlockSection.GetList(
							new BXFilter(
								new BXFilterItem(BXIBlockSection.Fields.SectionId, BXSqlFilterOperators.Equal, SectionId),
								new BXFilterItem(BXIBlockSection.Fields.ActiveGlobal, BXSqlFilterOperators.Equal, "Y"),
								new BXFilterItem(BXIBlockSection.Fields.Active, BXSqlFilterOperators.Equal, "Y"),
								new BXFilterItem(BXIBlockSection.Fields.IBlock.ID, BXSqlFilterOperators.Equal, iblockId)
							),
							new BXOrderBy(
								new BXOrderByPair(BXIBlockSection.Fields.Sort, BXOrderByDirection.Asc),
								new BXOrderByPair(BXIBlockSection.Fields.Name, BXOrderByDirection.Asc)
							)
						);

						resultList = ExtractMenuItemsFromCollection(executionVirtualPath, resultList, coll);

						if (resultList == null)
						{
							if (!parentSectionFound)
							{
								coll = BXIBlockSection.GetList(
									new BXFilter(
										new BXFilterItem(BXIBlockSection.Fields.ActiveGlobal, BXSqlFilterOperators.Equal, "Y"),
										new BXFilterItem(BXIBlockSection.Fields.Active, BXSqlFilterOperators.Equal, "Y"),
										new BXFilterItem(BXIBlockSection.Fields.ID, BXSqlFilterOperators.Equal, SectionId),
										new BXFilterItem(BXIBlockSection.Fields.IBlock.ID, BXSqlFilterOperators.Equal, iblockId)
									),
									null
								);
								if (coll != null)
								{
									if (coll.Count > 0)
									{
										parentSectionFound = true;
										parentSectionId = coll[0].SectionId;
									}
								}
							}

							if (parentSectionFound && parentSectionId > 0)
							{
								BXParamsBag<object> p = new BXParamsBag<object>();
								p["SECTION_ID"] = parentSectionId;

								if (Parameters.Get<bool>("EnableSEF") && SectionURL.Contains("#SECTION_CODE#"))
								{
									coll = BXIBlockSection.GetList(
										new BXFilter(
											new BXFilterItem(BXIBlockSection.Fields.ActiveGlobal, BXSqlFilterOperators.Equal, "Y"),
											new BXFilterItem(BXIBlockSection.Fields.Active, BXSqlFilterOperators.Equal, "Y"),
											new BXFilterItem(BXIBlockSection.Fields.ID, BXSqlFilterOperators.Equal, parentSectionId),
											new BXFilterItem(BXIBlockSection.Fields.IBlock.ID, BXSqlFilterOperators.Equal, iblockId)
										),
										null
									);
									if (coll != null)
									{
										if (coll.Count > 0)
											p["SECTION_CODE"] = coll[0].Code;
									}
								}

								parentLevelUri = MakeMenuUri(executionVirtualPath, p);
							}
							else
							{
								if (Parameters.Get<bool>("EnableSEF"))
									parentLevelUri = MakeLink(Parameters.Get<string>("SEFFolder"), "");
								else
									parentLevelUri = BXUri.ToAppRelativeUri(executionVirtualPath);
							}
						}
					}
				}
			}

			if (parentLevelUri == null)
			{
				if (resultList == null)
				{
					BXIBlockSectionCollection coll = BXIBlockSection.GetList(
						new BXFilter(
							new BXFilterItem(BXIBlockSection.Fields.SectionId, BXSqlFilterOperators.Equal, null),
							new BXFilterItem(BXIBlockSection.Fields.ActiveGlobal, BXSqlFilterOperators.Equal, "Y"),
							new BXFilterItem(BXIBlockSection.Fields.Active, BXSqlFilterOperators.Equal, "Y"),
							new BXFilterItem(BXIBlockSection.Fields.IBlock.ID, BXSqlFilterOperators.Equal, iblockId)
						),
						new BXOrderBy(
							new BXOrderByPair(BXIBlockSection.Fields.Sort, BXOrderByDirection.Asc),
							new BXOrderByPair(BXIBlockSection.Fields.Name, BXOrderByDirection.Asc)
						)
					);

					resultList = ExtractMenuItemsFromCollection(executionVirtualPath, resultList, coll);
				}
			}

			BXPublicMenu.BXLoadMenuCommandParameter r = new BXPublicMenu.BXLoadMenuCommandParameter(resultList, true, parentLevelUri);
			cmd.AddCommandResult("bitrix:catalog@" + executionVirtualPath, new BXCommandResult(BXCommandResultType.Ok, r));
		}
	}
        protected override void LoadComponentDefinition()
        {
            #region Properties
            List<BXParamValue> properties = new List<BXParamValue>(),
                                propertiesForUserReference = new List<BXParamValue>();
            int selectedIblockId = 0;
            if (Parameters.ContainsKey("IBlockId"))
                int.TryParse(Parameters["IBlockId"], out selectedIblockId);

            if (selectedIblockId > 0)
            {
                BXCustomFieldCollection customFields = BXIBlock.GetCustomFields(selectedIblockId);
                foreach (BXCustomField customField in customFields)
                {
                    string title = BXTextEncoder.HtmlTextEncoder.Decode(customField.EditFormLabel);
                    string code = customField.Name.ToUpper();
                    properties.Add(new BXParamValue(title, code));
                    if (string.Equals(customField.CustomTypeId, "Bitrix.System.Int", StringComparison.Ordinal))
                        propertiesForUserReference.Add(new BXParamValue(title, code));
                }
            }
            #endregion

            #region Iblock type
            List<BXParamValue> typeParamValue = new List<BXParamValue>();
            typeParamValue.Add(new BXParamValue(GetMessageRaw("SelectIBlockType"), string.Empty));

            BXIBlockTypeCollection iblockTypes = BXIBlockType.GetList(null, new BXOrderBy(new BXOrderByPair(BXIBlockType.Fields.Name, BXOrderByDirection.Asc)), null, null, BXTextEncoder.EmptyTextEncoder);
            foreach (BXIBlockType iblockType in iblockTypes)
                typeParamValue.Add(new BXParamValue(iblockType.Translations[BXLoc.CurrentLocale].Name, iblockType.Id.ToString()));

            ParamsDefinition["IBlockTypeId"].Values = typeParamValue;
            ParamsDefinition["IBlockTypeId"].RefreshOnDirty = true;
            #endregion

            #region Iblock
            int selectedIBlockType = 0;
            if (Parameters.ContainsKey("IBlockTypeId"))
                int.TryParse(Parameters["IBlockTypeId"], out selectedIBlockType);

            BXFilter filter = new BXFilter();
            if (selectedIBlockType > 0)
                filter.Add(new BXFilterItem(BXIBlock.Fields.Type.ID, BXSqlFilterOperators.Equal, selectedIBlockType));
            if (!string.IsNullOrEmpty(DesignerSite))
                filter.Add(new BXFilterItem(BXIBlock.Fields.Sites.SiteId, BXSqlFilterOperators.Equal, DesignerSite));

            List<BXParamValue> iblockParamValue = new List<BXParamValue>();
            iblockParamValue.Add(new BXParamValue(GetMessageRaw("SelectIBlockID"), string.Empty));
            BXIBlockCollection iblocks = BXIBlock.GetList(filter, new BXOrderBy(new BXOrderByPair(BXIBlock.Fields.Name, BXOrderByDirection.Asc)), null, null, BXTextEncoder.EmptyTextEncoder);
            foreach (BXIBlock iblock in iblocks)
                iblockParamValue.Add(new BXParamValue(iblock.Name, iblock.Id.ToString()));

            ParamsDefinition["IBlockId"].Values = iblockParamValue;
            ParamsDefinition["IBlockId"].RefreshOnDirty = true;
            #endregion

            #region Sorting
            List<BXParamValue> sortingFields = new List<BXParamValue>();
            sortingFields.Add(new BXParamValue(GetMessageRaw("ElementID"), "ID"));
            sortingFields.Add(new BXParamValue(GetMessageRaw("ElementName"), "Name"));
            sortingFields.Add(new BXParamValue(GetMessageRaw("Active"), "Active"));
            sortingFields.Add(new BXParamValue(GetMessageRaw("ActiveFromDate"), "ActiveFromDate"));
            sortingFields.Add(new BXParamValue(GetMessageRaw("ActiveUntilDate"), "ActiveToDate"));
            sortingFields.Add(new BXParamValue(GetMessageRaw("SortIndex"), "Sort"));
            sortingFields.Add(new BXParamValue(GetMessageRaw("DateOfModification"), "UpdateDate"));
            sortingFields.AddRange(properties);

            ParamsDefinition["SortBy"].Values = sortingFields;
            #endregion

            #region Access
            //RolesAuthorizedToManage && RolesAuthorizedToAdminister && RolesAuthorizedToView && RolesAuthorizedToManageOfActivation
            IList<BXParamValue> rolesAuthorizedToManage = ParamsDefinition["RolesAuthorizedToManage"].Values;
            if (rolesAuthorizedToManage.Count > 0)
                rolesAuthorizedToManage.Clear();

            IList<BXParamValue> rolesAuthorizedToAdminister = ParamsDefinition["RolesAuthorizedToAdminister"].Values;
            if (rolesAuthorizedToAdminister.Count > 0)
                rolesAuthorizedToAdminister.Clear();

            IList<BXParamValue> rolesAuthorizedToView = ParamsDefinition["RolesAuthorizedToView"].Values;
            if (rolesAuthorizedToView.Count > 0)
                rolesAuthorizedToView.Clear();

            IList<BXParamValue> authRolesAuthorizedToManageOfActivationValues = ParamsDefinition["RolesAuthorizedToManageOfActivation"].Values;
            if (authRolesAuthorizedToManageOfActivationValues.Count > 0)
                authRolesAuthorizedToManageOfActivationValues.Clear();

            BXRoleCollection roles = BXRoleManager.GetList(new BXFormFilter(new BXFormFilterItem("Active", true, BXSqlFilterOperators.Equal)), new BXOrderBy_old("RoleName", "Asc"));
            for (int i = 0; i < roles.Count; i++)
            {
                BXRole role = roles[i];
                BXParamValue v = new BXParamValue(role.Title, role.RoleName);
                rolesAuthorizedToManage.Add(v);
                rolesAuthorizedToAdminister.Add(v);
                rolesAuthorizedToView.Add(v);
                authRolesAuthorizedToManageOfActivationValues.Add(v);
            }
            //---
            //MannerOfIssueModificationPermission
            IList<BXParamValue> manOfIssueModificationPermissionValues = ParamsDefinition["MannerOfIssueModificationPermission"].Values;
            if (manOfIssueModificationPermissionValues.Count > 0)
                manOfIssueModificationPermissionValues.Clear();

            foreach (string n in Enum.GetNames(typeof(MannerOfIssueModificationPermission)))
                manOfIssueModificationPermissionValues.Add(new BXParamValue(GetMessageRaw(string.Concat("MannerOfIssueModificationPermission", n)), n));
            //---
            //MannerOfUserAssociation
            IList<BXParamValue> mannerOfUserAssociationValues = ParamsDefinition["MannerOfUserAssociation"].Values;
            if (mannerOfUserAssociationValues.Count > 0)
                mannerOfUserAssociationValues.Clear();

            foreach (string n in Enum.GetNames(typeof(MannerOfUserAssociation)))
                mannerOfUserAssociationValues.Add(new BXParamValue(GetMessageRaw(string.Concat("MannerOfUserAssociation", n)), n));
            //---
            //UserAssociatedByCustomIBlockProperty
            IList<BXParamValue> userAssociatedByCustomIBlockPropertyValues = ParamsDefinition["UserAssociatedByCustomIBlockProperty"].Values;
            if (userAssociatedByCustomIBlockPropertyValues.Count > 0)
                userAssociatedByCustomIBlockPropertyValues.Clear();

            userAssociatedByCustomIBlockPropertyValues.Add(new BXParamValue(GetMessageRaw("NotSelected"), string.Empty));
            for (int n = 0; n < propertiesForUserReference.Count; n++)
                userAssociatedByCustomIBlockPropertyValues.Add(propertiesForUserReference[n]);
            //---
            //MannerOfUserIdentification
            IList<BXParamValue> mannerOfUserIdentificationValues = ParamsDefinition["MannerOfUserIdentification"].Values;
            if (mannerOfUserIdentificationValues.Count > 0)
                mannerOfUserIdentificationValues.Clear();

            foreach (string n in Enum.GetNames(typeof(MannerOfUserIdentification)))
                mannerOfUserIdentificationValues.Add(new BXParamValue(GetMessageRaw(string.Concat("MannerOfUserIdentification", n)), n));
            //---
            IList<BXParamValue> elementStatusValues = ParamsDefinition["ElementActiveAfterSave"].Values;
            if (elementStatusValues.Count > 0)
                elementStatusValues.Clear();
            foreach (string n in Enum.GetNames(typeof(ElementStatus)))
                elementStatusValues.Add(new BXParamValue(GetMessageRaw(string.Concat("ElementStatus", n)), n));
            #endregion

            #region WebForm
            List<BXParamValue> fields = new List<BXParamValue>();
            fields.Add(new BXParamValue(GetMessageRaw("ElementFieldCaptionActive"), "Active"));
            fields.Add(new BXParamValue(GetMessageRaw("ElementFieldCaptionName"), "Name"));
            fields.Add(new BXParamValue(GetMessageRaw("ElementFieldCaptionActiveFromDate"), "ActiveFromDate"));
            fields.Add(new BXParamValue(GetMessageRaw("ElementFieldCaptionActiveToDate"), "ActiveToDate"));
            fields.Add(new BXParamValue(GetMessageRaw("ElementFieldCaptionSections"), "Sections"));
            fields.Add(new BXParamValue(GetMessageRaw("ElementFieldCaptionPreviewText"), "PreviewText"));
            fields.Add(new BXParamValue(GetMessageRaw("ElementFieldCaptionPreviewPicture"), "PreviewImage"));
            fields.Add(new BXParamValue(GetMessageRaw("ElementFieldCaptionDetailText"), "DetailText"));
            fields.Add(new BXParamValue(GetMessageRaw("ElementFieldCaptionDetailPicture"), "DetailImage"));

            IList<BXParamValue> requiredFieldsValues = ParamsDefinition["RequiredFields"].Values;
            if (requiredFieldsValues.Count > 0)
                requiredFieldsValues.Clear();

            IList<BXParamValue> editableFieldsValues = ParamsDefinition["EditFields"].Values;
            if (editableFieldsValues.Count > 0)
                editableFieldsValues.Clear();

            int fieldCount = fields.Count;
            for (int n = 0; n < fieldCount; n++)
            {
                requiredFieldsValues.Add(fields[n]);
                editableFieldsValues.Add(fields[n]);
            }


            editableFieldsValues.Add(new BXParamValue(GetMessageRaw("ElementFieldCaptionCaptcha"), "Captcha"));
            if (selectedIblockId > 0)
            {
                BXCustomFieldCollection customFields = BXIBlock.GetCustomFields(selectedIblockId);
                foreach (BXCustomField customField in customFields)
                {
                    string title = BXTextEncoder.HtmlTextEncoder.Decode(customField.EditFormLabel);
                    string code = customField.Name.ToUpper();
                    editableFieldsValues.Add(new BXParamValue(title, string.Concat("PROPERTY_", code)));
                }
            }
            #endregion

        }
 protected void BXSubscriptionsGrid_SelectCount(object sender, BXSelectCountEventArgs e)
 {
     if (UserId <= 0)
     {
         e.Count = 0;
         return;
     }
     currentFilter = new BXFilter(new BXFilterItem(BXForumSubscription.Fields.Subscriber.Id,BXSqlFilterOperators.Equal,UserId));
     currentFilter.Add(new BXFilter(BXSubscriptionsFilter.CurrentFilter, BXForumSubscription.Fields));
     e.Count = BXForumSubscription.Count(currentFilter);
 }
        protected override void LoadComponentDefinition()
        {
            //Iblock type
            List<BXParamValue> typeParamValue = new List<BXParamValue>();
            typeParamValue.Add(new BXParamValue(GetMessageRaw("SelectIBlockType"), ""));

            BXIBlockTypeCollection iblockTypes = BXIBlockType.GetList(null, new BXOrderBy(new BXOrderByPair(BXIBlockType.Fields.Name, BXOrderByDirection.Asc)), null, null, BXTextEncoder.EmptyTextEncoder);
            foreach (BXIBlockType iblockType in iblockTypes)
                typeParamValue.Add(new BXParamValue(iblockType.Translations[BXLoc.CurrentLocale].Name, iblockType.Id.ToString()));

            ParamsDefinition["IBlockTypeId"].Values = typeParamValue;
            ParamsDefinition["IBlockTypeId"].RefreshOnDirty = true;

            //Iblock
            int selectedIBlockType = 0;
            if (Parameters.ContainsKey("IBlockTypeId"))
                int.TryParse(Parameters["IBlockTypeId"], out selectedIBlockType);

            BXFilter filter = new BXFilter();
            if (selectedIBlockType > 0)
                filter.Add(new BXFilterItem(BXIBlock.Fields.Type.ID, BXSqlFilterOperators.Equal, selectedIBlockType));
            if (!String.IsNullOrEmpty(DesignerSite))
                filter.Add(new BXFilterItem(BXIBlock.Fields.Sites.SiteId, BXSqlFilterOperators.Equal, DesignerSite));

            List<BXParamValue> iblockParamValue = new List<BXParamValue>();
            iblockParamValue.Add(new BXParamValue(GetMessageRaw("SelectIBlockID"), "-"));
            BXIBlockCollection iblocks = BXIBlock.GetList(filter, new BXOrderBy(new BXOrderByPair(BXIBlock.Fields.Name, BXOrderByDirection.Asc)), null, null, BXTextEncoder.EmptyTextEncoder);
            foreach (BXIBlock iblock in iblocks)
                iblockParamValue.Add(new BXParamValue(iblock.Name, iblock.Id.ToString()));

            ParamsDefinition["IBlockId"].Values = iblockParamValue;
            ParamsDefinition["IBlockId"].RefreshOnDirty = true;

            //Properties
            int selectedIblockId = 0;
            if (Parameters.ContainsKey("IBlockId"))
                int.TryParse(Parameters["IBlockId"], out selectedIblockId);

            List<BXParamValue> sortProperties = new List<BXParamValue>();
            List<BXParamValue> properties = new List<BXParamValue>();
            properties.Add(new BXParamValue(GetMessageRaw("NotSelected"), "-"));

            if (selectedIblockId > 0)
            {
                BXCustomFieldCollection customFields = BXIBlock.GetCustomFields(selectedIblockId);
                foreach (BXCustomField customField in customFields)
                {
                    string title = BXTextEncoder.HtmlTextEncoder.Decode(customField.EditFormLabel);
                    string code = customField.Name.ToUpper();
                    properties.Add(new BXParamValue(title, code));
                    sortProperties.Add(new BXParamValue(title, "-" + code));
                }
            }

            //List<BXParamValue> properties1 = new List<BXParamValue>(properties);
            //properties1.RemoveAt(0);
            //ParamsDefinition["ListProperties"].Values = properties1;
            ParamsDefinition["ListProperties"].Values = properties;

            ParamsDefinition["DetailProperties"].Values = properties;
            ParamsDefinition["PropertyKeywords"].Values = properties;
            ParamsDefinition["PropertyDescription"].Values = properties;
            ParamsDefinition["TopProperties"].Values = properties;
            ParamsDefinition["IBlockElementPropertyForFilePath"].Values = properties;
            ParamsDefinition["IBlockElementPropertyForPlaylistPreviewImageFilePath"].Values = properties;
            ParamsDefinition["IBlockElementPropertyForPlayerPreviewImageFilePath"].Values = properties;
            ParamsDefinition["IBlockElementPropertyForDownloadingFilePath"].Values = properties;

            //Sorting
            List<BXParamValue> sortingFields = new List<BXParamValue>();
            sortingFields.Add(new BXParamValue(GetMessageRaw("ElementID"), "ID"));
            sortingFields.Add(new BXParamValue(GetMessageRaw("ElementName"), "Name"));
            sortingFields.Add(new BXParamValue(GetMessageRaw("ActiveFromDate"), "ActiveFromDate"));
            sortingFields.Add(new BXParamValue(GetMessageRaw("ActiveUntilDate"), "ActiveToDate"));
            sortingFields.Add(new BXParamValue(GetMessageRaw("SortIndex"), "Sort"));
            sortingFields.Add(new BXParamValue(GetMessageRaw("DateOfModification"), "UpdateDate"));
            sortingFields.AddRange(sortProperties);

            ParamsDefinition["ListSortBy"].Values = sortingFields;
            ParamsDefinition["TopSortBy"].Values = sortingFields;

            #region PlayerStretching
            string[] playerStretchingModeNameArr = Enum.GetNames(typeof(MediaPlayerStretchingMode));
            int playerStretchingModeNameArrCount = playerStretchingModeNameArr != null ? playerStretchingModeNameArr.Length : 0;
            if (playerStretchingModeNameArrCount > 0)
            {
                BXParamValue[] paramValueArr = new BXParamValue[playerStretchingModeNameArrCount];
                for (int i = 0; i < playerStretchingModeNameArrCount; i++)
                {
                    string playerStretchingModeName = playerStretchingModeNameArr[i];
                    paramValueArr[i] = new BXParamValue(GetMessageRaw(string.Concat("MediaPlayerStretchingMode", playerStretchingModeName)), playerStretchingModeName);
                }
                BXParam palyerStretchingModeParam = ParamsDefinition["PlayerStretching"];
                IList<BXParamValue> palyerStretchingModeParamVals = palyerStretchingModeParam.Values;
                if (palyerStretchingModeParamVals != null)
                {
                    if (palyerStretchingModeParamVals.Count > 0)
                        palyerStretchingModeParamVals.Clear();
                    for (int j = 0; j < playerStretchingModeNameArrCount; j++)
                        palyerStretchingModeParamVals.Add(paramValueArr[j]);
                }
                else
                    palyerStretchingModeParam.Values = new List<BXParamValue>(paramValueArr);
            }
            else
            {
                IList<BXParamValue> palyerStretchingModeParamVals = ParamsDefinition["PlayerStretching"].Values;
                if (palyerStretchingModeParamVals != null && palyerStretchingModeParamVals.Count > 0)
                    palyerStretchingModeParamVals.Clear();
            }
            #endregion

            #region PlayerDownloadingLinkTargetWindow
            IList<BXParamValue> playerDownloadingLinkTargetWindowVals = ParamsDefinition["PlayerDownloadingLinkTargetWindow"].Values;
            playerDownloadingLinkTargetWindowVals.Add(new BXParamValue(GetMessageRaw("PlayerDownloadingLinkTargetWindowSelf"), "_self"));
            playerDownloadingLinkTargetWindowVals.Add(new BXParamValue(GetMessageRaw("PlayerDownloadingLinkTargetWindowBlank"), "_blank"));
            #endregion
        }
    protected void ItemGrid_Select(object sender, BXSelectEventArgs e)
    {
        if (typeSelectError != true)
            typeSelectError = false;

        List<RatingVotingWrapper> list = new List<RatingVotingWrapper>();
        
        BXFilter f = new BXFilter(ItemFilter.CurrentFilter, BXRatingVoting.Fields);
        //f.Add(new BXFilterItem(BXRatingVoting.Fields.TotalVotes, BXSqlFilterOperators.Greater, 0));

        //если задан тип элемента и поисковая фраза - ищем поиском
        BXFilterItem searchFilter = null;

        if (ItemFilter.CurrentFilter.Exists(TypeFilterExist) && ItemFilter.CurrentFilter.Exists(VotingSubjectContainsExist))
        {
            #region запускаем поиск по введенной строке
            //ErrorMessage.Visible = false;
            List<BXSearchResult> results = new List<BXSearchResult>();

            string boundEntityTypeId = string.Empty,
                moduleSearchId = string.Empty, 
                searchQuery = string.Empty;
            BXFormFilterItem tmp = null;
            foreach (BXFormFilterItem f1 in ItemFilter.CurrentFilter)
            {
                if (f1.filterName == "BoundEntityTypeId")
                    boundEntityTypeId = f1.filterValue.ToString();
                else if (f1.filterName == "VotingSubjectContains")
                {
                    searchQuery = f1.filterValue.ToString();
                    //удаляем фильтр из списка по VotingSubjectContains, 
                    //чтобы не создавать лишних условий в фильтре
                    tmp = f1;
                }
            }

            ItemFilter.CurrentFilter.Remove(tmp);
            //если опознан модуль и есть результаты поиска по словосочетанию
            if (TryGetModuleId(boundEntityTypeId, out moduleSearchId))
                switch (moduleSearchId)
                {
                    case "iblock":
                        List<int> iblockElementIds = new List<int>();
                        results = SearchItems(moduleSearchId, searchQuery);
                        foreach (BXSearchResult r in results)
                        {
                            int var_i;
                            int.TryParse(r.Content.ItemId, out var_i);
                            iblockElementIds.Add(var_i);
                        }
                        searchFilter = new BXFilterItem(BXRatingVoting.Fields.BoundEntityId, BXSqlFilterOperators.In, iblockElementIds);
                        f.Add(searchFilter);
                        break;
                    case "blog":
                        List<int> blogPostIds = new List<int>();
                        results = SearchItems(moduleSearchId, searchQuery);
                        foreach (BXSearchResult r in results)
                        {
                            int var_i;
                            string var_s = r.Content.ItemId;
                            var_s = var_s.Remove(0, 1);
                            int.TryParse(var_s, out var_i);
                            blogPostIds.Add(var_i);
                        }
                        searchFilter = new BXFilterItem(BXRatingVoting.Fields.BoundEntityId, BXSqlFilterOperators.In, blogPostIds);
                        f.Add(searchFilter);
                        break;
                    case "forum":
                        List<int> forumPostIds = new List<int>();
                        results = SearchItems(moduleSearchId, searchQuery);
                        foreach (BXSearchResult r in results)
                        {
                            int var_i;
                            int.TryParse(r.Content.ItemId, out var_i);
                            forumPostIds.Add(var_i);
                        }
                        searchFilter = new BXFilterItem(BXRatingVoting.Fields.BoundEntityId, BXSqlFilterOperators.In, forumPostIds);
                        f.Add(searchFilter);
                        break;
                    case "user":
                        List<int> userIds = new List<int>();
                        BXUserCollection users = BXUserManager.GetList(new BXFormFilter(new BXFormFilterItem("username", searchQuery, BXSqlFilterOperators.Equal)), new BXOrderBy_old());
                        if (users.Count > 0)
                            searchFilter = new BXFilterItem(BXRatingVoting.Fields.BoundEntityId, BXSqlFilterOperators.Equal, users[0].UserId);
                        else
                        {
                            e.Data = list;
                            return;
                        }
                        break;
                    default:
                        e.Data = list;
                        return;
                }
            #endregion
        }
        else if (ItemFilter.CurrentFilter.Exists(VotingSubjectContainsExist) && !typeSelectError)
        {
            //ErrorMessage.Visible = true;
            ErrorMessage.AddErrorText(GetMessage("Error.ChooseSubjectType"));
            typeSelectError = true;
            e.Data = list;
            return;
        }

        BXSelect s = new BXSelect(
            BXSelectFieldPreparationMode.Normal,
            BXRatingVoting.Fields.Id,
            BXRatingVoting.Fields.Active,
            BXRatingVoting.Fields.BoundEntityTypeId,
            BXRatingVoting.Fields.BoundEntityId,      //за что или за кого голосуют
            BXRatingVoting.Fields.CreatedUtc,         //дата создания
            BXRatingVoting.Fields.LastCalculatedUtc,  //дата последней модификации голосования
            BXRatingVoting.Fields.TotalValue,         //суммарное значение голосов
            BXRatingVoting.Fields.TotalPositiveVotes, //количество голосов "за"
            BXRatingVoting.Fields.TotalNegativeVotes, //количество голосов "против"
            BXRatingVoting.Fields.TotalVotes,         //количество голосов
            BXRatingVoting.Fields.XmlId
        );

        BXRatingVotingCollection col = BXRatingVoting.GetList(
            f,
            new BXOrderBy(BXRatingVoting.Fields, string.IsNullOrEmpty(e.SortExpression) ? "CreatedUtc DESC" : e.SortExpression),
            s,
            new BXQueryParams(e.PagingOptions),
            BXTextEncoder.EmptyTextEncoder
        );

        int recalculateId = 0;

        if (!String.IsNullOrEmpty(Request["recalculate"]) && Request["recalculate"] == "Y")
            int.TryParse(Request["RecalculateId"], out recalculateId);

        foreach (BXRatingVoting item in col)
        {
            if (recalculateId > 0 && item.Id == recalculateId) 
                item.Calculate(true);
            list.Add(new RatingVotingWrapper(item, this));
        }
        e.Data = list;
    }
        public override void ProcessMessage(BXCommand cmd, bool executionContext, string executionVirtualPath)
        {
            if (cmd.Action == "Bitrix.Main.GeneratePublicMenu")
            {
                //Совпадает ли тип меню в параметрах компонента с типом, который запрашивает система.
                if (!Parameters.Get("GenerateMenuType", "left").Equals(cmd.Parameters.Get<string>("menuType"), StringComparison.InvariantCultureIgnoreCase))
                    return;

                //Генерируем меню только для тех адресов, которые выводит сам компонент.
                if (!EnableSef && !BXSiteRemapUtility.UnmapVirtualPath(executionVirtualPath).Equals(cmd.Parameters.Get<string>("uriPath"), StringComparison.InvariantCultureIgnoreCase))
                    return;
                else if (EnableSef && !cmd.Parameters.Get<string>("uriPath").StartsWith(Bitrix.IO.BXPath.ToVirtualRelativePath(SefFolder.TrimStart('\\', '/')) + "/", StringComparison.InvariantCultureIgnoreCase))
                    return;

                if (IBlockId < 0)
                    return;

                BXParamsBag<object> request = new BXParamsBag<object>();
                if (EnableSef)
                {
                    BXParamsBag<string> urlToPage = new BXParamsBag<string>();
                    urlToPage["index.page"] = CommonListPageTemplate;
                    urlToPage["index.all"] = CommonListShowAllTemplate;
                    urlToPage["list"] = ElementListTemplate;
                    urlToPage["list.page"] = SectionListPageTemplate;
                    urlToPage["list.all"] = SectionListShowAllTemplate;
                    urlToPage["detail"] = ElementDetailTemplate;

                    MapVariable(SefFolder, urlToPage, request, "index", BXUri.ToRelativeUri(cmd.Parameters.Get<string>("uri")));
                }
                else
                {
                    BXParamsBag<string> variableAlias = new BXParamsBag<string>();
                    variableAlias["SectionId"] = SectionIdVariable;
                    variableAlias["ElementId"] = ElementIdVariable;
                    variableAlias["PageId"] = PageIdVariable;
                    variableAlias["ShowAll"] = ShowAllVariable;

                    MapVariable(variableAlias, request, BXUri.ToRelativeUri(cmd.Parameters.Get<string>("uri")));
                }

                #region Menu Item Permission
                string permissionCacheKey = "mediaGallery-" + IBlockId.ToString() + "-menu-permission";
                if ((menuItemPermisson = (string)BXCacheManager.MemoryCache.Get(permissionCacheKey)) == null)
                {
                    menuItemPermisson = string.Empty;
                    StringBuilder menuItemRoles = new StringBuilder();

                    BXRoleCollection iblockRoles = BXRoleManager.GetAllRolesForOperation("IBlockRead", "iblock", IBlockId.ToString());
                    foreach (BXRole role in iblockRoles)
                    {
                        //Если доступно всем
                        if (role.RoleName == "Guest")
                        {
                            menuItemRoles = null;
                            break;
                        }
                        //Если доступно группе User, значит достаточно проверить только для этой группы
                        else if (role.RoleName == "User")
                        {
                            menuItemRoles = null;
                            menuItemPermisson = "User";
                            break;
                        }
                        else
                        {
                            menuItemRoles.Append(role.RoleName);
                            menuItemRoles.Append(";");
                        }
                    }

                    if (menuItemRoles != null && menuItemRoles.Length > 0)
                        menuItemPermisson = menuItemRoles.ToString();

                    BXCacheManager.MemoryCache.Insert(permissionCacheKey, menuItemPermisson);
                }
                #endregion

                int elementId = 0, sectionId = 0;
                string elementCode = String.Empty, sectionCode = String.Empty;

                elementId = request.Get<int>("ElementId", elementId);
                sectionId = request.Get<int>("SectionId", sectionId);
                elementCode = request.Get<string>("ElementCode", elementCode);
                sectionCode = request.Get<string>("SectionCode", sectionCode);

                string parentLevelUri = null;
                List<BXPublicMenuItem> menuList = null;

                //Указан идентификатор или символьный код
                if (elementId > 0 || !String.IsNullOrEmpty(elementCode))
                {
                    BXFilter elementFilter = new BXFilter(
                        new BXFilterItem(BXIBlockElement.Fields.IBlock.ID, BXSqlFilterOperators.Equal, IBlockId),
                        new BXFilterItem(BXIBlockElement.Fields.Active, BXSqlFilterOperators.Equal, "Y")
                    );

                    if (elementId > 0)
                        elementFilter.Add(new BXFilterItem(BXIBlockElement.Fields.ID, BXSqlFilterOperators.Equal, elementId));
                    if (!String.IsNullOrEmpty(elementCode))
                        elementFilter.Add(new BXFilterItem(BXIBlockElement.Fields.Code, BXSqlFilterOperators.Equal, elementCode));
                    if (sectionId > 0)
                        elementFilter.Add(new BXFilterItem(BXIBlockElement.Fields.Sections.Section.SectionId, BXSqlFilterOperators.Equal, sectionId));
                    if (!String.IsNullOrEmpty(sectionCode))
                        elementFilter.Add(new BXFilterItem(BXIBlockElement.Fields.Sections.Section.Code, BXSqlFilterOperators.Equal, sectionCode));

                    BXIBlockElementCollection element = BXIBlockElement.GetList(elementFilter, null);
                    if (element != null && element.Count > 0)
                    {
                        BXIBlockElement.BXInfoBlockElementSectionCollection sections = element[0].Sections;
                        if (sections != null && sections.Count > 0)
                        {
                            BXParamsBag<object> replaceItems = new BXParamsBag<object>();
                            replaceItems["SectionId"] = sections[0].SectionId;
                            replaceItems["SectionCode"] = GetSectionCode(sections[0].SectionId);

                            parentLevelUri = MakeMenuUriForElementList(executionVirtualPath, replaceItems); //Меню строится для раздела, к которому привязан элемент
                        }
                    }
                }

                //Если ничего не указано выводим все дерево
                Dictionary<string, BXPublicMenu.BXLoadMenuCommandParameter> menuTree = new Dictionary<string, BXPublicMenu.BXLoadMenuCommandParameter>();
                if (parentLevelUri == null && menuList == null)
                {
                    BXIBlockSectionCollection sectionsList = BXIBlockSection.GetList(
                        new BXFilter(
                            new BXFilterItem(BXIBlockSection.Fields.Active, BXSqlFilterOperators.Equal, "Y"),
                            new BXFilterItem(BXIBlockSection.Fields.ActiveGlobal, BXSqlFilterOperators.Equal, "Y"),
                            new BXFilterItem(BXIBlockSection.Fields.IBlock.ID, BXSqlFilterOperators.Equal, IBlockId)
                        ),
                        new BXOrderBy(
                            new BXOrderByPair(BXIBlockSection.Fields.LeftMargin, BXOrderByDirection.Asc)
                        )
                    );

                    int previousDepthLevel = 1;
                    int previousSectionId = 0;
                    Dictionary<int, MenuSectionTree> sectionTree = new Dictionary<int, MenuSectionTree>();
                    foreach (BXIBlockSection section in sectionsList)
                    {
                        BXParamsBag<object> replaceItems = new BXParamsBag<object>();
                        replaceItems["SectionId"] = section.Id;
                        replaceItems["SectionCode"] = section.Code ?? String.Empty;

                        sectionTree[section.Id] = new MenuSectionTree();
                        string url = MakeMenuUriForElementList(executionVirtualPath, replaceItems);
                        sectionTree[section.Id].url = url;
                        sectionTree[section.Id].sectionId = section.SectionId;

                        //Если предыдущий раздел не имеет вложенных (дочерних) разделов, то для него дополнительно указывается URL на родительскую секцию (и эл-ты меню для данной секции будут запрошены из этой родительской)
                        if (previousSectionId > 0 && section.DepthLevel <= previousDepthLevel)
                            sectionTree[previousSectionId].parentLevelUrl = sectionTree[sectionTree[previousSectionId].sectionId].url;
                        previousDepthLevel = section.DepthLevel;
                        previousSectionId = section.Id;

                        BXPublicMenuItem menuItem = new BXPublicMenuItem();
                        menuItem.Title = section.Name;
                        menuItem.Links.Add(url);
                        menuItem.Sort = section.LeftMargin;

                        if (!String.IsNullOrEmpty(menuItemPermisson))
                        {
                            menuItem.ConditionType = ConditionType.Group;
                            menuItem.Condition = menuItemPermisson;
                        }

                        if (!sectionTree.ContainsKey(section.SectionId))
                        {
                            sectionTree[section.SectionId] = new MenuSectionTree();
                            sectionTree[section.SectionId].menuItems = new List<BXPublicMenuItem>();

                            if (section.SectionId < 1)
                                sectionTree[section.SectionId].url = EnableSef ? SefFolder : BXUri.ToAppRelativeUri(executionVirtualPath);
                        }

                        if (sectionTree[section.SectionId].menuItems == null)
                            sectionTree[section.SectionId].menuItems = new List<BXPublicMenuItem>();

                        sectionTree[section.SectionId].menuItems.Add(menuItem);
                    }

                    //Последний раздел точно не имеет вложенных (дочерних) разделов, для него обязательно указывается URL на родительскую секцию (и эл-ты меню для данной секции будут запрошены из этой родительской)
                    if (sectionTree.ContainsKey(previousSectionId) && sectionTree.ContainsKey(sectionTree[previousSectionId].sectionId))
                        sectionTree[previousSectionId].parentLevelUrl = sectionTree[sectionTree[previousSectionId].sectionId].url;

                    foreach (KeyValuePair<int, MenuSectionTree> sectionItem in sectionTree)
                        menuTree.Add(
                            sectionItem.Value.url,
                            new BXPublicMenu.BXLoadMenuCommandParameter(sectionItem.Value.menuItems, true, sectionItem.Value.parentLevelUrl)
                        );
                }

                if (menuTree.Count > 0)
                    cmd.AddCommandResult("bitrix:mediaGallery@" + executionVirtualPath, new BXCommandResult(BXCommandResultType.Ok, menuTree));
                else if (menuList != null || parentLevelUri != null)
                {
                    BXPublicMenu.BXLoadMenuCommandParameter menuResult = new BXPublicMenu.BXLoadMenuCommandParameter(menuList, true, parentLevelUri);
                    cmd.AddCommandResult("bitrix:mediaGallery@" + executionVirtualPath, new BXCommandResult(BXCommandResultType.Ok, menuResult));
                }
            }
        }
Exemple #29
0
	public void Save(BXCustomPropertyCollection storage)
	{
		if (field == null)
			return;

		int elementId;
		int.TryParse(tbValue.Text, out elementId);

        BXFilter f = new BXFilter();
        f.Add(new BXFilterItem(BXIBlockElement.Fields.ID, BXSqlFilterOperators.Equal, elementId));
        if (iblockId > 0)
            f.Add(new BXFilterItem(BXIBlockElement.Fields.IBlock.ID, BXSqlFilterOperators.Equal, iblockId));
        BXIBlockElementCollection element = BXIBlockElement.GetList(f, null);

		if (element == null || element.Count != 1)
			elementId = 0;

		BXCustomType t = BXCustomTypeManager.GetCustomType(field.CustomTypeId);
		storage[field.Name] = new BXCustomProperty(field.Name, field.Id, t.DbType, t.IsClonable ? false : field.Multiple, elementId);
	}
    protected override void LoadComponentDefinition()
    {
        //IBlockTypeId
        List<BXParamValue> types = new List<BXParamValue>();
        types.Add(new BXParamValue("-", ""));
        BXIBlockTypeCollection typeCollection = BXIBlockType.GetList(null, new BXOrderBy(new BXOrderByPair(BXIBlockType.Fields.Sort, BXOrderByDirection.Asc)));
        foreach (BXIBlockType t in typeCollection)
            types.Add(new BXParamValue(t.Translations[BXLoc.CurrentLocale].Name, t.Id.ToString()));

        ParamsDefinition["IBlockTypeId"].Values = types;


        BXFilter iblockFilter = new BXFilter();
        if (Parameters.ContainsKey("IBlockTypeId"))
        {
            int typeId;
            int.TryParse(Parameters["IBlockTypeId"], out typeId);
            if (typeId > 0)
                iblockFilter.Add(new BXFilterItem(BXIBlock.Fields.Type.ID, BXSqlFilterOperators.Equal, typeId));
        }
        if (!string.IsNullOrEmpty(DesignerSite))
            iblockFilter.Add(new BXFilterItem(BXIBlock.Fields.Sites.SiteId, BXSqlFilterOperators.Equal, DesignerSite));

        //IBlockId
        List<BXParamValue> iblocks = new List<BXParamValue>();
        BXIBlockCollection iblockCollection = BXIBlock.GetList(iblockFilter, new BXOrderBy(new BXOrderByPair(BXIBlock.Fields.Sort, BXOrderByDirection.Asc)));
        foreach (BXIBlock b in iblockCollection)
            iblocks.Add(new BXParamValue(b.Name, b.Id.ToString()));

        ParamsDefinition["IBlockId"].Values = iblocks;


        //SortBy1 & SortBy2
        List<BXParamValue> sortFields = new List<BXParamValue>();
        sortFields.Add(new BXParamValue("ID", "ID"));
        sortFields.Add(new BXParamValue(GetMessageRaw("SortByName"), "Name"));
        sortFields.Add(new BXParamValue(GetMessageRaw("ActiveFromDate"), "ActiveFromDate"));
        sortFields.Add(new BXParamValue(GetMessageRaw("Sort"), "Sort"));
        sortFields.Add(new BXParamValue(GetMessageRaw("DateOfLastModification"), "UpdateDate"));

        ParamsDefinition["SortBy1"].Values = sortFields;
        ParamsDefinition["SortBy2"].Values = sortFields;

        //ActiveDateFormat & DetailActiveDateFormat
        List<BXParamValue> dateFormats = new List<BXParamValue>();
        DateTime now = DateTime.Now;
        dateFormats.Add(new BXParamValue(now.ToString("dd-MM-yyyy"), "dd-MM-yyyy"));
        dateFormats.Add(new BXParamValue(now.ToString("MM-dd-yyyy"), "MM-dd-yyyy"));
        dateFormats.Add(new BXParamValue(now.ToString("yyyy-MM-dd"), "yyyy-MM-dd"));
        dateFormats.Add(new BXParamValue(now.ToString("dd.MM.yyyy"), "dd.MM.yyyy"));
        dateFormats.Add(new BXParamValue(now.ToString("MM.dd.yyyy"), "MM.dd.yyyy"));
        dateFormats.Add(new BXParamValue(now.ToString("dd/MM/yyyy"), "dd/MM/yyyy"));
        dateFormats.Add(new BXParamValue(now.ToString("dd.MM.yyyy HH:mm"), "dd.MM.yyyy HH:mm"));
        dateFormats.Add(new BXParamValue(now.ToString("D"), "D"));
        dateFormats.Add(new BXParamValue(now.ToString("f"), "f"));

        ParamsDefinition["ActiveDateFormat"].Values = dateFormats;
        ParamsDefinition["DetailActiveDateFormat"].Values = dateFormats;

        //PropertyCode & DetailPropertyCode
        List<BXParamValue> properties = new List<BXParamValue>();
        if (Parameters.ContainsKey("IBlockId"))
        {
            int iblockId;
            int.TryParse(Parameters["IBlockId"], out iblockId);
            if (iblockId > 0)
            {
                BXCustomFieldCollection cfCollection = BXCustomEntityManager.GetFields(String.Format("IBlock_{0}", iblockId));
                foreach (BXCustomField f in cfCollection)
                    properties.Add(new BXParamValue(f.EditFormLabel, f.Name));
            }
        }

        ParamsDefinition["PropertyCode"].Values = properties;
        ParamsDefinition["DetailPropertyCode"].Values = properties;


        //GroupPermissions
        List<BXParamValue> rolesList = new List<BXParamValue>();
        BXRoleCollection roles = BXRoleManager.GetList(new BXFormFilter(new BXFormFilterItem("Active", true, BXSqlFilterOperators.Equal)), new BXOrderBy_old("RoleName", "Asc"));
        foreach (BXRole role in roles)
            rolesList.Add(new BXParamValue(role.Title, role.RoleName));

        ParamsDefinition["GroupPermissions"].Values = rolesList;

        foreach (string parDefKey in ParamsDefinition.Keys)
            ParamsDefinition[parDefKey].AdjustPresentation(this);
    }