<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace MVCBase.Areas.SuperAdmin.Public
{
    public class SuperAdminCommon
    {
        /// <summary>
        /// 生成初始化JS,用于初始化左侧栏焦点位置
        /// </summary>
        /// <param name="LI_ID"></param>
        /// <param name="A_ID"></param>
        /// <returns></returns>
        public static string JSInit(string LI_ID, string A_ID)
        {
            StringBuilder sbjs = new StringBuilder();
            sbjs.Append("$(\"#" + LI_ID + "\").addClass(\"current\");" + System.Environment.NewLine);
            sbjs.Append("$(\"#" + A_ID + "\").addClass(\"current\");" + System.Environment.NewLine);
            sbjs.Append("$(\"#main-nav li a.current\").parent().find(\"ul\").slideToggle(\"slow\");" + System.Environment.NewLine);
            return sbjs.ToString();
        }
    }
}<file_sep>﻿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.Security.Cryptography;
using System.IO;
using System.Text;

namespace MVCBase.Common
{
    public class Encrypt
    {
        /// <summary>
        /// 当前程序加密所使用的密钥

        /// </summary>
        public static readonly string sKey = "vingi3DESLDHzt/pRr/TOGSJPXANLG51";

        #region 加密方法
        /// <summary>
        /// 加密方法
        /// </summary>
        /// <param name="pToEncrypt">需要加密字符串</param>
        /// <param name="sKey">密钥</param>
        /// <returns>加密后的字符串</returns>
        public static string DESEncrypt(string pToEncrypt)
        {
            try
            {
                TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
                des.Key = Convert.FromBase64String(sKey);
                des.Mode = CipherMode.ECB;

                byte[] valBytes = Encoding.Unicode.GetBytes(pToEncrypt);
                ICryptoTransform transform = des.CreateEncryptor();

                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, transform, CryptoStreamMode.Write);
                cs.Write(valBytes, 0, valBytes.Length);
                cs.FlushFinalBlock();
                byte[] returnBytes = ms.ToArray();
                cs.Close();

                return Convert.ToBase64String(returnBytes);
            }
            catch (Exception ex)
            {
                System.Web.HttpContext.Current.Response.Write("写入配置信息失败，详细信息：" + ex.Message.Replace("\r\n", "").Replace("'", ""));
            }

            return "";
        }
        #endregion

        #region 解密方法
        /// <summary>
        /// 解密方法
        /// </summary>
        /// <param name="pToDecrypt">需要解密的字符串</param>
        /// <param name="sKey">密匙</param>
        /// <returns>解密后的字符串</returns>
        public static string DESDecrypt(string pToDecrypt)
        {
            try
            {
                TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
                des.Key = Convert.FromBase64String(sKey);
                des.Mode = CipherMode.ECB;

                byte[] valBytes = Convert.FromBase64String(pToDecrypt);
                ICryptoTransform transform = des.CreateDecryptor();

                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, transform, CryptoStreamMode.Write);
                cs.Write(valBytes, 0, valBytes.Length);
                cs.FlushFinalBlock();
                byte[] returnBytes = ms.ToArray();
                cs.Close();

                return Encoding.Unicode.GetString(returnBytes);
            }
            catch (Exception ex)
            {
                System.Web.HttpContext.Current.Response.Write("读取配置信息失败，详细信息：" + ex.Message.Replace("\r\n", "").Replace("'", ""));
            }
            return "";
        }
        #endregion


        #region MD5编码方法
        /// <summary>
        /// MD5编码方法
        /// </summary>
        /// <param name="pToDecrypt">需要编码的字符串</param>
        /// <returns>编码后的字符串</returns>
        public static string MD5Encrypt(string pToEncrypt)
        {
            return FormsAuthentication.HashPasswordForStoringInConfigFile(pToEncrypt, "MD5");
        }
        #endregion

        #region SHA1编码方法
        /// <summary>
        /// MD5编码方法
        /// </summary>
        /// <param name="pToDecrypt">需要编码的字符串</param>
        /// <returns>编码后的字符串</returns>
        public static string SHA1Encrypt(string pToEncrypt)
        {
            return FormsAuthentication.HashPasswordForStoringInConfigFile(pToEncrypt, "SHA1");
        }
        #endregion

    }

}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
namespace MVCBase.Common
{
    public class HtmlPagerControl
    {
        private string _clickevent;
        private int _current_page = 1;
        private int _display_count = 5;
        private int _display_page_count;
        private string _href_page = string.Empty;
        private List<HtmlPageInfo> _items = new List<HtmlPageInfo>();
        private int _left_display_number;
        private string _middle_seperator = "...";
        private int _page_count;
        private int _right_display_number;
        private int _step;
        private int _totalcount;
        private string _totalpageid = string.Empty;

        public HtmlPagerControl(int pageCount, int display_page_count, int totalcount)
        {
            this._page_count = pageCount;
            this._display_page_count = display_page_count;
            this._totalcount = totalcount;
            this._step = display_page_count / 2;
        }

        public void Add(HtmlPageInfo info)
        {
            try
            {
                info.CurrentPage = this._current_page;
                this._items.Add(info);
            }
            catch
            {
                throw new Exception("类型不匹配");
            }
        }

        private void Init()
        {
            HtmlPageInfo info;
            HtmlPageInfo info2;
            HtmlPageInfo info3;
            HtmlPageInfo info4;
            if ((this._current_page - this._step) < 1)
            {
                this._left_display_number = 1;
                this._right_display_number = (this._left_display_number + this._display_page_count) - 1;
            }
            else
            {
                this._left_display_number = this._current_page - this._step;
                this._right_display_number = this._current_page + this._step;
            }
            if (this._right_display_number >= this._page_count)
            {
                this._right_display_number = this._page_count;
                this._left_display_number = ((this._right_display_number - this._display_page_count) <= 0) ? 1 : (this._right_display_number - (this._display_page_count - 1));
            }
            if ((this._right_display_number - this._left_display_number) == this._display_page_count)
            {
                this._right_display_number--;
            }
            if (this._current_page > 1)
            {
                info = new HtmlPageInfo();
                info.CurrentPage = this._current_page;
                info.HrefPage = this._href_page;
                info.ClickEvent = this._clickevent;
                info.IndexPage = 1;
                info.Text = "首頁";
                info.Width = 50;
                info2 = new HtmlPageInfo();
                info2.CurrentPage = this._current_page;
                info2.IndexPage = this._current_page - 1;
                info2.HrefPage = this._href_page;
                info2.ClickEvent = this._clickevent;
                info2.Text = "上一頁";
                info2.Width = 50;
            }
            else
            {
                info = null;
                info2 = null;
            }
            if (this._current_page < this._page_count)
            {
                info3 = new HtmlPageInfo();
                info3.CurrentPage = this._current_page;
                info3.HrefPage = this._href_page;
                info3.ClickEvent = this._clickevent;
                info3.IndexPage = this._current_page + 1;
                info3.Text = "下一頁";
                info3.Width = 50;
                info4 = new HtmlPageInfo();
                info4.CurrentPage = this._current_page;
                info4.HrefPage = this._href_page;
                info4.ClickEvent = this._clickevent;
                info4.IndexPage = this._page_count;
                info4.Text = "末頁";
                info4.Width = 50;
            }
            else
            {
                info4 = null;
                info3 = null;
            }
            if (info != null)
            {
                this._items.Add(info);
            }
            if (info2 != null)
            {
                this._items.Add(info2);
            }
            for (int i = this._left_display_number; i <= this._right_display_number; i++)
            {
                HtmlPageInfo item = new HtmlPageInfo();
                item.IndexPage = i;
                if (this._href_page.EndsWith("/"))
                {
                    this._href_page.Remove(this._href_page.Length - 1, 1);
                }
                item.HrefPage = this._href_page;
                item.ClickEvent = this._clickevent;
                item.CurrentPage = this._current_page;
                item.IndexPage = i;
                this._items.Add(item);
            }
            if (info3 != null)
            {
                this._items.Add(info3);
            }
            if (info4 != null)
            {
                this._items.Add(info4);
            }
        }

        private List<int> ListPage(int current, int place, bool reverse)
        {
            List<int> list = new List<int>();
            while (current != place)
            {
                list.Add(current);
                if (reverse)
                {
                    current++;
                }
                else
                {
                    current--;
                }
            }
            return list;
        }

        public void RemoveAll()
        {
            this._items.Clear();
        }

        public string Render()
        {
            this.Init();
            StringBuilder builder = new StringBuilder();
            builder.Append("<div style=\"text-align: center;margin: 10px;\">");
            if (this._page_count > 1)
            {
                //builder.Append("<div style=\"text-align: center;margin: 10px;font-family: 黑体;\"><div style=\"float: left;\">總 <span style=\"color: red;\">" + this._totalcount.ToString() + "</span> 筆</div><div style=\"float: right;\">共 <span id=\"" + this._totalpageid + "\" style=\"color: red;\">" + this._page_count.ToString() + "</span> 頁</div>");
                foreach (HtmlPageInfo info in this._items)
                {
                    builder.Append(info.Render());
                }
            }
            //else
            //{
            //    builder.Append("<div style=\"text-align: center;margin: 10px;font-family: 黑体;\"><div style=\"float: left;\">總 <span style=\"color: red;\">" + this._totalcount.ToString() + "</span> 筆</div><div style=\"float: right;\">共 <span id=\"" + this._totalpageid + "\" style=\"color: red;\">" + this._page_count.ToString() + "</span> 頁</div>");
            //}
            builder.Append("<div style=\"clear: both;\"></div></div>");
            return builder.ToString();
        }

        public string ClickEvent
        {
            get
            {
                return this._clickevent;
            }
            set
            {
                this._clickevent = value;
            }
        }

        public int CurrentPage
        {
            get
            {
                return this._current_page;
            }
            set
            {
                if (value > this._page_count)
                {
                    this._current_page = this._page_count;
                }
                else if (value < 1)
                {
                    this._current_page = 1;
                }
                else
                {
                    this._current_page = value;
                }
            }
        }

        public int Displaycount
        {
            get
            {
                return this._display_count;
            }
            set
            {
                this._display_count = value;
            }
        }

        public string HrefPage
        {
            get
            {
                return this._href_page;
            }
            set
            {
                this._href_page = value;
            }
        }

        public HtmlPageInfo this[int index]
        {
            get
            {
                if ((index >= this._page_count) || (index < 0))
                {
                    throw new Exception("索引超出大小");
                }
                return this._items[index];
            }
        }

        public List<HtmlPageInfo> Items
        {
            get
            {
                return this._items;
            }
            set
            {
                this._items = value;
            }
        }

        public int left_display_number
        {
            get
            {
                return this._left_display_number;
            }
        }

        public string MiddleSeperator
        {
            get
            {
                return this._middle_seperator;
            }
            set
            {
                this._middle_seperator = value;
            }
        }

        public int PageCount
        {
            get
            {
                return this._page_count;
            }
        }

        public int right_display_number
        {
            get
            {
                return this._right_display_number;
            }
        }

        public int step
        {
            get
            {
                return this._step;
            }
        }

        public string TotalPageId
        {
            get
            {
                return this._totalpageid;
            }
            set
            {
                this._totalpageid = value;
            }
        }
    }
}<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCBase.Domain.Entity;
using MVCBase.DAL;
using NHibernate;

namespace MVCBase.Areas.SuperAdmin.Controllers
{
    public class MediumListController : Controller
    {
        //
        // GET: /SuperAdmin/MediumList/

        public ActionResult Index()
        {
            ViewBag.jsInit = Public.SuperAdminCommon.JSInit("MediumManage", "MediumList");

            Medium dal = new Medium();
            IList<Ba_Medium> medium = dal.Getmedium();

            return View(medium);
        }

    }
}
<file_sep>﻿using NHibernate;
using NHibernate.Cfg;
using MVCBase.Domain.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MVCBase.DAL
{
    public class News
    {
        ISession session;
        public News()
        {
            session = (new NHibernateHelper()).GetSession();
        }

        public void Add(Ba_News news)
        {
            session.Save(news);
            session.Flush();
        }

        public void Update(Ba_News news)
        {
            session.Update(news);
            session.Flush();
        }

        public void SaveOrUpdate(Ba_News news)
        {
            session.SaveOrUpdate(news);
            session.Flush();
        }

        public Ba_News GetSingleNewsById(int Ns_ID)
        {
            return session.Get<Ba_News>(Ns_ID);
        }

        public IList<Ba_News> GetNews()
        {
            return session.CreateQuery("from Ba_News as ns where ns.Ns_State=:st")
                .SetBoolean("st", true).List<Ba_News>();
        }

        public IList<Ba_News> GetNews(int pagenum)
        {
            int pagestep = 3;
            return session.CreateQuery("from Ba_News as ns where ns.Ns_State=:st order by ns.Ns_BuildTime desc")
                .SetBoolean("st", true)
                .SetFirstResult((pagenum - 1) * pagestep)
                .SetMaxResults(pagenum * pagestep)
                .List<Ba_News>();
        }
    }
}
<file_sep>HAICHI
======

海基<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Cfg;

namespace MVCBase.DAL
{
    class NHibernateHelper
    {
        private ISessionFactory _sessionFactory;
        private string path = System.Web.HttpContext.Current.Server.MapPath("~/hibernate.cfg.xml");
        public NHibernateHelper()
        {
            _sessionFactory = GetSessionFactory();
        }
        private ISessionFactory GetSessionFactory()
        {
            return (new Configuration()).Configure(path).BuildSessionFactory();
        }
        public ISession GetSession()
        {
            Configuration cfg = new Configuration().Configure(path);
            ISession session = cfg.BuildSessionFactory().OpenSession();
            return session;
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.IO;
using System.Text;

namespace MVCBase.Common
{
    public class TRIP3DES
    {

        //密钥

        private string sKey = "<KEY>";

        //矢量，矢量可以为空

        private string sIV = "vingiDES";

        //构造一个对称算法

        private SymmetricAlgorithm mCSP = new TripleDESCryptoServiceProvider();



        public TRIP3DES(string _sKey, string _sIV)
        {
            sKey = _sKey;
            sIV = _sIV;
        }


        #region public string EncryptString(string Value)

        /// 

        /// 加密字符串

        /// 

        /// 输入的字符串

        /// 加密后的字符串

        public string EncryptString(string Value)
        {

            ICryptoTransform ct;

            MemoryStream ms;

            CryptoStream cs;

            byte[] byt;

            mCSP.Key = Convert.FromBase64String(sKey);

            mCSP.IV = Convert.FromBase64String(sIV);

            //指定加密的运算模式

            mCSP.Mode = System.Security.Cryptography.CipherMode.ECB;

            //获取或设置加密算法的填充模式

            mCSP.Padding = System.Security.Cryptography.PaddingMode.PKCS7;

            ct = mCSP.CreateEncryptor(mCSP.Key, mCSP.IV);

            byt = Encoding.UTF8.GetBytes(Value);

            ms = new MemoryStream();

            cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);

            cs.Write(byt, 0, byt.Length);

            cs.FlushFinalBlock();

            cs.Close();

            //return Convert.ToBase64String(ms.ToArray());
            //return Convert.ToChar(ms.ToArray()).ToString();

            string strResult = "";
            byte[] b = ms.ToArray();
            for (int i = 0; i < b.Length; i++)
            {
                strResult += b[i].ToString("x").PadLeft(2, '0');
            }
            return strResult;
        }

        #endregion



        #region public string DecryptString(string Value)

        /// 

        /// 解密字符串

        /// 

        /// 加过密的字符串

        /// 解密后的字符串

        public string DecryptString(string Value)
        {

            ICryptoTransform ct;

            MemoryStream ms;

            CryptoStream cs;

            byte[] byt;

            mCSP.Key = Convert.FromBase64String(sKey);

            mCSP.IV = Convert.FromBase64String(sIV);

            mCSP.Mode = System.Security.Cryptography.CipherMode.ECB;

            mCSP.Padding = System.Security.Cryptography.PaddingMode.PKCS7;

            ct = mCSP.CreateDecryptor(mCSP.Key, mCSP.IV);

            //byt = Convert.FromBase64String(Value);

            byt = new byte[Value.Length / 2];
            int bi = 0;
            for (int i = 0; i < Value.Length; i += 2)
            {
                byt[bi] = (byte)Int32.Parse(Value.Substring(i, 2), System.Globalization.NumberStyles.HexNumber);
                bi++;
            }

            ms = new MemoryStream();

            cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);

            cs.Write(byt, 0, byt.Length);

            cs.FlushFinalBlock();

            cs.Close();



            return Encoding.UTF8.GetString(ms.ToArray());

        }

        #endregion

    }

}<file_sep>﻿using System;

namespace MVCBase.Domain.Entity
{
    public class Ba_Medium
    {
        /// <summary>
        /// Ns_ID
        /// </summary>
        public virtual int Ns_ID { get; set; }
        /// <summary>
        /// Ns_Title
        /// </summary>
        public virtual string Ns_Title { get; set; }
        /// <summary>
        /// Ns_SubTitle
        /// </summary>
        public virtual string Ns_SubTitle { get; set; }
        /// <summary>
        /// Ns_Content
        /// </summary>
        public virtual string Ns_Content { get; set; }
        /// <summary>
        /// Ns_BuildTime
        /// </summary>
        public virtual DateTime? Ns_BuildTime { get; set; }
        /// <summary>
        /// Ns_State
        /// </summary>
        public virtual bool Ns_State { get; set; }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCBase.Domain.Entity;
using MVCBase.DAL;
using NHibernate;

namespace MVCBase.Controllers
{
    public class HomeController : Controller
    {
        private static log4net.ILog log = log4net.LogManager.GetLogger("Quote");
        public ActionResult Index()
        {
            //ViewBag.Message = "欢迎使用 ASP.NET MVC!";

            ////Sample dal = new Sample();
            ////var customer = dal.GetCustomerById(3);
            ////customer.FirstName = "Vingi";
            ////customer.LastName = "Chen";
            ////dal.UpdateCustomer(customer);

            //Admin dal = new Admin();
            //var model = dal.GetAdminById(1);
            //ViewBag.Message = model.Ad_AdminPwd;
            //ViewBag.Model = model;

            return View();
        }

        public ActionResult About()
        {
            return View();
        }

        public ActionResult Product()
        {
            return View();
        }

        public ActionResult Key()
        {
            return View();
        }

        public ActionResult People()
        {
            return View();
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCBase.Domain.Entity;
using MVCBase.DAL;
using NHibernate;

namespace MVCBase.Controllers
{
    public class ListController : Controller
    {
        //
        // GET: /List/

        public ActionResult News(int? id)
        {
            News dal = new News();
            IList<Ba_News> model = dal.GetNews(id.HasValue ? (int)id : 1);

            IList<Ba_News> allmodel = dal.GetNews();
            int pagenum = 1;
            if (allmodel.Count % 3 == 0)
                pagenum = allmodel.Count / 3;
            else
                pagenum = allmodel.Count / 3 + 1;
            int currentpage = id.HasValue ? (int)id : 1;
            Common.HtmlPagerControl page = new Common.HtmlPagerControl(pagenum, 3, 7);
            page.CurrentPage = currentpage;
            ViewBag.currentpage = currentpage;
            page.ClickEvent = "onclick=\"topage(this);\"";
            ViewBag.pageinfo = page.Render();

            return View(model);
        }

        public ActionResult Medium(int? id)
        {
            Medium dal = new Medium();
            IList<Ba_Medium> model = dal.Getmedium(id.HasValue ? (int)id : 1);

            IList<Ba_Medium> allmodel = dal.Getmedium();
            int pagenum = 1;
            if (allmodel.Count % 3 == 0)
                pagenum = allmodel.Count / 3;
            else
                pagenum = allmodel.Count / 3 + 1;
            int currentpage = id.HasValue ? (int)id : 1;
            Common.HtmlPagerControl page = new Common.HtmlPagerControl(pagenum, 3, 7);
            page.CurrentPage = currentpage;
            ViewBag.currentpage = currentpage;
            page.ClickEvent = "onclick=\"topage(this);\"";
            ViewBag.pageinfo = page.Render();

            return View(model);
        }

    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;

namespace MVCBase.API
{
    /// <summary>
    /// StaticRequestHandler 的摘要说明
    /// </summary>
    public class StaticRequestHandler : IHttpHandler
    {
        /// <summary>
        /// 静态文件合并处理程式
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
            //该处理程式因含有敏感字符,故不经过XSS过滤
            string type = !string.IsNullOrWhiteSpace(context.Request.QueryString["type"]) ? context.Request.QueryString["type"] : string.Empty;
            switch (type)
            {
                case "css":
                    context.Response.ContentType = "text/css";
                    break;
                case "js":
                    context.Response.ContentType = "text/javascript";
                    break;
                case "javascript":
                    context.Response.ContentType = "text/javascript";
                    break;
                default:
                    context.Response.ContentType = "text/css";
                    break;
            }

            //该处理程式因含有敏感字符,故不经过XSS过滤
            string files_str = !string.IsNullOrWhiteSpace(context.Request.QueryString["f"]) ? context.Request.QueryString["f"] : string.Empty;
            string[] files = files_str.Split(',');

            for (int i = 0; i < files.Length; ++i)
            {
                if (!string.IsNullOrWhiteSpace(files[i]) && (files[i].EndsWith(".css") || files[i].EndsWith(".js")))
                {
                    try
                    {
                        string path = System.Web.HttpContext.Current.Server.MapPath(files[i].StartsWith("~/") ? files[i] : context.Request.ApplicationPath + "/" + files[i]);
                        StreamReader sr = new StreamReader(path, Encoding.GetEncoding("UTF-8"), false);
                        context.Response.Write(sr.ReadToEnd() + Environment.NewLine);
                        context.Response.Expires = 60 * 24 * 30; //30天过期
                        sr.Close();
                        sr.Dispose();
                    }
                    catch (Exception) { }

                }
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}<file_sep>﻿using System;
using NHibernate;
using NHibernate.Cfg;
using MVCBase.Domain.Entity;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MVCBase.DAL
{
    public class Medium
    {
        ISession session;
        public Medium()
        {
            session = (new NHibernateHelper()).GetSession();
        }

        public void Add(Ba_Medium medium)
        {
            session.Save(medium);
            session.Flush();
        }

        public void Update(Ba_Medium medium)
        {
            session.Update(medium);
            session.Flush();
        }

        public void SaveOrUpdate(Ba_Medium medium)
        {
            session.SaveOrUpdate(medium);
            session.Flush();
        }

        public Ba_Medium GetSinglemediumById(int Ns_ID)
        {
            return session.Get<Ba_Medium>(Ns_ID);
        }

        public IList<Ba_Medium> Getmedium()
        {
            return session.CreateQuery("from Ba_Medium as ns where ns.Ns_State=:st")
                .SetBoolean("st", true).List<Ba_Medium>();
        }

        public IList<Ba_Medium> Getmedium(int pagenum)
        {
            int pagestep = 3;
            return session.CreateQuery("from Ba_Medium as ns where ns.Ns_State=:st order by ns.Ns_BuildTime desc")
                .SetBoolean("st", true)
                .SetFirstResult((pagenum - 1) * pagestep)
                .SetMaxResults(pagenum * pagestep)
                .List<Ba_Medium>();
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCBase.Domain.Entity;
using MVCBase.DAL;
using NHibernate;

namespace MVCBase.Areas.SuperAdmin.Controllers
{
    public class NewsOperateController : Controller
    {
        //
        // GET: /SuperAdmin/NewsOperate/

        public ActionResult Index(int? id)
        {
            ViewBag.jsInit = Public.SuperAdminCommon.JSInit("NewsManage", "NewsOperate");
            var model = new Ba_News();
            if (id != null)
            {
                News dal = new News();
                model = dal.GetSingleNewsById((int)id);
            }
            if (model == null)
                model = new Ba_News();

            ViewBag.model = model;

            if (model.Ns_ID.Equals(0))
                ViewBag.Title = "新增最新消息";
            else
                ViewBag.Title = "更新最新消息";

            return View();
        }

        [HttpPost,ValidateInput(false)]
        public string Submit(NewsOperate_Form form)
        {
            string result = string.Empty;
            News dal = new News();
            var model = dal.GetSingleNewsById(form.news_id);
            if (model == null)
                model = new Ba_News();
            model.Ns_Title = form.news_title;
            model.Ns_SubTitle = form.news_subtitle;
            model.Ns_Content = form.news_description;
            model.Ns_BuildTime = DateTime.Now;
            model.Ns_State = true;
            try
            {
                dal.SaveOrUpdate(model);
                result = "1";
            }
            catch (System.Exception ex)
            {
                result = ex.ToString();
            }

            return result;
        }

        public string Delete(int id)
        {
            string result = "0";
            News dal = new News();
            var model = dal.GetSingleNewsById(id);
            if (model != null)
            {
                model.Ns_State = false;
                dal.Update(model);
                result = "1";
            }

            return result;
        }

    }

    public class NewsOperate_Form
    {
        public int news_id { get; set; }
        public string news_title { get; set; }
        public string news_subtitle { get; set; }
        public string news_description { get; set; }
    }
}
<file_sep>﻿using MVCBase.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCBase.Domain.Entity;
using MVCBase.DAL;
using System.Configuration;

namespace MVCBase.Areas.SuperAdmin.Controllers
{
    public class LoginController : Controller
    {
        //
        // GET: /SuperAdmin/Login/

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public string Login(SuperAdmin superadmin)
        {
            string str = string.Empty;
            if (superadmin.Verify())
            {
                str = Login(superadmin.LoginName, superadmin.Password) ? "1" : "2";
            }

            return str;
        }
                
        [NonAction]
        public bool Login(string LoginName, string Password)
        {
            bool istrue = false;

            Admin dal = new Admin();
            IList<Ba_Admin> admins = dal.GetModel(LoginName, Common.Encrypt.MD5Encrypt(Password));
            istrue = admins.Count > 0 ? true : false;

            if (istrue)
            {
                //更新最后login时间
                admins[0].Ad_LastLoginTime = DateTime.Now;
                dal.Update(admins[0]);

                //写入cookies
                setcookie(admins[0]);
            }

            return istrue;
        }

        //设置cookies
        public void setcookie(Ba_Admin entity)
        {
            string _domain = ConfigurationManager.AppSettings["WebDomain"];
            HttpCookieCollection cookiecollect = new HttpCookieCollection();
            HttpCookie Account = null;
            HttpCookie Username = null;

            if (!string.IsNullOrEmpty(entity.Ad_AdminName))
            {
                Account = new HttpCookie("SuperAccount", Encrypt.DESEncrypt(entity.Ad_AdminName + System.Configuration.ConfigurationManager.AppSettings["AccountKey"]));
                Username = new HttpCookie("Superusername", entity.Ad_AdminName);
            }
            cookiecollect.Add(Account);
            cookiecollect.Add(Username);

            for (int i = 0; i < cookiecollect.Count; i++)
            {
                if (!_domain.Equals("localhost"))
                    cookiecollect[i].Domain = _domain;
                System.Web.HttpContext.Current.Response.Cookies.Add(cookiecollect[i]);
            }
        }
    }

    public class SuperAdmin
    {
        public string LoginName { get; set; }
        public string Password { get; set; }

        //验证返回数据的正确性
        public bool Verify()
        {
            bool istrue = true;

            //验证数据是否异常
            if (string.IsNullOrEmpty(this.LoginName) ||
                string.IsNullOrEmpty(this.Password))
            {
                istrue = false;
            }

            return istrue;
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
using MVCBase.Domain.Entity;

namespace MVCBase.DAL
{
    public class Admin
    {
        ISession session;
        public Admin()
        {
            session = (new NHibernateHelper()).GetSession();
        }

        public void CreateAdmin(Ba_Admin admin)
        {
            session.Save(admin);
            session.Flush();
        }

        public Ba_Admin GetAdminById(int Ad_ID)
        {
            //Configuration cfg = new Configuration().Configure(path);
            //ISession session = cfg.BuildSessionFactory().OpenSession();
            return session.Get<Ba_Admin>(Ad_ID);
        }

        public void Update(Ba_Admin admin)
        {
            session.Update(admin);
            session.Flush();
        }

        public IList<Ba_Admin> GetModel(string adminname, string adminpwd)
        {
            //session.Get<Ba_Admin>()
            return session.CreateQuery("from Ba_Admin as ad where ad.Ad_AdminName=:an and ad.Ad_AdminPwd=:ap")
                .SetString("an", adminname).SetString("ap", adminpwd).List<Ba_Admin>();
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
using MVCBase.Domain.Entity;

namespace MVCBase.DAL
{
    public class Sample
    {
        ISession session;
        public Sample()
        {
            session = (new NHibernateHelper()).GetSession();
        }

        public void CreateCustomer(Customer customer)
        {
            //Configuration cfg = new Configuration().Configure(path);
            //ISession session = (new NHibernateHelper()).GetSession();
            session.Save(customer);
            session.Flush();
        }

        public void UpdateCustomer(Customer customer)
        {
            //ISession session = (new NHibernateHelper()).GetSession();
            session.SaveOrUpdate(customer);
            session.Flush();
        }
        public Customer GetCustomerById(int customerId)
        {
            //Configuration cfg = new Configuration().Configure(path);
            //ISession session = cfg.BuildSessionFactory().OpenSession();
            return session.Get<Customer>(customerId);
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using MVCBase.Domain.Entity;
using MVCBase.DAL;
using NHibernate;

namespace MVCBase.Areas.SuperAdmin.Controllers
{
    public class NewsListController : Controller
    {
        //
        // GET: /SuperAdmin/NewsList/

        public ActionResult Index()
        {
            ViewBag.jsInit = Public.SuperAdminCommon.JSInit("NewsManage", "NewsList");

            News dal = new News();
            IList<Ba_News> news = dal.GetNews();
            ViewBag.news = news;

            return View(news);
        }

    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCBase.Domain.Entity;
using MVCBase.DAL;
using NHibernate;

namespace MVCBase.Areas.SuperAdmin.Controllers
{
    public class MediumOperateController : Controller
    {
        //
        // GET: /SuperAdmin/MediumOperate/

        public ActionResult Index(int? id)
        {
            ViewBag.jsInit = Public.SuperAdminCommon.JSInit("MediumManage", "MediumOperate");
            var model = new Ba_Medium();
            if (id != null)
            {
                Medium dal = new Medium();
                model = dal.GetSinglemediumById((int)id);
            }
            if (model == null)
                model = new Ba_Medium();

            ViewBag.model = model;

            if (model.Ns_ID.Equals(0))
                ViewBag.Title = "新增媒體報道";
            else
                ViewBag.Title = "更新媒體報道";

            return View();
        }

        [HttpPost,ValidateInput(false)]
        public string Submit(MediumOperate_Form form)
        {
            string result = string.Empty;
            Medium dal = new Medium();
            var model = dal.GetSinglemediumById(form.medium_id);
            if (model == null)
                model = new Ba_Medium();
            model.Ns_Title = form.medium_title;
            model.Ns_SubTitle = form.medium_subtitle;
            model.Ns_Content = form.medium_description;
            model.Ns_BuildTime = DateTime.Now;
            model.Ns_State = true;
            try
            {
                dal.SaveOrUpdate(model);
                result = "1";
            }
            catch (System.Exception ex)
            {
                result = ex.ToString();
            }

            return result;
        }

        public string Delete(int id)
        {
            string result = "0";
            Medium dal = new Medium();
            var model = dal.GetSinglemediumById(id);
            if (model != null)
            {
                model.Ns_State = false;
                dal.Update(model);
                result = "1";
            }

            return result;
        }

    }

    public class MediumOperate_Form
    {
        public int medium_id { get; set; }
        public string medium_title { get; set; }
        public string medium_subtitle { get; set; }
        public string medium_description { get; set; }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCBase.Domain.Entity;
using MVCBase.DAL;
using NHibernate;

namespace MVCBase.Controllers
{
    public class DetailController : Controller
    {
        //
        // GET: /Detail/

        public ActionResult News(int? id)
        {
            News dal = new News();
            Ba_News model = dal.GetSingleNewsById(id.HasValue ? (int)id : 1);

            return View(model);
        }

        public ActionResult Medium(int? id)
        {
            Medium dal = new Medium();
            Ba_Medium model = dal.GetSinglemediumById(id.HasValue ? (int)id : 1);

            return View(model);
        }

    }
}
<file_sep>using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Data.SqlClient;


namespace MVCBase.Common
{
    public class Database
    {
        private string sConnectionString = "";
        private SqlConnection Conn;

        public Database() { }

        public Database(string strcon)
        {
            sConnectionString = strcon;
        }

        public string StrCon
        {
            get
            {
                return sConnectionString;
            }
            set
            {
                sConnectionString = value;
            }
        }

        public void Conncetion()
        {
            if (sConnectionString == "" || sConnectionString == null)
            {
                sConnectionString = "";
            }
        }
        private void Open()
        {
            Conncetion();
            Conn = new SqlConnection(sConnectionString);

            if (Conn.State == ConnectionState.Closed)
                Conn.Open();

        }

        public void Close()
        {
            if (Conn != null)
            {
                if (Conn.State == ConnectionState.Open)
                    Conn.Close();
                Conn.Dispose();
                Conn = null;
            }
        }

        private void Dispose()
        {
            if (Conn != null)
                Conn.Dispose();
            Conn = null;
        }

        public SqlDataReader ExecuteReader(string cmdText, CommandType cmdType)
        {
            this.Open();
            SqlCommand cmd = new SqlCommand();

            cmd.Connection = Conn;
            cmd.CommandType = cmdType;
            cmd.CommandText = cmdText;

            try
            {

                return cmd.ExecuteReader(CommandBehavior.CloseConnection);
            }

            catch
            {
                this.Close();
                return null;
            }
        }

        public SqlDataReader ExecuteReader(string cmdText, CommandType cmdType, params SqlParameter[] CmdParams)
        {
            this.Open();
            SqlCommand cmd = new SqlCommand();

            cmd.Connection = Conn;
            cmd.CommandType = cmdType;
            cmd.CommandText = cmdText;

            if (CmdParams != null)
            {
                foreach (SqlParameter Param in CmdParams)
                {
                    cmd.Parameters.Add(Param);
                }
            }

            try
            {
                SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();

                return reader;
            }

            catch
            {
                this.Close();
                return null;
            }
        }

        public DataSet GetDataSet(string cmdText, CommandType cmdType)
        {
            Conncetion();
            SqlCommand cmd = new SqlCommand();
            using (SqlConnection Conn = new SqlConnection(sConnectionString))//调用完直接释放资源 适用与非连接环境
            {
                cmd.Connection = Conn;
                cmd.CommandType = cmdType;
                cmd.CommandText = cmdText;

                SqlDataAdapter ada = new SqlDataAdapter();
                ada.SelectCommand = cmd;

                DataSet ds = new DataSet();
                try
                {
                    ada.Fill(ds);
                }
                catch (SqlException)
                {
                }

                return ds;
            }
        }

        public DataSet GetDataSet(string cmdText, CommandType cmdType, SqlParameter[] adaParams)
        {
            Conncetion();
            SqlCommand cmd = new SqlCommand();
            using (SqlConnection Conn = new SqlConnection(sConnectionString))
            {
                cmd.Connection = Conn;
                cmd.CommandType = cmdType;
                cmd.CommandText = cmdText;

                SqlDataAdapter ada = new SqlDataAdapter();

                if (adaParams != null)
                {
                    foreach (SqlParameter Param in adaParams)
                    {
                        cmd.Parameters.Add(Param);
                    }
                }

                ada.SelectCommand = cmd;

                DataSet ds = new DataSet();
                try
                {
                    ada.Fill(ds);
                }
                catch (SqlException)
                {
                }


                cmd.Parameters.Clear();

                return ds;
            }
        }

        public DataTable GetDataTable(string cmdText)
        {
            DataTable tempdt = new DataTable();
            try
            {
                tempdt = GetDataSet(cmdText, CommandType.Text).Tables[0];
            }
            catch (Exception)
            {
            }

            return tempdt;
        }

        public DataTable GetDataTable(string cmdText, CommandType cmdType)
        {
            DataTable tempdt = new DataTable();
            try
            {
                tempdt = GetDataSet(cmdText, cmdType).Tables[0];
            }
            catch (Exception)
            {
            }

            return tempdt;
        }

        public DataTable GetDataTable(string cmdText, CommandType cmdType, SqlParameter[] adaParams)
        {
            return GetDataSet(cmdText, cmdType, adaParams).Tables[0];
        }

        public int ExecuteNonQuery(string cmdText, CommandType cmdType)
        {
            int i;
            try
            {
                this.Open();
                SqlCommand cmd = new SqlCommand();

                cmd.Connection = Conn;
                cmd.CommandType = cmdType;
                cmd.CommandText = cmdText;

                i = cmd.ExecuteNonQuery();
            }

            catch (SqlException e)
            {
                throw e;
            }
            finally
            {
                this.Close();
            }

            return i;

        }

        public int ExecuteNonQuery(string cmdText, CommandType cmdType, SqlParameter[] cmdParams)
        {
            int i;
            try
            {
                this.Open();
                SqlCommand cmd = new SqlCommand();

                cmd.Connection = Conn;
                cmd.CommandType = cmdType;
                cmd.CommandText = cmdText;

                foreach (SqlParameter Param in cmdParams)
                {
                    cmd.Parameters.Add(Param);
                }


                i = cmd.ExecuteNonQuery();
            }

            catch (SqlException e)
            {
                throw e;
            }
            finally
            {
                this.Close();
            }

            return i;
        }

        public int ExecuteReturnValue(string cmdText, CommandType cmdType)
        {
            SqlCommand cmd;
            try
            {
                this.Open();
                cmd = new SqlCommand();

                cmd.Connection = Conn;
                cmd.CommandType = cmdType;
                cmd.CommandText = cmdText;

                cmd.Parameters.Add(new SqlParameter("ReturnValue", SqlDbType.Int, 4,
                ParameterDirection.ReturnValue, false, 0, 0, string.Empty, DataRowVersion.Default, null));

                cmd.ExecuteNonQuery();
            }

            catch (SqlException e)
            {
                throw e;
            }
            finally
            {
                this.Close();
            }

            return (int)cmd.Parameters["ReturnValue"].Value;
        }

        public int ExecuteReturnValue(string cmdText, CommandType cmdType, SqlParameter[] cmdParams)
        {
            SqlCommand cmd;
            try
            {
                this.Open();
                cmd = new SqlCommand();

                cmd.Connection = Conn;
                cmd.CommandType = cmdType;
                cmd.CommandText = cmdText;

                foreach (SqlParameter Param in cmdParams)
                {
                    cmd.Parameters.Add(Param);
                }

                cmd.Parameters.Add(new SqlParameter("ReturnValue", SqlDbType.Int, 4,
                    ParameterDirection.ReturnValue, false, 0, 0, string.Empty, DataRowVersion.Default, null));

                cmd.ExecuteNonQuery();
            }

            catch (SqlException e)
            {
                throw e;
            }
            finally
            {
                this.Close();
            }

            return (int)cmd.Parameters["ReturnValue"].Value;
        }

        public object ExecuteScalar(string cmdText)
        {
            object o;
            try
            {
                this.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = Conn;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = cmdText;
                o = cmd.ExecuteScalar();
            }
            catch (SqlException e)
            {
                throw e;
            }
            finally
            {
                this.Close();
            }
            return o;
        }

        public object ExecuteScalar(string cmdText, CommandType cmdType)
        {
            object o;
            try
            {
                this.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = Conn;
                cmd.CommandType = cmdType;
                cmd.CommandText = cmdText;
                o = cmd.ExecuteScalar();
            }
            catch (SqlException e)
            {
                throw e;
            }
            finally
            {
                this.Close();
            }
            return o;
        }

        public object ExecuteScalar(string cmdText, CommandType cmdType, SqlParameter[] cmdParams)
        {
            object o;
            SqlCommand cmd = new SqlCommand();
            try
            {
                this.Open();
                cmd.Connection = Conn;
                cmd.CommandType = cmdType;
                cmd.CommandText = cmdText;
                foreach (SqlParameter Param in cmdParams)
                {
                    cmd.Parameters.Add(Param);
                }
                o = cmd.ExecuteScalar();
            }
            catch (SqlException e)
            {
                throw e;
            }
            finally
            {
                cmd.Parameters.Clear();
                this.Close();
            }
            return o;
        }

        //------------------------------------------------------------------------------------


        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="procName">存储过程名</param>
        /// <returns>是否执行成功</returns>
        public bool RunProc(string procName)
        {
            try
            {
                SqlCommand cmd = CreateCommand(procName, null, CommandType.StoredProcedure);
                cmd.ExecuteNonQuery();
                return Convert.ToInt32(cmd.Parameters["ReturnValue"].Value) == 0 ? true : false;
            }
            catch { return false; }
            finally
            {
                Close();
            }
        }

        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="procName">存储过程名</param>
        /// <param name="prams">执行该存储过程所需要的 sql 参数数组 SqlParameter[]</param>
        /// <returns>是否执行成功</returns>
        public int RunProc(string procName, SqlParameter[] prams)
        {
            try
            {
                SqlCommand cmd = CreateCommand(procName, prams, CommandType.StoredProcedure);
                cmd.ExecuteNonQuery();
                return Convert.ToInt32(cmd.Parameters["ReturnValue"].Value);
            }
            catch (Exception ex)
            {
                string s = ex.Message;
                return 0;
            }
            finally
            {
                Close();
            }
        }

        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="procName">存储过程名</param>
        /// <param name="dataReader">SqlDataReader 用来接受存储过程索取的数据集</param>
        /// <returns>是否执行成功</returns>
        public bool RunProc(string procName, out SqlDataReader dataReader)
        {
            try
            {
                SqlCommand cmd = CreateCommand(procName, null, CommandType.StoredProcedure);
                dataReader = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
                return true;
            }
            catch
            {
                dataReader = null;
                return false;
            }
            finally
            {
                Close();
            }
        }

        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="procName">存储过程名</param>
        /// <param name="prams">执行该存储过程所需要的 sql 参数数组 SqlParameter[]</param>
        /// <param name="dataReader">SqlDataReader 用来接受存储过程索取的数据集</param>
        /// <returns>是否执行成功</returns>
        public bool RunProc(string procName, SqlParameter[] prams, out SqlDataReader dataReader)
        {
            try
            {
                SqlCommand cmd = CreateCommand(procName, prams, CommandType.StoredProcedure);
                dataReader = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
                return true;
            }
            catch { dataReader = null; return false; }
            finally
            {
                Close();
            }
        }


        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="procName">存储过程名</param>	
        /// <param name="dataset">DataSet 用来接受存储过程索取的数据集</param>
        /// <returns>是否执行成功</returns>
        public bool RunProc(string procName, out DataSet dataset)
        {
            try
            {
                SqlCommand cmd = CreateCommand(procName, null, CommandType.StoredProcedure);

                SqlDataAdapter da = new SqlDataAdapter(cmd);

                dataset = new DataSet();
                da.Fill(dataset);
                return true;
            }
            catch { dataset = null; return false; }
            finally
            {
                Close();
            }
        }

        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="procName">存储过程名</param>
        /// <param name="prams">执行该存储过程所需要的 sql 参数数组 SqlParameter[]</param>
        /// <param name="dataset">DataSet 用来接受存储过程索取的数据集</param>
        /// <returns>是否执行成功</returns>
        public bool RunProc(string procName, SqlParameter[] prams, out DataSet dataset)
        {
            try
            {
                SqlCommand cmd = CreateCommand(procName, prams, CommandType.StoredProcedure);

                SqlDataAdapter da = new SqlDataAdapter(cmd);

                dataset = new DataSet();

                da.Fill(dataset);
                return true;
            }
            catch { dataset = null; return false; }
            finally
            {
                Close();
            }
        }


        /// <summary>
        /// 为存储过程创建 SqlCommand 对象
        /// </summary>
        /// <param name="procName_sSQL">要创建 SqlCommand 对象的存储过程名---///---或者是 普通的SQL 语句(含sql参数)</param>
        /// <param name="prams">存储过程所需的 sql 参数数组 SqlParameter[]</param>
        /// <returns>创建 SqlCommand 对象</returns>
        private SqlCommand CreateCommand(string procName_sSQL, SqlParameter[] prams, CommandType cmdType)
        {
            // 确认已经打开 数据连接对象 SqlConnection
            Open();

            SqlCommand cmd = new SqlCommand(procName_sSQL, Conn);
            cmd.CommandType = cmdType;

            // 向SqlCommand 对象 添加sql 参数
            if (prams != null)
            {
                foreach (SqlParameter parameter in prams)
                    cmd.Parameters.Add(parameter);
            }

            if (cmdType == CommandType.StoredProcedure)
            {
                // 向SqlCommand 对象 添加返回值 sql 参数 ---- ReturnValue
                cmd.Parameters.Add(
                    new SqlParameter("ReturnValue", SqlDbType.Int, 4,
                    ParameterDirection.ReturnValue, false, 0, 0,
                    string.Empty, DataRowVersion.Default, null));
            }
            return cmd;
        }

        /// <summary>
        /// 执行存储过程(支持 事务 SqlTransaction)
        /// </summary>
        /// <param name="transaction">SqlTransaction 事务对象</param>
        /// <param name="procName">存储过程名</param>
        /// <param name="prams">执行该存储过程所需要的 sql 参数数组 SqlParameter[]</param>
        /// <returns></returns>
        public bool RunProc(SqlTransaction transaction, string procName, SqlParameter[] prams)
        {
            try
            {
                SqlCommand cmd = CreateCommand(transaction, procName, prams, CommandType.StoredProcedure);
                cmd.ExecuteNonQuery();
                return Convert.ToInt32(cmd.Parameters["ReturnValue"].Value) == 0 ? true : false;
            }
            catch { return false; }
            finally
            {
                Close();
            }
        }

        /// <summary>
        /// 为存储过程创建 SqlCommand 对象 (支持 事务 SqlTransaction)
        /// </summary>
        /// <param name="transaction">SqlTransaction 事务对象</param>
        /// <param name="procName_sSQL">存储过程名---///---或者是 普通的SQL 语句(含sql参数)</param>
        /// <param name="prams">存储过程所需要的 sql 参数数组 SqlParameter[]</param>
        /// <returns></returns>
        private SqlCommand CreateCommand(SqlTransaction transaction, string procName_sSQL, SqlParameter[] prams, CommandType cmdType)
        {
            // 确认已经打开 数据连接对象 SqlConnection
            if (transaction.Connection.State != ConnectionState.Open)
            {
                transaction.Connection.ConnectionString = StrCon.ToString();
                transaction.Connection.Open();
            }

            SqlCommand cmd = new SqlCommand(procName_sSQL, transaction.Connection, transaction);
            cmd.CommandType = cmdType;

            //-- 向SqlCommand 对象 添加sql 参数
            if (prams != null)
            {
                foreach (SqlParameter parameter in prams)
                    cmd.Parameters.Add(parameter);
            }

            if (cmdType == CommandType.StoredProcedure)
            {
                // 向SqlCommand 对象 添加返回值 sql 参数 ---- ReturnValue
                cmd.Parameters.Add(
                    new SqlParameter("ReturnValue", SqlDbType.Int, 4,
                    ParameterDirection.ReturnValue, false, 0, 0,
                    string.Empty, DataRowVersion.Default, null));
            }
            return cmd;
        }


        /// <summary>
        /// 创建存储过程/命令文本的 sql 输入参数(SqlParameter)
        /// </summary>
        /// <param name="ParamName">参数名</param>
        /// <param name="DbType">参数类型</param>
        /// <param name="Size">参数数值范围</param>
        /// <param name="Value">参数值</param>
        /// <returns>构造出输入参数</returns>
        public SqlParameter MakeInParam(string ParamName, SqlDbType DbType, int Size, object Value)
        {
            return MakeParam(ParamName, DbType, Size, ParameterDirection.Input, Value);
        }

        /// <summary>
        /// 创建存储过程/命令文本的 sql 输出参数(SqlParameter)
        /// </summary>
        /// <param name="ParamName">参数名</param>
        /// <param name="DbType">参数类型</param>
        /// <param name="Size">参数数值范围</param>
        /// <returns>构造出输出参数</returns>
        public SqlParameter MakeOutParam(string ParamName, SqlDbType DbType, int Size)
        {
            return MakeParam(ParamName, DbType, Size, ParameterDirection.Output, null);
        }

        /// <summary>
        /// 创建存储过程/命令文本的 sql 参数(SqlParameter)
        /// </summary>
        /// <param name="ParamName">参数名</param>
        /// <param name="DbType">参数类型</param>
        /// <param name="Size">参数数值范围</param>
        /// <param name="Direction">参数操作形式</param>
        /// <param name="Value">参数值</param>
        /// <returns>构造出 SqlParameter</returns>
        public SqlParameter MakeParam(string ParamName, SqlDbType DbType, Int32 Size, ParameterDirection Direction, object Value)
        {
            SqlParameter param;

            if (Size > 0)
                param = new SqlParameter(ParamName, DbType, Size);
            else
                param = new SqlParameter(ParamName, DbType);

            param.Direction = Direction;
            if (!(Direction == ParameterDirection.Output && Value == null))
                param.Value = Value;

            return param;
        }


        public DataSet ExecuteNonQuery(string SqlStr)
        {
            //sConncetion();
            SqlConnection SqlCon = new SqlConnection(sConnectionString);
            SqlCon.Open();
            SqlCommand SqlCom = new SqlCommand(SqlStr.ToString(), SqlCon);
            SqlCom.CommandType = CommandType.Text;
            //SqlCom.ExecuteNonQuery();
            DataSet ObjDs = new DataSet();
            SqlDataAdapter SqlDa = new SqlDataAdapter(SqlCom);
            SqlDa.Fill(ObjDs);


            SqlCon.Close();
            return ObjDs;
        }

    }
}<file_sep>﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Text;
using System.Drawing;
using System.Xml;
using System.Collections;
using System.Data.SqlClient;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;

namespace MVCBase.Common
{
    public class common
    {
        private static log4net.ILog log = log4net.LogManager.GetLogger("common");

        #region 防止XSS注入 获取request
        /// <summary>
        /// 防止XSS注入 获取request
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string request(string str)
        {
            string returnstr = string.Empty;
            if (!string.IsNullOrEmpty(System.Web.HttpContext.Current.Request[str]))
                returnstr = XSSInject.XSSInject.FilterXSS(System.Web.HttpContext.Current.Request[str].Trim());

            return returnstr;
        }

        public static string requestForm(string str)
        {
            string returnstr = string.Empty;
            if (!string.IsNullOrEmpty(System.Web.HttpContext.Current.Request.Form[str]))
                returnstr = XSSInject.XSSInject.FilterXSS(System.Web.HttpContext.Current.Request.Form[str].Trim());

            return returnstr;
        }

        public static string requestQueryString(string str)
        {
            string returnstr = string.Empty;
            if (!string.IsNullOrEmpty(System.Web.HttpContext.Current.Request.QueryString[str]))
                returnstr = XSSInject.XSSInject.FilterXSS(System.Web.HttpContext.Current.Request.QueryString[str].Trim());

            return returnstr;
        }

        public static string requestCookies(string str)
        {
            string returnstr = string.Empty;
            if (System.Web.HttpContext.Current.Request.Cookies[str] != null)
                returnstr = XSSInject.XSSInject.FilterXSS(System.Web.HttpContext.Current.Request.Cookies[str].Value.Trim());

            return returnstr;
        }
        #endregion

        #region 过滤SQL注入;
        /// <summary>
        /// 过滤SQL注入;
        /// </summary>
        /// <param name="str">传入string进行SQL过滤</param>
        public static string Sqlstr(string str)
        {
            str = str.Trim();
            if (str == "" || str == string.Empty || str == null)
                return "";

            str = str.Replace(';', '；');
            str = str.Replace('(', '（');
            str = str.Replace(')', '）');

            return str;
        }
        #endregion

        #region 执行正则提取出值
        //执行正则提取出值#region 执行正则提取出值
        /**/
        /**********************************
         * 函数名称:GetRegValue
         * 功能说明:执行正则提取出值
         * 参    数:HtmlCode:html源代码
         * 调用示例:
         *          string GetValue=GetRegValue(Reg,HtmlCode)
         *          Response.Write(GetValue);
         * ********************************/
        /**/
        /// <summary>
        /// 执行正则提取出值
        /// </summary>
        /// <param name="Reg">正则表达式</param>
        /// <param name="HtmlCode">HtmlCode源代码</param>
        /// <returns></returns>
        public static string GetRegValue(string RegexString, string RemoteStr)
        {
            string MatchVale = "";
            //string MatchVale = "0";  //为预防正则匹配为空值,导致insert into失败而修改
            Regex r = new Regex(RegexString);
            Match m = r.Match(RemoteStr);
            if (m.Success)
            {
                MatchVale = m.Value;
            }
            return MatchVale.Replace("\r", "").Replace("\n", "");
        }
        #endregion

    }
}<file_sep>﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace MVCBase.Areas.SuperAdmin.Public
{
    /// <summary>
    /// UploadHandler 的摘要说明
    /// </summary>
    public class UploadHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Charset = "utf-8";
            HttpPostedFile oFile = context.Request.Files["Filedata"];
            string strUploadPath = HttpContext.Current.Server.MapPath("/ImageUpload") + "\\";
            if (oFile != null)
            {
                if (!Directory.Exists(strUploadPath))
                {
                    Directory.CreateDirectory(strUploadPath);
                }
                Random ro = new Random();
                string stro = ro.Next(100, 100000000).ToString();//产生一个随机数用于新命名的图片
                string NewName = DateTime.Now.ToString("yyyyMMdd") + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + stro;
                if (oFile.FileName.Length > 0)
                {
                    string FileExtention = Path.GetExtension(oFile.FileName);
                    string fileallname = strUploadPath + NewName + FileExtention;
                    oFile.SaveAs(fileallname);
                    //异步到image server
                    try
                    {
                        //string re = Upload_Request("http://vingi.soufun.tw/ReceiveImage.ashx?filename=" + NewName + "_1" + FileExtention, fileallname, NewName + FileExtention, context);
                        //string re = uploadtt(fileallname);
                        string re = "/ImageUpload/" + NewName + FileExtention;
                        if (string.IsNullOrEmpty(Common.common.requestQueryString("immediate")))
                        {
                            context.Response.Write(re);
                        }
                        else
                        {
                            context.Response.Write("{\"err\":\"\",\"msg\":\"" + re + "\"}"﻿﻿);
                        }
                        //FileInfo file = new FileInfo(fileallname);
                        //file.Delete();
                        context.Response.End();
                    }
                    catch (Exception ex) { }

                }
            }
            else
            {
                context.Response.Write("0");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}<file_sep>﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
namespace MVCBase.Common
{
    public class HtmlPageInfo : ICloneable
    {
        private Dictionary<string, string> _attributes = new Dictionary<string, string>();
        private string _clickevent = string.Empty;
        private int _current_page = 1;
        private string _href_page = string.Empty;
        private int _index_page = 1;
        private string _mouseout = "this.style.backgroundColor='#ffffff';this.style.color='#000000';this.style.border='1px solid #cccccc';";
        private string _mouseover = "this.style.backgroundColor='#cccccc';this.style.color='#FF7F00';this.style.border='1px solid #999999';";
        private string _text = string.Empty;
        private int _width = 0x19;

        public void AddAttribute(object dictionary)
        {
            Type type = dictionary.GetType();
            if (type != null)
            {
                PropertyInfo[] properties = type.GetProperties();
                foreach (PropertyInfo info in properties)
                {
                    string str = "";
                    str = info.GetValue(dictionary, null).ToString();
                    try
                    {
                        this._attributes.Remove(info.Name.Replace("_", "-"));
                    }
                    catch
                    {
                    }
                    this._attributes.Add(info.Name.Replace("_", "-"), str);
                }
            }
        }

        public object Clone()
        {
            return base.MemberwiseClone();
        }

        private string CreateStyle()
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("");
            if (this._attributes.Count > 0)
            {
                foreach (KeyValuePair<string, string> pair in this._attributes)
                {
                    builder.Append(pair.Key + ":" + pair.Value);
                    builder.Append(";");
                }
            }
            return builder.ToString();
        }

        public string Render()
        {
            if (this._index_page <= 0)
            {
                this._index_page = 1;
            }
            StringBuilder builder = new StringBuilder();
            if (!this._text.Equals("首頁") && !this._text.Equals("末頁"))
            {
                builder.Append("<span " + this._clickevent + " ");
                if (this._text.Equals("下一頁"))
                    builder.Append(" class=\"page_r\" ");
                else if (this._text.Equals("上一頁"))
                    builder.Append(" class=\"page_l\" ");
                else
                    builder.Append(" class=\"page_p\" id=\"page" + this._index_page.ToString() + "\" ");

                builder.Append(this.CreateStyle());
                builder.Append(">");
                //builder.Append(string.IsNullOrEmpty(this._text) ? this._index_page.ToString() : this._text);
                builder.Append("</span>");
            }
            return builder.ToString();
        }

        public string ClickEvent
        {
            get
            {
                return this._clickevent;
            }
            set
            {
                this._clickevent = value;
            }
        }

        public int CurrentPage
        {
            get
            {
                return this._current_page;
            }
            set
            {
                this._current_page = value;
            }
        }

        public string HrefPage
        {
            get
            {
                return this._href_page;
            }
            set
            {
                this._href_page = value;
            }
        }

        public int IndexPage
        {
            get
            {
                return this._index_page;
            }
            set
            {
                this._index_page = value;
            }
        }

        public string MouseOut
        {
            get
            {
                return this._mouseout;
            }
            set
            {
                this._mouseout = value;
            }
        }

        public string MouseOver
        {
            get
            {
                return this._mouseover;
            }
            set
            {
                this._mouseover = value;
            }
        }

        public string Text
        {
            get
            {
                return this._text;
            }
            set
            {
                this._text = value;
            }
        }

        public int Width
        {
            get
            {
                return this._width;
            }
            set
            {
                if (value <= 10)
                {
                    this._width = value;
                }
                else
                {
                    this._width = value;
                }
            }
        }
    }

}<file_sep>﻿using System;

namespace MVCBase.Domain.Entity
{
    public class Ba_Admin
    {
        /// <summary>
        /// Ad_ID
        /// </summary>
        public virtual int Ad_ID { get; set; }
        /// <summary>
        /// Ad_AdminName
        /// </summary>
        public virtual string Ad_AdminName { get; set; }
        /// <summary>
        /// Ad_AdminPwd
        /// </summary>
        public virtual string Ad_AdminPwd { get; set; }
        /// <summary>
        /// Ad_LastLoginTime
        /// </summary>
        public virtual DateTime? Ad_LastLoginTime { get; set; }
        /// <summary>
        /// Ad_BuildTime
        /// </summary>
        public virtual DateTime? Ad_BuildTime { get; set; }
        /// <summary>
        /// Ad_State
        /// </summary>
        public virtual int? Ad_State { get; set; }        

    }
}<file_sep>﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

namespace MVCBase.Common.SqlInject
{
    public class SqlstrAny : IHttpModule
    {
        public void Init(HttpApplication application)
        {
            application.BeginRequest += (new
            EventHandler(this.Application_BeginRequest));
        }
        private void Application_BeginRequest(Object source, EventArgs e)
        {
            ProcessRequest pr = new ProcessRequest();
            pr.StartProcessRequest();
        }
        public void Dispose()
        {
        }
    }

    public class ProcessRequest
    {
        private static string SqlStr = System.Configuration.ConfigurationManager.AppSettings["SqlInject"].ToString();
        private static string sqlErrorPage = System.Configuration.ConfigurationSettings.AppSettings["SQLInjectErrPage"].ToString();
        ///
        /// 用来识别是否是流的方式传输
        ///
        ///
        ///
        bool IsUploadRequest(HttpRequest request)
        {
            return StringStartsWithAnotherIgnoreCase(request.ContentType, "multipart/form-data");
        }
        ///
        /// 比较内容类型
        ///
        ///
        ///
        ///
        private static bool StringStartsWithAnotherIgnoreCase(string s1, string s2)
        {
            return (string.Compare(s1, 0, s2, 0, s2.Length, true, System.Globalization.CultureInfo.InvariantCulture) == 0);
        }

        //SQL注入式攻击代码分析
        #region SQL注入式攻击代码分析
        ///
        /// 处理用户提交的请求
        ///
        public void StartProcessRequest()
        {
            HttpRequest Request = System.Web.HttpContext.Current.Request;
            HttpResponse Response = System.Web.HttpContext.Current.Response;
            try
            {
                string getkeys = "";
                if (IsUploadRequest(Request)) return; //如果是流传递就退出
                //字符串参数
                if (Request.QueryString != null)
                {
                    for (int i = 0; i < Request.QueryString.Count; i++)
                    {
                        getkeys = Request.QueryString.Keys[i];
                        if (!ProcessSqlStr(Request.QueryString[getkeys]))
                        {
                            Response.Redirect(sqlErrorPage + "?errmsg=QueryString中含有非法字符串&amp;sqlprocess=true");
                            Response.End();
                        }
                    }
                }
                //form参数
                if (Request.Form != null)
                {
                    for (int i = 0; i < Request.Form.Count; i++)
                    {
                        getkeys = Request.Form.Keys[i];
                        if (!ProcessSqlStr(Request.Form[getkeys]))
                        {
                            Response.Redirect(sqlErrorPage + "?errmsg=Form中含有非法字符串&amp;sqlprocess=true");
                            Response.End();
                        }
                    }
                }
                //cookie参数
                if (Request.Cookies != null)
                {
                    for (int i = 0; i < Request.Cookies.Count; i++)
                    {
                        getkeys = Request.Cookies.Keys[i];
                        if (!ProcessSqlStr(Request.Cookies[getkeys].Value))
                        {
                            Response.Redirect(sqlErrorPage + "?errmsg=Cookie中含有非法字符串&amp;sqlprocess=true");
                            Response.End();
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                // 错误处理: 处理用户提交信息!
                if (!(ex is HttpRequestValidationException))
                {
                    Response.Clear();
                    Response.Write("CustomErrorPage配置错误");
                    Response.End();
                }
            }
        }

        ///
        /// 分析用户请求是否正常
        ///
        /// 传入用户提交数据
        /// 返回是否含有SQL注入式攻击代码
        private bool ProcessSqlStr(string Str)
        {
            bool ReturnValue = true;
            try
            {
                if (Str != "")
                {
                    string[] anySqlStr = SqlStr.Split('|');
                    foreach (string ss in anySqlStr)
                    {
                        if (Str.IndexOf(ss) >= 0)
                        {
                            ReturnValue = false;
                            break;
                        }
                    }
                }
            }
            catch
            {
                ReturnValue = false;
            }
            return ReturnValue;
        }
        #endregion
    }
}
