【知識碎片】Net項目經驗積累

後臺傳JSON到js報錯

MVC控制器傳json到前端JS"變爲" 致使JS報錯javascript

重點是必定要在@ViewBag.typeJson兩邊加雙引號,而且後臺用css

編碼前臺解碼html

ViewBag.typeJson=System.Web.HttpUtility.UrlEncode(JsonConvert.SerializeObject(info));

 

var data =eval('(' + decodeURIComponent( "@ViewBag.typeJson") + ')'); 

 

響應報文 隱藏服務器信息

X-Powered-By:ASP.NET  這個須要在IIS中移除

選擇你須要修改的站點並雙擊HTTP響應頭部分前端

全部的自定義HTTP頭全在這裏了,刪除相應的頭僅須要點擊右邊的」Remove」java

在代碼中實現的react

HttpContext.Response.Headers.Remove("X-AspNet-Version");
HttpContext.Response.Headers.Remove("X-AspNetMvc-Version");jquery

HttpContext.Response.Headers.Set("Server", "Nginx-57blog-VIP");nginx

在webconfig中實現的web

MVC的版本信息正則表達式

<httpRuntime enableVersionHeader="false" />

在wencongig中加這個就能夠了

 

URL重寫方案總結

方法一:使用現成的 插件,好比:ISAPI_Rewrite、IIS Rewrite、 Apache HTTP服務器的 mod_rewrite等,它們都是基於 正則表達式解析器開發的重寫引擎。它們的使用方法查看它們自帶的幫助便可。
方法二:本身寫的代碼實現動態網頁靜態化,方法也有好幾種:
一、建立FSO對象,利用此對象將所需的內容動態建立到文件中生成 HTML頁面;
二、利用模板技術,將模板中特殊代碼的值替換爲從 表單或是數據庫字段中接受過來的值 生成 HTML文件
三、使用Server.Transfer轉換技術,
方法三:使用HttpWebRequest請求客戶端的方式,獲取返回資源,生成 靜態頁面。通常這樣只須要獲取網頁內容便可,其它資源可放置在服務器上,自動加載。(注:此方法缺點明顯,須要大量更改匹配URL,建議慎用)
方法四:在asp中有IhttpModule接口。Ihttpmodule能夠簡單理解爲一個能夠在執行像.aspx,或者mvc中control/action前,添加咱們自定義的操做的東西。
咱們只須要編寫這麼一個HttpModule就能夠了,當用戶第一次請求asp處理時,咱們能夠在ihttpmodule中攔截到這個請求,而後獲取到此次請求應該返回的html代碼,而後咱們返回這些html給用戶,並保存剛纔咱們獲取到的html到文件內,當用戶下次請求時,咱們只須要直接返回咱們已經保存的html文件便可。

數據庫設計

一、表的設計合理(三範式)

二、添加合適的索引

三、分表技術(水平分割、垂直分割

四、定時清除垃圾數據、定時進行碎片整理

五、多用存儲過程、觸發器

六、讀寫分離

良好的數據庫: 介紹存儲空間 保證數據完整性 糟糕的:數據冗(rong)餘 不完整數據

分庫解決方案 

本身設定必定的規則 好比hash 或者取膜

好比ID  單數設定一個鏈接字符串  雙數設定一個鏈接字符串

或者根據ID的位數  或者根據拼音  漢字筆畫字符長度等

當ID時單數的時候  存的時候存到1庫  取得時候又計算ID等於單數的時候去1庫取

若是是獲取列表頁沒有問題  用戶ID爲3的文章文章都存在庫1上獲取的時候 不須要獲取全部用戶的文章

網站架構演變:單主機-緩存服務器-頁面緩存-服務器集羣-數據庫分庫--分佈式數據庫

負載均衡

硬件Netscaler F5 Radware Array

軟件 LVS nginx apache tengine(淘寶的,提交給nginx nginx不接受,就本身寫了)

LVS:http://www.cnblogs.com/edisonchou/p/4281978.html 

搭建主機 :
須要安裝一個軟件 keepalived
故障移除 把服務器關掉一個,在轉發的時候就不轉發到這臺機器
故障恢復 啓動後,又開始轉發
主機掛了 備機接管主機的工做

經過心跳檢查檢測主機是否掛了

nginx  反向代理服務器  異步非阻塞式  官方高併發5W   實際生產2-3W 

 

管道事件

第一個事件  beginrequrest   第七個第八個之間 根據文件擴展名判斷是通常處理程序仍是頁面程序,若是是ashx就建立httphandler實例  若是是aspx就建立Page對象(每次請求都會有一個IhttpHandler對象去處理當前請求)

在第七個事件以前若是指定了handler  在第七第八個事件之間就建立指定的handler

1-7之間若是指定當前請求處理程序,7-8就不會建立

11-12 執行剛剛建立的IhhttpHandler.processrequest() 若是是page 執行聲明週期

 

Page類回調技術 單頁模式

在前臺頁面直接寫一個 protected void Page_Load(obeject obj,Event e)  就不須要後臺頁面了   能夠直接刪除了,要放在 <script runat="server"></script> 內

這裏面也能夠寫其餘函數  不過仍是寫在後臺效率高,直接編譯dl了,aspx是動態編譯效率低

<%@ Page Language="C#" ContentType="text/html" ResponseEncoding="gb2312" %>
<%@ Implements Interface="System.Web.UI.ICallbackEventHandler" %>
<%@ Import Namespace="System.Text" %>
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>用戶註冊</title>
<script language="javascript">
//客戶端執行的方法
//下面的方法是接收並處理服務器方法執行的返回結果
function Success(args, context)
{
    message.innerText  = args;
}
//下面的方式是當接收服務器方法處理的結果發生異常時調用的方法
function Error(args, context)
{
    message.innerText  = '發生了異常';
}
</script>
<script language="c#" runat="server">
string result="";
// 定義在服務器端運行的回調方法.
public void RaiseCallbackEvent(String eventArgument)
{
 if(eventArgument.ToLower().IndexOf("admin")!=-1)
 {
  result=eventArgument+"不能做爲用戶名註冊。";
 }
 else
 {
  result=eventArgument+"能夠註冊。";
 }
 //throw new Exception();
}
//定義返回回調方法執行結果的方法
public string GetCallbackResult()
{
 return result;
}
//服務器上執行的方法
public void Page_Load(Object sender,EventArgs e)
{
 // 獲取當前頁的ClientScriptManager的引用
    ClientScriptManager csm = Page.ClientScript;
 // 獲取回調引用。會在客戶端生成WebForm_DoCallback方法,調用它來達到異步調用。這個方式是微軟寫的方法,會被髮送到客戶端
 //注意這裏的"Success"和"Error"兩個字符串分別客戶端代碼中定義的兩個javascript函數
 //下面的方法最後一個參數的意義:true表示執行異步回調,false表示執行同步回調
 String reference = csm.GetCallbackEventReference(this, "args","Success","","Error",false);
 String callbackScript = "function CallServerMethod(args, context) {/n" + 
  reference + ";/n }";
 // 向當前頁面註冊javascript腳本代碼
 csm.RegisterClientScriptBlock(this.GetType(), "CallServerMethod", 
  callbackScript, true);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<table border="1" cellpadding="0" cellspacing="0" width="400px">
<tr>
<td width="100px">用戶名</td><td><input type="text" size="10" maxlength="20" id="txtUserName" onblur="CallServerMethod(txtUserName.value,null)" /><span id="message"></span></td>
</tr>
<tr>
<td>密碼</td><td><input type="password" size="10" maxlength="20" id="txtPwd" /></td>
</tr>
</table>
</form>
</body>
</html>
View Code

經過一個aspx文件直接獲取服務器web.config文件

<%@ Page Language="C#" ContentType="text/html" ResponseEncoding="gb2312" %>

<%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System.IO"%>
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>用戶註冊</title>
<script language="javascript">

</script>
<script language="c#" runat="server">
string result="";

//服務器上執行的方法
public void Page_Load(Object sender,EventArgs e)
{
            using (FileStream fs = new FileStream(Server.MapPath("/")+"Web.config", FileMode.Open, FileAccess.Read))
            {
                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);
                string msg = System.Text.Encoding.UTF8.GetString(buffer);
                //Response.Write(msg);

                string timeNow = DateTime.Now.ToString();
                Response.Clear();
                Response.Buffer = false;
                Response.ContentType = "application/octet-stream";
                Response.AppendHeader("content-disposition", "attachment;filename=" + "Web" + ".config;");

                Response.Write(msg);
                Response.Flush();
                Response.End();
            }
}
</script>
</head>
<body>

</body>
</html>
View Code

系統Host

host 地址C:\Windows\System32\drivers\etc  

刷新緩存命令:

cmd   ipconfig /flushdns

多個域名綁定一個IP  

127.0.0.1       localhost www.57blog.com xiaoshi57.57blog.com #多個用空格隔開便可

 

QQ登陸

張善友博客 http://www.cnblogs.com/shanyou/archive/2012/02/05/2338797.html

NVelocity 視圖模板引擎

NVelocity 視圖模板引擎 如 razor vtemplate

CDN加速

全國各地布服務器  把資源放到每一個服務器上,就叫CDN加速

 

 API認證原理

api認證  想到就記下來了

用一個md五、hash或者其餘的加密算法

這個祕鑰由如下部分組成:

tiame: 時間(動態的就行能夠不是時間(guid))

key: 隨意寫一個鹽就能夠,這個鹽不能傳輸,客戶端和服務端以後便可

其餘的就無所謂了

而後加一塊兒生成MD5,把這個MD5傳給服務端  服務端把客戶端傳來的時間加上鹽而後計算出MD5和你傳來的MD5值對比,便可

 

訂單存儲過程

存儲過程比放在程序裏的SQL速度快

存儲過程只編譯一次  程序裏的每次請求都須要編譯

 安全 不會有SQL注入

缺點 可移植性差

互聯網項目通常不用存儲過程  

create proc createOrder
@address nvarchar(255),--收貨人地址
@orderId nvarchar(50),--訂單號
@userId int,--用戶編號
@totalMoney money output --總金額
as
begin
  declare @error int
  set @error=0
  begin transaction
   ---計算總金額
  select @totalMoney=sum([Count]*UnitPrice)from Cart inner join Books on Cart.BookId=Books.Id where Cart.UserId=@userId
   set @error=@@error+@error
  --向訂單主表中插入數據。
  insert into dbo.Orders(OrderId, OrderDate, UserId, TotalPrice, PostAddress, state) values(@orderId,getdate(),@userId,@totalMoney,@address,0)
set @error=@@error+@error
 --行訂單明細表中插入數據
  insert into dbo.OrderBook(OrderID, BookID, Quantity, UnitPrice) select @orderId,Cart.BookId,Cart.Count,Books.UnitPrice from Cart inner join Books on Cart.BookId=Books.Id where Cart.UserId=@userId
  set @error=@@error+@error
--刪除購物車表中的數據
  delete from Cart where UserId=@userId
  set @error=@@error+@error
  if @error>0
    begin
        rollback transaction--回滾
    end
  else
     begin
        commit transaction--提交
     end 
end
View Code

 

正則過濾禁用詞

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace BookShop.BLL
{
    public class Articel_WordsManager
    {
        DAL.Articel_WordsService dal = new DAL.Articel_WordsService();
        public bool Insert(Model.Articel_Words model)
        {
            return dal.Insert(model)>0;
        }
        /// <summary>
        /// 判斷用戶的評論中是否有禁用詞
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool CheckForbid(string msg)
        {
            List<string> list = dal.GetForbidWord();//獲取全部的禁用詞 放入緩存中。
            string regex = string.Join("|",list.ToArray());//aa|bb|cc|
            return Regex.IsMatch(msg, regex);
            //foreach (string word in list)
            //{
            //    msg.Contains(word);
            //    break;
            //}

        }
        /// <summary>
        /// 審查詞過濾
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool CheckMod(string msg)
        {

            List<string> list = dal.GetModWord();//獲取全部的審查詞,放入緩存中。
            string regex = string.Join("|", list.ToArray());//aa|bb|cc|
            regex = regex.Replace(@"\", @"\\").Replace("{2}",@".{0,2}");
            return Regex.IsMatch(msg, regex);
        }
        /// <summary>
        /// 替換詞過濾
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public string CheckReplace(string msg)
        {
            List<Model.Articel_Words> list = dal.GetReplaceWord();//放入緩存中。
            foreach (Model.Articel_Words model in list)
            {
                msg = msg.Replace(model.WordPattern, model.ReplaceWord);
            }
            return msg;
        }
    }
}
View Code

 

生成靜態頁面

/// <summary>
        /// 將商品的信息生成靜態頁面
        /// </summary>
        public void CreateHtmlPage(int id)
        {
            Model.Book model=dal.GetModel(id);
            //獲取模板文件
            string template = HttpContext.Current.Request.MapPath("/Template/BookTemplate.html");
            string fileContent = File.ReadAllText(template);
            fileContent = fileContent.Replace("$title", model.Title).Replace("$author", model.Author).Replace("$unitprice",model.UnitPrice.ToString("0.00")).Replace("$isbn",model.ISBN).Replace("$content",model.ContentDescription).Replace("$bookId",model.Id.ToString());
            string dir = "/HtmlPage/" + model.PublishDate.Year + "/" + model.PublishDate.Month + "/" + model.PublishDate.Day + "/";
            Directory.CreateDirectory(Path.GetDirectoryName(HttpContext.Current.Request.MapPath(dir)));
            string fullDir = dir + model.Id + ".html";
            File.WriteAllText(HttpContext.Current.Request.MapPath(fullDir), fileContent, System.Text.Encoding.UTF8);

        }
View Code

 

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>

    <title>$title</title>
    <meta content="北京市新華書店王府井書店,致力於提供專業化購書服務.網上購書選擇新華書店王府井書店(網上書店),購書放心有保障.王府井書店電話:010-65132842.010-65252592" name="description"/>
<meta content="王府井書店 新華書店 網上書店 網上購書 北京圖書大廈" name="keywords"/>

    <link href="/Css/tableStyle.css" rel="stylesheet" /><!--在模板文件中引用外部文件時必定要使用絕對路徑-->
    <link href="/Css/index.css" rel="stylesheet" />
    <script src="/js/jquery-1.7.1.js"></script>
    <script src="/ckeditor/ckeditor.js"></script>
    <style type="text/css">
      
        .itcast_comments{ width:620px;color: #333;font: normal 12px/24px Helvetica, Tahoma, Arial, sans-serif; font-size:14px;}
           .reply_btn{ font-size:14px; background:#cc0000; padding:8px 15px; border:none; color:#fff; cursor: pointer; font:"Microsoft YaHei"; font-weight:bold;}
           .reply_box{border:1px solid #CCC; font-size:14px;}
    </style>
    <script type="text/javascript">
        $(function () {
            $("#btnAdd").click(function () {
                addComment();
            });
            loadComment();//加載評論
            loadUBBCode();//加載UBB編輯器
        });
        //加載UBB編輯器
        function loadUBBCode() {
            CKEDITOR.replace('txtContent',
    {
        extraPlugins: 'bbcode',
        removePlugins: 'bidi,button,dialogadvtab,div,filebrowser,flash,format,forms,horizontalrule,iframe,indent,justify,liststyle,pagebreak,showborders,stylescombo,table,tabletools,templates',
        toolbar:
        [
            ['Source', '-', 'Save', 'NewPage', '-', 'Undo', 'Redo'],
            ['Find', 'Replace', '-', 'SelectAll', 'RemoveFormat'],
            ['Link', 'Unlink', 'Image'],
            '/',
            ['FontSize', 'Bold', 'Italic', 'Underline'],
            ['NumberedList', 'BulletedList', '-', 'Blockquote'],
            ['TextColor', '-', 'Smiley', 'SpecialChar', '-', 'Maximize']
        ],
        smiley_images:
        [
            'regular_smile.gif', 'sad_smile.gif', 'wink_smile.gif', 'teeth_smile.gif', 'tounge_smile.gif',
            'embaressed_smile.gif', 'omg_smile.gif', 'whatchutalkingabout_smile.gif', 'angel_smile.gif', 'shades_smile.gif',
            'cry_smile.gif', 'kiss.gif'
        ],
        smiley_descriptions:
        [
            'smiley', 'sad', 'wink', 'laugh', 'cheeky', 'blush', 'surprise',
            'indecision', 'angel', 'cool', 'crying', 'kiss'
        ]
    });
        }

       //加載評論
        function loadComment() {
            $.post("/ashx/BookComment.ashx", { "action": "load", "bookId": $bookId }, function (data) {
                var serverData = $.parseJSON(data);
                var serverDataLength = serverData.length;
                for (var i = 0; i < serverDataLength; i++) {
                    $("<li>" + serverData[i].CreateDateTime + ":" + serverData[i].Msg + "</li>").appendTo("#commentList");
                }
            });
        }
        //添加評論
        function addComment() {
            //var msg = $("#txtContent").val();
            var oEditor = CKEDITOR.instances.txtContent;//找到UBB編輯器
            var msg = oEditor.getData();//獲取編輯器內容
            if (msg != "") {
                $.post("/ashx/BookComment.ashx", { "action": "add", "msg": msg, "bookId": $bookId }, function (data) {
                    var serverData = data.split(':');
                    if (serverData[0] == "ok") {
                        // $("#txtContent").val("");
                        oEditor.setData("");
                        $("#txtContent").focus();
                        loadComment();
                        $("#txtMsg").text(serverData[1]);
                    } else {
                        $("#txtMsg").text(serverData[1]);
                    }

                });
            } else {
                $("#txtMsg").text("評論內容不能爲空!!");
                $("#txtContent").focus();
            }
        }
    </script>
</head>
<body>
    <center>
    <div class="top">
    <div class="m_c" style="width: 736px; height: 27px">
    <span class="l">
      <a href="http://www.beifabook.com" target="_blank">北發圖書網主網站</a> |&nbsp;
      <a href="http://www.bjbb.com" target="_blank">北京圖書大廈</a>&nbsp; |
      <a href="../default.aspx" target="_blank"><font color="#00A0E9">王府井書店</font></a>&nbsp;|
      <a href="http://www.zgcbb.com/" target="_blank">中關村圖書大廈</a>&nbsp; |
      <a href="http://www.yycbook.com/" target="_blank">亞運村圖書大廈</a>&nbsp; |
      <a href="http://www.hs-book.com" target="_blank">花市書店</a>&nbsp; |
      <a href="/OrderInfo.aspx" >個人訂單</a></span></div></div>


    <div style="WIDTH: 750px; text-align: left;"><img src="/images/集團網站1.jpg" width="780" height="93" /><br />
&nbsp;&nbsp;&nbsp;&nbsp;         </div>
        </center>

    <table>
        <tr><td>書名</td><td>$title</td></tr>
         <tr><td>做者</td><td>$author</td></tr>
         <tr><td>單價</td><td>$unitprice</td></tr>
         <tr><td>封面</td><td><img src="/Images/BookCovers/$isbn.jpg" /></td></tr>
        <tr><td>簡介</td><td>$content</td></tr>
    </table>
    <hr />
    <ul id="commentList" class="itcast_comments">

    </ul>
    <textarea id="txtContent" rows="20" cols="100" class="reply_box" placeholder="有什麼感想?來講說!!"></textarea><br />
    <input type="button" value="發佈評論" id="btnAdd" class="reply_btn" /><span id="txtMsg" style="font-size:14px;color:red"></span>
    <div id="footer">
  <table border="0" width="100%" class="categories1">
    <tr>
      <td align="center"> 
        <ul>
            <li><a href='#'>關於咱們王府井書店</li>
          <li><a href="#">書店營業時間:9:30-21:00 </a> </li>
          <li> <a href="#"; target=_blank; ><img src="/images/logo123x40.jpg" width="123" height="40" border="0"></a> <a href="#"; target=_blank; ><img border="0" src="/Images/kaixin.jpg"></a> </li>
          <li>&nbsp;<span lang="zh-cn"><a title="京ICP備08001692號" href="http://www.miibeian.gov.cn">京ICP備08987373號</a></span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </li>
        </ul></td>
    </tr>
  </table>
</div>


</body>
</html>
View Code

發送郵件 找回密碼

/// <summary>
      /// 找回用戶的密碼
      /// </summary>
      /// <param name="userInfo"></param>
        public void FindUserPwd(Model.User userInfo)
        {
            BLL.SettingsManager bll = new SettingsManager();
            //系統產生一個新的密碼,而後更新數據庫,再將新的密碼發送到用戶的郵箱中。
            string newPwd = Guid.NewGuid().ToString().Substring(0,8);
            userInfo.LoginPwd = newPwd;//必定要將系統產生的新密碼加密之後更新到數據庫中,可是發送到用戶郵箱中的密碼必須是明文的。
            dal.Update(userInfo);
            MailMessage mailMsg = new MailMessage();//兩個類,別混了,要引入System.Net這個Assembly
            mailMsg.From = new MailAddress(bll.GetValue("系統郵件地址"));//源郵件地址 
            mailMsg.To.Add(new MailAddress(userInfo.Mail));//目的郵件地址。能夠有多個收件人
            mailMsg.Subject = "在商城網站中的新的帳戶";//發送郵件的標題 
            StringBuilder sb = new StringBuilder();
            sb.Append("用戶名是:"+userInfo.LoginId);
            sb.Append("新密碼是:"+newPwd);
            mailMsg.Body =sb.ToString();//發送郵件的內容 
            //mailMsg.IsBodyHtml = true;
            SmtpClient client = new SmtpClient(bll.GetValue("系統郵件SMTP"));//smtp.163.com,smtp.qq.com
            client.Credentials = new NetworkCredential(bll.GetValue("系統郵件用戶名"), bll.GetValue("系統郵件密碼"));
            client.Send(mailMsg);//注意:發送大量郵件時阻塞,因此能夠將要發送的郵件先發送到隊列中。



        }
View Code

.Net自帶緩存helper

using System;
using System.Web;
using System.Collections;

public class CookiesHelper
{
    /**//// <summary>
    /// 獲取數據緩存
    /// </summary>
    /// <param name="CacheKey"></param>
    public static object GetCache(string CacheKey)
    {
        System.Web.Caching.Cache objCache = HttpRuntime.Cache;
        return objCache[CacheKey];
    }

    /**//// <summary>
    /// 設置數據緩存
    /// </summary>
    public static void SetCache(string CacheKey, object objObject)
    {
        System.Web.Caching.Cache objCache = HttpRuntime.Cache;
        objCache.Insert(CacheKey, objObject);
    }

    /**//// <summary>
    /// 設置數據緩存
    /// </summary>
    public static void SetCache(string CacheKey, object objObject, TimeSpan Timeout)
    {
        System.Web.Caching.Cache objCache = HttpRuntime.Cache;
        objCache.Insert(CacheKey, objObject, null, DateTime.MaxValue, Timeout, System.Web.Caching.CacheItemPriority.NotRemovable, null);
    }

    /**//// <summary>
    /// 設置數據緩存
    /// </summary>
    public static void SetCache(string CacheKey, object objObject, DateTime absoluteExpiration, TimeSpan slidingExpiration)
    {
        System.Web.Caching.Cache objCache = HttpRuntime.Cache;
        objCache.Insert(CacheKey, objObject, null, absoluteExpiration, slidingExpiration);
    }

    /**//// <summary>
    /// 移除指定數據緩存
    /// </summary>
    public static void RemoveAllCache(string CacheKey)
    {
        System.Web.Caching.Cache _cache = HttpRuntime.Cache;
        _cache.Remove(CacheKey);
    }

    /**//// <summary>
    /// 移除所有緩存
    /// </summary>
    public static void RemoveAllCache()
    {
        System.Web.Caching.Cache _cache = HttpRuntime.Cache;
        IDictionaryEnumerator CacheEnum = _cache.GetEnumerator();
        while (CacheEnum.MoveNext())
        {
            _cache.Remove(CacheEnum.Key.ToString());
        }
    }
}
View Code

Url重寫 

把帶參數的改寫成不帶參數的,BookDetail.aspx?id=52 -->BookDetai_52.aspx

有利於SEO優化

(不推薦這樣在管道寫,推薦使用IIS插件 url rewrite)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

namespace BookShop.Web
{
    public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {

        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 請求管道中第一個事件觸發之後調用的方法,完成URL重寫。
        /// URL重寫。
       ///帶參數的URL地址進行改寫。改寫成不帶參數的。
        //BookDetail.aspx?id=2;   BookDetail_2.aspx

        //爲何將帶參數的URL地址改爲不帶參數的?URL重寫的目的就是SEO。

        //SEO.

        //怎樣進行URL重寫?

        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            string url = Request.AppRelativeCurrentExecutionFilePath;//~/BookDetail_4976.aspx
            Match match=Regex.Match(url, @"~/BookDetail_(\d+).aspx");
            if (match.Success)
            {
                Context.RewritePath("/BookDetail.aspx?id="+match.Groups[1].Value);
            }

            //Match match = Regex.Match(url, @"~/BookDetail_(\d+).aspx");
            //if (match.Success)
            //{
            //    Context.RewritePath("/BookDetail.aspx?id=" + match.Groups[1].Value);
            //}




        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }
}
View Code

 

SWFUpload 文件上傳

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CutPhoto.aspx.cs" Inherits="BookShop.Web.Member.CutPhoto" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <link href="../Css/themes/ui-lightness/jquery-ui-1.8.2.custom.css" rel="stylesheet" />
       <script src="../js/jquery-1.7.1.js"></script>
    <script src="../js/jquery-ui-1.8.2.custom.min.js"></script>
    <script src="../SWFUpload/swfupload.js"></script>
    <script src="../SWFUpload/handlers.js"></script>
      <script type="text/javascript">
          var swfu;
          window.onload = function () {
              swfu = new SWFUpload({
                  // Backend Settings
                  upload_url: "/ashx/upload.ashx?action=upload",
                  post_params: {
                      "ASPSESSID": "<%=Session.SessionID %>"
                },

                // File Upload Settings
                file_size_limit: "2 MB",
                file_types: "*.jpg;*.gif",
                file_types_description: "JPG Images",
                file_upload_limit: 0,    // Zero means unlimited

                // Event Handler Settings - these functions as defined in Handlers.js
                //  The handlers are not part of SWFUpload but are part of my website and control how
                //  my website reacts to the SWFUpload events.
                swfupload_preload_handler: preLoad,
                swfupload_load_failed_handler: loadFailed,
                file_queue_error_handler: fileQueueError,
                file_dialog_complete_handler: fileDialogComplete,
                upload_progress_handler: uploadProgress,
                upload_error_handler: uploadError,
                upload_success_handler: showImage,
                upload_complete_handler: uploadComplete,

                // Button settings
                button_image_url: "/SWFUpload/images/XPButtonNoText_160x22.png",
                button_placeholder_id: "spanButtonPlaceholder",
                button_width: 160,
                button_height: 22,
                button_text: '<span class="button">請選擇上傳圖片<span class="buttonSmall">(2 MB Max)</span></span>',
                button_text_style: '.button { font-family: Helvetica, Arial, sans-serif; font-size: 14pt; } .buttonSmall { font-size: 10pt; }',
                button_text_top_padding: 1,
                button_text_left_padding: 5,

                // Flash Settings
                flash_url: "/SWFUpload/swfupload.swf",    // Relative to this file
                flash9_url: "/SWFUpload/swfupload_FP9.swf",    // Relative to this file

                custom_settings: {
                    upload_target: "divFileProgressContainer"
                },

                // Debug Settings
                debug: false
            });
        }
        //上傳成功之後調用該方法
        function showImage(file, serverData) {
            // $("#showPhoto").attr("src", serverData);
            var data = serverData.split(':');
            //將上傳成功的圖片做爲DIV的背景
            $("#hiddenImageUrl").val(data[0]);//將上傳成功的圖片路徑存儲到隱藏域中。
            $("#divContent").css("backgroundImage", "url('" + data[0] + "')").css("width",data[1]+"px").css("height",data[2]+"px");
        }

        $(function () {
            //讓DIV能夠移動與拖動大小
            $("#divCut").draggable({ containment: "#divContent", scroll: false }).resizable({
                containment: "#divContent"
            });
            $("#btnCut").click(function () {
                cutPhoto();
            });
        })
          //截取頭像
        function cutPhoto() {
            //計算要截取的頭像的範圍。
            var y = $("#divCut").offset().top - $("#divContent").offset().top;//縱座標
            var x = $("#divCut").offset().left - $("#divContent").offset().left;
            var width = $("#divCut").width();
            var heigth = $("#divCut").height();
            var pars = {
                "x": x,
                "y": y,
                "width": width,
                "height": heigth,
                "action": "cut",
                "imgSrc": $("#hiddenImageUrl").val()
                
            };
            $.post("/ashx/upload.ashx", pars, function (data) {
                $("#showPhoto").attr("src",data);
            });

        }

    </script>
</head>
<body>
    <form id="form1" runat="server">
   <div id="content">
        <div id="swfu_container" style="margin: 0px 10px;">
            <div>
                <span id="spanButtonPlaceholder"></span>
            </div>
            <div id="divFileProgressContainer" style="height: 75px;"></div>
            <div id="thumbnails"></div>
            <div id="divContent" style="width:300px; height:300px;">
                <div id="divCut" style="width:100px;height:100px; border:solid red 1px">
                </div>

            </div>
            <input type="button" value="截取圖片" id="btnCut" />
            <input type="hidden" id="hiddenImageUrl" />
            <img id="showPhoto"></img>
        </div>
        </div>
    </form>
</body>
</html>
View Code

 

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;

namespace BookShop.Web.ashx
{
    /// <summary>
    /// upload 的摘要說明
    /// </summary>
    public class upload : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string action = context.Request["action"];
            if (action == "upload")//上傳圖片
            {
                ProcessFileUpload(context);
            }
            else if (action =="cut")//截取圖片
            {
                ProcessCutPhoto(context);
            }
            else
            {
                context.Response.Write("參數錯誤!!");
            }
        }
        /// <summary>
        /// 文件上傳
        /// </summary>
        /// <param name="context"></param>
        private void ProcessFileUpload(HttpContext context)
        {
            HttpPostedFile file = context.Request.Files["Filedata"];
            if (file != null)
            {
                string fileName = Path.GetFileName(file.FileName);
                string fileExt = Path.GetExtension(fileName);
                if (fileExt == ".jpg")
                {
                    string dir = "/ImageUpload/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + "/";
                    if (!Directory.Exists(context.Request.MapPath(dir)))
                    {
                        Directory.CreateDirectory(context.Request.MapPath(dir));
                    }
                    string newfileName = Guid.NewGuid().ToString();
                    string fullDir = dir + newfileName + fileExt;
                    file.SaveAs(context.Request.MapPath(fullDir));
                    using (Image img = Image.FromFile(context.Request.MapPath(fullDir)))
                    {
                        context.Response.Write(fullDir + ":" + img.Width + ":" + img.Height);
                    }

                    //file.SaveAs(context.Request.MapPath("/ImageUpload/"+fileName));
                    //context.Response.Write("/ImageUpload/" + fileName);
                }
            }
        }

        /// <summary>
        /// 圖片的截取
        /// </summary>
        /// <param name="context"></param>
        private void ProcessCutPhoto(HttpContext context)
        {
            int x = Convert.ToInt32(context.Request["x"]);
            int y = Convert.ToInt32(context.Request["y"]);
            int width = Convert.ToInt32(context.Request["width"]);
            int height = Convert.ToInt32(context.Request["height"]);
            string imgSrc = context.Request["imgSrc"];//獲取上傳成功的圖片的路徑
            using (Bitmap map = new Bitmap(width, height))
            {
                using (Graphics g = Graphics.FromImage(map))
                {
                    using (Image img = Image.FromFile(context.Request.MapPath(imgSrc)))
                    {
                        //第一個參數:表示畫哪張圖片.
                        //二:畫多麼大。
                        //三:畫原圖的哪塊區域
                        g.DrawImage(img, new Rectangle(0, 0, width, height), new Rectangle(x, y, width, height), GraphicsUnit.Pixel);
                        string newfileName = Guid.NewGuid().ToString();
                        string fullDir = "/ImageUpload/" + newfileName + ".jpg";
                        map.Save(context.Request.MapPath(fullDir),System.Drawing.Imaging.ImageFormat.Jpeg);
                        context.Response.Write(fullDir);

                    }
                   
                }
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
View Code

 

一邊處理程序調用session

通常處理程序調用session 必須實現接口 IReadOnlySessionState

 

spring.net

1 ioc  控制反轉  之前本身new 這個是交給容器new

2 di  依賴注入  在建立類實例的時候  能夠給一些屬性完成初始化複製  (spring.net  配置文件中ref和value 等同,只是他是指的對象)

3 aop 面向切面編程 權限校驗 日誌處理

Unity  微軟推出的實現 ioc di

 

Memcache

 socket通訊,網站服務器上安裝客戶端端,其餘的緩存服務器 稱爲服務端,經過它的算法,取其中一個存取

沒有主從  存取都是在memcache客戶端

 惰性刪除:它並無提供監控數據過時的機制,而是惰性的,當查詢到某個key數據時,若是過時那麼直接拋棄,若是存滿了,把一些不常常訪問的刪除掉

http://www.cnblogs.com/caokai520/p/4390646.html

實例代碼 建議修改一下 把下面的兩個結合一下

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Memcached.ClientLibrary;


namespace Hep.Memcached.Uitils
{
    public class MemberHelper
    {
        static SockIOPool _pool;

        #region 建立Memcache服務
        /// <summary>
        /// 建立Memcache服務
        /// </summary>
        /// <param name="serverlist">IP端口列表</param>
        /// <param name="poolName">Socket鏈接池名稱</param>
        /// <returns>Memcache客戶端代理類</returns>
        private static MemcachedClient CreateServer(ArrayList serverlist, string poolName)
        {
            if (_pool != null)
            {
            }
            else
            {
                ////初始化memcache服務器池
                _pool = SockIOPool.GetInstance(poolName);
                //設置Memcache池鏈接點服務器端。
                _pool.SetServers(serverlist);

                ////其餘參數根據須要進行配置 

                //各服務器之間負載均衡的設置
                _pool.SetWeights(new int[] { 1 });
                //socket pool設置
                _pool.InitConnections = 5; //初始化時建立的鏈接數
                _pool.MinConnections = 5; //最小鏈接數
                _pool.MaxConnections = 250; //最大鏈接數
                //鏈接的最大空閒時間,下面設置爲6個小時(單位ms),超過這個設置時間,鏈接會被釋放掉
                _pool.MaxIdle = 1000 * 60 * 60 * 6;
                //通信的超時時間,下面設置爲3秒(單位ms),.NET版本沒有實現
                _pool.SocketTimeout = 1000 * 3;
                //socket鏈接的超時時間,下面設置表示鏈接不超時,即一直保持鏈接狀態
                _pool.SocketConnectTimeout = 0;
                _pool.Nagle = false; //是否對TCP/IP通信使用Nalgle算法,.NET版本沒有實現
                //維護線程的間隔激活時間,下面設置爲60秒(單位s),設置爲0表示不啓用維護線程
                _pool.MaintenanceSleep = 60;
                //socket單次任務的最大時間,超過這個時間socket會被強行中斷掉(當前任務失敗)
                _pool.MaxBusy = 1000 * 10;
                _pool.Initialize();

            }
            //建立了一個Memcache客戶端的代理類。
            MemcachedClient mc = new MemcachedClient();
            mc.PoolName = poolName;
            mc.EnableCompression = false;//是否壓縮 

            return mc;
        }
        #endregion

        #region 緩存是否存在
        /// <summary>
        /// 緩存是否存在
        /// </summary>
        /// <param name="serverlist">IP端口列表</param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static bool CacheIsExists(ArrayList serverlist, string poolName, string key)
        {
            MemcachedClient mc = CreateServer(serverlist, poolName);

            if (mc.KeyExists(key))
            {
                return true;
            }
            else
            {
                return false;
            }

        }
        #endregion

        #region 添加緩存

        #region 添加緩存(鍵不存在則添加,鍵存在則不能添加)
        /// <summary>
        /// 添加緩存(鍵不存在則添加,鍵存在則不能添加)
        /// </summary>
        /// <param name="serverlist">IP端口列表</param>
        /// <param name="poolName">鏈接池名稱</param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="minutes">過時分鐘數</param>
        /// <returns></returns>
        public static bool AddCache(ArrayList serverlist, string poolName, string key, string value, int minutes)
        {
            MemcachedClient mc = CreateServer(serverlist, poolName);
            return mc.Add(key, value, DateTime.Now.AddMinutes(minutes));
        }
        #endregion

        #region 添加緩存(鍵不存在則添加,鍵存在則不能添加)
        /// <summary>
        /// 添加緩存(鍵不存在則添加,鍵存在則不能添加)
        /// </summary>
        /// <param name="serverlist">IP端口列表</param>
        /// <param name="poolName">鏈接池名稱</param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="minutes">過時分鐘數</param>
        /// <returns></returns>
        public static bool AddCache(ArrayList serverlist, string poolName, string key, object value, int minutes)
        {
            MemcachedClient mc = CreateServer(serverlist, poolName);
            return mc.Add(key, value, DateTime.Now.AddMinutes(minutes));
        }
        #endregion

        #region 添加緩存(鍵不存在則添加,鍵存在則覆蓋)
        /// <summary>
        /// 添加緩存(鍵不存在則添加,鍵存在則覆蓋)
        /// </summary>
        /// <param name="serverlist">IP端口列表</param>
        /// <param name="poolName">鏈接池名稱</param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="minutes">過時分鐘數</param>
        /// <returns></returns>
        public static bool SetCache(ArrayList serverlist, string poolName, string key, string value, int minutes)
        {
            MemcachedClient mc = CreateServer(serverlist, poolName);
            return mc.Set(key, value, DateTime.Now.AddMinutes(minutes));
        }
        #endregion

        #region 添加緩存(鍵不存在則添加,鍵存在則覆蓋)
        /// <summary>
        /// 添加緩存(鍵不存在則添加,鍵存在則覆蓋) object 類型
        /// </summary>
        /// <param name="serverlist">IP端口列表</param>
        /// <param name="poolName">鏈接池名稱</param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="minutes">過時分鐘數</param>
        /// <returns></returns>
        public static bool SetCache(ArrayList serverlist, string poolName, string key, object value, int minutes)
        {
            MemcachedClient mc = CreateServer(serverlist, poolName);
            return mc.Set(key, value, DateTime.Now.AddMinutes(minutes));
        }
        #endregion

        #endregion

        #region 替換緩存

        #region 替換緩存(鍵存在的才能替換,不存在則不替換)
        /// <summary>
        /// 替換緩存(鍵存在的才能替換,不存在則不替換)
        /// </summary>
        /// <param name="serverlist">IP端口列表</param>
        /// <param name="poolName">鏈接池名稱</param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="minutes">過時分鐘數</param>
        /// <returns></returns>
        public static bool ReplaceCache(ArrayList serverlist, string poolName, string key, string value, int minutes)
        {
            MemcachedClient mc = CreateServer(serverlist, poolName);
            return mc.Replace(key, value, DateTime.Now.AddMinutes(minutes));
        }
        #endregion

        #endregion

        #region 獲取緩存

        #region 獲取單個鍵對應的緩存
        /// <summary>
        /// 獲取單個鍵對應的緩存
        /// </summary>
        /// <param name="serverlist">IP端口列表</param>
        /// <param name="poolName">鏈接池名稱</param>
        /// <param name="key"></param> 
        /// <returns></returns>
        public static object GetCache(ArrayList serverlist, string poolName, string key)
        {
            MemcachedClient mc = CreateServer(serverlist, poolName);
            if (mc.KeyExists(key))
            {
                return mc.Get(key);
            }
            else
            {
                return "";
            }
        }
        #endregion

        #region 獲取鍵數組對應的值
        /// <summary>
        /// 獲取鍵數組對應的值
        /// </summary>
        /// <param name="serverlist">IP端口列表</param>
        /// <param name="poolName">鏈接池名稱</param>
        /// <param name="keys">鍵列表</param>
        /// <returns>Hashtable鍵值對</returns>
        public static Hashtable GetCacheHt(ArrayList serverlist, string poolName, string[] keys)
        {
            MemcachedClient mc = CreateServer(serverlist, poolName);
            return mc.GetMultiple(keys);
        }
        #endregion

        #region 獲取鍵數組對應的值
        /// <summary>
        /// 獲取鍵數組對應的值
        /// </summary>
        /// <param name="serverlist">IP端口列表</param>
        /// <param name="poolName">鏈接池名稱</param>
        /// <param name="keys">鍵列表</param>
        /// <returns>值的數組(不包含鍵)</returns>
        public static object[] GetCacheList(ArrayList serverlist, string poolName, string[] keys)
        {
            MemcachedClient mc = CreateServer(serverlist, poolName);
            object[] list = mc.GetMultipleArray(keys);
            ArrayList returnList = new ArrayList();
            for (int i = 0; i < list.Length; i++)
            {
                if (list[i] != null)
                {
                    returnList.Add(list[i]);
                }
            }
            return returnList.ToArray();
        }
        #endregion

        #endregion

        #region 刪除緩存
        /// <summary>
        /// 刪除緩存
        /// </summary>
        /// <param name="serverlist">IP端口列表</param>
        /// <param name="poolName">鏈接池名稱</param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static bool DelCache(ArrayList serverlist, string poolName, string key)
        {
            MemcachedClient mc = CreateServer(serverlist, poolName);
            return mc.Delete(key);
        }
        #endregion

        #region 清空全部緩存
        /// <summary>
        /// 清空全部緩存
        /// </summary>
        /// <param name="serverlist">IP端口列表</param>
        /// <param name="poolName">鏈接池名稱</param>
        /// <returns></returns>
        public static bool FlushAll(ArrayList serverlist, string poolName)
        {
            MemcachedClient mc = CreateServer(serverlist, poolName);
            return mc.FlushAll();
        }
        #endregion

    }
}
View Code

 

{
        private static readonly ILog Logger = LogManager.GetCurrentClassLogger();

        private readonly MemcachedClient _cache;

        public MemcachedCachePolicy()
        {
            _cache = MemcachedClient.GetInstance("MemcachedConfig");
            
            _cache.MaxPoolSize = 10000;
        }

        public void Add<T>(string key, T value)
        {
            if (_cache.Set(key, value))
            {
                Logger.Debug("Set _cache for key successed, key[" + key + "]");
            }
            else
            {
                Logger.Debug("Set _cache for key failed");
            }
        }

        public void Add<T>(string key, T value, DateTime dt)
        {
            _cache.Set(key, value, dt);
        }

        public T Get<T>(string key)
        {
            try
            {
                return (T)_cache.Get(key);
            }
            catch (Exception e)
            {
                Logger.Debug("Get _cache for key failed, key[" + key + "]", e);
                _cache.Delete(key);
                return default(T);
            }
        }

        public void Add(string key, object value)
        {
            _cache.Set(key, value);
        }

        public void Add(string key, object value, DateTime dt)
        {
            _cache.Set(key, value, dt);
        }

        public object Get(string key)
        {
            return _cache.Get(key);
        }

        public void Delete(string key)
        {
            _cache.Delete(key);
        }
    }
View Code

 

using Memcached.ClientLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CZBK.ItcastOA.Common
{
   public class MemcacheHelper
    {
       private static readonly MemcachedClient mc = null;

       static MemcacheHelper()
       {
           //最好放在配置文件中
           string[] serverlist = { "127.0.0.1:11211", "10.0.0.132:11211" };

           //初始化池
           SockIOPool pool = SockIOPool.GetInstance();
           pool.SetServers(serverlist);

           pool.InitConnections = 3;
           pool.MinConnections = 3;
           pool.MaxConnections = 5;

           pool.SocketConnectTimeout = 1000;
           pool.SocketTimeout = 3000;

           pool.MaintenanceSleep = 30;
           pool.Failover = true;

           pool.Nagle = false;
           pool.Initialize();

           // 得到客戶端實例
            mc = new MemcachedClient();
           mc.EnableCompression = false;
       }
       /// <summary>
       /// 存儲數據
       /// </summary>
       /// <param name="key"></param>
       /// <param name="value"></param>
       /// <returns></returns>
       public static bool Set(string key,object value)
       {
          return mc.Set(key, value);
       }
       public static bool Set(string key, object value,DateTime time)
       {
           return mc.Set(key, value,time);
       }
       /// <summary>
       /// 獲取數據
       /// </summary>
       /// <param name="key"></param>
       /// <returns></returns>
       public static object Get(string key)
       {
           return mc.Get(key);
       }
       /// <summary>
       /// 刪除
       /// </summary>
       /// <param name="key"></param>
       /// <returns></returns>
       public static bool Delete(string key)
       {
           if (mc.KeyExists(key))
           {
               return mc.Delete(key);

           }
           return false;

       }
    }
}
View Code

 

 多線程處理 lucene.net  單例模式

using CZBK.ItcastOA.Model.EnumType;
using Lucene.Net.Analysis.PanGu;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;

namespace CZBK.ItcastOA.WebApp.Models
{
    public sealed class IndexManager
    {
        //不用寫跟新方法了,由於添加的時候,是先刪除而後添加
        //單列模式 sealed 不容許被繼承
        // 只容許在本身的類中 建立私有的構造函數
        //readonly 不容許改 只讀的
        
        private static readonly IndexManager indexManager = new IndexManager();
        private IndexManager()
        {
        //建立私有的構造函數 保證不被外部new
        }
        public static IndexManager GetInstance()
        {
            return indexManager;
        }
        public Queue<ViewModelContent> queue = new Queue<ViewModelContent>();
        /// <summary>
        /// 向隊列中添加數據
        /// </summary>
        /// <param name="id"></param>
        /// <param name="title"></param>
        /// <param name="content"></param>
        public void AddQueue(int id, string title, string content)
        {
            ViewModelContent viewModel = new ViewModelContent();
            viewModel.Id = id;
            viewModel.Title = title;
            viewModel.Content = content;
            viewModel.LuceneTypeEnum = LuceneTypeEnum.Add; 
            queue.Enqueue(viewModel);
        }
        /// <summary>
        /// 要刪除的數據
        /// </summary>
        /// <param name="id"></param>
        public void DeleteQueue(int id)
        {
            ViewModelContent viewModel = new ViewModelContent();
            viewModel.Id = id;
            viewModel.LuceneTypeEnum = LuceneTypeEnum.Delete;
            queue.Enqueue(viewModel);
        }
      

        /// <summary>
        /// 開始一個線程
        /// </summary>
        public void StartThread()
        {
            Thread thread = new Thread(WriteIndexContent);
            thread.IsBackground = true;
            thread.Start();
        }
        /// <summary>
        /// 檢查隊列中是否有數據,若是有數據獲取。
        /// </summary>
        private void WriteIndexContent()
        {
            while (true)
            {
                if (queue.Count > 0)
                {
                    CreateIndexContent();
                }
                else
                {
                    Thread.Sleep(3000);
                }
            }
        }
        private void CreateIndexContent()
        {
            string indexPath = @"C:\lucenedir";//注意和磁盤上文件夾的大小寫一致,不然會報錯。將建立的分詞內容放在該目錄下。//將路徑寫到配置文件中。
            FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NativeFSLockFactory());//指定索引文件(打開索引目錄) FS指的是就是FileSystem
            bool isUpdate = IndexReader.IndexExists(directory);//IndexReader:對索引進行讀取的類。該語句的做用:判斷索引庫文件夾是否存在以及索引特徵文件是否存在。
            if (isUpdate)
            {
                //同時只能有一段代碼對索引庫進行寫操做。當使用IndexWriter打開directory時會自動對索引庫文件上鎖。
                //若是索引目錄被鎖定(好比索引過程當中程序異常退出),則首先解鎖(提示一下:若是我如今正在寫着已經加鎖了,可是尚未寫完,這時候又來一個請求,那麼不就解鎖了嗎?這個問題後面會解決)
                if (IndexWriter.IsLocked(directory))
                {
                    IndexWriter.Unlock(directory);
                }
            }
            IndexWriter writer = new IndexWriter(directory, new PanGuAnalyzer(), !isUpdate, Lucene.Net.Index.IndexWriter.MaxFieldLength.UNLIMITED);//向索引庫中寫索引。這時在這裏加鎖。
           //若是隊列中有數據,獲取隊列中的數據寫到Lucene.Net中。
            while(queue.Count>0)
            {
                ViewModelContent viewModel=queue.Dequeue();
                writer.DeleteDocuments(new Term("Id",viewModel.Id.ToString()));//刪除
                if (viewModel.LuceneTypeEnum == LuceneTypeEnum.Delete)
                {
                    continue;
                }
                Document document = new Document();//表示一篇文檔。
                //Field.Store.YES:表示是否存儲原值。只有當Field.Store.YES在後面才能用doc.Get("number")取出值來.Field.Index. NOT_ANALYZED:不進行分詞保存
                document.Add(new Field("Id", viewModel.Id.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));

                //Field.Index. ANALYZED:進行分詞保存:也就是要進行全文的字段要設置分詞 保存(由於要進行模糊查詢)

                //Lucene.Net.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS:不只保存分詞還保存分詞的距離。
                document.Add(new Field("Title", viewModel.Title, Field.Store.YES, Field.Index.ANALYZED, Lucene.Net.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS));
                document.Add(new Field("Content", viewModel.Content, Field.Store.YES, Field.Index.ANALYZED, Lucene.Net.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS));
                writer.AddDocument(document);

            }
            writer.Close();//會自動解鎖。
            directory.Close();//不要忘了C
        }

    }
}
View Code

調用上面的單列

using CZBK.ItcastOA.WebApp.Models;
using log4net;
using Spring.Web.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace CZBK.ItcastOA.WebApp
{
    // 注意: 有關啓用 IIS6 或 IIS7 經典模式的說明,
    // 請訪問 http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : SpringMvcApplication //System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            log4net.Config.XmlConfigurator.Configure();//讀取了配置文件中關於Log4Net配置信息.
            IndexManager.GetInstance().StartThread();//開始線程掃描LuceneNet對應的數據隊列。 這裏就不能new了 由於你是單列模式  因此直接掉他的方法建立實例,他只容許本身的內部建立

            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            //開啓一個線程,掃描異常信息隊列。
            string filePath = Server.MapPath("/Log/");
            ThreadPool.QueueUserWorkItem((a) => {
                while (true)
                {
                    //判斷一下隊列中是否有數據
                    if (MyExceptionAttribute.ExecptionQueue.Count() > 0)
                    {
                        Exception ex=MyExceptionAttribute.ExecptionQueue.Dequeue();
                        if (ex != null)
                        {
                            //將異常信息寫到日誌文件中。
                            //string fileName = DateTime.Now.ToString("yyyy-MM-dd");
                            //File.AppendAllText(filePath+fileName+".txt",ex.ToString(),System.Text.Encoding.UTF8);
                            ILog logger = LogManager.GetLogger("errorMsg");
                            logger.Error(ex.ToString());
                        }
                        else
                        {
                            //若是隊列中沒有數據,休息
                            Thread.Sleep(3000);
                        }
                    }
                    else
                    {
                        //若是隊列中沒有數據,休息
                        Thread.Sleep(3000);
                    }
                }
            
            
            },filePath);

        }
       //異常處理的過濾器。
    }
}
View Code

測試上面的隊列

using CZBK.ItcastOA.WebApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CZBK.ItcastOA.WebApp.Controllers
{
    public class TestController : Controller
    {
        //
        // GET: /Test/

        public ActionResult Index()
        {
            return View();
        }
        public ActionResult ShowResult()
        {
            int a = 2;
            int b = 0;
            int c = a / b;
            return Content(c.ToString());
        }
        public ActionResult TestCreate()
        {
            Model.Books model = new Model.Books();
            model.AurhorDescription = "jlkfdjf";
            model.Author = "asfasd";
            model.CategoryId = 1;
            model.Clicks = 1;
            model.ContentDescription = "Ajax高級編程";
            model.EditorComment = "adfsadfsadf";
            model.ISBN = "111111111111111111";
            model.PublishDate = DateTime.Now;
            model.PublisherId = 72;
            model.Title = "Ajax";
            model.TOC = "aaaaaaaaaaaaaaaa";
            model.UnitPrice = 22.3m;
            model.WordsCount = 1234;
            //1.將數據先存儲到數據庫中。獲取剛插入的數據的主鍵ID值。
            IndexManager.GetInstance().AddQueue(9999, model.Title, model.ContentDescription);//向隊列中添加
            return Content("ok");
        }

    }
}
View Code

lucene.net 返回的時候 爲何只返回文檔的編號  而不是吧整個文檔返回?

節省內存,若是把符合結果的文檔所有返回,那樣佔的內存就大了

拿到文檔ID以後  在根據文檔ID   單條搜索文檔內容

此處我感受  lucene是能夠存文檔內容的   看具體需求吧

 

區分同一from表單不一樣按鈕提交

 當一個form表單 有兩個提交按鈕的時候怎麼區別?  好比 「搜索」、「建立索引庫」

根據 submit的值,點哪一個提交哪一個的值,另外一個值是空

if(!string.IsNullOrEmpty(Request["btnSearth"])){}

Quartz.net

using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CZBK.ItcastOA.QuartzNet
{
    class Program
    {
        static void Main(string[] args)
        {
            IScheduler sched;
            ISchedulerFactory sf = new StdSchedulerFactory();
            sched = sf.GetScheduler();
            //IndexJob爲實現了IJob接口的類,執行的事情寫在Execute方法內
            //job1:工做名字 隨便寫   group1:分組的組名  隨便寫
            JobDetail job = new JobDetail("job1", "group1", typeof(IndexJob));
            
            //5秒後開始第一次運行
            DateTime ts = TriggerUtils.GetNextGivenSecondDate(null, 5);
            
            //每隔5s執行一次/TimeSpan.FromHours(1);//一小時
            TimeSpan interval = TimeSpan.FromSeconds(5);
            
            //每若干小時運行一次,小時間隔由appsettings中的IndexIntervalHour參數指定
            //trigger1:觸發器名字 隨便寫
            Trigger trigger = new SimpleTrigger("trigger1", "group1", "job1", "group1", ts, null,SimpleTrigger.RepeatIndefinitely, interval);

            sched.AddJob(job, true);
            sched.ScheduleJob(trigger);
            sched.Start();
            Console.ReadKey();
        }
    }
}
View Code

 

using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CZBK.ItcastOA.QuartzNet
{
    /// <summary>
    /// 完成工做任務的定義。
    /// </summary>
   public class IndexJob:IJob
    {
       /// <summary>
       /// 將明細表中的數據插入到彙總表中。
       /// </summary>
       /// <param name="context"></param>
       IBLL.IKeyWordsRankService bll = new BLL.KeyWordsRankService();
       public void Execute(JobExecutionContext context)
        {
            //執行的工做
            bll.DeleteAllKeyWordsRank();
            bll.InsertKeyWordsRank();
        }
    }
}
View Code

 

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CZBK.ItcastOA.BLL
{
   public partial class KeyWordsRankService:BaseService<Model.KeyWordsRank>,IBLL.IKeyWordsRankService
    {
       /// <summary>
       /// 將統計的明細表的數據插入。
       /// </summary>
       /// <returns></returns>
        public bool InsertKeyWordsRank()
        {
            string sql = "insert into KeyWordsRank(Id,KeyWords,SearchCount) select newid(),KeyWords,count(*)  from SearchDetails where DateDiff(day,SearchDetails.SearchDateTime,getdate())<=7 group by SearchDetails.KeyWords";
            return this.CurrentDBSession.ExecuteSql(sql)>0;
        }
       /// <summary>
       /// 刪除彙總中的數據。
       /// </summary>
       /// <returns></returns>
        public bool DeleteAllKeyWordsRank()
        {
            //用這句刪除表中的數據是很是快的
            string sql = "truncate table KeyWordsRank";
           return this.CurrentDBSession.ExecuteSql(sql)>0;
        }
        public List<string> GetSearchMsg(string term)
        {
           //KeyWords like term%
            string sql = "select KeyWords from KeyWordsRank where KeyWords like @term";
           return this.CurrentDBSession.ExecuteQuery<string>(sql, new SqlParameter("@term",term+"%" ));
        }
    }
}
View Code

 

session原理

memcache  分佈式session原理  建立緩存的惟一key  GUID  而後以cookie的形式存客戶瀏覽器內存上,這就是原生session的原理 

 

隊列:

dot.net 自帶了隊列  隊列和棧相反,隊列是先進 先出

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;

namespace CZBK.ItcastOA.WebApp.Models
{
    public class MyExceptionAttribute : HandleErrorAttribute
    {
        //靜態的 保證在一個隊列裏,若是每次都new得話就不是一個隊列了
        public static Queue<Exception> ExecptionQueue = new Queue<Exception>();
        /// <summary>
        /// 能夠捕獲異常數據
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnException(ExceptionContext filterContext)
        {
          
            base.OnException(filterContext);
            Exception ex = filterContext.Exception;
            //寫到隊列
            ExecptionQueue.Enqueue(ex);
            //跳轉到錯誤頁面.
            filterContext.HttpContext.Response.Redirect("/Error.html");
        }
    }
}
View Code

 

熱詞展現  

autocomplete 插件 效果 相似智能提示 當你在搜索框輸入「你」  會提示「你好」「你好嗎」等下拉一系列 你提供的詞

 

WebService

socket通訊

方法上又一個 [webMethod] 特性標籤  證實別的程序能夠調用該方法

soap 基於http協議 相似http協議 有請求頭  請求體

另外一個應用場景 SOA 面向服務編程  做爲項目的服務層

WCF 協議就比較多了  http  tcp  契約:服務 消息 錯誤等四大契約

要引用 serviceModel 在接口上添加特性標籤 [serviceContract](服務契約)   在方法上添加特性標籤[Operationcontract](操做契約)

部署:IIS  控制檯 winfor 等均可以  能夠寄宿到多種程序

爲了使AJAX或JS調用服務,必須標記服務的AspNet兼容模式爲Allowed或Required。其次,操做契約必須標記爲WebGet或WebInvoke,WebGet屬性標記了一個能夠用http get方法調用的操做,而WebInvoke屬性標記了一個能夠用http post方法調用的操做。

http://www.cnblogs.com/cokkiy/archive/2009/10/22/jsCallWCF.html

 

-- 垃圾堆

 

手動解耦 能夠在web.config  配置dll  達到解耦效果

抽象工廠 經過反射

簡單工廠 直接new

 

ztree:本身不用管層級關係,給一組json數組,主要根據pid分層

若是想給數據 能夠建立一個ztree的的model  而後給model複製,而後序列化傳給前臺

 

savechange 設計模式:工做單元模式 :一個業務對多張表的操做,只連一次數據庫,完成條記錄的更新

簡單工廠:返回父類或者接口的多種形態

抽象工廠:經過反射建立

單例:相似靜態類  能夠繼承  擴展  延遲加載.....保證程序只new一次   好比隊列 就能夠放在單列裏面

 

session跨域 也是用內存 cookie實現
webapi 圖片分佈式存儲 nginx monodb QQ登陸 工做流 圖片延遲加載
Echarts NPOI t4 lucene.Net+盤古分詞 fineui log4net json.net
Hbiulder 分佈式session memcache redis Quartz.net soa aop 正則 ztree
隊列 緩存 管道19事件
分佈式session解決:惟一key cookie存到客戶端

富文本  異步  json  序列化  ORM  二維碼

clr (common language ruantian) 公共語言運行時 .net framwork

il .net語言轉換爲機器語言的額中間語言 僞彙編

數據庫三範式
存儲過程 觸發器 設計模式

數據結構 二叉樹 集合 圖形
排序算法 冒泡等

 壓力測試http://www.ikende.com/

相關文章
相關標籤/搜索