using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Web;
using System.Web.UI;
using TopWinCMS.BLL;
using TopWinCMS.Common;
namespace TopWinCMS.WebUI.Admin
{
    /// <summary>
    /// Admin_Index_Main 的摘要说明。
    /// </summary>
    public partial class Admin_Index_Main : System.Web.UI.Page
    {
        protected string strUpDate = "";


        [DllImport("kernel32")]
        public static extern void GlobalMemoryStatus(ref MEMORY_INFO meminfo);

        //定义内存的信息结构
        [StructLayout(LayoutKind.Sequential)]
        public struct MEMORY_INFO
        {
            public uint dwLength;
            public uint dwMemoryLoad;
            public uint dwTotalPhys;
            public uint dwAvailPhys;
            public uint dwTotalPageFile;
            public uint dwAvailPageFile;
            public uint dwTotalVirtual;
            public uint dwAvailVirtual;
        }

        protected void Page_Load(object sender, System.EventArgs e)
        {
            if (!(IsPostBack))
            {
                if (Request["Action"] == null)
                {
                    RunningInfo();

                    LB_Version.Text = "TopWinCMS  " + SystemInfo.AssemblyVersion;

                    LB_DataType.Text = (Config.DAL == "TopWinCMS.AccessDAL" ? "Access数据库" : "SQLServer 数据库");
                }
                else
                {

                }
            }
        }

        #region  RunningInfo
        /// <summary>
        /// 运行信息
        /// </summary>
        private void RunningInfo()
        {
            try
            {
                LB_aspnetn.Text = (Process.GetCurrentProcess().WorkingSet64 / 1048576).ToString("N2") + " MB";
            }
            catch
            {
                LB_aspnetn.Text = "系统拒绝提供。";
            }

            try
            {
                LB_aspnetcpu.Text = (Process.GetCurrentProcess().TotalProcessorTime).TotalSeconds.ToString("N0") + " 秒";
            }
            catch { LB_aspnetcpu.Text = "系统拒绝提供。"; }

            LB_serverstart.Text = (System.Environment.TickCount / 3600000).ToString("N2");
            try
            {
                LB_prstart.Text = Process.GetCurrentProcess().StartTime.ToString();
            }
            catch { LB_prstart.Text = "系统拒绝提供。"; }


            try
            {
                LB_CpuUsage.Text = TopWinCMS.Common.Utilities.CpuUsage.Create().Query().ToString();
            }
            catch { }

            int maxThreadNum, portThreadNum;
            System.Threading.ThreadPool.GetMaxThreads(out maxThreadNum, out portThreadNum);
            LB_GetMaxThreads.Text = maxThreadNum.ToString();


            LB_ProcessThread.Text = Process.GetCurrentProcess().Threads.Count.ToString();

            //调用GlobalMemoryStatus函数获取内存的相关信息
            MEMORY_INFO MemInfo;
            MemInfo = new MEMORY_INFO();
            GlobalMemoryStatus(ref MemInfo);
            LB_dwMemoryLoad.Text = MemInfo.dwMemoryLoad + " %";//正在使用内存
            LB_dwAvailPhys.Text = dFileSize(MemInfo.dwAvailPhys);//剩余物理内存
            LB_dwAvailPageFile.Text = dFileSize(MemInfo.dwAvailPageFile);//LbdwAvailPageFile


            LB_servers.Text = Session.Contents.Count.ToString();
            LB_servera.Text = Application.Contents.Count.ToString();
            LB_Cache.Text = HttpRuntime.Cache.Count.ToString();
            LB_CacheMax.Text = dFileSize(HttpRuntime.Cache.EffectivePrivateBytesLimit);



        }
        #endregion
        private void GetRunningInfo(HtmlTextWriter writer)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();


            try
            {
                dic.Add("LB_aspnetn", (Process.GetCurrentProcess().WorkingSet64 / 1048576).ToString("N2") + " MB");
            }
            catch
            {
                dic.Add("LB_aspnetn", "系统拒绝提供。");
            }

            try
            {
                dic.Add("LB_aspnetcpu", (Process.GetCurrentProcess().TotalProcessorTime).TotalSeconds.ToString("N0") + " 秒");
            }
            catch
            {
                dic.Add("LB_aspnetcpu", "系统拒绝提供。");
            }

            dic.Add("LB_serverstart", (System.Environment.TickCount / 3600000).ToString("N2"));

            try
            {
                dic.Add("LB_prstart", Process.GetCurrentProcess().StartTime.ToString());
            }
            catch { dic.Add("LB_prstart", "系统拒绝提供。"); }


            try
            {
                dic.Add("LB_CpuUsage", TopWinCMS.Common.Utilities.CpuUsage.Create().Query().ToString());
            }
            catch { dic.Add("LB_CpuUsage", "系统拒绝提供。"); }

            int maxThreadNum, portThreadNum;
            System.Threading.ThreadPool.GetMaxThreads(out maxThreadNum, out portThreadNum);
            dic.Add("LB_GetMaxThreads", maxThreadNum.ToString());


            dic.Add("LB_ProcessThread", Process.GetCurrentProcess().Threads.Count.ToString());

            //调用GlobalMemoryStatus函数获取内存的相关信息
            MEMORY_INFO MemInfo;
            MemInfo = new MEMORY_INFO();
            GlobalMemoryStatus(ref MemInfo);
            dic.Add("LB_dwMemoryLoad", MemInfo.dwMemoryLoad + " %");//正在使用内存
            dic.Add("LB_dwAvailPhys", dFileSize(MemInfo.dwAvailPhys));//剩余物理内存
            dic.Add("LB_dwAvailPageFile", dFileSize(MemInfo.dwAvailPageFile));//LbdwAvailPageFile


            dic.Add("LB_servers", Session.Contents.Count.ToString());
            dic.Add("LB_servera", Application.Contents.Count.ToString());
            dic.Add("LB_Cache", HttpRuntime.Cache.Count.ToString());
            dic.Add("LB_CacheMax", dFileSize(HttpRuntime.Cache.EffectivePrivateBytesLimit));

            MyStringBuilder json = new MyStringBuilder();
            json.AppendLine("{");
            foreach (KeyValuePair<string, string> item in dic)
            {
                json.AppendFormat("\"{0}\":\"{1}\",", item.Key, item.Value);
            }
            json.TrimEnd();
            json.AppendLine("}");

            Response.Write(json.ToString());
        }


        private void GetRunningInfo2(HtmlTextWriter writer)
        {
            List<string> list = new List<string>();
            try
            {
                Response.Write((Process.GetCurrentProcess().WorkingSet64 / 1048576).ToString("N2") + " MB" + "|");
            }
            catch
            {
                Response.Write("系统拒绝提供。" + "|");
            }

            try
            {
                Response.Write((Process.GetCurrentProcess().TotalProcessorTime).TotalSeconds.ToString("N0") + " 秒" + "|");
            }
            catch
            {
                Response.Write("系统拒绝提供。" + "|");
            }

            Response.Write((System.Environment.TickCount / 3600000).ToString("N2") + "|");
            try
            {
                Response.Write(Process.GetCurrentProcess().StartTime.ToString() + "|");
            }
            catch { Response.Write("系统拒绝提供。" + "|"); }


            try
            {
                Response.Write(TopWinCMS.Common.Utilities.CpuUsage.Create().Query().ToString() + "|");
            }
            catch { }

            int maxThreadNum, portThreadNum;
            System.Threading.ThreadPool.GetMaxThreads(out maxThreadNum, out portThreadNum);
            Response.Write(maxThreadNum.ToString() + "|");


            Response.Write(Process.GetCurrentProcess().Threads.Count.ToString() + "|");

            //调用GlobalMemoryStatus函数获取内存的相关信息
            MEMORY_INFO MemInfo;
            MemInfo = new MEMORY_INFO();
            GlobalMemoryStatus(ref MemInfo);
            Response.Write(MemInfo.dwMemoryLoad + " %" + "|");//正在使用内存
            Response.Write(dFileSize(MemInfo.dwAvailPhys) + "|");//剩余物理内存
            Response.Write(dFileSize(MemInfo.dwAvailPageFile) + "|");//LbdwAvailPageFile


            Response.Write(Session.Contents.Count.ToString() + "|");
            Response.Write(Application.Contents.Count.ToString() + "|");
            Response.Write(HttpRuntime.Cache.Count.ToString() + "|");
            Response.Write(dFileSize(HttpRuntime.Cache.EffectivePrivateBytesLimit) + "|");
        }

        private static string dFileSize(double FileSize)
        {

            if (FileSize < 1024)
            {
                return FileSize + " B";
            }
            else if ((FileSize < 1024 * 1024))
            {

                return Math.Round((FileSize / 1024), 2) + " KB";
            }
            else
            {

                return Math.Round(FileSize / (1024 * 1024), 2) + " MB";
            }
        }




        protected override void Render(HtmlTextWriter writer)
        {
            //base.Render(writer);
            if (Request["Action"] == "GetRunningInfo")
            {
                //System.IO.TextWriter tempWriter = new System.IO.StringWriter();
                //base.Render(new HtmlTextWriter(tempWriter));



                Context.Response.Expires = 0;
                Context.Response.CacheControl = "no-cache";
                Context.Response.ContentType = "text/plain";

                GetRunningInfo(writer);
            }
            else
            {
                base.Render(writer);

            }
        }
    }
}