6月 16

配合之前的自动生成DAL代码

做做简单后台还是很快的。

sb.AppendLine("            "+ClassName+"Info info = new "+ClassName+"Info();");
foreach (var item in list)
{
    sb.AppendLine("            info." + item.COLUMN_NAME + " = HttpContext.Request.Form[\"" + item.COLUMN_NAME + "\"];");
}
sb.AppendLine("            var result="+ClassName+"DAL.Insert(info);");
sb.AppendLine("            return Json(new { IsSuccess = result });");

   StringBuilder sb = new StringBuilder();




            var keysList = list.FindAll(a => a.COLUMN_KEY == "PRI");


            foreach (var item in keysList)
            {
                sb.AppendLine("            var " + FirstLetterLower( item.COLUMN_NAME) + " = HttpContext.Request.Form[\"" + item.COLUMN_NAME + "\"];");
            }



            for (int index = 0; index < keysList.Count; index++)
            {
                sb.AppendFormat("{0} {1}{2}", GetCsharpType(keysList[index].DATA_TYPE), keysList[index].COLUMN_NAME, index == keysList.Count - 1 ? "" : ",");
            }
            sb.Append(")\r\n");
            sb.Append("{\r\n");
            sb.Append("using (IDbConnection connection = new MySqlConnection(Config.ConnectionString))\r\n");
            sb.Append("{\r\n");
            sb.AppendFormat("var result = connection.Execute(@\"DELETE FROM `{0}` WHERE\r\n", TableName);
            for (int index = 0; index < keysList.Count; index++)
            {
                sb.AppendFormat("\t\t\t\t\t\t\t\t\t\t\t\t\t`{0}`=?{0}{1}\r\n", keysList[index].COLUMN_NAME, index == keysList.Count - 1 ? "" : ",");
            }
            sb.Append("\t\t\t\t\t\t\t\t\t\t\t\t\t\",new {");
            for (int index = 0; index < keysList.Count; index++)
            {
                sb.AppendFormat("{0}={0}{1}\r\n", keysList[index].COLUMN_NAME, index == keysList.Count - 1 ? "" : ",");
            }
            sb.Append("});\r\n");




            return sb.ToString();



             


        }

  

        private static string FirstLetterLower(string input)

        {

            return input.Substring(0,1).ToLower() + input.Substring(1);

        }

written by ocean

6月 05

网上直接扒了一段代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace XXX
{ 
    public struct RASCONN
    {
        public int dwSize;
        public IntPtr hrasconn;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 257)]
        public string szEntryName;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 17)]
        public string szDeviceType;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 129)]
        public string szDeviceName;
    }
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    public struct RasStats
    {
        public int dwSize;
        public int dwBytesXmited;
        public int dwBytesRcved;
        public int dwFramesXmited;
        public int dwFramesRcved;
        public int dwCrcErr;
        public int dwTimeoutErr;
        public int dwAlignmentErr;
        public int dwHardwareOverrunErr;
        public int dwFramingErr;
        public int dwBufferOverrunErr;
        public int dwCompressionRatioIn;
        public int dwCompressionRatioOut;
        public int dwBps;
        public int dwConnectionDuration;
    }
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    public struct RasEntryName
    {
        public int dwSize;
        //[MarshalAs(UnmanagedType.ByValTStr,SizeConst=(int)RasFieldSizeConstants.RAS_MaxEntryName + 1)]
        public string szEntryName;
        //#if WINVER5
        //  public int dwFlags;
        //  [MarshalAs(UnmanagedType.ByValTStr,SizeConst=260+1)]
        //  public string szPhonebookPath;
        //#endif
    }
    public class RAS
    {
        [DllImport("Rasapi32.dll", EntryPoint = "RasEnumConnectionsA",
             SetLastError = true)]
        internal static extern int RasEnumConnections
            (
            ref RASCONN lprasconn, // buffer to receive connections data
            ref int lpcb, // size in bytes of buffer
            ref int lpcConnections // number of connections written to buffer
            );

        [DllImport("rasapi32.dll", CharSet = CharSet.Auto)]
        internal static extern uint RasGetConnectionStatistics(
            IntPtr hRasConn,       // handle to the connection
            [In, Out]RasStats lpStatistics  // buffer to receive statistics
            );
        [DllImport("rasapi32.dll", CharSet = CharSet.Auto)]
        public extern static uint RasHangUp(
            IntPtr hrasconn  // handle to the RAS connection to hang up
            );
        [DllImport("rasapi32.dll", CharSet = CharSet.Auto)]
        public extern static uint RasEnumEntries(
            string reserved,              // reserved, must be NULL
            string lpszPhonebook,         // pointer to full path and
            //  file name of phone-book file
            [In, Out]RasEntryName[] lprasentryname, // buffer to receive
            //  phone-book entries
            ref int lpcb,                  // size in bytes of buffer
            out int lpcEntries             // number of entries written
            //  to buffer
            );
        [DllImport("wininet.dll", CharSet = CharSet.Auto)]
        public extern static int InternetDial(
            IntPtr hwnd,
            [In]string lpszConnectoid,
            uint dwFlags,
            ref int lpdwConnection,
            uint dwReserved
            );
        public RAS()
        {
        }
    }
    public enum DEL_CACHE_TYPE //要删除的类型。
    {
        File,//表示internet临时文件
        Cookie //表示Cookie
    }
    public class RASDisplay
    {
        [DllImport("wininet.dll", CharSet = CharSet.Auto)]
        public static extern bool DeleteUrlCacheEntry(
            DEL_CACHE_TYPE type
            );
        private string m_duration;
        private string m_ConnectionName;
        private string[] m_ConnectionNames;
        private double m_TX;
        private double m_RX;
        private bool m_connected;
        private IntPtr m_ConnectedRasHandle;
        RasStats status = new RasStats();
        public RASDisplay()
        {
            m_connected = true;
            RAS lpras = new RAS();
            RASCONN lprasConn = new RASCONN();
            lprasConn.dwSize = Marshal.SizeOf(typeof(RASCONN));
            lprasConn.hrasconn = IntPtr.Zero;
            int lpcb = 0;
            int lpcConnections = 0;
            int nRet = 0;
            lpcb = Marshal.SizeOf(typeof(RASCONN));
            nRet = RAS.RasEnumConnections(ref lprasConn, ref lpcb, ref
            lpcConnections);
            if (nRet != 0)
            {
                m_connected = false;
                return;
            }
            if (lpcConnections > 0)
            {
                //for (int i = 0; i < lpcConnections; i++)
                //{
                RasStats stats = new RasStats();
                m_ConnectedRasHandle = lprasConn.hrasconn;
                RAS.RasGetConnectionStatistics(lprasConn.hrasconn, stats);

                m_ConnectionName = lprasConn.szEntryName;
                int Hours = 0;
                int Minutes = 0;
                int Seconds = 0;
                Hours = ((stats.dwConnectionDuration / 1000) / 3600);
                Minutes = ((stats.dwConnectionDuration / 1000) / 60) - (Hours * 60);
                Seconds = ((stats.dwConnectionDuration / 1000)) - (Minutes * 60) - (Hours * 3600);

                m_duration = Hours + " hours " + Minutes + " minutes " + Seconds + " secs";
                m_TX = stats.dwBytesXmited;
                m_RX = stats.dwBytesRcved;
                //}
            }
            else
            {
                m_connected = false;
            }

            int lpNames = 1;
            int entryNameSize = 0;
            int lpSize = 0;
            RasEntryName[] names = null;
            entryNameSize = Marshal.SizeOf(typeof(RasEntryName));
            lpSize = lpNames * entryNameSize;
            names = new RasEntryName[lpNames];
            names[0].dwSize = entryNameSize;
            uint retval = RAS.RasEnumEntries(null, null, names, ref lpSize, out lpNames);
            //if we have more than one connection, we need to do it again
            if (lpNames > 1)
            {
                names = new RasEntryName[lpNames];
                for (int i = 0; i < names.Length; i++)
                {
                    names[i].dwSize = entryNameSize;
                }
                retval = RAS.RasEnumEntries(null, null, names, ref lpSize, out lpNames);
            }
            m_ConnectionNames = new string[names.Length];

            if (lpNames > 0)
            {
                for (int i = 0; i < names.Length; i++)
                {
                    m_ConnectionNames[i] = names[i].szEntryName;
                }
            }
        }
        public string Duration
        {
            get
            {
                return m_connected ? m_duration : "";
            }
        }
        public string[] Connections
        {
            get
            {
                return m_ConnectionNames;
            }
        }
        public double BytesTransmitted
        {
            get
            {
                return m_connected ? m_TX : 0;
            }
        }
        public double BytesReceived
        {
            get
            {
                return m_connected ? m_RX : 0;
            }
        }
        public string ConnectionName
        {
            get
            {
                return m_connected ? m_ConnectionName : "";
            }
        }
        public bool IsConnected
        {
            get
            {
                return m_connected;
            }
        }
        public int Connect(string Connection)
        {
            int temp = 0;
            uint INTERNET_AUTO_DIAL_UNATTENDED = 2;
            int retVal = RAS.InternetDial(IntPtr.Zero, Connection, INTERNET_AUTO_DIAL_UNATTENDED, ref temp, 0);
            return retVal;
        }
        public void Disconnect()
        {
            RAS.RasHangUp(m_ConnectedRasHandle);
        }
    }

}

调用代码

        static void Main(string[] args)
        {
            for (int index = 0; index < 10; index++)
            {
                GetAddressIP();
                RASDisplay ras = new RASDisplay();
                Console.WriteLine("断开连接 start");
                ras.Disconnect();//断开连接
                Console.WriteLine("断开连接 end");
                Thread.Sleep(5000);
                Console.WriteLine("重新拨号 start");
                ras.Connect("ADSL");//重新拨号
                Console.WriteLine("重新拨号 end");

                Console.WriteLine("Sleep start");
                Thread.Sleep(5000);
                Console.WriteLine("Sleep start");
            }
            return;
        }

实际发现有点问题,找到了解决方法
1、右击“网上邻居”–属性;
2、选择“宽带连接”,右击“属性”- >“选项”;
3、把“提示名称、密码和证书等”前面的对号去掉,点“确定”退出;
4、生成模式务必改成x86

 

测试使用xp系统+.net4.0

written by ocean \\ tags:

5月 27

log4net不用介绍了,很久以前就在使用了 零配置使用Log4Net

 

确实非常方便,一般小项目都是直接调用就好了,免除了配置的麻烦,直到最近遇到点小麻烦.

在一个站点我需要两个logger实例,记录两种类型的日志,并且把文件也分开到两个地方,但是实际用下来发现无法分离log内容,会有很多重复.

 

查了之后才明白,每个logger都会继承父类的东西,需要设置logger的additivity属性即可,

就像这样.

   <logger name='loggerRoot'  additivity='false'>

 可惜,我翻遍了也没找到可以用code设置additivity的方法.

 

找到配置的初始化方法.

//默认配置,就是把配置写到config文件的那种
public static ICollection Configure();
//配置从一个文件读取
public static ICollection Configure(FileInfo configFile);
//配置从一个流中获取
public static ICollection Configure(Stream configStream);

灵机一动.把配置字符串以流方式传进去实例化,规避配置文件

        static LogHelper()
        { 
            string xml = @"
  <log4net>
   <logger name='loggerRoot'  additivity='false'>
      <level value='ALL' />
      <appender-ref ref='LogAppender' />
    </logger>
   <logger name='loggerExe'  additivity='false'>
      <level value='ALL' />
      <appender-ref ref='LogExeAppender' />
    </logger>
  <appender name='LogAppender' type='log4net.Appender.RollingFileAppender'>
      <param name='File' value='logs/' />
      <param name='AppendToFile' value='true' /> 
      <param name='RollingStyle' value='Date' />
      <param name='DatePattern' value='yyyy.MM.dd"".log""' />
      <param name='StaticLogFileName' value='false' />
      <lockingModel type='log4net.Appender.FileAppender+MinimalLock' />
      <layout type='log4net.Layout.PatternLayout'>
        <param name='ConversionPattern' value='[%d][%p] - %m%n' />
      </layout>
    </appender>
  <appender name='LogExeAppender' type='log4net.Appender.RollingFileAppender'>
      <param name='File' value='logs/visit/' />
      <param name='AppendToFile' value='true' /> 
      <param name='RollingStyle' value='Date' />
      <param name='DatePattern' value='yyyy.MM.dd.HH"".log""' />
      <param name='StaticLogFileName' value='false' />
      <lockingModel type='log4net.Appender.FileAppender+MinimalLock' />
      <layout type='log4net.Layout.PatternLayout'>
        <param name='ConversionPattern' value='[%d][%p] - %m%n' />
      </layout>
    </appender>
  </log4net>
";
            using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
            {
                XmlConfigurator.Configure(stream);
            }
            logger = LogManager.GetLogger("loggerRoot");
           
        }
        static log4net.ILog logger = null;

试了一下果然可以了,从此可以以通用的方式定制自己的零配置log组件,太棒了,给自己点个赞

2017.6.21更新

加入asp.net core下的初始化方法

    static LogHelper()
        {
            string xml = @"
  <log4net>
   <logger name='loggerRoot'  additivity='false'>
      <level value='ALL' />
      <appender-ref ref='LogAppender' />
    </logger>
  <appender name='LogAppender' type='log4net.Appender.RollingFileAppender'>
      <param name='File' value='logs/' />
      <param name='AppendToFile' value='true' /> 
      <param name='RollingStyle' value='Date' />
      <param name='DatePattern' value='yyyy.MM.dd"".log""' />
      <param name='StaticLogFileName' value='false' />
      <lockingModel type='log4net.Appender.FileAppender+MinimalLock' />
      <layout type='log4net.Layout.PatternLayout'>
        <param name='ConversionPattern' value='[%d][%p] - %m%n' />
      </layout>
    </appender>
  </log4net>
";

            ILoggerRepository repository = LogManager.CreateRepository("NETCoreRepository");
            using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
            {               
                XmlConfigurator.Configure(repository, stream);
            }
            logger = LogManager.GetLogger(repository.Name, "loggerRoot");

        }

written by ocean \\ tags: ,

5月 22

 首先建表

CREATE TABLE `sys_visitlog` (
`Id`  int(11) NOT NULL AUTO_INCREMENT ,
`Url`  varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,
`Ip`  varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,
`Agent`  varchar(2000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,
`AddDate`  datetime NULL DEFAULT NULL ,
`Type`  int(255) NULL DEFAULT NULL ,
`SubDomain`  varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,
PRIMARY KEY (`Id`),
)
ENGINE=InnoDB
DEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ci
AUTO_INCREMENT=2564
ROW_FORMAT=COMPACT
;

 组件代码

    public class LogDBHelper
    {
        public static string ConnectionString = System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];
        /// <summary>
        /// 访问日志到db
        /// </summary>
        /// <param name="url"></param>
        /// <param name="ip"></param>
        /// <param name="angent"></param>
        /// <param name="type">1,get    2,post</param>
        public static bool AddVisitLog(string url, string ip, string agent, int type, string SubDomain)
        {
            try
            {
                DateTime now = DateTime.Now;

                using (IDbConnection connection = new MySqlConnection(ConnectionString))
                {
                    var result = connection.Execute(@"insert into `sys_visitlog`(`Url`,`Ip`,`Agent`,`AddDate`,`Type`,`SubDomain`)
                                                                values
                                                                (?Url,?Ip,?Agent,?AddDate,?Type,?SubDomain)",
                                                       new { Url = url, Ip = ip, Agent = agent, AddDate = now, Type = type, SubDomain = SubDomain });
                    return result > 0;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
            }
            return false;
        }
    }

调用代码,埋点

            string url = HttpContext.Current.Request.Url.ToString().ToLower();
            string ip = IPHelper.ClientIP;
            var agentObject = HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"];
            var SubDomain = HttpContext.Current.Request.Url.Host;
            LogDBHelper.AddVisitLog(url,
                ip,
                agentObject,
                ((HttpContext.Current.Request.RequestType == "POST") ? 2 : 1),
                SubDomain);

最后记录一下查看的语句

select count(*) c,url,ip from sys_visitlog  GROUP BY ip,url ORDER BY c DESC;

过滤

select count(*) c,url,ip from sys_visitlog  GROUP BY ip,url  HAVING count(*)>2

 post

select * FROM sys_visitlog WHERE Type=2

written by ocean

1月 20

开发了个新网站,里面会存在一些表里需要统计记录点击数,然后按照点击数出一个热门列表的功能.

 

然后就渐渐发现这个是一个很常见的功能,很多表都有这个需求,一般做法都是在每个表中加Hit字段,然后order by hit 取列表,这也没什么,关键是我这个小站点,后台在本机,没在线上,所以如果更新数据的话,大多数情况就是覆盖更新,然后就会出现一个问题就是这些表里的点击数量又没了,因为被覆盖了.

当然也不是解决不了,就是不要覆盖更新,写个程序慢慢更新,或者写个sql自己定义更新的列.不过我比较懒,还是嫌麻烦,身为程序员,我懒我自豪

所以就有了这个插件形式存在的表,所有的点击数都记录在这个表里,更新的时候不覆盖这个表就好了,耶

表定义

CREATE TABLE `sys_hit` (
`TableName`  varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' ,
`Key1`  varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' ,
`Key2`  varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' ,
`Key3`  varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL  DEFAULT '' ,
`Count`  int(11) NOT NULL DEFAULT 0 ,
PRIMARY KEY (`TableName`, `Key1`, `Key2`, `Key3`)
)
ENGINE=InnoDB
DEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ci
ROW_FORMAT=COMPACT
;

tablename就是要添加hit的表的名称, key1,key2,key3是指该表的主键,

如果但主键就只用Key1,双主键就Key1,Key2,三主键就Key1,Key2,Key3,四主键嘛就再加字段喽

一般三个就够了,一般哦

 

数据实体

    public class HitInfo
    {
        public string TableName { get; set; }
        public int Domain { get; set; }
        public string Key { get; set; }
        public int Count { get; set; }
    }

数据访问类

public class HitDAL
    { 
        /// <summary>
        /// 点击埋点
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="domain"></param>
        /// <param name="key"></param>
        public static void Hit(string tableName, object key1, object key2,object key3)
        {
            try
            {
                var isUpdate = UpdateHit(tableName, key1,key2,key3);
                if (!isUpdate)
                {
                    Insert(tableName, key1, key2, key3);
                }
            }
            catch (Exception ex) //Catch掉,因为不能影响主进程
            {
                LogHelper.Info("点击量更新错误" + ex.Message);
            }
        }

        private static bool UpdateHit(string tableName, object key1, object key2, object key3)
        { 
            using (IDbConnection connection = new MySqlConnection(Config.ConnectionString))
            {
                var result = connection.Execute(@"UPDATE sys_hit SET `Count`=`Count`+1 WHERE TableName=?TableName AND Key1=?Key1 AND `Key2`=?Key2 AND `Key3`=?Key3 ", new { TableName = tableName, Key1 = key1, Key2 = key2, Key3 = key3 });
                return result > 0;
            }
        }

        private static bool Insert(string tableName, object key1, object key2, object key3)
        {
            using (IDbConnection connection = new MySqlConnection(Config.ConnectionString))
            {
                var result = connection.Execute(@"insert sys_hit(TableName,Key1,`Key2`,Key3,`Count`)values(?TableName,?Key1,?Key2,?Key3,?Count)", new { TableName = tableName,  Key1 = key1, Key2 = key2, Key3 = key3, Count = 1 });
                return result > 0;
            }
        }
 
    }

数据访问还是用的Dapper+Mysql的形式

现在是调用埋点,双主键

            //更新点击数量
            if (model.Book != null) HitDAL.Hit("tb_book", ((int)this.Domain), id.ToString(), string.Empty);

三主键

            //更新点击数量
            if (model.TVDetail != null) HitDAL.Hit("tb_tvdetail", ((int)this.Domain), tvcode, id);

 

接下来是最关键的取数据了

        /// <summary>
        /// 获取点击榜前10
        /// </summary>
        /// <param name="count"></param>
        /// <param name="domain"></param>
        /// <returns></returns>
      public static List<BookInfo> GetHotBookInfos(int pageSize, EnumDomain domain)
      {
          using (IDbConnection connection = new MySqlConnection(Config.ConnectionString))
          {
              var info = connection.Query<BookInfo>(@"select Id,Title,`Count` from tb_book INNER JOIN sys_hit ON tb_book.id =sys_hit.Key2
                                                     where  domain=?Domain order by `Count` desc limit ?PageSize",
                  new { PageSize = pageSize, Domain = (int)domain }).ToList();
              return info;
          }
      }

在此发现Mysql一个很有意思的性质,条件字段类型不一样也没有问题,好赞!!!

OK,记录到此结束

虽然性能肯定会有所降低,但是就以我的数据量来说,真心没觉得有啥慢的,带来的方便确实是大大的,而且是通用的,噢耶!!!

written by ocean

6月 29

2015.9.17更新BootStrap版本

调用方式

         <%=this.PaginationHTML(this.PageIndex,this.PAGESIZE,this.TotalRec,a=>"?pageindex="+a)   %>

函数

        /// <summary>
        /// 分页导航代码,基于Bootstrap
        /// </summary>
        /// <param name="PageIndex"></param>
        /// <param name="PageSize"></param>
        /// <param name="TotalRec"></param>
        /// <param name="func"></param>
        /// <returns></returns>
        public string PaginationHTML(int PageIndex, int PageSize, int TotalRec,Func<int,string> func)
        { 

            int totalPage = (TotalRec % PageSize == 0 ? TotalRec / PageSize : TotalRec / PageSize + 1);

            if (totalPage == 1) //如果只有1页则不显示
                return string.Empty;

            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<ul class=\"pagination\">");  
            for (int i = 1; i <=  totalPage; i++)
            {

                if (i == PageIndex)
                    sb.AppendLine(string.Format("<li class=\"active\"><a href=\"{1}\">{0}</a></li>", i, func(i)));
                else
                    sb.AppendLine(string.Format("<li><a href=\"{1}\">{0}</a></li>", i, func(i))); 
            } 
            sb.AppendLine("</ul>");  
            return sb.ToString(); 
        }

在公司里开发一些页面经常要坐分页,做了一个通用点的,备份一下,以后只要copy了

.cs端

using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 using System.Web.UI;  
 using System.Web.UI.WebControls;  
 using System.Text;  
 
 namespace WebFormTest
 
 {
 
    public partial class WebForm1 : System.Web.UI.Page
 
    {
 
      public int PageIndex = 1;  
      private int pageSize = 12;  
      private int totalCount = 0;  
      const int PageShowNum = 5;//导航条显示半数
 
      public string CurrentUrl = "WebForm1.aspx";  
 
      private int totalPage
 
      {
 
        get
 
        {
 
          return (totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1);  
        }
 
      }
 
 
      /// <summary>
 
      /// 检查参数
 
      /// </summary>
 
      private void CheckParam()  
      {
 
        if (!int.TryParse(Request.QueryString["pageIndex"], out PageIndex))  
          PageIndex = 1;  
      }
 
 
      protected void Page_Load(object sender, EventArgs e)  
      {
 
        this.CheckParam();  
 
        if (!Page.IsPostBack)  
        {
 
          this.BindData();  
        }
 
      }
 
 
      /// <summary>
 
      /// 绑定展示数据
 
      /// </summary>
 
      private void BindData()  
      {
 
        List<int> list = GetData();//获取数据
 
        this.totalCount = list.Count;  
        PagedDataSource datasource = new PagedDataSource();  
        datasource.AllowPaging = true;  
        datasource.DataSource = list;  
        datasource.PageSize = pageSize;  
        datasource.CurrentPageIndex = PageIndex 1;  
        rpt.DataSource = datasource;  
        rpt.DataBind();  
 
        this.SetPager(PageIndex, totalPage);  
      }
 
 
      /// <summary>
 
      /// 用来获取数据
 
      /// </summary>
 
      /// <returns></returns>
 
      private List<int> GetData()  
      {
 
        List<int> list = new List<int>();
 
        for (int index = 1; index < 1000; index++)
 
        {
 
          list.Add(index);  
        }
 
        return list;  
      }     
    
 
      /// <summary>
 
      /// 设置分页
 
      /// </summary>
 
      /// <param name="currentNum">当前页,也就是PageIndex</param>
 
      /// <param name="totalNum">总页数</param>
 
      private void SetPager(int currentNum, int totalNum)  
      {
 
        int _beginNum = 1, _endNum = 1;  
        _beginNum = PageShowNum < currentNum ? currentNum PageShowNum : 1;  
        if (PageShowNum + currentNum >= totalNum)  
        {
 
          _endNum = totalNum;  
        }
 
        else
 
        {
 
          if (int.Equals(_beginNum, 1))  
          {
 
            _endNum = 2 * PageShowNum + _beginNum;  
          }
 
          else
 
          {
 
            _endNum = PageShowNum + currentNum;  
          }
 
        }
 
        StringBuilder sb = new StringBuilder("&nbsp;&nbsp;");  
 
        if (currentNum > 1)  
        {
 
          sb.AppendFormat(" <a class='f_a' href='{0}'> {1} </a>&nbsp;", CurrentUrl, "首页");  
        }
 
        else if (currentNum == 1)  
        {
 
          sb.Append(" <a class='f_a' > 首页 </a>&nbsp;");  
        }
 
 
        string _className = string.Empty;  
        while (_beginNum <= _endNum)  
        {
 
          if (_beginNum == PageIndex)  
          {
 
            _className = "f_s";  
            sb.AppendFormat(" <a class='{0}' style='color:red' > {1} </a>&nbsp;", PageIndex, _beginNum);  
 
          }
 
          else
 
          {
 
            _className = "f_a";  
            sb.AppendFormat(" <a  href='{0}?pageIndex={1}'> {1} </a>&nbsp;", CurrentUrl, _beginNum);  
          }
 
          _beginNum++;
 
        }
 
 
        if (currentNum < totalNum)  
        {
 
          sb.AppendFormat(" <a href='{0}?pageIndex={1}'> {2} </a>&nbsp;",CurrentUrl,totalNum,"尾页");  
       
        }
 
        else if (currentNum == totalNum)  
        {
 
          sb.Append(" <a class='f_a' > 尾页 </a>&nbsp;");  
        }
 
        sb.Append("<input type='text' id='txtPageIndex' style='width:40px;font-size:12px'  onKeyPress='return Page.GoEnter(event)' /> 页 <input type='button' onclick='return Page.GoPage()' value='GO' />");  
        sb.AppendFormat("&nbsp;&nbsp;&nbsp;&nbsp;{0}/{1} 页  共 {2} 篇", currentNum, totalNum, totalCount);  
 
        ltrPage.Text = sb.ToString();  
 
        ClientScript.RegisterClientScriptBlock(Page.GetType(), "ChannelArray", "var totalPage=" + totalNum + ";\r\n", true);  
      }
 
 
    }
 
 }
 

.aspx页面代码

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebFormTest.WebForm1" %>
 
 
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
 <html xmlns="http://www.w3.org/1999/xhtml">
 
 <head runat="server">
 
    <title></title>
 
 </head>
 
 <body>
 
    <form id="form1" runat="server">
 
    <div>
 
      <asp:Repeater ID="rpt" runat="server">
 
        <ItemTemplate>
 
          <%# Container.DataItem.ToString() %>
 
          <br />
 
        </ItemTemplate>
 
      </asp:Repeater>
 
      <br />
 
      <asp:Literal ID="ltrPage" runat="server" />
 
    </div>
 
    <script type="text/javascript">
 
      (function (win) {
 
        if (!win.Page) {
 
          var Page = {
 
            GoPage: function () {
 
              var page = document.getElementById("txtPageIndex").value;  
              if (page.length === 0) {
 
                alert("请您输入页码");  
                return false;  
              };
 
              var IsNum = function () {
 
                var strNum = '1234567890';  
                var isNum = true;  
                for (var i = 0; i < page.length; i += 1) {
 
                  var c = page.charAt(i);  
                  if (strNum.indexOf(c) < 0) {
 
                    isNum = false;  
                    break;  
                  };
 
                };
 
                return isNum;  
              }
 
              if (IsNum()) {
 
                if (parseInt(page) > totalPage && parseInt(page) > 1) {
 
                  alert("您输入的页数超过总页数,请重新输入!");  
                  return false;  
                };
 
                var currentUrl = "<%=CurrentUrl %>" + "?pageIndex=" + page;  
                location.href = currentUrl;  
                return false;  
              } else {
 
                alert("您输入的信息有误,请重新输入!");  
              }
 
 
            },
 
            GoEnter: function (evt) {
 
              evt = evt || window.event;  
              if (evt && evt.keyCode == 13)  
                return Page.GoPage();  
            }
 
          }
 
          win.Page = Page;  
        }
 
        document.getElementById("txtPageIndex").value = "<%=PageIndex %>";  
      })(window);  
    </script>
 
    </form>
 
 </body>
 
 </html>
 

written by ocean