自定义的sitemapprovider(Sql)

前台使用menu或treeview 
页面-menu控件:
        this.Menu1.StaticEnableDefaultPopOutImage = false;
        this.SiteMapDataSource1.ShowStartingNode = false;

数据库:
create table SiteMap(NId int primary key identity(0,1),Url varchar(50),[Name] varchar(20),PId int,Roles varchar(10))
insert into SiteMap values('/','',null,'*')
--添加项--
insert into SiteMap values('~/Index.aspx#1','首页',0,'')
go
insert into SiteMap values('~/Index.aspx#2','中心概况',0,'')
go
insert into SiteMap values('~/Index.aspx#3','中心简介',2,'')
go
insert into SiteMap values('~/Index.aspx#4','联系我们',2,'')
go
insert into SiteMap values('~/Index.aspx#5','科学研究',0,'')
go
insert into SiteMap values('~/Index.aspx#6','科研机构',5,'')
go
insert into SiteMap values('~/Index.aspx##7','博士后流动站',5,'')
go
Roles暂时未用

Web.Config:
 <connectionStrings>
    <add name="SiteMap" connectionString="server=.;database=mycast;uid=sa;pwd=" />
 </connectionStrings>
<siteMap defaultProvider="SqlSiteMapProvider">
      <providers>
           <add  name="SqlSiteMapProvider" type="SqlSiteMapProvider"   />
      </providers>
 </siteMap>
Web.sitemap:
<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
  <siteMapNode url="/" title=""  description=""  roles="*">
    <siteMapNode provider="SqlSiteMapProvider"></siteMapNode>
  </siteMapNode>
</siteMap>
SqlSiteMapProvider.cs:
using System;
using System.Data;
using System.Configuration;
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.Data.SqlClient;
using System.Collections.Generic;


/// <summary>
/// SqlSiteMapProvider 的摘要说明
/// </summary>
public class SqlSiteMapProvider: StaticSiteMapProvider
{
    private SiteMapNode rootNode = null;
    private SqlConnection sqlConn = null;
   
    private DataView siteMapDataView = null;

    private Dictionary<string,SiteMapNode> container = new Dictionary<string,SiteMapNode>();

    private string sqlConnStr = "";

 public SqlSiteMapProvider()
 {
        sqlConnStr = ConfigurationManager.ConnectionStrings["SiteMap"].ToString();// "server=.;database=mycast;uid=sa;pwd=";//
 }

    //是否初始化连接
    private bool inited = false;
    public virtual bool IsInited
    {
        get
        {
            return inited;
        }
    }

    public override SiteMapNode RootNode
    {
        get
        {
            SiteMapNode tmp = null;
            tmp = BuildSiteMap();
            return tmp;
           
        }
    }

    protected override SiteMapNode GetRootNodeCore()
    {
        return RootNode;
    }
    /// <summary>
    /// 初始化
    /// </summary>
    /// <param name="name">string</param>
    /// <param name="attributes">NameValueCollection</param>
    public override void Initialize(string name, System.Collections.Specialized.NameValueCollection attributes)
    {
        if (inited)
            return;
        base.Initialize(name, attributes);
        if (sqlConnStr == null || sqlConnStr.Length == 0)
        {
            throw new Exception("未找到连接串");
        }
        else
        {
            sqlConn = new SqlConnection(sqlConnStr);
        }
        inited = true;
    }

    protected override void Clear()
    {
        lock (this)
        {
            rootNode = null;
            base.Clear();
        }
    }

    public override SiteMapNode BuildSiteMap()
    {
        lock (this)
        {
            if (!IsInited)
            {
                throw new Exception("尚未初始化连接");
            }
            if (rootNode == null)
            {
                Clear();
               
                if (sqlConn.State == ConnectionState.Closed)
                    sqlConn.Open();

                //父节点
                int rootNodeId = -1;
                SqlCommand rootNodeCommand =
                    new SqlCommand("SELECT NId, Url, Name,Roles FROM SiteMap WHERE PId is NULL",
                                     sqlConn);
                SqlDataReader rootNodeReader = rootNodeCommand.ExecuteReader();

                if (rootNodeReader.HasRows)
                {
                    rootNodeReader.Read();
                    rootNodeId = rootNodeReader.GetInt32(0);
                    rootNode = new SiteMapNode(this, rootNodeId.ToString(), rootNodeReader.GetString(1), rootNodeReader.GetString(2));
                }
                else
                {
                    rootNodeReader.Close();
                    return null;
                }
                rootNodeReader.Close();
               

                SiteMapNodeCollection smnc =rootNode.ChildNodes;

                string strSql = "select * from SiteMap WHERE PId is not NULL ";
                SqlDataAdapter sda = new SqlDataAdapter(strSql, sqlConn);
                DataSet ds = new DataSet();
                sda.Fill(ds);
                sqlConn.Close();
                siteMapDataView = ds.Tables[0].DefaultView;

                container.Add(rootNode.Key,rootNode);

                BuildStruts(smnc, "0");

            }

            return rootNode;
        }
    }

    private void BuildStruts(SiteMapNodeCollection smnc, string PId)
    {
        DataView dv = siteMapDataView;
        SiteMapNode tmpCN,tmpPN;

        dv.RowFilter = "PId = '" + PId + "'";
       
        if(container.ContainsKey(PId))
        {
            tmpPN = container[PId];
        }else
        {
           
            tmpPN = rootNode;
        }
        foreach (DataRowView drv in dv)
        {
                string key = drv.Row["NId"].ToString();
                string url = drv.Row["Url"].ToString();
                string title = drv.Row["Name"].ToString();
                tmpCN = new SiteMapNode(this, key, url, title);
                container.Add(tmpCN.Key, tmpCN);
                AddNode(tmpCN,tmpPN);
                BuildStruts(tmpCN.ChildNodes, key);
        }
    }

}


你可能感兴趣的:(Provider)