8月 29

这里借助一个开源项目 CassiniDev

 

项目地址(官方下载)

下载回来的压缩包里有很多的exe及dll文件, 下面是每个文件的作用描述:

直接使用的:

CassiniDev.exe:对应.net framework 3.5, asp.net 2.0, windowform gui

CassiniDev4.exe: 对应.net framework 4, asp.net 4.0, windowform gui

CassiniDev-console.exe:对应.net framework 3.5, asp.net 2.0, 控制台程序

CassiniDev4-console.exe:对应.net framework 4, asp.net 4.0, 控制台程序

供二次开发的:

CassiniDev-lib.dll:对应.net framework 3.5, asp.net 2.0

CassiniDev4-lib.dll:对应.net framework 4, asp.net 4.0

供VS调试用的(即用来替换掉VS自带的ASP.Net development server):

WebDev.WebServer.exe

WebDev.WebServer20.exe

WebDev.WebServer40.exe

 

written by ocean

8月 27

很久以前用nvelocity的时候就觉得这个MVC模板引擎用来做代码生成器模板不错,后来由于各种原因也没有试试

 

这两天看了个 ASP.NET的MVC模板引擎用来做代码生成器的帖子,发现真的很好用

功能不一定比CodeSmith强大,但是至少不用破解了,而且掌握源码更安心

 

下面简单记录一下

首先需要下载 RazorEngine

引用相关dll

 

比方说我模板内容是

xzcc 
我是测试: @Model.Name 
我的地址是 : @Model.Url

调用代码

string template = File.ReadAllText(@"D:\Work\AutoCode\Ascend.QuickFramework\Ascend.QuickFramework.MvcApplication\Views\Model.cshtml"); 
 
         dynamic viewBag = new ExpandoObject(); 
         viewBag.Name = "赫洋的Blog"; 
         viewBag.Url = "http://blog.wx6.org"; 
         string result = Razor.Parse(template, viewBag);

最后的输出结果为

xzcc 
我是测试: 赫洋的Blog 
我的地址是 : http://blog.wx6.org

 

written by ocean

8月 12

现在的浏览器对window.open都会做拦截,主要是为了防止广告

 

代码记录一下  有待改进

<!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> 
    <title></title> 
    <script src="jquery-easyui-1.3.3/jquery.min.js" type="text/javascript"></script> 
  
     <script type="text/javascript"> 
         $(function () { 
             $("#btnA").click(function () { 
  
                 var a = $("<a href='http://www.wx6.org' target='_blank'>文学乐</a>").get(0); 
  
                 var e = document.createEvent('MouseEvents'); 
                 e.initEvent('click', true, true); 
                 a.dispatchEvent(e); 
             }); 
  
             $("#btnA").click(function () { 
                 window.open("http://www.wx6.org"); 
             }); 
         }); 
      
      
    </script> 
  
  
</head> 
<body> 
 <input type="button" value="Test A" id="btnA">  <br /> 
  <input type="button" value="Test Open" id="btnOpen">  <br /> 
  
</body> 
</html>

 

 

written by ocean

8月 09

有时候会做一些临时性的东西,每次写个页面真麻烦

以前非常看不上GridView,觉得没有执行效率,但是试了试发现开发效率一级棒,在小页面中完全够用

特做了该页面模板,以后套起来就方便啦.

前台页面

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FiledList.aspx.cs" Inherits="Demo.SystemUI.FiledList" %> 
<%@ Import Namespace="Demo.SystemClassLibrary.Enum" %> 
<!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"> 
        
  
        
         <asp:Button ID="BtAdd" runat="server" Text="新增" OnClick="btnAdd_Click" />  
             
         <asp:Button ID="BtBack" runat="server" Text="返回首页" OnClick="btnBack_Click" />  
         <br /> 
  
<asp:GridView ID="GridView1"  
         runat="server"
            AutoGenerateColumns="False" CellPadding="4"  
           OnRowCancelingEdit="GridView1_RowCancelingEdit"
            OnRowDeleting="GridView1_RowDeleting" 
            OnRowEditing="GridView1_RowEditing" 
            OnRowUpdating="GridView1_RowUpdating"
             OnRowDataBound="GridView1_RowDataBound"
             DataKeyNames="TableName,FiledName"> 
             <Columns>  
  
  
                <asp:TemplateField HeaderText="表名"> 
                    <ItemTemplate> 
                        <%# Eval("TableName")%> 
                    </ItemTemplate> 
                    <EditItemTemplate> 
                        <asp:TextBox ID="TableName" Text='<%# Eval("TableName") %>' runat="server" Width="100px" /> 
                    </EditItemTemplate> 
                    <ItemStyle Width="100px" /> 
                </asp:TemplateField> 
  
  
                <asp:TemplateField HeaderText="列名"> 
                    <ItemTemplate> 
                        <%# Eval("FiledName")%> 
                    </ItemTemplate> 
                    <EditItemTemplate> 
                        <asp:TextBox ID="FiledName" Text='<%# Eval("FiledName") %>' runat="server" Width="100px" /> 
                    </EditItemTemplate> 
                    <ItemStyle Width="100px" /> 
                </asp:TemplateField>  
                      <asp:TemplateField HeaderText="类别"> 
                    <ItemTemplate> 
                        <%# ((EnumSQLDataType)((Demo.SystemUI.TB_Filed)Container.DataItem).Type).ToString()%> 
                    </ItemTemplate> 
                    <EditItemTemplate> 
                        <asp:HiddenField ID="TypeValue" runat="server" Value='<%# Eval("Type") %>' /> 
                        <asp:DropDownList ID="TypeText" runat="server" va Width="100px" /> 
                    </EditItemTemplate>  
               </asp:TemplateField> 
  
                <asp:TemplateField HeaderText="长度"> 
                    <ItemTemplate> 
                        <%# Eval("Length")%> 
                    </ItemTemplate> 
                    <EditItemTemplate> 
                        <asp:TextBox ID="Length" Text='<%# Eval("Length") %>' runat="server" Width="100px" /> 
                    </EditItemTemplate>  
                </asp:TemplateField>  
  
  
  
  
  
                 <asp:TemplateField HeaderText="主键"> 
                    <ItemTemplate> 
                       <asp:CheckBox Checked='<%# Eval("IsKey") %>' Enabled="false" runat="server" Width="50px" /> 
                    </ItemTemplate> 
                    <EditItemTemplate> 
                    <asp:CheckBox ID="IsKey" Checked='<%# Eval("IsKey") %>' runat="server" Width="50px" />  
                    </EditItemTemplate>  
                </asp:TemplateField> 
                      <asp:TemplateField HeaderText="自增"> 
                    <ItemTemplate> 
                       <asp:CheckBox Checked='<%# Eval("IsIdentity") %>' Enabled="false" runat="server" Width="50px" /> 
                    </ItemTemplate> 
                    <EditItemTemplate> 
                    <asp:CheckBox ID="IsIdentity" Checked='<%# Eval("IsIdentity") %>' runat="server" Width="50px" />  
                    </EditItemTemplate>  
                </asp:TemplateField> 
                      <asp:TemplateField HeaderText="外键"> 
                    <ItemTemplate> 
                       <asp:CheckBox Checked='<%# Eval("IsForeignKey") %>' Enabled="false" runat="server" Width="50px" /> 
                    </ItemTemplate> 
                    <EditItemTemplate> 
                    <asp:CheckBox ID="IsForeignKey" Checked='<%# Eval("IsForeignKey") %>' runat="server" Width="50px" />  
                    </EditItemTemplate>  
                </asp:TemplateField>  
                <asp:TemplateField HeaderText="外键表"> 
                    <ItemTemplate> 
                        <%# Eval("ForeignTable")%> 
                    </ItemTemplate> 
                    <EditItemTemplate> 
                        <asp:TextBox ID="ForeignTable" Text='<%# Eval("ForeignTable") %>' runat="server" Width="100px" /> 
                    </EditItemTemplate>  
                </asp:TemplateField>   
                    
                     
                       
  
                  <asp:TemplateField ShowHeader="False">   
                    <ItemTemplate>   
                        <asp:LinkButton  runat="server" CausesValidation="False" CommandName="Edit"  
                            Text="编辑"></asp:LinkButton>   
                    </ItemTemplate>   
                    <EditItemTemplate> 
                      
                    <asp:LinkButton  runat="server" CausesValidation="False" CommandName="UpDate"  
                            Text="更新"></asp:LinkButton> 
                    <asp:LinkButton  runat="server" CausesValidation="False" CommandName="Cancel"  
                            Text="取消"></asp:LinkButton>   
                    </EditItemTemplate> 
                </asp:TemplateField>   
  
                 <asp:TemplateField ShowHeader="False">   
                    <ItemTemplate>   
                        <asp:LinkButton  runat="server" CausesValidation="False" CommandName="Delete"  
                            Text="删除" OnClientClick='<%#  "if (!confirm(\"你确定要删除吗?\")) return false;"%>'></asp:LinkButton>   
                    </ItemTemplate>   
                </asp:TemplateField>    
  
             </Columns>  
         </asp:GridView> 
  
         <br /> 
  
    </form> 
</body> 
</html>

后台代码

 

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using Demo.SystemClassLibrary.Enum; 
using System.Collections; 
using System.Data; 
using Demo.SystemClassLibrary; 
  
namespace Demo.SystemUI 
{ 
    public partial class FiledList : System.Web.UI.Page 
    { 
  
  
        /// <summary> 
        /// 新增按钮 
        /// </summary> 
        /// <param name="sender"></param> 
        /// <param name="e"></param> 
        protected void btnAdd_Click(object sender, EventArgs e) 
        { 
            List<TB_Filed> list = null; 
            using (var db = new DB_SystemEntities()) 
            { 
                list = (from s in db.TB_Filed 
                        where s.TableName == this.TableName 
                        select s).ToList<TB_Filed>(); 
            } 
            list.Add(new TB_Filed() 
            { 
                Type = 1, 
                IsKey = false, 
                IsForeignKey = false, 
                TableName = this.TableName, 
                Length = 0, 
                IsIdentity = false
            }); 
  
            this.GridView1.EditIndex = list.Count - 1; 
  
            GridView1.DataSource = list; 
            GridView1.DataBind(); 
  
        } 
  
        /// <summary> 
        /// 返回按钮 
        /// </summary> 
        /// <param name="sender"></param> 
        /// <param name="e"></param> 
        protected void btnBack_Click(object sender, EventArgs e) 
        { 
            Response.Redirect("~/default.aspx"); 
  
        } 
  
  
  
  
        public string TableName = string.Empty; 
  
        protected void Page_Load(object sender, EventArgs e) 
        { 
            this.TableName = Request.QueryString["tablename"]; 
  
            if (!Page.IsPostBack) 
            { 
                BindDataSource(); 
            } 
        } 
  
        void BindDataSource() 
        { 
            List<TB_Filed> list = null; 
            using (var db = new DB_SystemEntities()) 
            { 
                list = (from s in db.TB_Filed 
                        where s.TableName == this.TableName 
                        select s).ToList<TB_Filed>(); 
            } 
  
  
            GridView1.DataSource = list; 
            GridView1.DataBind(); 
        } 
  
  
        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) 
        { 
            string tableName = GridView1.DataKeys[e.RowIndex].Values[0].ToString(); 
            string filedName = GridView1.DataKeys[e.RowIndex].Values[1].ToString(); 
  
            using (var db = new DB_SystemEntities()) 
            { 
                TB_Filed field = db.TB_Filed.FirstOrDefault(cc => cc.TableName == tableName && cc.FiledName == filedName); 
                if (field != null) 
                { 
                    db.TB_Filed.DeleteObject(field); 
                    db.SaveChanges(); 
  
                } 
            } 
            BindDataSource(); 
        } 
        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) 
        { 
            GridView1.EditIndex = e.NewEditIndex; 
            BindDataSource(); 
        } 
        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) 
        { 
            string filedName = ((TextBox)(GridView1.Rows[e.RowIndex].FindControl("FiledName"))).Text; 
            string tableName = ((TextBox)(GridView1.Rows[e.RowIndex].FindControl("TableName"))).Text; 
            int sqlDataType = int.Parse(((DropDownList)(GridView1.Rows[e.RowIndex].FindControl("TypeText"))).SelectedValue); 
            int length = int.Parse(((TextBox)(GridView1.Rows[e.RowIndex].FindControl("length"))).Text); 
  
            bool isKey = ((CheckBox)(GridView1.Rows[e.RowIndex].FindControl("iskey"))).Checked; 
            bool isIdentity = ((CheckBox)(GridView1.Rows[e.RowIndex].FindControl("IsIdentity"))).Checked; 
            bool isForeignKey = ((CheckBox)(GridView1.Rows[e.RowIndex].FindControl("IsForeignKey"))).Checked; 
            string foreignTable = ((TextBox)(GridView1.Rows[e.RowIndex].FindControl("ForeignTable"))).Text; 
  
            using (var db = new DB_SystemEntities()) 
            { 
                TB_Filed field = db.TB_Filed.FirstOrDefault(cc => cc.TableName == tableName && cc.FiledName == filedName); 
                bool isNew = false; 
                if (field == null) 
                { 
                    field = new TB_Filed(); 
                    isNew = true; 
                } 
                field.TableName = tableName; 
                field.FiledName = filedName; 
                field.Type = sqlDataType; 
                field.Length = length; 
                field.IsKey = isKey; 
                field.IsIdentity = isIdentity; 
                field.IsForeignKey = isForeignKey; 
                field.ForeignTable = foreignTable; 
  
                if (isNew) 
                    db.AddToTB_Filed(field); 
  
                db.SaveChanges(); 
            } 
            GridView1.EditIndex = -1; 
            BindDataSource(); 
        } 
  
        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) 
        { 
            GridView1.EditIndex = -1; 
            BindDataSource(); 
        } 
  
        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
        { 
            if (((DropDownList)e.Row.FindControl("TypeText")) != null) 
            { 
                DropDownList ddlTypeText = (DropDownList)e.Row.FindControl("TypeText"); 
  
                Other.FillDropDownList(ddlTypeText, typeof(EnumSQLDataType)); 
                ddlTypeText.SelectedValue = ((HiddenField)e.Row.FindControl("TypeValue")).Value; 
            } 
        } 
    } 
}

 

written by ocean

8月 08

探针是干什么的就不用多说了,主要记录一下在开发文学乐的时候写的探针

直接上代码

ASPX页面

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Aspx.aspx.cs" Inherits="HeYang.WX6.MainWeb.Aspx" %> 
<%@ Import Namespace="System.Collections.Generic" %> 
<!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 id="Head1" runat="server"> 
    <title>Asp.net探针---文学乐(www.wx6.org)</title> 
      
            <style type="text/css"> 
        BODY { FONT-SIZE: 12px; COLOR: #000000 } 
        TABLE { FONT-SIZE: 12px; COLOR: #000000 } 
        TD { FONT-SIZE: 12px; COLOR: #000000 } 
        FORM { PADDING-RIGHT: 0px; PADDING-LEFT: 0px; PADDING-BOTTOM: 0px; MARGIN: 0px; PADDING-TOP: 0px } 
        TD TD { PADDING-LEFT: 12px } 
        A { COLOR: #000090 } 
        A:hover { COLOR: #ff3333 } 
        .InputTxt { BORDER-RIGHT: #333333 1px solid; BORDER-TOP: #333333 1px solid; FONT-SIZE: 12px; BORDER-LEFT: #333333 1px solid; WIDTH: 120px; BORDER-BOTTOM: #333333 1px solid; HEIGHT: 18px } 
        .Button { BORDER-RIGHT: #333333 1px solid; BORDER-TOP: #333333 1px solid; FONT-SIZE: 12px; BACKGROUND: #ffffff; BORDER-LEFT: #333333 1px solid; WIDTH: 32px; BORDER-BOTTOM: #333333 1px solid; HEIGHT: 16px } 
        .TrHead { FONT-WEIGHT: 600; FONT-SIZE: 12px; BACKGROUND: #339900; COLOR: #ffffff; HEIGHT: 28px; TEXT-ALIGN: center } 
        </style>  
          
</head> 
<body> 
    <form id="form1" runat="server"> 
  
  
<table width="100%" align="center" border="0"> 
                <tr> 
                    <td style="FONT-WEIGHT: 600; FONT-SIZE: 16px; COLOR: #339900" align="center" height="30"> 
                    <a target="_blank" href="http://www.wx6.org"> 
                    <h1>ASP.NET探针</h1> 
                    </a> <a target="_blank" href="http://www.wx6.org">wx6.org</a></td> 
                </tr> 
            </table> 
            <table style="FONT-SIZE: 12px; COLOR: black; FONT-FAMILY: Verdana, Tahoma; BORDER-COLLAPSE: collapse; BACKGROUND-COLOR: whitesmoke"
                borderColor="#666666" cellSpacing="0" width="760" align="center" bgColor="#eeeeee"
                border="1"> 
                <tr> 
                    <td align="center"> 
                        <table style="BORDER-COLLAPSE: collapse" borderColor="#ffffff" cellSpacing="0" width="95%"
                            align="center" border="1"> 
  
                            <% foreach (KeyValuePair<string, Dictionary<string,string>> data in this.Data) 
                               { %> 
                            <tr> 
                                <td class="TrHead" colSpan="2" style="HEIGHT: 21px"><%=data.Key %></td> 
                            </tr> 
                               <%  
                                      foreach (KeyValuePair<string, string> item in data.Value)                                        
                                  {%> 
                                   <tr> 
                                <td width="38%" align="left" style="height: 29px"><%=item.Key %></td> 
                                <td align="left" style="height: 29px"><%=item.Value %></td> 
                          </tr>  
                            <% } 
                               } %>  
                            
                        </table> 
                      <BR> 
                      <table width="95%" border="0"> 
                <tr> 
                    <td align="center" class="TrHead">Asp.net探针.Copyright 2009-2012 <a target="_blank" href="http://www.wx6.org"> 
                            wx6.org</a> All Rights Reserved 
                  
                </tr> 
            </table> 
            </td> </tr> </table> 
              
    </form> 
</body> 
</html>

后缀文件

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using HeYang.Framework.Tools; 
  
namespace HeYang.WX6.MainWeb 
{ 
    public partial class Aspx : System.Web.UI.Page 
    { 
        public Dictionary<string, Dictionary<string, string>> Data; 
  
        protected void Page_Load(object sender, EventArgs e) 
        { 
            WebSiteProber web = new WebSiteProber(); 
            Data = web.Data; 
        } 
    } 
}

最重要的WebSiteProber

using System; 
using System.Collections.Generic; 
using System.Text; 
using System.Web; 
using System.Runtime.InteropServices; 
using System.Diagnostics; 
using HeYang.Framework.Helper; 
  
namespace HeYang.Framework.Tools 
{ 
    public class WebSiteProber 
    { 
  
        public Dictionary<string, Dictionary<string, string>> Data = new Dictionary<string, Dictionary<string, string>>(); 
  
  
        public WebSiteProber() 
        { 
            this.AddGeneralServer(); 
            this.AddWebSiteInfo(); 
  
            this.AddServerCPU(); 
            this.AddServerMemory(); 
        } 
  
  
  
  
        #region -- 内存信息 -- 
        private void AddServerMemory() 
        { 
            Dictionary<string, string> dic = new Dictionary<string, string>(); 
            MEMORY_INFO memory = new MEMORY_INFO(); 
            GlobalMemoryStatus(ref memory); 
            try
            { 
                dic.Add("物理内存总数", (memory.dwTotalPhys / 1024 / 1024) + "M"); 
            } 
            catch (Exception ex) { }; 
            try
            { 
                dic.Add("可用物理内存数", (memory.dwAvailPhys / 1024 / 1024).ToString() + "M"); 
            } 
            catch (Exception ex) 
            { 
                dic.Add("可用物理内存数", "-"); 
            }; 
            try
            { 
                dic.Add("物理内存负载", (memory.dwMemoryLoad).ToString() + "%"); 
            } 
            catch (Exception ex) { }; 
            try
            { 
                dic.Add("虚拟内存总数", (memory.dwTotalVirtual / 1024 / 1024).ToString() + "M"); 
            } 
            catch (Exception ex) { }; 
            try
            { 
                dic.Add("可用虚拟内存数", (memory.dwAvailVirtual / 1024 / 1024).ToString() + "M"); 
            } 
            catch (Exception ex) { }; 
            try
            { 
                dic.Add("当前程序占用的内存", ((Double)GC.GetTotalMemory(false) / 1048576).ToString("N2") + "M"); 
            } 
            catch (Exception ex) { }; 
            try
            { 
                dic.Add("ASP.NET占用的内存", ((Double)Process.GetCurrentProcess().WorkingSet64 / 1048576).ToString("N2") + "M"); 
            } 
            catch (Exception ex) 
            { 
                dic.Add("ASP.NET占用的内存", "-"); 
            }; 
  
            this.Data.Add("服务器内存信息", dic); 
        } 
  
        [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; 
        } 
        #endregion 
  
        #region -- CPU -- 
        private void AddServerCPU() 
        { 
            Dictionary<string, string> dic = new Dictionary<string, string>(); 
            CPU_INFO cpu = new CPU_INFO(); 
            GetSystemInfo(ref cpu); 
            try
            { 
                dic.Add("CPU类型", Environment.GetEnvironmentVariable("PROCESSOR_IDENTIFIER").ToString()); 
                //dic.Add("CPU类型", Environment.GetEnvironmentVariable("PROCESSOR_IDENTIFIER").ToString()); 
                //cpu.dwProcessorType.ToString()); 
            } 
            catch (Exception ex) { }; 
            try
            { 
                dic.Add("CPU数量", cpu.dwNumberOfProcessors.ToString()); 
            } 
            catch (Exception ex) { }; 
  
  
            this.Data.Add("服务器CPU信息", dic); 
        } 
        [DllImport("kernel32")] 
        public static extern void GetSystemInfo(ref CPU_INFO cpuinfo); 
        //定义CPU的信息结构 
        [StructLayout(LayoutKind.Sequential)] 
        public struct CPU_INFO 
        { 
            public uint dwOemId; 
            public uint dwPageSize; 
            public uint lpMinimumApplicationAddress; 
            public uint lpMaximumApplicationAddress; 
            public uint dwActiveProcessorMask; 
            public uint dwNumberOfProcessors; 
            public uint dwProcessorType; 
            public uint dwAllocationGranularity; 
            public uint dwProcessorLevel; 
            public uint dwProcessorRevision; 
        } 
        #endregion 
  
        #region -- 一般信息 -- 
        /// <summary> 
        /// 添加服务器一般信息 
        /// </summary> 
        private void AddGeneralServer() 
        { 
            Dictionary<string, string> dic = new Dictionary<string, string>(); 
            try
            { 
                dic.Add("服务器名称", HttpContext.Current.Server.MachineName); 
            } 
            catch (Exception ex) { }; 
            try
            { 
                dic.Add("服务器IP地址", HttpContext.Current.Request.ServerVariables["LOCAl_ADDR"]); 
  
            } 
            catch (Exception ex) { }; 
            try
            { 
                dic.Add("服务器.Net版本", string.Concat(new object[] { Environment.Version.Major, ".", Environment.Version.Minor, Environment.Version.Build, ".", Environment.Version.Revision })); 
            } 
            catch (Exception ex) { }; 
  
            try
            { 
                dic.Add("服务器时间", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); 
            } 
            catch (Exception ex) { }; 
  
            try
            { 
                int totalSeconds = (Environment.TickCount / 0x3e8); 
                int day = totalSeconds / (24 * 60 * 60); 
                int hour = (totalSeconds % (24 * 60 * 60)) / (60 * 60); 
                int min = (totalSeconds % (60 * 60)) / 60; 
                int sec = totalSeconds % 60; 
                dic.Add("服务器开机时间", string.Format("{0}天{1}小时{2}分{3}秒", day, hour, min, sec)); 
            } 
            catch (Exception ex) { }; 
  
            #region -- 信任等级 -- 
            try
            { 
                AspNetHostingPermissionLevel current = AspNetHostingPermissionLevel.None; 
                foreach (AspNetHostingPermissionLevel trustLevel in
                    new AspNetHostingPermissionLevel[] {   
                 AspNetHostingPermissionLevel.Unrestricted,   
                 AspNetHostingPermissionLevel.High,   
                 AspNetHostingPermissionLevel.Medium,   
                 AspNetHostingPermissionLevel.Low,   
                 AspNetHostingPermissionLevel.Minimal    
             }) 
                { 
                    try
                    { 
                        current = trustLevel; 
                        new AspNetHostingPermission(trustLevel).Demand(); 
                        break; 
                    } 
                    catch (System.Security.SecurityException) 
                    { 
                        continue; 
                    } 
                } 
                string msg = string.Empty; 
                switch (current) 
                { 
                    case AspNetHostingPermissionLevel.Unrestricted: 
                        msg = "完全信任"; break; 
                    default: 
                        msg = current.ToString(); 
                        break; 
                } 
                dic.Add("信任等级", msg); 
            } 
            catch (Exception ex) { }; 
            #endregion 
  
            try
            {  
                dic.Add("客户端IP", IPHelper.ClientIP ); 
            } 
            catch (Exception ex) { }; 
  
            this.Data.Add("服务器一般信息", dic); 
        } 
        #endregion 
  
        #region -- 网站信息 -- 
  
        #endregion 
        private void AddWebSiteInfo() 
        { 
            Dictionary<string, string> dic = new Dictionary<string, string>(); 
            try
            { 
                dic.Add("网站域名", HttpContext.Current.Request.ServerVariables["SERVER_NAME"].ToString()); 
            } 
            catch (Exception ex) { }; 
            try
            { 
                dic.Add("网站文件夹", HttpContext.Current.Request.PhysicalApplicationPath); 
            } 
            catch (Exception ex) { }; 
            try
            { 
                dic.Add("服务器IIS版本", HttpContext.Current.Request.ServerVariables["Server_SoftWare"].ToString()); 
            } 
            catch (Exception ex) { }; 
            try
            { 
                dic.Add("压缩支持", HttpContext.Current.Request.ServerVariables["Http_Accept_Encoding"]); 
            } 
            catch (Exception ex) { };  
  
            this.Data.Add("网站一般信息", dic); 
        } 
    } 
}

 

written by ocean

8月 07

新公司这边的所有物理层次基本是UI+WCF+DB的三层

但是却绑架了开发模式,每次也得开N个Visual Studio,几个VS间切换来切换去,确实麻烦

想起以前有研究过的 C#本地调用,远程调用 当时是远程用的remoting,现在就换成wcf而已

 

研究了一下  做了个demo,记录下来

 

项目结构

Wcf.InterfaceLibrary      协议层,主要是接口契约和实体类,Library工程

WcfHost.WcfServiceLibrary      Service层,实现接口契约,Library工程

WcfHost.ConsoleApplication     WCF的宿主,Console工程

WcfClient.ConsoleApplication    Client调用层,此处为Console工程

 

其中 Server和Client同时引用契约层,因为要实现本地调用,所以,Client还需要引用Service实现dll

当然部署环境是不用的

 

契约层

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
using System.ServiceModel;  
using System.Runtime.Serialization;  
    
namespace Wcf.InterfaceLibrary  
{  
    [ServiceContract]  
    public interface ITestService2  
    {  
        [OperationContract]  
        DateTime GetSystemDate();  
    
        [OperationContract]  
        UserInfo GetModel(int userId);  
    
    }  
    
    [DataContract]  
    public class UserInfo  
    {  
        [DataMember]  
        public int UserId { get; set; }  
        [DataMember]  
        public string UserName { get; set; }  
        [DataMember]  
        public string Url { get; set; }  
    }  
    
    [ServiceContract]  
    public interface ITestService  
    {  
        [OperationContract]  
        int Add(int a, int b);  
    
        [OperationContract]  
        string GetData(string msg);  
    }  
}

Service实现层

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
using Wcf.InterfaceLibrary;  
    
namespace WcfHost.WcfServiceLibrary  
{  
        
    public class TestService : ITestService  
    {  
        public int Add(int a, int b)  
        {  
            return a + b;  
        }  
    
        public string GetData(string msg)  
        {  
            return "Server Result : " + msg;  
        }  
    }  
    public class TestService2 : ITestService2  
    {  
        public DateTime GetSystemDate()  
        {  
            return DateTime.Now;  
        }  
    
        public UserInfo GetModel(int userId)  
        {  
            return new UserInfo()  
            {  
                UserId = userId,  
                UserName = "Name" + userId,  
                Url = "http://blog.wx6.org"
            };  
        }  
    }  
    
    public class TestService3  
    {  
        public int XXX()  
        {  
            return 1;  
        }  
    }  
}

宿主层,此处实现批量寄宿

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
using System.ServiceModel;  
using WcfHost.WcfServiceLibrary;  
using System.Reflection;  
    
namespace WcfHost.ConsoleApplication  
{  
    class Program  
    {   
        private static Dictionary<string, ServiceHost> serviceHosts = new Dictionary<string, ServiceHost>();   
        static void Main(string[] args)  
        {   
            try
            {  
                //通过反射获取所有的type  
                Type[] types = Assembly.Load(new AssemblyName("WcfHost.WcfServiceLibrary")).GetTypes();  
    
                foreach (var type in types)  
                {  
                    Type[] interfaces = type.GetInterfaces();  
                    foreach (var inter in interfaces)  
                    {  
                        if (inter.IsDefined(typeof(ServiceContractAttribute), false))  
                        {  
                            serviceHosts.Add(type.Name, new ServiceHost(type));  
                            break;  
                        }  
                    }  
                }  
                foreach (var host in serviceHosts.Keys)  
                {  
                    serviceHosts[host].Open();  
                    System.Console.WriteLine(host + " Started");  
                }   
                Console.ReadLine();    
            }  
            catch (Exception ex)  
            {  
                Console.WriteLine(ex);  
            }   
            Console.ReadLine();  
        }  
    }  
}

宿主的配置app.config

<?xml version="1.0" encoding="utf-8" ?>  
<configuration>   
  <system.serviceModel>  
         
    <services>  
      <service name="WcfHost.WcfServiceLibrary.TestService">  
        <endpoint address="net.tcp://localhost:1234/TestService"
                   binding="netTcpBinding" contract="Wcf.InterfaceLibrary.ITestService"></endpoint>  
      </service>  
      <service name="WcfHost.WcfServiceLibrary.TestService2">  
        <endpoint address="net.tcp://localhost:1234/TestService2"
                   binding="netTcpBinding" contract="Wcf.InterfaceLibrary.ITestService2"></endpoint>  
      </service>  
    </services>   
  </system.serviceModel>   
</configuration>  

Client端

最终要的文件,ServiceFactory,实现了远程与本地调用的切换

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
using System.ServiceModel;  
using System.Reflection;  
using System.Collections;  
using System.ServiceModel.Channels;  
using Wcf.InterfaceLibrary;  
    
namespace WcfClient.ConsoleApplication  
{  
    public class ServiceFactory  
    {  
        static ServiceFactory()  
        {  
    
            //初始化  
            if (IsLocalInvoke)//本地调用  
            {  
                Type[] types = Assembly.Load(new AssemblyName(DllNameService)).GetTypes();  
                foreach (var type in types)  
                {  
                    Type[] interfaces = type.GetInterfaces();  
                    foreach (var inter in interfaces)  
                    {  
                        if (inter.IsDefined(typeof(ServiceContractAttribute), false))  
                        {  
                            dynamic obj = Activator.CreateInstance(type);  
                            services.Add(inter.FullName, obj);  
                        }  
                    }  
                }  
            }  
            else //远程wcf  
            {  
                Type[] types = Assembly.Load(new AssemblyName(DllNameInterface)).GetTypes();  
                foreach (var inter in types)  
                {  
    
                    if (inter.IsDefined(typeof(ServiceContractAttribute), false))  
                    {  
                        var channelType = typeof(ChannelFactory<>).MakeGenericType(inter);  
                        dynamic channelFactory = Activator.CreateInstance(channelType, inter.FullName);  
                        var service = channelFactory.CreateChannel();  
                        services.Add(inter.FullName, service);  
                    }  
                }  
            }  
        }  
    
    
        /// <summary>  
        /// 配置,是否启用本地开发  
        /// </summary>  
        public static bool IsLocalInvoke = false;  
    
        /// <summary>  
        /// 配置,接口实现类  
        /// </summary>  
        public static string DllNameService = "WcfHost.WcfServiceLibrary";  
    
        /// <summary>  
        /// 配置,接口类  
        /// </summary>  
        public static string DllNameInterface = "Wcf.InterfaceLibrary";  
    
    
        private static Dictionary<string, object> services = new Dictionary<string, object>();  
    
        public static T GetService<T>()  
        {  
            string typeName = typeof(T).ToString();  
    
            return (T)services[typeName];  
        }  
    }  
}

客户端配置文件app.config

<?xml version="1.0"?>  
<configuration>  
  <system.serviceModel>  
    
    <client>   
          <endpoint 
             name="Wcf.InterfaceLibrary.ITestService"
            address="net.tcp://localhost:1234/TestService"
              binding="netTcpBinding"  
              contract="Wcf.InterfaceLibrary.ITestService"  />  
    
          <endpoint
       name="Wcf.InterfaceLibrary.ITestService2"
      address="net.tcp://localhost:1234/TestService2"
        binding="netTcpBinding"
        contract="Wcf.InterfaceLibrary.ITestService2"  />  
        </client>   
        
  </system.serviceModel>    
</configuration>

客户端调用

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
using System.ServiceModel;  
using Wcf.InterfaceLibrary;  
    
namespace WcfClient.ConsoleApplication  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
    
            ITestService iTestService = ServiceFactory.GetService<ITestService>();  
            var result = iTestService.GetData("ocean");  
    
            if (result != null)  
            {  
            }  
    
            ITestService2 iTestService2 = ServiceFactory.GetService<ITestService2>();  
            var result2 = iTestService2.GetSystemDate();  
    
            if (result2 != null)  
            {  
            }  
    
            var user = iTestService2.GetModel(1);  
            if (user != null)  
            {  
            }  
    
        }  
    }  
}

 

整个代码还是有一定的局限性

首先,只能支持单ServiceDLL和单interfaceDLL

二,只能单接口对单实现类

三,endpoint的name必须是接口的全限定名

实际项目中有待改进 ,另外项目运行效率有待测试

 

written by ocean