代码改变世界

位运算设置权限续(转)

2012-09-28 17:10  C#与.NET探索者  阅读(168)  评论(0编辑  收藏  举报
复制代码
0  1 2 4 8 16,32,64,128,256,512,1024,20484096,8192
--2的n次方 tinyint类型就够用了
--
0 无权限
--
1 可读(read)
--
2 可新增(insert)
--
4 可修改(update)
--
8 可删除(delete)
--
16 可审核
...
权限的组合
read +insert = 1+2=3 
read +insert +delete = 1+2+8=11
read + update+delete =1+4+8=13


select 1 | 2     权限的加法 就是逻辑[]运算 --结果: 3
select 3 & (~1)   权限的减法, 使用[]运算+[]运算来实现 --结果: 2

select 1 | 13     一次添加n个权限 --结果: 13
select 13 & (~11)   一次减去n个权限 --结果:4

select (3 & 2)  权限的判断 --结果:2

--例子
Select * From Customer Where ( @Status is null Or [Status] & @Status = [Status])

int[] power = new int[] { 1248163264 };
int value = 126;       
for (int i = 0; i < power.Length; i++)
{
    if ((value & power[i]!= 0)
    {
        Console.WriteLine("有power[{0}]={1}所代表的权限", i, power[i]);
    }
}


--读取权限
private int[] GetPermission(int PermissionSum)
{
    List<int> list = new List<int>();
    int[] table = {1,2,4,8,16,32,64};
    for (int i = table.Length-1; i >-1; i--)
    {
        if (table[i] == PermissionSum)
        {
            list.Add(table[i]);
            break;
        }
        if (table[i] > PermissionSum)
        {
            continue;
        }
        PermissionSum -= table[i];
        list.Add(table[i]);
    }
    return list.ToArray();
}

http://www.cnblogs.com/zhuqil/archive/2010/04/02/Permission.html
复制代码
 
复制代码
using System.ComponentModel; 
public enum ProjectPhase 

    [Description("Requirements Gathering")] 
     RequirementsGathering = 1
    [Description("Analysis and Design")] 
     AnalysisDesign = 1
}
//EnumExtensions
public static string GetEnumDescription(Enum value)
{
    FieldInfo fi = value.GetType().GetField(value.ToString());

    DescriptionAttribute[] attributes =
        (DescriptionAttribute[])fi.GetCustomAttributes(
        typeof(DescriptionAttribute),
        false);

    if (attributes != null &&
        attributes.Length > 0)
        return attributes[0].Description;
    else
        return value.ToString();
}
复制代码

Binding an enumeration to a dropdown list

复制代码
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;

public enum ActiveFrom : int
{
[Description("Now")]
DateOfPurchase = 0,
[Description("Tomorrow")]
OnLogin = 1,
[Description("Day After Tomorrow")]
OnActivation = 2
}

public static class Extensions
{
public static IEnumerable BindWithEnum() where TEnum : struct
{
Type enumType = typeof(TEnum);

Type descriptionAttributeType = typeof(DescriptionAttribute);

List list = new List();

foreach (int value in Enum.GetValues(enumType))
{
MemberInfo enumObj = enumType.GetMember(Enum.ToObject(enumType, value).ToString()).SingleOrDefault();

object attr = enumObj.GetCustomAttributes(descriptionAttributeType, false).SingleOrDefault();

if (attr == nullcontinue;

string description = ((DescriptionAttribute)attr).Description;

list.Add(new { Code = value, Name = description });
}

return list;
}
}
复制代码
 
复制代码
//Pick a Random Enum in C# (Better than my old post)
static T RandomEnum() {
   if ( typeof( T ).IsEnum ) {
   var names = Enum.GetNames( typeof( T ) );
   return ( T )Enum.Parse( typeof( T ), names[ threadsafeRandom.Value.Next( 0, names.Length ) ] );
      }
  return default( T );
}

static readonly ThreadLocal threadsafeRandom = new ThreadLocal( () => new Random( RandomSeed() ) );
复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using System.Text;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string s1 = TextBox1.Text.Trim();
        TextBox2.Text = SetBase64Str(TextBox1.Text);
    }

    //解密
    internal static string GetBase64Str(string text1)
    {
        byte[] bytes = Convert.FromBase64String(text1);
        return Encoding.Unicode.GetString(bytes, 0, bytes.Length);
    }

    //加密
    internal static string SetBase64Str(string text)
    {
        string result = Convert.ToBase64String(System.Text.Encoding.Unicode.GetBytes(text));
        return result;
    }
    //乱码
    internal static string A(string text)
    {
        string str = "";
        for (int i = 0; i < text.Length; i++)
        {
            str = str + ((char)(0xff - ((byte)text[i])));
        }
        return str;
    }



    protected void Button2_Click(object sender, EventArgs e)
    {
        //  string strPage = HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath;
        string strPage = TextBox3.Text.Trim();
        //  if (!CheckMasterPower(strPage.Substring(strPage.LastIndexOf("/") + 1)))
        if (!CheckMasterPower(strPage))
        {
            Alert("Sorry! 您没有此项【操作权限】!");

        }
        else
        {
            Alert("成功!");
        }
    }

    public void Alert(string msg)
    {
        HttpContext.Current.Response.Write("<script>alert(\"" + msg + "\");</script>");
    }



    public bool CheckMasterPower(string A_1)
    {
        if (A_1.ToLower() == "main.aspx")
        {
            return true;
        }
        string[, ,] strArray = SystemArray();
        int length = strArray.GetLength(0);
        for (int i = 0; i < length; i++)
        {
            int num3 = strArray.GetLength(2);
            for (int j = 1; j < num3; j++)
            {
                if (strArray[i, 0, j] == null)
                {
                    break;
                }
                if (strArray[i, 0, j].ToLower().IndexOf(A_1.ToLower()) > -1)
                {
                    return this.IsHasPower(i.ToString() + j.ToString());
                }
            }
        }
        return false;
    }



    public bool IsHasPower(string A_1)
    {
        // return ((HttpContext.Current.Session["UserPower"] != null) && (("," + HttpContext.Current.Session["UserPower"].ToString() + ",").IndexOf("," + A_1 + ",") > -1));

        return ((("," + TextBox4.Text.Trim() + ",").IndexOf("," + A_1 + ",") > -1));
    }


    public string[, ,] SystemArray()
    {
        string[, ,] strArray = new string[6, 8, 8];
        strArray[0, 0, 0] = "系统配置";
        strArray[0, 1, 0] = "系统信息";
        strArray[0, 0, 1] = "MWebConfig.Aspx";
        strArray[0, 2, 0] = "公司信息";
        strArray[0, 0, 2] = "MCompany.Aspx";
        strArray[0, 3, 0] = "系统重启";
        strArray[0, 0, 3] = "Reset.Aspx";
        strArray[0, 4, 0] = "统计图标";
        strArray[0, 0, 4] = "MStatLogo.Aspx";
        strArray[0, 5, 0] = "邮件服务";
        strArray[0, 0, 5] = "MStmp.Aspx";
        strArray[0, 6, 0] = "网站导航";
        strArray[0, 0, 6] = "Navigate.Aspx";
        strArray[1, 0, 0] = "网站管理";
        strArray[1, 1, 0] = "站点列表";
        strArray[1, 0, 1] = "MWebList.Aspx";
        strArray[2, 0, 0] = "账户管理";
        strArray[2, 1, 0] = "管理员管理";
        strArray[2, 0, 1] = "Master.aspx";
        strArray[2, 2, 0] = "用户管理";
        strArray[2, 0, 2] = "MUserList.Aspx";
        strArray[3, 0, 0] = "信息管理";
        strArray[3, 1, 0] = "网站公告";
        strArray[3, 0, 1] = "MNotify.aspx";
        strArray[3, 2, 0] = "新闻聚焦";
        strArray[3, 0, 2] = "MNews.aspx";
        strArray[3, 3, 0] = "用户反馈";
        strArray[3, 0, 3] = "MMessage.aspx";
        strArray[4, 0, 0] = "网站广告";
        strArray[4, 1, 0] = "广告管理";
        strArray[4, 0, 1] = "MFrendLick.aspx|MSponsorLink.aspx|MAdImg.aspx|MAdCode.aspx";
        strArray[5, 0, 0] = "技术员专区";
        strArray[5, 1, 0] = "系统运行";
        strArray[5, 0, 1] = "ShowAppRuned.aspx";
        strArray[5, 2, 0] = "源数据";
        strArray[5, 0, 2] = "ShowDatabase.aspx";
        strArray[5, 3, 0] = "缓存数据";
        strArray[5, 0, 3] = "ShowCache.aspx";
        strArray[5, 4, 0] = "作业情况";
        strArray[5, 0, 4] = "ShowTask.aspx";
        strArray[5, 5, 0] = "程序报错";
        strArray[5, 0, 5] = "ShowError.aspx";
        strArray[5, 6, 0] = "升级参考";
        strArray[5, 0, 6] = "ShowConsult.aspx";
        strArray[5, 7, 0] = "活跃指数";
        strArray[5, 0, 7] = " ShowActive.aspx";
        return strArray;
    }

    //生成权限列表
    protected void Button3_Click(object sender, EventArgs e)
    {
        this.ltrPowerList.Text = GetMasterPowerList("01,02,03,04,05,06,11,21,22,31,32,33,41,51,52,53,54,55,56,57");
    }

    public string GetMasterPowerList(string admin_power)
    {
        return PowerList(admin_power);
    }

    public string PowerList(string admin_power)
    {
        string[, ,] strArray = this.SystemArray();
        admin_power = "," + admin_power + ",";
        StringBuilder builder = new StringBuilder();
        builder.Append("<table width='98%' cellpadding='5' cellspacing='0'  border='0' >");
        for (int i = 0; i < strArray.GetLength(0); i++)
        {
            builder.Append("<tr><td height=25 class="forumRowHighlight" colspan=2 align=left><strong>" + strArray[i, 0, 0] + "</strong></td></tr>");
            builder.Append("<tr><td height=20 class="forumrow" colspan=2 align=left>");
            for (int j = 1; j < strArray.GetLength(1); j++)
            {
                if (strArray[i, j, 0] == null)
                {
                    break;
                }
                builder.Append("&nbsp;&nbsp;&nbsp;&nbsp;<input type=checkbox class='checkbox' name='website_power' value=" + i.ToString() + j.ToString() + ",");
                if (admin_power.IndexOf("," + i.ToString() + j.ToString() + ",") > -1)
                {
                    builder.Append(" checked");
                }
                builder.Append(">" + i.ToString() + j.ToString() + "." + strArray[i, j, 0]);
                if ((j % 5) == 0)
                {
                    builder.Append("<br><br>");
                }
            }
            builder.Append("</td></tr>");
        }
        builder.Append("</table>");
        return builder.ToString();
    }

}