1. 程式人生 > 其它 >常見.NET功能程式碼彙總

常見.NET功能程式碼彙總

1,在Web上修改指定檔案位置的Web.config

這裡需要使用 WebConfigurationManager 類,但必須使用WebConfigurationFileMap類來指定檔案位置,看程式碼:

long appId = 123;

 //修改網站的配置檔案
 var configFile = new FileInfo(configFilePath);
 var vdm = new VirtualDirectoryMapping(configFile.DirectoryName, true, configFile.Name);
 var wcfm = new WebConfigurationFileMap();
 wcfm.VirtualDirectories.Add("/", vdm);
 var config = WebConfigurationManager.OpenMappedWebConfiguration(wcfm, "/", siteName);
 AppSettingsSection appSection = (AppSettingsSection)config.GetSection("appSettings");
 appSection.Settings["abc"].Value = "system tag";
 appSection.Settings["appId"].Value = appId.ToString();
 config.Save();

 上面的程式碼參考自 stackoverflow ,但是OpenMappedWebConfiguration 必須指定第3個引數,否則會報錯。不過,siteName 並不要求與IIS的站點名字對應,隨意寫一個也可以。

 2,使用angularJS 繫結站點資訊

首先定義一個 webSiteListApp HTML程式碼片斷:

<div ng-app="webSiteListApp" class="container">
    <div ng-controller="webSiteListController">
        <ul>
            <li ng-repeat="item in siteList">
                站點名:{{item.SiteName}} ------繫結資訊:{{item.DomainPort}}
            </li>
        </ul>
    </div>
</div>

然後定義module和service:

<script type="text/javascript">
    // 參考 http://www.infragistics.com/community/blogs/dhananjay_kumar/archive/2015/05/13/how-to-use-angularjs-in-asp-net-mvc-and-entity-framework-4.aspx

    var webSiteListApp = angular.module("webSiteListApp", []);
    webSiteListApp.controller("webSiteListController", function ($scope, webSiteService) {
        getSiteList();
        function getSiteList() {
            var list = webSiteService.getSiteList()
            .success(function (sites) {
                $scope.siteList = sites;
                console.log($scope.siteList);
            })
            .error(function (error) {
                $scope.status = 'Unable to load customer data: ' + error.message;
                console.log($scope.status);
            });
          
        }
    });
    webSiteListApp.factory("webSiteService", ["$http", function ($http) {
        var webSiteService = {};
        webSiteService.getSiteList = function () {
            return $http.get("/SiteManage/GetServerBindings");
        }
        return webSiteService;
    }]);
</script>

這裡定義了一個叫做 webSiteListApp 的module,然後註冊一個 webSiteListController 的控制器,該控制器在前面的HTMl程式碼中定義,最後建立一個 webSiteService ,它監聽後來MVC來的資料,該資料對應的ASP.NET MVC 方法如下:

        public JsonResult GetServerBindings()
        {
            var siteList = IISControlHelper.IISWorker.GetServerBindings();
            return Json(siteList, JsonRequestBehavior.AllowGet);
        }

3,IIS管理程式

可以建立,刪除網站,新增應用程式池,程式碼如下:

using System;
using System.Collections;
using System.Collections.Generic;
using System.DirectoryServices;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace IISControlHelper
{
    /// <summary>
    /// IIS 操作方法集合
    /// http://blog.csdn.net/ts1030746080/article/details/8741399 錯誤
    /// </summary>
    public class IISWorker
    {
        private static string HostName = "localhost";

        /// <summary>
        /// 獲取本地IIS版本
        /// </summary>
        /// <returns></returns>
        public static string GetIIsVersion()
        {
            try
            {
                DirectoryEntry entry = new DirectoryEntry("IIS://" + HostName + "/W3SVC/INFO");
                string version = entry.Properties["MajorIISVersionNumber"].Value.ToString();
                return version;
            }
            catch (Exception se)
            {
                //說明一點:IIS5.0中沒有(int)entry.Properties["MajorIISVersionNumber"].Value;屬性,將丟擲異常 證明版本為 5.0
                return string.Empty;
            }
        }

        /// <summary>
        /// 建立虛擬目錄網站
        /// </summary>
        /// <param name="webSiteName">網站名稱</param>
        /// <param name="physicalPath">物理路徑</param>
        /// <param name="domainPort">站點+埠,如192.168.1.23:90</param>
        /// <param name="isCreateAppPool">是否建立新的應用程式池</param>
        /// <returns></returns>
        public static int CreateWebSite(string webSiteName, string physicalPath, string domainPort,bool isCreateAppPool)
        {
            DirectoryEntry root = new DirectoryEntry("IIS://" + HostName + "/W3SVC");
            // 為新WEB站點查詢一個未使用的ID
            int siteID = 1;
            foreach (DirectoryEntry e in root.Children)
            {
                if (e.SchemaClassName == "IIsWebServer")
                {
                    int ID = Convert.ToInt32(e.Name);
                    if (ID >= siteID) { siteID = ID + 1; }
                }
            }
            // 建立WEB站點
            DirectoryEntry site = (DirectoryEntry)root.Invoke("Create", "IIsWebServer", siteID);
            site.Invoke("Put", "ServerComment", webSiteName);
            site.Invoke("Put", "KeyType", "IIsWebServer");
            site.Invoke("Put", "ServerBindings", domainPort );
            site.Invoke("Put", "ServerState", 2);
            site.Invoke("Put", "FrontPageWeb", 1);
            site.Invoke("Put", "DefaultDoc", "Default.html");
            // site.Invoke("Put", "SecureBindings", ":443:");
            site.Invoke("Put", "ServerAutoStart", 1);
            site.Invoke("Put", "ServerSize", 1);
            site.Invoke("SetInfo");
            // 建立應用程式虛擬目錄

            DirectoryEntry siteVDir = site.Children.Add("Root", "IISWebVirtualDir");
            siteVDir.Properties["AppIsolated"][0] = 2;
            siteVDir.Properties["Path"][0] = physicalPath;
            siteVDir.Properties["AccessFlags"][0] = 513;
            siteVDir.Properties["FrontPageWeb"][0] = 1;
            siteVDir.Properties["AppRoot"][0] = "LM/W3SVC/" + siteID + "/Root";
            siteVDir.Properties["AppFriendlyName"][0] = "Root";

            if (isCreateAppPool)
            {
                DirectoryEntry apppools = new DirectoryEntry("IIS://" + HostName + "/W3SVC/AppPools");

                DirectoryEntry newpool = apppools.Children.Add(webSiteName, "IIsApplicationPool");
                newpool.Properties["AppPoolIdentityType"][0] = "4"; //4
                newpool.Properties["ManagedPipelineMode"][0] = "0"; //0:整合模式 1:經典模式
                newpool.Properties["ManagedRuntimeVersion"][0] = "v4.0";
                newpool.CommitChanges();
                siteVDir.Properties["AppPoolId"][0] = webSiteName;
            }

            siteVDir.CommitChanges();
            site.CommitChanges();
            return siteID;
        }

        /// <summary>
        /// 得到網站的物理路徑
        /// </summary>
        /// <param name="rootEntry">網站節點</param>
        /// <returns></returns>
        public static string GetWebsitePhysicalPath(DirectoryEntry rootEntry)
        {
            string physicalPath = "";
            foreach (DirectoryEntry childEntry in rootEntry.Children)
            {
                if ((childEntry.SchemaClassName == "IIsWebVirtualDir") && (childEntry.Name.ToLower() == "root"))
                {
                    if (childEntry.Properties["Path"].Value != null)
                    {
                        physicalPath = childEntry.Properties["Path"].Value.ToString();
                    }
                    else
                    {
                        physicalPath = "";
                    }
                }
            }
            return physicalPath;
        }

        /// <summary>
        /// 獲取站點名
        /// </summary>
        public static List<IISInfo> GetServerBindings()
        {
            List<IISInfo> iisList = new List<IISInfo>();
            string entPath = String.Format("IIS://{0}/w3svc", HostName);
            DirectoryEntry ent = new DirectoryEntry(entPath);
        
            foreach (DirectoryEntry child in ent.Children)
            {
                if (child.SchemaClassName.Equals("IIsWebServer", StringComparison.OrdinalIgnoreCase))
                {
                    if (child.Properties["ServerBindings"].Value != null)
                    {
                        object objectArr = child.Properties["ServerBindings"].Value;
                        string serverBindingStr = string.Empty;
                        if (IsArray(objectArr))//如果有多個繫結站點時
                        {
                            object[] objectToArr = (object[])objectArr;
                            serverBindingStr = objectToArr[0].ToString();
                        }
                        else//只有一個繫結站點
                        {
                            serverBindingStr = child.Properties["ServerBindings"].Value.ToString();
                        }
                        IISInfo iisInfo = new IISInfo();
                        iisInfo.DomainPort = serverBindingStr;
                        iisInfo.AppPool = child.Properties["AppPoolId"].Value.ToString();//應用程式池,有可能不準確
                        object objComment=child.Properties["ServerComment"].Value;
                        if (objComment != null)
                        {
                            iisInfo.SiteName = objComment.ToString();
                        }
                        iisList.Add(iisInfo);
                    }
                }
            }
            return iisList;
        }


        public static bool CreateAppPool(string appPoolName, string Username, string Password)
        {
            bool issucess = false;
            try
            {
                //建立一個新程式池
                DirectoryEntry newpool;
                DirectoryEntry apppools = new DirectoryEntry("IIS://" + HostName + "/W3SVC/AppPools");
                newpool = apppools.Children.Add(appPoolName, "IIsApplicationPool");

                //設定屬性 訪問使用者名稱和密碼 一般採取預設方式
                newpool.Properties["WAMUserName"][0] = Username;
                newpool.Properties["WAMUserPass"][0] = Password;
                newpool.Properties["AppPoolIdentityType"][0] = "3";
                newpool.CommitChanges();
                issucess = true;
                return issucess;
            }
            catch // (Exception ex) 
            {
                return false;
            }
        }


        /// <summary>
        /// 建立程式池後關聯相應應用程式及虛擬目錄
        /// </summary>
        public static void SetAppToPool(string appname,string poolName)
        {
            //獲取目錄
            DirectoryEntry getdir = new DirectoryEntry("IIS://localhost/W3SVC");
            foreach (DirectoryEntry getentity in getdir.Children)
            {
                if (getentity.SchemaClassName.Equals("IIsWebServer"))
                {
                    //設定應用程式程式池 先獲得應用程式 在設定應用程式程式池
                    //第一次測試根目錄
                    foreach (DirectoryEntry getchild in getentity.Children)
                    {
                        if (getchild.SchemaClassName.Equals("IIsWebVirtualDir"))
                        {
                            //找到指定的虛擬目錄.
                            foreach (DirectoryEntry getsite in getchild.Children)
                            {
                                if (getsite.Name.Equals(appname))
                                {
                                    //【測試成功通過】
                                    getsite.Properties["AppPoolId"].Value = poolName;
                                    getsite.CommitChanges();
                                }
                            }
                        }
                    }
                }
            }
        }


        /// <summary>
        /// 判斷object物件是否為陣列
        /// </summary>
        public static bool IsArray(object o)
        {
            return o is Array;
        }
    }

    public class IISInfo
    {
        public string SiteName { get; set; }
        public string DomainPort { get; set; }
        public string AppPool { get; set; }

    }
}

然後,寫一個頁面來建立網站:

前端HTML:

 <form action="/SiteManage/CreateWebSite">
        <fieldset>網站名稱(不能重複):————<input type="text" name="siteName" class="myInput" />  </fieldset>
        <fieldset>網站基準目錄(伺服器):———<input type="text" name="physicalPath" class="myInput" /></fieldset>
        <fieldset>繫結域名(不能重複):————<input type="text" name="domain" class="myInput" /></fieldset>
        <fieldset>網站壓縮檔案路徑(伺服器):—<input type="text" name="zipFile" class="myInput" value="@ViewBag.ZipFile" /> 如果伺服器沒有網站壓縮檔案,請先上傳。</fieldset>

        <input type="submit" name="submit1" value="提交" />
    </form>

後端Controller:

 public ActionResult CreateWebSite(string siteName, string physicalPath, string domain, string zipFile)
        {
            bool hasErr = false;
            string message = "";
            string webSiteFolder = "";
            //檢查引數,physicalPath 允許不存在,之後解壓縮檔案的時候將自動建立
            if (string.IsNullOrEmpty(siteName) || 
                string.IsNullOrEmpty(physicalPath) || 
                string.IsNullOrEmpty(domain) || 
                string.IsNullOrEmpty(zipFile))
            {
                hasErr = true;
                message = "引數不能為空!";
            }
            

            //檢查是否已經包含了要繫結的域名,如果是,則不允許建立
            if (!hasErr)
            {
                var list = IISControlHelper.IISWorker.GetServerBindings();
                foreach (var item in list)
                {
                    if (string.Compare(item.DomainPort, domain, StringComparison.OrdinalIgnoreCase) > 0)
                    {
                        hasErr = true;
                        message = domain + " 域名已經繫結過,不能建立繫結此域名的新站點。";
                        break;
                    }
                }
            }
            
            //檢查網站目錄並解壓縮檔案到網站目錄
            if (!hasErr)
            {
                try
                {
                    webSiteFolder = CheckWebSiteFolder(physicalPath, zipFile);
                    if (System.IO.File.Exists(zipFile))
                    {
                        UnZipFile(zipFile, physicalPath);
                    }
                    else
                    {
                        message = zipFile+" 檔案不存在!";
                        hasErr = true;
                    }
                }
                catch (Exception ex1)
                {
                    message = ex1.Message;
                    hasErr = true;
                }
            }
            
            if (!hasErr)
            {
                try
                {
                   
                    //建立網站
                    int siteNumber;
                    siteNumber = IISControlHelper.IISWorker.CreateWebSite(siteName, webSiteFolder, "*:80:" + domain, true);
                    message = siteNumber > 0 ? "成功" : "失敗";
                }
                catch (System.Runtime.InteropServices.COMException exCom)
                {
                    hasErr = true;
                    if (exCom.HResult == -2147024713)
                    {
                        message = "網站名已經存在!";//(應用程式池IIS程序)檔案已經存在,上面的方法預設會建立跟網站同名的應用程式池名稱
                    }
                    else
                    {
                        message = exCom.Message;
                    }
                }
                catch (Exception ex2)
                {
                    hasErr = true;
                    message = ex2.Message;
                }
               
            }

            ViewBag.SiteName = siteName;
            ViewBag.PhysicalPath = webSiteFolder;
            ViewBag.Domain = domain;
            ViewBag.ResultDesc = message;

            return View("CreateResult");
        }

注意這裡會建立一個跟站點名字同名的應用程式池,預設是.NET 4.0,建立後即啟動站點。

相關程式碼下載,點選這裡

4,ASP.NET MVC 上傳檔案

前端HTML:

    <form action="/SiteManage/Upload" method="post" enctype="multipart/form-data">
        上傳網站壓縮檔案:<input type="file" name="file1" value="" style="width:300px;" class="myInput" /> <input type="submit" name="submit2" value="上傳" />
        <span>@ViewBag.Message </span>
    </form>

後端Controller:

public ActionResult Upload()
        {
            string message = "";
            HttpPostedFileBase file = Request.Files["file1"];
            if (System.IO.Path.GetExtension(file.FileName).ToLower() != ".zip")
            {
                message = "只能上傳ZIP格式的壓縮檔案。";
                return RedirectToAction("Index", new { zipFile = "", message });
            }
            else
            {
                string filePath = System.IO.Path.Combine(HttpContext.Server.MapPath("../Uploads"), System.IO.Path.GetFileName(file.FileName));
                file.SaveAs(filePath);
                message = "上傳成功";
                return RedirectToAction("Index", new { zipFile= filePath,message});
            }
        }

注意Request.Files["file1"] 表示獲取前端HTML頁面的檔案雙傳控制元件名字 file1 對應的檔案。

5,.NET解壓縮檔案

.NET 4.5之後,集成了檔案解壓縮功能,下面是使用方法:

 /// <summary>
        /// 解壓縮檔案到指定目錄,將在指定目錄下解壓出一個壓縮檔名字的最終的目錄
        /// </summary>
        /// <param name="ZipPath">ZIP檔案路徑</param>
        /// <param name="ExtractPath">要解壓縮的目錄</param>
        private void UnZipFile(string ZipPath,string ExtractPath)
        {
            //string NewFile = @"c:usersexampleuserNewFile.txt";
            if (System.IO.File.Exists(ZipPath))
            {
                using (ZipArchive Archive = ZipFile.Open(ZipPath, ZipArchiveMode.Update))
                {
                    //Archive.CreateEntryFromFile(NewFile, "NewEntry.txt");
                    //如果目錄下面有檔案,將解壓縮失敗,所以之前先備份目錄
                    Archive.ExtractToDirectory(ExtractPath);
                }
            }

        }

注意這裡支援ZIP格式,不是RAR格式,同時需要使用 using System.IO.Compression;相關的程式集。

6,備份資料夾

如果需要備份資料夾,可以使用Move 方法實現,看程式碼:

  /// <summary>
        /// 檢查站點目錄,如果原來的目錄已經存在,將自動備份,如果該目錄不存在,將自動建立
        /// </summary>
        /// <param name="physicalPath"></param>
        /// <param name="zipFile"></param>
        /// <returns></returns>
        private  string CheckWebSiteFolder(string physicalPath, string zipFile)
        {
            string webSiteFolder = System.IO.Path.Combine(physicalPath, System.IO.Path.GetFileNameWithoutExtension(zipFile));
            if (System.IO.Directory.Exists(webSiteFolder))
            {
                System.IO.Directory.Move(webSiteFolder, webSiteFolder + "_back" + DateTime.Now.ToString("yyyyMMddHHmmss"));
            }
            //此目錄
            return webSiteFolder;

 7,給MVC頁面傳遞資料

可以使用ViewBag 方式,例如下面的方式:

 public ActionResult Index(string zipFile="",string message="")
        {
            string iisVersion = IISControlHelper.IISWorker.GetIIsVersion();
            ViewBag.IISVerion = iisVersion;
            ViewBag.ZipFile = zipFile;
            ViewBag.Message = message;
          
            return View();
        }

ViewBag 是動態型別,在前端頁面直接使用它既可。

也可以通過Action傳遞一個物件給頁面,方法如下:

 public ActionResult Index(string zipFile="",string message="")
 {
      var siteList = IISControlHelper.IISWorker.GetServerBindings();
      return View(siteList);
 }

然後,在 index.cshtml 頁面的頭部,引入這個Model:

@model List<IISControlHelper.IISInfo>
@{
    ViewBag.Title = "ASP.NET線上建立網站Demo";
}

8,SQL語句建立Access資料庫表

可以使用SqlServer的基本建表語句,但是有幾點不同,首先,不能使用User這樣的關鍵詞,然後,在建立自增欄位上與SqlServer不同。

Access需要採用下面的方式:

[User ID] autoincrement PRIMARY KEY

不能使用下面的方式:

[User ID] Integer PRIMARY KEY autoincrement

PRIMARY KEY語句必須放在 autoincrement 之後,否則語法錯。可見,Access功能的確很簡單。

完整的一個建立表語句:

CREATE TABLE [Users](
[User ID]  autoincrement PRIMARY KEY
,[First Name] text
,[Last Name] text
,[Age] Integer

)

PDF.NET SOD Ver5.3.3.0724 釋出,增加了Access Code First 支援,可以生成上面的建表語句。

 9,VS複製專案生成的檔案到另外一個專案執行目錄下

這個問題常見於DLL需要動態載入的情況下,該DLL是在另外一個專案下生成,主體專案執行前需要拷貝到當前執行目錄下。 如果DLL的原始碼經常修改,手工複製比較費事情,採用專案的 生成時間--〉後期生成命令列,輸入下面類似的命令:

XCOPY "$(TargetPath)" "$(ProjectDir)..MainExeProjbin$(ConfigurationName)" /Y /D /R

這個命令會將當前專案生成的DLL複製到 跟當前專案資料夾同級的MainExeProjbin資料夾下面去,$(ConfigurationName) 通常表示 Debug,Release.

10,使用XCopy備份指定日期之後的資料

使用下面的命令:

xcopy C:SourceDoc D:CopyedDoc /i /s /y /EXCLUDE:D:CopyedDocexcludeFile.txt /d:7-1-2010 

這將備份 SourceDoc 目錄下面的 7月1日之後所有的檔案和資料夾,exclued 檔案包含了要排除的檔案,比如: obj bin .jpeg .png .gif

11,使用jQuery為表格動態新增行

在表格中定義一個模板行,將它作為第一行,然後使用jQuery動態新增行:

<table id="TableID" style="width:100%;background: green;">
        <thead>
            <th>測試</th>
            <th>測試</th>
        </thead>
        <tbody id="list_data" class="list-data">
            <tr id="">
                <td><input type="text" value="Test"></td>
                <td><input type="text" value="Test"></td>
            </tr>

        </tbody>
        
</table>

然後使用如下JS程式碼實現:

<script src="http://cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
    <script src="scripts/myplus.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $("#AddRow").click(function(){
            AddRow();
        });
    });
    function AddRow(){
        var row = $("#list_data tr").eq(0).clone();
        row.appendTo("#list_data");
    }
    
</script>

關鍵程式碼在於 tr節點的克隆。

12,搜尋當前目錄的子目錄或者上級目錄下的子目錄中特定的目錄

首先,搜尋當前目錄下的子目錄,如果沒有,逐層搜尋上級目錄下面的所有子目錄,有沒有特定的目錄。為了防止其它子目錄可能跟目標目錄重名,還可以同時指定目標目錄下特定的一級子目錄或者檔案。這也是一個“深度優先搜尋”的例子。下面是完整的程式碼:

/// <summary>
    /// 搜尋特定的目錄
    /// </summary>
    public class SearchSpecFolder
    {
        /// <summary>
        /// 當前搜尋總次數
        /// </summary>
        public int SerachCount { get; private set; }

        /// <summary>
        /// 搜尋指定的目錄名稱,先從當前目錄的子目錄進行搜尋,如果沒有搜尋到,從當前目錄的父目錄開始搜尋
        /// </summary>
        /// <param name="baseDir">搜尋開始的目錄</param>
        /// <param name="targetName">目標目錄名稱</param>
        /// <param name="matchChildDir">可選需要繼續匹配的目標目錄下的子目錄</param>
        /// <param name="matchChildFile">可需要繼續選匹配的目標目錄下的檔案</param>
        /// <returns>如果沒有搜尋到,返回空字串</returns>
        public string SearchSpectionFolderWithParent(string baseDir, string targetName, string matchChildDir=null, string matchChildFile=null)
        {
            Console.WriteLine("--Search Parent:{0}", baseDir);
            string obj = SearchSpectionChildFolder(baseDir, targetName, matchChildDir, matchChildFile);
            if (obj == "")
            {
                //如果子目錄沒有搜尋到,搜尋上級目錄
                var parentDir = System.IO.Directory.GetParent(baseDir);
                if (parentDir == null)
                    return "";
                return SearchSpectionFolderWithParent(parentDir.FullName, targetName, matchChildDir, matchChildFile);
            }
            return obj;
        }

        /// <summary>
        /// 從子目錄搜尋包含指定目錄名稱的目錄,可以選擇用一個子目錄或者目錄下面的一個檔案來匹配當前是正確的目標目錄(因為在其它目錄下可能有重名的當前目錄名稱)
        /// </summary>
        /// <param name="baseFolder">當前目錄</param>
        /// <param name="targetName">指定的目錄名稱</param>
        /// <param name="matchChildDir">可選需要繼續匹配的目標目錄下的子目錄</param>
        /// <param name="matchChildFile">可需要繼續選匹配的目標目錄下的檔案</param>
        /// <returns>匹配的目錄名稱</returns>
        private string SearchSpectionChildFolder(string baseFolder, string targetName, string matchChildDir, string matchChildFile)
        {
            SerachCount++;
            if (baseFolder == "")
                return "";
            //搜尋當前子目錄
            var allDir = System.IO.Directory.GetDirectories(baseFolder);
            foreach (var dir in allDir)
            {
                Console.WriteLine(dir);
                if (dir.EndsWith(targetName, StringComparison.OrdinalIgnoreCase))
                {
                    //匹配到目標目錄,還需要匹配它的子目錄名稱或者包含的一個檔名稱
                    if (!string.IsNullOrEmpty(matchChildDir))
                    {
                        string objPath = System.IO.Path.Combine(dir, matchChildDir);
                        if (System.IO.Directory.GetDirectories(dir).Contains(objPath))
                            return dir;
                    }
                    else if (!string.IsNullOrEmpty(matchChildFile))
                    {
                        string objPath = System.IO.Path.Combine(dir, matchChildFile);
                        if (System.IO.Directory.GetFiles(dir).Contains(matchChildFile))
                            return dir;
                    }
                    else
                    {
                        return dir;
                    }
                }
                //深度優先,搜尋子目錄
                string temp = SearchSpectionChildFolder(dir, targetName, matchChildDir, matchChildFile);
                if (temp != "")
                    return temp;
            }
            return "";//未找到,返回空
        }
    }

13,模擬死鎖

在2個查詢視窗分別執行執行事務1,2,將導致死鎖:

--事務模擬測試2
begin tran

UPDATE Table1 set END_TIME=GETDATE() where  id=N'f998b30a5d384f7ebfeb4646fbed6c88';
WaitFor Delay '00:0:20';

update Table2  set END_TIME=GETDATE() where ID='94b9f18f953f4a3b837153969c6bfc1d';
WaitFor Delay '00:0:10';
Rollback tran


--事務模擬測試2
begin tran

update Table2  set END_TIME=GETDATE() where ID='94b9f18f953f4a3b837153969c6bfc1d';

WaitFor Delay '00:00:20';
UPDATE Table1 set END_TIME=GETDATE() where  id=N'f998b30a5d384f7ebfeb4646fbed6c88';
WaitFor Delay '00:00:20';
Rollback tran

執行後,會出現下面類似的死鎖資訊:

訊息 1205,級別 13,狀態 51,第 2 行 事務(程序 ID 89)與另一個程序被死鎖在 鎖 資源上,並且已被選作死鎖犧牲品。請重新執行該事務。

注意:必須在測試程式碼上,rollback tran 前,也增加

WaitFor Delay '00:00:20';

否則,SQLSERVER 2008 不會出現死鎖,好多例子都沒有這一句,是無法模擬死鎖的。

除了使用Update語句,Insert語句在事務中,更容易出現死鎖,比如如下的例子:

SQL1:

use DBDemo  
begin tran
insert into [BookMarks]([BookMarkName]
      ,[BookMarkDesc]
      ,[BookMarkText]) values('人民日報合集2014','人民日報合集2015','人民日報合集2015')
waitfor delay '00:00:10'
select * from [BookMarks] where [BookMarkName] = '人民日報合集2014'
commit tran

SQL2:

use DBDemo  
begin tran
insert into [BookMarks]([BookMarkName]
      ,[BookMarkDesc]
      ,[BookMarkText]) values('人民日報合集2015','人民日報合集2015','人民日報合集2015')
waitfor delay '00:00:10'
select * from [BookMarks] where [BookMarkName] = '人民日報合集2015'
commit tran

同時執行這2個查詢,發現執行時間超過了語句中需要延遲的10秒,然後,其中一個查詢出現了死鎖:

(1 行受影響)
訊息 1205,級別 13,狀態 45,第 7 行
事務(程序 ID 52)與另一個程序被死鎖在 鎖 資源上,並且已被選作死鎖犧牲品。請重新執行該事務。

這說明,在事務情況下,Insert語句將會使用表鎖,而不是行鎖,從而增大了死鎖的機率。

14,Word內建的mso圖示

在進行VSTO程式設計的時候,會有一個 ribbon.xml配置檔案,用於配置自定義的功能區按鈕,這些按鈕的圖片可以是Word內建的,如下配置:

<button id="PreviewPDF" label="預覽報告" size="large" imageMso="FilePrintPreview"  onAction="OnButtonClicked"  screentip="預覽報告" supertip="預覽報告" />

那麼去哪裡找這些 mso圖片呢?下面這個網站,可以線上瀏覽這些圖片並獲取關聯的名稱:

http://www.soltechs.net/CustomUI/imageMso01.asp?gal=3&count=no

15,線上操作Excel

在伺服器安裝Excel來操作不是一個好主意,需要複雜的COM+許可權配置,並且還可能出現程序衝突,所以大家都常用第三方的Excel操作庫,除了NPOI,還可以使用

EPPLUS,它能夠操作xlsx格式的檔案,功能比較強大。

16,文件開發

除了Office,還可以使用WPS,或者使用開源的 LibreOffice ,這個可以參考此新聞:http://news.cnblogs.com/n/545200/

17,物件序列化找不到建構函式的問題

 在使用MemCached的時候,採用二進位制序列化,但爆出下面這個錯誤:

“The constructor to deserialize an object of type 'DeserializationIssue.MyDictionary' was not found.”,進過檢查,的確該類沒有建構函式,於是增加一個,仍然不行,後來從這篇文章知道,還需要一個序列化需要的建構函式,該建構函式接收兩個引數,型別分別是:SerializationInfo和StreamingContext 。於是,按照下面的樣子即可解決問題:

[Serializable]
    public class NameValueItem : NameValueCollection
    {
        /// <summary>
        /// 為二進位制序列化提供預設建構函式
        /// </summary>
        public NameValueItem() { }
        protected NameValueItem(SerializationInfo info, StreamingContext context) : base(info, context) { }
        public List<NameValueItem> Children { get; set; }
    }

18,建立資料庫訂閱,出現 錯誤22022 SQLServerAgent 的問題解決

這裡的原因可能跟建立前 SqlServerAgent沒自動執行有關,刪除當前訂閱,刪除報錯的作業任務,並啟動代理服務,最好,重新建立一次釋出訂閱即好。

 19,SqlServer釋出-訂閱行資料過大無法複製的問題

選擇“伺服器屬性”-》高階-》最大文字複製大小,預設是 65536(64K),修改成需要的數量即可。

20,Windows Server 2012 加入域(AD)後,IIS 網站訪問沒有許可權的問題

之前,需要把網站的目錄授權給 IIS_IUSRS 使用者組,但是伺服器加入域之後,該使用者組變成了 "伺服器名IIS_USRS" ,訪問網站的時候提示說沒有許可權訪問網站的檔案目錄。

此時,除了IIS_IUSRS 使用者之外,還需要把 IUSR 使用者授權給網站目錄,原因是下面的說法:

IIS 7的內建使用者(組)突破了SID的限制,因為IIS7在呼叫這些內建使用者(組)時,使用的是使用者名稱而非SID。而且在不同語言版本的系統中,IIS 7的內建使用者(組)都是IUSR(IIS_IUSRS)。其中,IUSR用於取代IUSR_MachineName,IIS_IUSRS用於取代IIS_WPG。

21,瀏覽器執行本機應用程式

可以使用wscript.shell 執行,注意只有IE支援,並需要IE設定安全級別,HTML程式碼如下:

<html>
<head>
<title>IE呼叫本地程式測試</title>
</head>
<bodey>
<h2>IE呼叫本地程式測試</h2>
<br>請在IE下執行此程式
<script>
function openFile(filename){
  try{
       var obj= new ActiveXObject("wscript.shell");
       if(obj){
           obj.Run("""+filename+""",1,false);
           obj=null;
        }
    }catch(e){
        alert(e);
    }
}

openFile("notepad");
</script>
</body>
</html>

22,查詢表所有的鍵

 SqlServer可以通過下面的語句查詢實現:

select * from sysobjects where parent_obj in (select id from sysobjects where name='Tb_Customer') 

結果列 xtype包含 下列資訊: UQ:唯一鍵 PK:主鍵 F:外來鍵

(本節完)