using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint;
using System.Reflection;
namespace Bamboo.ApplicationPageSecurity.WebControls
{
public class AppPageActionControl : SPSecurityTrimmedControl
{
protected MenuItemTemplate menuItem;
private bool shouldRender = false;
protected bool CustomShouldRender
{
get
{
bool hasCustomRights = this.HasCustomRights();
Type baseType = this.GetType().BaseType;
object obj = baseType.InvokeMember(
"ShouldRender",
BindingFlags.GetProperty | BindingFlags.NonPublic | BindingFlags.Instance,
null, this, new object [] {});
if (obj != null)
{
return (bool)obj && hasCustomRights;
}
else
{
return false;
}
}
}
protected virtual SPBasePermissions AppPagePermissions
{
get
{
SPBasePermissions permissions = base.Permissions
| SPBasePermissions.ViewFormPages // Don't forget this, if custom action takes to an application page
| SPBasePermissions.BrowseUserInfo
| SPBasePermissions.CreateGroups
| SPBasePermissions.ManageLists;
return permissions;
}
}
private bool HasCustomRights()
{
bool hasCustomRights = false;
//write here a custom logic to check if user has enough rights to access application page
//if yes, set userCheckedForCustomLogic to true;
hasCustomRights = true;
return hasCustomRights;
}
private void SetAppPagePermissionProperties()
{
base.Permissions = this.AppPagePermissions;
// DoesUserHavePermission is called on the current SPWeb
base.PermissionContext = PermissionContext.CurrentSite;
// It make sure user have all permissions
base.PermissionMode = PermissionMode.All;
//By default any users (included AnonymousUsersOnly), but I only wanted to deal with Authenticated Users only
base.AuthenticationRestrictions = AuthenticationRestrictions.AuthenticatedUsersOnly;
}
private void CreateAndAddMenuItem()
{
this.menuItem = new MenuItemTemplate();
this.menuItem.Title = "AppPage";
this.menuItem.Text = "AppPage";
this.menuItem.Description = "AppPage Description";
this.menuItem.Sequence = 1040;
this.menuItem.ClientOnClickNavigateUrl = "~site/_layouts/Bamboo.ApplicationPageSecurity/AppPage.aspx";
this.Controls.Add(menuItem);
}
protected override void OnInit(EventArgs e)
{
this.SetAppPagePermissionProperties();
base.OnInit(e);
}
protected override void OnLoad(EventArgs e)
{
base.EnsureChildControls();
base.OnLoad(e);
}
protected override void CreateChildControls()
{
this.CreateAndAddMenuItem();
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (this.CustomShouldRender == true)
{
this.shouldRender = true;
}
else
{
this.shouldRender = false;
base.Visible = false;
}
}
protected override void Render(System.Web.UI.HtmlTextWriter output)
{
if (this.shouldRender == true)
{
base.Render(output);
}
else
{
base.Visible = false;
}
}
}
}