TheBeerHouse 系列四:从表示层开始下(我怎样限制你的自由??)

- -开始胡说八道前
先说说页面的结构~~上次忘了说

-就是这样的~~有意思点意思吧~~首先它几乎所有的页面页的 MasterPageFile="~/Template.master",但是后台都来自于自定义类: BasePage(上有政策~~下有对策阿)

我们先来看看,Template.master

public partial class TemplateMaster : System.Web.UI.MasterPage
   
{
      
private bool _enablePersonalization = false;
       
/// <summary>
      
/// 是否显示PersonalizationManager,他是用来管理WebPar
       
/// </summary>

      public bool EnablePersonalization
      
{
         
get return _enablePersonalization; }
         
set
         
{
            _enablePersonalization 
= value;
            
//--- --当用户登录并且输入的是true的时候才显示--也就是说~~不登陆要操作WebPar没门
            PersonalizationManager1.Visible = (this.Page.User.Identity.IsAuthenticated && value);
         }

      }
 protected void Page_Load(object sender, EventArgs e)
      
{

    
//--外国朋友的安全意识高啊 - -这里如果没有通过验证则不显示
         if (!this.Page.User.Identity.IsAuthenticated)
            PersonalizationManager1.Visible 
= false;
      }

}



----但我认为 EnablePersonalization是个双重保险,当我们输入false即便用户登录了也显示阿,关于
PersonalizationManager-可以看看系列系列三



第二 BasePage


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using MB.TheBeerHouse.BLL.Store;

namespace MB.TheBeerHouse.UI
{
   
public class BasePage : System.Web.UI.Page
   
{
      
protected override void InitializeCulture()
      
{
         
string culture = (HttpContext.Current.Profile as ProfileCommon).Preferences.Culture;
          
//--设置设置与页面向关联的区域性ID
         this.Culture = culture;
          
//--UiId
         this.UICulture = culture;
      }


      
protected override void OnPreInit(EventArgs e)
      
{
}


      
protected override void OnLoad(EventArgs e)
      
{
         
// add onfocus and onblur javascripts to all input controls on the forum,
         
// so that the active control has a difference appearance
          
//---给整个控件在函数中定义的类型挂样式表---------false代表第一次传送的是顶级控件不挂样式表,如果该控件还有子控件则递规调用
          
//SetInputControlsHighlight继续挂样式表
         Helpers.SetInputControlsHighlight(this"highlight"false);

         
base.OnLoad(e);
      }


       
/// <summary>
      
/// 获得asp.net比如这里是/TBH_Web 
       
/// </summary>

     public string BaseUrl
    
{
        
get
        
{
            
//--判断下结尾又没有/
            string url = this.Request.ApplicationPath;
            
if (url.EndsWith("/"))
                
return url;
            
else
                
return url + "/";
        }

    }


    
//--FullBaseUrl = "http://localhost:/TBH_Web/",--就是得到网络路径的根目录
    public string FullBaseUrl
    
{
        
get
        
{//--this.Request.Url.AbsoluteUri = "http://localhost/TBH_Web/Default3.aspx"
            return this.Request.Url.AbsoluteUri.Replace(
               
this.Request.Url.PathAndQuery, ""+ this.BaseUrl;
            
//-this.Request.Url.PathAndQuery = "/TBH_Web/Default3.aspx"
        }

    }


       
//---跳转的登陆页
      protected void RequestLogin()
      
{
         
this.Response.Redirect(FormsAuthentication.LoginUrl + 
            
"?ReturnUrl=" + this.Request.Url.PathAndQuery);
      }


      
public string FormatPrice(object price)
      
{
         
return Convert.ToDecimal(price).ToString("N2"+ " " + Globals.Settings.Store.CurrencyCode;
      }

   }

}

//--

- -ok基本上就是这些了让我来进入正题吧

上一篇~~曾经讲过一种权限管理~~不过是自动的这次让我们来看看- -手动怎么管理阿- -

namespace MB.TheBeerHouse.UI.Admin
{
   
public partial class _Default : BasePage
   
{
      
protected void Page_Load(object sender, EventArgs e)
      
{
    
//--权限审核
         panAdmin.Visible = (this.User.IsInRole("Administrators"));
         panEditor.Visible 
= (this.User.IsInRole("Administrators"|| this.User.IsInRole("Editors"));
         panStoreKeeper.Visible 
= (this.User.IsInRole("Administrators"|| this.User.IsInRole("StoreKeepers"));
         panModerator.Visible 
= (this.User.IsInRole("Administrators"|| this.User.IsInRole("Editors"|| this.User.IsInRole("Modearators"));
         panContributor.Visible 
= (this.User.IsInRole("Administrators"|| this.User.IsInRole("Editors"|| this.User.IsInRole("Contributors"));
      }

   }

}

- -接下来看看如何配置这些权限

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using MB.TheBeerHouse;

namespace MB.TheBeerHouse.UI.Admin
{
   
public partial class EditUser : BasePage
   
{
      
string userName = "";

      
protected void Page_Load(object sender, EventArgs e)
      
{
         
// retrieve the username from the querystring
         userName = this.Request.QueryString["UserName"];

         lblRolesFeedbackOK.Visible 
= false;
         lblProfileFeedbackOK.Visible 
= false;

         
if (!this.IsPostBack)
         
{
             
//--这个是编辑Profile的自定义控件
            UserProfile1.UserName = userName;

            
// 取得用户信息
            MembershipUser user = Membership.GetUser(userName);
            lblUserName.Text 
= user.UserName;
            lnkEmail.Text 
= user.Email;
            lnkEmail.NavigateUrl 
= "mailto:" + user.Email;
             
//--得到注册时间
            lblRegistered.Text = user.CreationDate.ToString("f");
             
//--得到上次进行身份验证的时间
            lblLastLogin.Text = user.LastLoginDate.ToString("f");
            lblLastActivity.Text 
= user.LastActivityDate.ToString("f");
             
//--是否在线
            chkOnlineNow.Checked = user.IsOnline;

             
//--是否可以用成员资格验证
            chkApproved.Checked = user.IsApproved;

             
//--这里比较有意思--首先--反映是否因为被锁定而不能验证
            chkLockedOut.Checked = user.IsLockedOut;

            
//---如果没有锁定那么不显示上面的chkLockedOut控件
            chkLockedOut.Enabled = user.IsLockedOut;

            BindRoles();
         }

      }

       
/// <summary>
       
/// 绑定角色信息
       
/// </summary>

      private void BindRoles()
      
{
         
// fill the CheckBoxList with all the available roles, and then select
         
// those that the user belongs to

          
//---得到所有角色
         chklRoles.DataSource = Roles.GetAllRoles();
         chklRoles.DataBind();
          
//--得到用户所属的角色集合
         foreach (string role in Roles.GetRolesForUser(userName))
            chklRoles.Items.FindByText(role).Selected 
= true;
      }


      
protected void btnUpdateProfile_Click(object sender, EventArgs e)
      
{//--调用自定义控件的保存方法
         UserProfile1.SaveProfile();
         lblProfileFeedbackOK.Visible 
= true;
      }


       
/// <summary>
       
/// 创造一个角色
       
/// </summary>
       
/// <param name="sender"></param>
       
/// <param name="e"></param>

      protected void btnCreateRole_Click(object sender, EventArgs e)
      
{
          
//---首先看看脚色是否不存在
         if (!Roles.RoleExists(txtNewRole.Text.Trim()))
         
{
            Roles.CreateRole(txtNewRole.Text.Trim());
            BindRoles();
         }

      }


      
protected void btnUpdateRoles_Click(object sender, EventArgs e)
      
{

          
//--这个更新比较烦人

         
// first remove the user from all roles,得到用户所有的角色
         string[] currRoles = Roles.GetRolesForUser(userName);
          
//--如果用后有角色存在则删除这个用户得到的所有角色
         if (currRoles.Length > 0)
            Roles.RemoveUserFromRoles(userName, currRoles);
         
// and then add the user to the selected roles
         List<string> newRoles = new List<string>();

          
//--角色列表中的数据收集起来
         foreach (ListItem item in chklRoles.Items)
         
{
            
if (item.Selected)
               newRoles.Add(item.Text);
         }

          
//--在给用户添加
         Roles.AddUserToRoles(userName, newRoles.ToArray());

         lblRolesFeedbackOK.Visible 
= true;
      }


      
protected void chkApproved_CheckedChanged(object sender, EventArgs e)
      
{
         MembershipUser user 
= Membership.GetUser(userName);
          
//--决定一个用户是否可以验证
         user.IsApproved = chkApproved.Checked;
         Membership.UpdateUser(user);
      }


      
protected void chkLockedOut_CheckedChanged(object sender, EventArgs e)
      
{
         
if (!chkLockedOut.Checked)
         
{
            MembershipUser user 
= Membership.GetUser(userName);
             
//--给用户状态解除锁定
            user.UnlockUser();
            chkLockedOut.Enabled 
= false;
         }

      }

   }

}


//--在来就是管理了
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Profile;
using MB.TheBeerHouse;

namespace MB.TheBeerHouse.UI.Admin
{
   
public partial class ManageUsers : BasePage
   
{
      
private MembershipUserCollection allUsers = Membership.GetAllUsers();

      
protected void Page_Load(object sender, EventArgs e)
      
{
         
if (!this.IsPostBack)
         
{
            lblTotUsers.Text 
= allUsers.Count.ToString();
             
//--获取当前访问网站的成员总数
            lblOnlineUsers.Text = Membership.GetNumberOfUsersOnline().ToString();
             
//--这个作用比较有意义啊~~就是将用户作A ~Z ,+All的排序
            string[] alphabet = "A;B;C;D;E;F;G;J;K;L;M;N;O;P;Q;R;S;T;U;V;W;X;Y;Z;All".Split(';');
            rptAlphabet.DataSource 
= alphabet;
            rptAlphabet.DataBind();
         }

      }


      
private void BindUsers(bool reloadAllUsers)
      
{
         
if (reloadAllUsers)//True是绑定所有用户
            allUsers = Membership.GetAllUsers();

         MembershipUserCollection users 
= null;
          
//-这里是搜索
         string searchText = "";
          
//--如果搜索不是空的化
         if (!string.IsNullOrEmpty(gvwUsers.Attributes["SearchText"]))
            searchText 
= gvwUsers.Attributes["SearchText"];

         
bool searchByEmail = false;
         
if (!string.IsNullOrEmpty(gvwUsers.Attributes["SearchByEmail"]))
            searchByEmail 
= bool.Parse(gvwUsers.Attributes["SearchByEmail"]);

          
//--如果搜索不是空,则查找指定成员
         if (searchText.Length > 0)
         
{
            
if (searchByEmail)
               users 
= Membership.FindUsersByEmail(searchText);
            
else
               users 
= Membership.FindUsersByName(searchText);
         }

         
else
         
{
             
//否则绑定所有的
            users = allUsers;
         }


         gvwUsers.DataSource 
= users;
         gvwUsers.DataBind();
      }


      
protected void rptAlphabet_ItemCommand(object source, RepeaterCommandEventArgs e)
      
{
         gvwUsers.Attributes.Add(
"SearchByEmail"false.ToString());
         
if (e.CommandArgument.ToString().Length == 1)
         
{
         
//--绑定
            gvwUsers.Attributes.Add("SearchText", e.CommandArgument.ToString() + "%");
            BindUsers(
false);
         }

         
else
         
{
            gvwUsers.Attributes.Add(
"SearchText""");
            BindUsers(
false);
         }


      }


      
protected void gvwUsers_RowCreated(object sender, GridViewRowEventArgs e)
      
{
         
if (e.Row.RowType == DataControlRowType.DataRow)
         
{
            ImageButton btn 
= e.Row.Cells[6].Controls[0as ImageButton;
            btn.OnClientClick 
= "if (confirm('Are you sure you want to delete this user account?') == false) return false;";
         }

      }


      
protected void gvwUsers_RowDeleting(object sender, GridViewDeleteEventArgs e)
      
{
         
string userName = gvwUsers.DataKeys[e.RowIndex].Value.ToString();
         ProfileManager.DeleteProfile(userName);
         Membership.DeleteUser(userName);
         BindUsers(
true);
         lblTotUsers.Text 
= allUsers.Count.ToString();
      }

       
//--如果单击搜索
      protected void btnSearch_Click(object sender, EventArgs e)
      
{
         
bool searchByEmail = (ddlSearchTypes.SelectedValue == "E-mail");
          
//---这里有意思用的是like搜索
         gvwUsers.Attributes.Add("SearchText""%" + txtSearchText.Text + "%");
         gvwUsers.Attributes.Add(
"SearchByEmail", searchByEmail.ToString());
         BindUsers(
false);
      }

   }

}

 

//---权限的应用

if (!this.IsPostBack)
         
{
            
// if a ID param is present on the querystring, switch to Edit mode for that article,
            
// but only after checking that the current user is an Administrator or an Editor
            if (!string.IsNullOrEmpty(this.Request.QueryString["ID"]))
            
{
            
//--如果用户登录了并且是有管理员权限--或者有编辑角色
               if (this.User.Identity.IsAuthenticated &&
                  (
this.User.IsInRole("Administrators"|| this.User.IsInRole("Editors")))
               
{
//--将DataView切换成--带有编辑模式的状态
                  dvwArticle.ChangeMode(DetailsViewMode.Edit);
                
//--然后帮定  
        UpdateTitle();
               }

               
else
                  
throw new SecurityException("You are not allowed to edit existent articles!");
            }

         }


//---这个是在创建DabeView里面的一项的时候形成的
 protected void dvwArticle_ItemCreated(object sender, EventArgs e)
      
{
         Control ctl 
= dvwArticle.FindControl("txtBody");
         
if (ctl != null)
         
{
         
//---这个是一个javascript的在线编辑器
            FCKeditor txtBody = ctl as FCKeditor;
        
//---这里估计是制定文件夹的位置,因有点脚本哦  
            txtBody.BasePath = this.BaseUrl + "FCKeditor/";
         }

      }

 
//--再绑定的时候触发
      protected void dvwArticle_DataBound(object sender, EventArgs e)
      
{
         
// Tn InserMode, preselect the checkboxes to make the article listed and to allow comments
         
// The Approved checkbox is selected and enabled only if the user belongs to the
         
// Administrators or Editors group instead.
         
//--如果是插入模式
         if (dvwArticle.CurrentMode == DetailsViewMode.Insert)
         
{
            CheckBox chkApproved 
= dvwArticle.FindControl("chkApproved"as CheckBox;
            CheckBox chkListed 
= dvwArticle.FindControl("chkListed"as CheckBox;
            CheckBox chkCommentsEnabled 
= dvwArticle.FindControl("chkCommentsEnabled"as CheckBox;

            chkListed.Checked 
= true;
            chkCommentsEnabled.Checked 
= true;
             
//--除非是管理员或者是有编辑权限否则-这里返回false
            bool canApprove = (this.User.IsInRole("Administrators"|| this.User.IsInRole("Editors"));
            chkApproved.Enabled 
= canApprove;
            chkApproved.Checked 
= canApprove;
         }

      }


     
protected void dvwArticle_ModeChanged(object sender, EventArgs e)
      
{
         UpdateTitle();
      }


      
private void UpdateTitle()
      
{
         lblNewArticle.Visible 
= (dvwArticle.CurrentMode == DetailsViewMode.Insert);
         lblEditArticle.Visible 
= !lblNewArticle.Visible;
      }
posted @ 2007-05-17 22:22  苹果王子  阅读(3143)  评论(3编辑  收藏  举报