原先整理的一些C#程式碼片段

2012022814:44

[-- 參考語法 start --]
            if (!string.IsNullOrEmpty(控制項名稱.Value)) 控制項名稱.Attributes["readonly"] = "readonly";

            WebConfigurationManager.ConnectionStrings["ftswebConnectionString"].ConnectionString
            ConfigurationManager.ConnectionStrings["trdataConnectionString"].ConnectionString

            //webform
            string Acc = System.Web.Configuration.WebConfigurationManager.AppSettings["Acc"];
           
            //winform
            string SQLitePath = System.Configuration.ConfigurationSettings.AppSettings["SQLiteName"]
[-- 參考語法 end --]

 

[-- 網頁快取,單位為秒 start --]
<%@ OutputCache Duration ="900"  VaryByParam="*" %>
[-- 網頁快取,單位為秒 end --]

 

[-- DataReader語法 start --]
    << Sample 1 >>
            //DB連線字串(可自行設定由Web.Config取得)
            SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ftswebConnectionString"].ConnectionString);
            string sqlString = "UPDATE  FSCABIN SET LastNO=LastNO-1 WHERE cabin=@cabin";

            DataTable dt = new DataTable();
            using (SqlCommand cmd = new SqlCommand(sqlString, conn))
            {
                try
                {
                    cmd.Parameters.Add("@cabin", SqlDbType.Char, 2).Value = cabin;  //帶參數
                    if (conn.State != ConnectionState.Open) conn.Open();
                    dt.Load(cmd.ExecuteReader());
                }
                catch (Exception)
                {
                }
                finally
                {
                    if (conn.State != ConnectionState.Closed) conn.Close();
                }
            }

            //將結果繫結到下拉選單中
            this.DropDownList_user.DataSource = dt;
            this.DropDownList_user.DataTextField = "name";
            this.DropDownList_user.DataValueField = "id";
            this.DropDownList_user.DataBind();
   *****************************************************************************************************************
    << Sample 2 >>
            SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ftswebConnectionString"].ConnectionString);
            string sqlString = "UPDATE  FSCABIN SET LastNO=LastNO-1 WHERE cabin=@cabin";
            SqlCommand cmd = new SqlCommand(sqlString, conn);
            cmd.Parameters.Add("@cabin", SqlDbType.Char, 2).Value = cabin;  //帶參數
            conn.Open();
            cmd.ExecuteNonQuery();

            int i = 0;
            sqlString = "select LastNO from FSCABIN WHERE cabin in ('" + cabin + "')";
            cmd = new SqlCommand(sqlString, conn);
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                if (int.Parse(dr["LastNO"].ToString()) < 0)
                { i = 1; }
            }
            dr.Dispose();

            cmd.Dispose();
            conn.Close();
   *****************************************************************************************************************
    << Sample 3 >>
        #region 自定義的資料庫連結 ExecuteNonQuery、ExecuteScalar、ExecuteReader

        /// <summary>
        /// 執行 ExecuteNonQuery,傳回 int
        /// </summary>
        /// <returns></returns>
        public static int ExecuteNonQuery(string query, SqlConnection conn)
        {
            int result = 0;
            using (SqlCommand cmd = new SqlCommand(query, conn))
            {
                try
                {
                    if (conn.State != ConnectionState.Open) conn.Open();
                    result = cmd.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    HttpContext.Current.Response.Write("<font size='2' color='red'><br>SqlCommand執行異常<br><br>" + query + "<br><br>" + ex.ToString() + "<br></font>");
                    HttpContext.Current.Response.End();
                }
                finally
                {
                    if (conn.State != ConnectionState.Closed) conn.Close();
                }
            }
            return result;
        }

        /// <summary>
        /// 執行 ExecuteScalar,傳回 object
        /// </summary>
        /// <returns></returns>
        public static object ExecuteScalar(string query, SqlConnection conn)
        {
            object result = null;
            using (SqlCommand cmd = new SqlCommand(query, conn))
            {
                try
                {
                    if (conn.State != ConnectionState.Open) conn.Open();
                    result = cmd.ExecuteScalar();
                }
                catch (Exception ex)
                {
                    HttpContext.Current.Response.Write("<font size='2' color='red'><br>SqlCommand執行異常<br><br>" + query + "<br><br>" + ex.ToString() + "<br></font>");
                    HttpContext.Current.Response.End();
                }
                finally
                {
                    if (conn.State != ConnectionState.Closed) conn.Close();
                }
            }
            return result;
        }

        /// <summary>
        /// 執行 ExecuteReader,傳回 DataTable
        /// </summary>
        /// <returns></returns>
        public static DataTable ExecuteReader(string query, SqlConnection conn)
        {
            DataTable result = new DataTable();
            using (SqlCommand cmd = new SqlCommand(query, conn))
            {
                try
                {
                    if (conn.State != ConnectionState.Open) conn.Open();
                    result.Load(cmd.ExecuteReader());
                }
                catch (Exception ex)
                {
                    HttpContext.Current.Response.Write("<font size='2' color='red'><br>SqlCommand執行異常<br><br>" + query + "<br><br>" + ex.ToString() + "<br></font>");
                    HttpContext.Current.Response.End();
                }
                finally
                {
                    if (conn.State != ConnectionState.Closed) conn.Close();
                }
            }
            return result;
        }
        #endregion
[-- DataReader語法 end --]

 

[-- DataSet語法 start --]
            DataSet ds = new DataSet();

            SqlConnection Conn = new SqlConnection("資料庫連線字串");
            SqlDataAdapter myAdapter  = new SqlDataAdapter("select * from test", Conn);

            // ---- 不用寫Conn.Open() ,DataAdapter會自動開啟

            //***********************************
            //*** .Fill()方法之後,資料庫連線就中斷囉!
            //---------------------------------------------------------
            Response.Write("<hr />1. Fill()方法之前,資料庫連線 Conn.State ---- " + Conn.State.ToString() + "<hr />") ;
            //***********************************

            myAdapter.Fill(ds, "test");    //---- 執行SQL指令。取出資料,放進 DataSet。

            //***********************************
            //*** .Fill()方法之後,資料庫連線就中斷囉!
            //---------------------------------------------------------
            Response.Write("<hr />2. Fill()方法之後,資料庫連線 Conn.State ---- " + Conn.State.ToString() + "<hr />") ;
            //***********************************

            GridView1.DataSource = ds ;
            GridView1.DataBind();

            //---- 不用寫,DataAdapter會自動關閉
            //if (Conn.State == ConnectionState.Open)
            //{
            //  Conn.Close();
            //  Conn.Dispose();
            //}

            ds.Dispose();
[-- DataSet語法 end --]

 

[-- 自訂一個類別,並用LINQ的語法查詢List內容 start --]
        protected void Page_Load(object sender, EventArgs e)
        {
            List<People> list = new List<People>();
            list.Add(new People("a1", 12));
            list.Add(new People("b1", 25));
            list.Add(new People("c1", 37));
            list.Add(new People("d1", 46));
            list.Add(new People("a2", 75));
            list.Add(new People("b2", 33));
            list.Add(new People("c2", 24));
            list.Add(new People("d2", 67));

            // 用 LINQ 的語法查詢 List 內容
            List<People> list2 = (
                from p in list
                where p.Age >= 30
                orderby p.Age descending    //反向排序
                select p
            ).ToList<People>();    //將 list 排序後的資料寫到 list2 中

            foreach (People c in list2)
            {
                Response.Write("姓名 = " + c.Name + " 年齡 = " + c.Age + "<br>");
            }
        }

        //自訂一個類別
        public class People
        {
            public string Name { get; set; }
            public int Age { get; set; }

            public People(string data1, int data2)
            {
                Name = data1;
                Age = data2;
            }
        }
[-- 自訂一個類別,並用LINQ的語法查詢List內容 end --]

 

[-- 建立控制項陣列,加入到List清單 start --]
            //建立控制項陣列
            Control[] myArray = new Control[] { CHN_NMA1, ENG_NMA1, SexA1, BIRTH_DTA1, NATIONALITYA1, PASSPORT_NOA1, EXPIRE_DTA1, ID_NOA1, isCoA1 };

            //將控制項陣列加入List清單
            List<Control[]> mylist = new List<Control[]>();
            mylist.Add(myArray);

            //直接存取某一控制項的方法
            ((HtmlInputText)((Control[])mylist[0])[0]).Value = "okok!!!";

            //使用for迴圈存取控制項的方法
            for (int i = 0; i < myArray.Length; i++)
            {
                switch (((Control)((Control[])mylist[0])[i]).GetType().ToString())
                {
                    case "System.Web.UI.HtmlControls.HtmlInputText":
                        ((HtmlInputText)mylist[0][i]).Value = i.ToString();
                        break;
                    case "System.Web.UI.WebControls.RadioButtonList":
                        if (((RadioButtonList)mylist[0][i]).SelectedValue == "")
                        {
                            ((RadioButtonList)mylist[0][i]).SelectedIndex = 0;
                        }
                        break;
                    case "System.Web.UI.HtmlControls.HtmlInputCheckBox":
                        if (((HtmlInputCheckBox)mylist[0][i]).Value == "1")
                        {
                            ((HtmlInputCheckBox)mylist[0][i]).Checked = true;
                        }
                        break;
                    default:
                        Response.Write(i + " ==> " + ((Control)mylist[0][i]).GetType().ToString() + "<br>");
                        break;
                }
            }

            //使用foreach迴圈存取控制項的方法
            int i = 0;
            foreach (Control c in mylist[0])
            {
                i++;
                switch (c.GetType().ToString())
                {
                    case "System.Web.UI.HtmlControls.HtmlInputText":
                        ((HtmlInputText)c).Value = "HtmlInputText" + i;
                        break;
                    case "System.Web.UI.WebControls.RadioButtonList":
                        if (((RadioButtonList)c).SelectedValue == "")
                        {
                            ((RadioButtonList)c).SelectedIndex = 0;
                        }
                        break;
                    case "System.Web.UI.HtmlControls.HtmlInputCheckBox":
                        if (((HtmlInputCheckBox)c).Value == "1")
                        {
                            ((HtmlInputCheckBox)c).Checked = true;
                        }
                        break;
                    default:
                        Response.Write(i + " ==> " + c.GetType().ToString() + "<br>");
                        break;
                }
            }
[-- 建立控制項陣列,加入到List清單 end --]

 

[-- 使用二維索引的List清單判斷控制項型別 start --]
            List<List<Control>> list = new List<List<Control>>();

            list.Add(new List<Control>());   //<== 先加入一維List
            list[0].Add(Name1);              //<== 加入二維List
            list[0].Add(Sex1);
            list[0].Add(isCheck1);

            list.Add(new List<Control>());
            list[1].Add(Name2);
            list[1].Add(Sex2);
            list[1].Add(isCheck2);

            //使用for迴圈存取控制項的方法
            for (int i = 0; i < list[0].Count; i++)
            {
                switch (list[0][i].GetType().ToString())
                {
                    case "System.Web.UI.HtmlControls.HtmlInputText":
                        ((HtmlInputText)list[0][i]).Value = "HtmlInputText" + i;
                        break;
                    case "System.Web.UI.WebControls.RadioButtonList":
                        //Response.Write(((RadioButtonList)list[0][i]).SelectedValue + "<br>");
                        if (((RadioButtonList)list[0][i]).SelectedValue == "")
                        {
                            ((RadioButtonList)list[0][i]).SelectedIndex = 0;
                        }
                        break;
                    case "System.Web.UI.HtmlControls.HtmlInputCheckBox":
                        //Response.Write(((HtmlInputCheckBox)list[0][i]).Value + "<br>");
                        if (((HtmlInputCheckBox)list[0][i]).Value == "1")
                        {
                            ((HtmlInputCheckBox)list[0][i]).Checked = true;
                        }
                        break;
                    default:
                        Response.Write(i + " ==> " + list[0][i].GetType().ToString() + "<br>");
                        break;
                }
            }
[-- 使用二維索引的List清單判斷控制項型別 end --]

 

[-- 自訂資料集更新功能 start --]
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Web;
        using System.Web.UI;
        using System.Web.UI.WebControls;
        using System.Data;
        using System.Data.SQLite;

        namespace FTS_MSN_Import_Ticket.dataset.TicketTableAdapters // <==改成你要的TableAdapters
        {
            public partial class Msn_ModifyTableAdapter // <==改成你要的TableAdapter,就可以使用內建的TA 不需重新再寫
            {
                public virtual int CommandExecute(string QueryString)
                {
                    global::System.Data.SQLite.SQLiteCommand command = new SQLiteCommand(QueryString, this.Connection);
                    global::System.Data.ConnectionState previousConnectionState = command.Connection.State;
                    if (((command.Connection.State & global::System.Data.ConnectionState.Open)
                                != global::System.Data.ConnectionState.Open))
                    {
                        command.Connection.Open();
                    }
                    int returnValue;
                    try
                    {
                        returnValue = command.ExecuteNonQuery();
                    }
                    finally
                    {
                        if ((previousConnectionState == global::System.Data.ConnectionState.Closed))
                        {
                            command.Connection.Close();
                        }
                    }
                    return returnValue;
                }
            }
        }

        namespace FTSwebgene.db.WebgeneDBTableAdapters
        {
            public partial class EventRORequire1TableAdapter
            {
                public virtual int Update(string sql)
                {
                    this.Adapter.UpdateCommand = new global::System.Data.SqlClient.SqlCommand();
                    this.Adapter.UpdateCommand.Connection = this.Connection;
                    this.Adapter.UpdateCommand.CommandText = sql;
                    this.Adapter.UpdateCommand.CommandType = global::System.Data.CommandType.Text;
                    global::System.Data.ConnectionState previousConnectionState = this.Adapter.UpdateCommand.Connection.State;
                    if (((this.Adapter.UpdateCommand.Connection.State & global::System.Data.ConnectionState.Open)
                                != global::System.Data.ConnectionState.Open))
                    {
                        this.Adapter.UpdateCommand.Connection.Open();
                    }
                    try
                    {
                        int returnValue = this.Adapter.UpdateCommand.ExecuteNonQuery();
                        return returnValue;
                    }
                    finally
                    {
                        if ((previousConnectionState == global::System.Data.ConnectionState.Closed))
                        {
                            this.Adapter.UpdateCommand.Connection.Close();
                        }
                    }
                }
            }
        }
[-- 自訂資料集更新功能 end --]

 

[-- 委派(delegate) start --]
        delegate int del(int i);
        static void Main(string[] args)
        {
            del myDelegate = x => x * x;    //Lambda 表示式,把左邊的參數傳入右邊的匿名方法
            int j = myDelegate(5);   //結果 j = 25
        }
[-- 委派(delegate) end --]

 

[-- 擴充方法 start --]
        public static class lalala
        {
            public static string keep10chars(this string str)
            {
                return (str.Length > 10) ? str.Substring(0, 10) : str;
            }
        }
       
        撰寫擴充方法就是這麼簡單而已, 以下幾個重點要記住:
        1.它必須包在一個宣告為 public static 的類別裡面 (如上例中的 public static class lalala)
          類別名稱可以隨便取, 並不影響執行及引用。
        2.方法必須以 public static [type] 宣告 (如上例中的 public static string)。
        3.方法不能沒有參數, 而且其型別必須以 this [type] 宣告 (如上例中的 this string)。
[-- 擴充方法 end --]

 

[-- 新增目錄、複製檔案、刪除目錄及裡面所有檔案 start --]
        //找出目錄底下的所有檔案做刪除
        string FolderPath = Application.StartupPath + "\\XmlFile";

        string fileName = ConfigurationSettings.AppSettings["SQLiteName"];

        //當目錄不存在時新增目錄
        if (!Directory.Exists(FolderPath))
        {
            Directory.CreateDirectory(FolderPath);
        }

        //複製檔案
        for (int i = 6; i >= 0; i--)
        {
            if (i==0)
            {
                string sourceFile = Path.Combine(FolderPath, fileName);
                string destFile = Path.Combine(FolderPath, fileName + (i + 1).ToString());
                File.Copy(sourceFile, destFile, true);
            }
            else
            {
                string sourceFile = Path.Combine(FolderPath, fileName + i.ToString());
                string destFile = Path.Combine(FolderPath, fileName + (i + 1).ToString());

                //當檔案不存在時新增檔案
                if (!File.Exists(sourceFile))
                {
                    FileStream fs = new FileStream(sourceFile, FileMode.Create);
                    fs.Close();
                }
               
                File.Copy(sourceFile, destFile, true);
            }
        }
       
        //逐筆比對時間是否超過7天,是就刪除
        string[] files = Directory.GetFiles(FolderPath);
        foreach (string file in files)
        {
            FileInfo fi = new FileInfo(file);
            if (fi.LastWriteTime < DateTime.Now.AddDays(-7))
                File.Delete(file);
        }

        //刪除空資料夾
        Directory.Delete(FolderPath);
[-- 新增目錄、複製檔案、刪除目錄及裡面所有檔案 end --]

 

[-- 檔案上傳 start --]
        #region 檔案上傳 SaveFileAndReturnPath
        private string SaveFileAndReturnPath()
        {
            string return_file_path = "";
            if (FileUpload1.FileName != "")
            {
                string upload_excel_Dir = Server.MapPath("/");
                return_file_path = System.IO.Path.Combine(upload_excel_Dir, FileUpload1.FileName);

                FileUpload1.SaveAs(return_file_path);
            }
            return return_file_path;
        }
        #endregion
[-- 檔案上傳 end --]

 

[-- 跳出Alert視窗 start --]
        ClientScript.RegisterClientScriptBlock(typeof(System.Web.UI.Page), "AlertID", "alert('跳出Alert視窗');", true);
[-- 跳出Alert視窗 end --]

 

[-- 取得網頁模板裡之特定內容 start --]
    << Sample 1 >>
        using System.Web;      //加入參考 System.Web.dll     for Win Form

        public void GetTemplate()
        {
            string url = WebConfigurationManager.AppSettings["WebPath"];
            System.Net.WebClient clientIE = new System.Net.WebClient();
            byte[] bufferData = clientIE.DownloadData(url);
            string httpContentText = System.Text.Encoding.Default.GetString(bufferData);
            string tt = HttpContext.Current.Server.HtmlDecode(httpContentText);    //for Web Form
            //string tt = HttpUtility.HtmlDecode(httpContentText);                 //for Win Form
        }
   *****************************************************************************************************************
    << Sample 2 >>
        string WebPath = WebConfigurationManager.AppSettings["WebPath"];
        string Url = WebPath + "List.aspx?Student_Number=" + Student_Number;
        WebRequest request = WebRequest.Create(Url);
        WebResponse response = request.GetResponse();
        Stream resStream = response.GetResponseStream();
        //StreamReader sr = new StreamReader(resStream, System.Text.Encoding.GetEncoding("big5"));    //網頁為big5編碼
        StreamReader sr = new StreamReader(resStream, System.Text.Encoding.UTF8);
        string Content = sr.ReadToEnd();
        resStream.Close();
        sr.Close();
[-- 取得網頁模板裡之特定內容 end --]

 

[-- 將 Datatable 與 DataGridView 綁在一起 start --]
            //方式一
            DataTable dt = new DataTable("table");
            DataColumn colItem = new DataColumn("item", Type.GetType("System.String"));
            dt.Columns.Add(colItem);

            // Add five items.
            DataRow NewRow;
            for (int i = 0; i < 5; i++)
            {
                NewRow = dt.NewRow();
                NewRow["item"] = "Item " + i;
                dt.Rows.Add(NewRow);
            }

            // Change the values in the table.
            dt.Rows[0]["item"] = "cat";
            dt.Rows[1]["item"] = "dog";
            dt.AcceptChanges();

   *****************************************************************************************************************

            //方式二
            //DataTable dt = new DataTable();
            //dt.Columns.Add(new DataColumn("Item", typeof(string)));
            //dt.Columns.Add(new DataColumn("Color", typeof(string)));
            //dt.Rows.Add(new string[] { "cat", "brown" });
            //dt.Rows.Add(new string[] { "dog", "white" });

            //原本的 dataGridView
            dataGridView1.DataSource = dt;

            //過濾後的 dataGridView
            DataView view = new DataView(dt);
            view.RowFilter = "Item='" + "dog" + "'";
            DataTable table = view.ToTable();
            dataGridView2.DataSource = table;
[-- 將 Datatable 與 DataGridView 綁在一起 end --]

 

[-- 自行修改 DataTable 的內容取代原有內容 start --]
            DataTable dt = new DataTable();
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["trdataConnectionString"].ConnectionString);
            string query = "SELECT 顯示欄位1, 顯示欄位2, 顯示欄位3, '自訂欄位,這是說明內容......' AS '原本欄位', '' AS '自訂欄位1', '' AS '自訂欄位2' FROM table1 WHERE Date = @StartDate";
            //宣告欲自行修改的欄位 (不宣告修改會出錯)
            dt.Columns.Add(new DataColumn("自訂欄位1", typeof(string)));
            dt.Columns.Add(new DataColumn("自訂欄位2", typeof(string)));
            using (SqlCommand cmd = new SqlCommand(query, conn))
            {
                conn.Open();
                cmd.Parameters.Add(new SqlParameter("@StartDate", StartDate));    //自訂的參數
                dt.Load(cmd.ExecuteReader());
                conn.Close();
            }
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                //設定自行修改的內容取代原有內容
                string[] sArrWord = dt.Rows[i]["原本欄位"].ToString().Trim().Split(',');
                dt.Rows[i]["自訂欄位1"] = sArrWord[0];
                dt.Rows[i]["自訂欄位2"] = sArrWord[1];
                dt.AcceptChanges();
            }
            GridView1.DataSourceID = null;
            GridView1.DataSource = dt;
            GridView1.DataBind();
[-- 自行修改 DataTable 的內容取代原有內容 end --]

 

[-- 發送信件 start --]
        #region 發送信件 Mail
        /// <summary>
        /// 發送信件 Mail
        /// </summary>
        /// <returns></returns>
        public static void Mail(string Title, string Content)
        {
            string MailList = WebConfigurationManager.AppSettings["MailList_Punch"];    //aaa@@ftstour.com.tw;[email protected]
            Title += " - " + DateTime.Now.ToString();

            //發送信件
            string[] arrMailAddress = MailList.Split(';');
            MailMessage newMail = new MailMessage();
            newMail.From = new MailAddress("良友旅行社-訊息通知<[email protected]>");
            newMail.Priority = MailPriority.Low;
            newMail.BodyEncoding = System.Text.Encoding.UTF8;
            newMail.IsBodyHtml = true;
            newMail.Body = Content;
            foreach (string mailAddress in arrMailAddress)
            {
                if (mailAddress.Length > 0)