2013年9月17日 星期二
原先整理的一些C#程式碼片段
[-- 參考語法 start --]
//公司的北風資料庫位置
Data Source=192.168.100.168;Initial Catalog=Northwind;Persist Security Info=True;User ID=cowell;Password=tr2000
//從app.config文件中讀取資料庫連接字串訊息
String MySQLConnectionString = global::TicketKeyin.Properties.Settings.Default.trdataConnectionString;
在 Web.Config 內使用|DataDirectory| 連接字串變數來取代應用程式 App_Data 目錄的檔案路徑
可以把資料庫連接字串修改為下面的內容:
<connectionString>
data source=|DataDirectory|NLog_Record.s3db;
</connectionString>
//泛型常式中要使用到Session時,必須先實做IRequiresSessionState介面
if (!string.IsNullOrEmpty(控制項名稱.Value)) 控制項名稱.Attributes["readonly"] = "readonly";
//webform (Web.config)
string isTest = WebConfigurationManager.AppSettings["isTest"];
string connStr = WebConfigurationManager.ConnectionStrings["trdataConnectionString"].ConnectionString
//winform (App.config)
string isTest = ConfigurationManager.AppSettings["isTest"]
string connStr = ConfigurationManager.ConnectionStrings["trdataConnectionString"].ConnectionString
//執行時間計算
Stopwatch sw = new Stopwatch();
sw.Start();
......要執行的程式......
sw.Stop();
string time = "總計花費的時間 ==> " + sw.Elapsed;
//5秒後自動轉址
Response.AddHeader("Refresh", "5; url=OrderTicket4A.aspx?OP_SQ=123456");
//註冊JavaScript至Client端 (須搭配 <form runat="server">)
Page.ClientScript.RegisterStartupScript(this.GetType(), "webMessage", "alert('欄位請勿空白');", true);
//取得來源網址
string SourcePage = Request.UrlReferrer.ToString();
//取得UTC時間+8小時,讓系統不再有時差問題
DateTime.UtcNow.AddHours(8)
//事件委派的精簡語法
this.textBox1.Leave += new EventHandler(delegate(object o, EventArgs e)
{
this.textBox1.Focus();
});
//取得四捨五入後的「值」,例:1234.5678 --> 1234.57
double result = Convert.ToDouble(Math.Round(row.GetCell(j).NumericCellValue, 2, MidpointRounding.AwayFromZero));
//網頁編碼轉換 (BIG5 to UTF8)
byte[] bCharSet = System.Text.Encoding.GetEncoding("BIG5").GetBytes(Request["name"]);
Response.Write(System.Text.Encoding.UTF8.GetString(bCharSet));
[-- 參考語法 end --]
[-- 新增一個項目至組態檔appSettings節點 start --]
// 獲取應用程序組態檔位置
System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/");
// 宣告設定一個appSettings節點的項目
int appStgCnt = System.Configuration.ConfigurationManager.AppSettings.Count;
string newKey = "NewKey" + appStgCnt.ToString();
string newValue = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString();
// 新增至組態檔appSettings節點中
config.AppSettings.Settings.Add(newKey, newValue);
// 將組態檔存檔
config.Save(System.Configuration.ConfigurationSaveMode.Modified);
// 讀取appSettings節點
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.Collections.Specialized.NameValueCollection appSettings = System.Web.Configuration.WebConfigurationManager.AppSettings;
for (int i = 0; i < appSettings.Count; i++)
{
string appEntry = String.Format("#{0} Key: {1} Value: {2} <br/>", i, appSettings.GetKey(i), appSettings[i]);
sb.Append(appEntry);
}
[-- 新增一個項目至組態檔appSettings節點 end --]
[-- 取得路徑 start --]
//例:Url = http://localhost:8080/Demo/index.aspx
用 Request.Url.Scheme 會取得 http
用 Request.Url.Authority 會取得 localhost:8080
用 Request.Url.FilePath 會取得 /Demo/index.aspx
用 Path.GetFileName(Url) 會取得 index.aspx
//例:取得 http://localhost:8080/Demo/template/取代的網頁.htm
string Url = HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + HttpContext.Current.Request.FilePath;
Url = Url.Replace(Path.GetFileName(Url), "template/取代的網頁.htm");
//相關路徑
string ExeBasePath = AppDomain.CurrentDomain.BaseDirectory; //程式所在位置路徑,而非執行時所在位置
string FolderPath = Path.GetFullPath(ExeBasePath + "MyForder"); //傳回指定目錄的絕對路徑
string SourceFile = Path.Combine(FolderPath, "StartDate.zip"); //傳回指定檔案的絕對路徑
[-- 取得路徑 end --]
[-- 取得來自原先網頁 Request.Form 傳入的所有參數內容 start --]
NameValueCollection request = (NameValueCollection)Request.Form;
string urlParameters = null;
string s = null;
foreach (var key in request.AllKeys)
{
//參數內容先去除特定欄位的值
if (!("'__VIEWSTATE','Field1'").Contains("'" + key + "'"))
{
//urlParameters += s + key + "=" + HttpUtility.UrlDecode(request[key], System.Text.Encoding.GetEncoding("BIG5"));
urlParameters += s + key + "=" + Server.UrlEncode(request[key]);
s = "&";
}
}
string url = "OrderTicket2A.aspx?" + urlParameters;
HttpContext.Current.Response.Redirect(url);
[-- 取得來自原先網頁 Request.Form 傳入的所有參數內容 end --]
[-- 調用Server.Execute,獲取模板網頁內容 start --]
string ReportContent = null;
using (StringWriter sw = new StringWriter())
{
//抓取模板網頁內容
Server.Execute("html/報表01.htm", sw);
ReportContent = sw.ToString();
}
[-- 調用Server.Execute,獲取模板網頁內容 end --]
[-- 移除網頁標籤 RemoveHtmlTag start --]
public string RemoveHtmlTag(string html)
{
string result = html;
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"<[^>]+>|]+>");
result = regex.Replace(result, "");
return result;
}
[-- 移除網頁標籤 RemoveHtmlTag end --]
[-- 取亂數 start --]
<< Sample 1 >>
int total = 30;
Random rnd = new Random();
for (int i = 0; i < 50; i++)
{
button1.Text = (rnd.Next(total)+1).ToString(); //<--取得亂數值的範圍 1 ~ 30
//直接秀出,不會等待程式全部完成
Application.DoEvents();
Thread.Sleep(50);
}
*****************************************************************************************************************
<< Sample 2 >>
//隨機不重複陣列
int start = 1; //開始
int end = 30; //結束
int count = end - start + 1;
int[] randomValues = new int[count];
Random rnd = new Random((int)DateTime.Now.Ticks);
int randomValue;
for (int i = 0; i < count; i++)
{
do
{
randomValue = rnd.Next(start, end + 1);
} while (randomValues.Contains(randomValue));
randomValues[i] = randomValue;
}
[-- 取亂數 end --]
[-- 設置 Cookie start --]
//設置時間間隔
DateTime dt = DateTime.Now;
TimeSpan ts = new TimeSpan(0, 0, 1, 0, 0); //時間間隔為1分鐘 (天,小時,分鐘,秒,毫秒)
dt.Add(ts);
HttpCookie cookie1 = new HttpCookie("MyCookieName", "MyCookieValue");
cookie1.Expires = dt; //設置過期時間
cookie1.Domain = "www.ftstour.com.tw";
Response.AppendCookie(cookie1);
[-- 設置 Cookie 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 --]
[-- SQLite + TableAdapter (交易模式) start --]
FtsDBTableAdapter ta = new FtsDBTableAdapter();
ta.Connection.ConnectionString = connectionString;
//判斷連接的狀態。如果是關閉狀態,則打開
if (ta.Connection.State != ConnectionState.Open) ta.Connection.Open();
using (SQLiteTransaction trans = ta.Connection.BeginTransaction()) //採用交易模式
{
ta.Transaction = trans;
try
{
//do it...
trans.Commit(); //交易完成
}
catch (Exception ex)
{
trans.Rollback(); //交易回復
}
finally
{
//判斷連接的狀態。如果是打開狀態,則關閉
if (ta.Connection.State != ConnectionState.Closed) ta.Connection.Close();
}
}
[-- SQLite + TableAdapter (交易模式) 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 --]
[-- 按鈕委派實例(webForm) start --]
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Test_WebForm._Default" %>
<html>
<body>
<form id="Form1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button1" CommandName="按鍵 1" />
<asp:Button ID="Button2" runat="server" Text="Button2" CommandName="按鍵 2" />
<br>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Test_WebForm
{
public partial class _Default : System.Web.UI.Page
{
#region 透過委派 (Delegate) 方式,取得對應的作用按鈕,引發相關的 Click 事件
//1.委派宣告
public delegate void ClickEventHandler(object sender, EventArgs e);
//2.定義事件並用switch判斷來做相關處理
protected void ClickEvent(object sender, EventArgs e)
{
//判斷哪個鍵被按
TextBox1.Text = "你按下的是" + ((Button)sender).CommandName;
//用switch判斷來呼叫各自的方法處理
switch (((Button)sender).ID)
{
case "Button1":
btnClick1();
break;
case "Button2":
btnClick2();
break;
}
}
//3.呼叫各自的方法
protected void btnClick1()
{
TextBox1.BackColor = System.Drawing.Color.SkyBlue;
}
protected void btnClick2()
{
TextBox1.BackColor = System.Drawing.Color.Yellow;
}
#endregion
//4.引用ClickEvent事件
protected void Page_Load(object sender, EventArgs e)
{
Button1.Click += new EventHandler(ClickEvent);
Button2.Click += new EventHandler(ClickEvent);
}
}
}
[-- 按鈕委派實例(webForm) end --]
[-- 按鈕委派實例(winForm) - 另外創建委派類別 start --]
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//5.建立自定義的對應事件函數
private void Method1(object sender, EventArgs e)
{
MessageBox.Show(((Button)sender).Name + "被點擊了喔");
}
private void Method2(object sender, EventArgs e)
{
MessageBox.Show(((Button)sender).Name + "被執行了喔");
}
private void Form1_Load(object sender, EventArgs e)
{
//6.將類別實體化
MyButtonDelegate myBtnDelegate = new MyButtonDelegate();
//7.引用方法
myBtnDelegate.Add(button1, Method1);
myBtnDelegate.Add(button2, Method2);
}
}
//1.建置一個可共用的按鈕委派類別 (方便重覆使用)
public class MyButtonDelegate
{
//2.委派宣告
public delegate void ClickDelegate(object sender, EventArgs e);
//3.建立方法,設定Button及欲呼叫的事件函數
public void Add(object sender, ClickDelegate ClickEvent)
{
if (ClickEvent != null)
{
//4.拋出Click事件給相對應的Button
((Button)sender).Click += new EventHandler(ClickEvent);
}
}
}
[-- 按鈕委派實例(winForm) - 另外創建委派類別 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 --]
//讀取文字檔中原有內容
string content = null;
using (StreamReader sr = new StreamReader(SourceFile))
{
content = sr.ReadToEnd(); //一次讀取到檔尾
//while (!sr.EndOfStream)
//{
// content += sr.ReadLine(); // 每次讀取一行,直到檔尾
//}
}
//寫入文字內容 (檔案不存在時會自動新增檔案)
using (StreamWriter sw = new StreamWriter(SourceFile, false)) //true 附加寫入,false 覆蓋寫入
{
sw.Write(content);
sw.WriteLine(DateTime.Now.ToString() + " - This is a test.");
}
[-- 文字讀寫 end --]
[-- 檔案上傳 start --]
<asp:FileUpload id="FileUpload1" runat="server" />
#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), "AlertMsg", "alert('跳出Alert視窗');", true);
[-- 跳出Alert視窗 end --]
[-- 獲取網頁編碼,自動區分網頁編碼 start --]
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(getHtml("http://tw.yahoo.com/", null));
}
//獲取網頁編碼,自動區分網頁編碼
private string getHtml(string url, string charSet)
//url是要訪問的網站地址,charSet是目標網頁的編碼
//如果傳入的是null或者"",就自動分析網頁的編碼
{
WebClient myWebClient = new WebClient();
myWebClient.Proxy = null; //.NET中的默認代理是開啟的,使用默認代理時,只有等待超時後才會繞過代理,從而導致第一次連接特別慢
byte[] myDataBuffer = myWebClient.DownloadData(url);
string strWebData = Encoding.Default.GetString(myDataBuffer);
//獲取網頁編碼描述訊息
Match charSetMatch = Regex.Match(strWebData, " ]*)charset=(\")?(.*)?\"", RegexOptions.IgnoreCase | RegexOptions.Multiline);
string webCharSet = charSetMatch.Groups[3].Value;
if (charSet == null || charSet == "") charSet = webCharSet;
if (charSet != null && charSet != "" && Encoding.GetEncoding(charSet) != Encoding.Default)
{
strWebData = Encoding.GetEncoding(charSet).GetString(myDataBuffer);
}
return strWebData;
}
[-- 獲取網頁編碼,自動區分網頁編碼 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();
clientIE.Proxy = null;
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);
request.Proxy = null;
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();
*****************************************************************************************************************
<< Sample 3 >>
//準備要傳送的參數內容
//Encoding encoding = Encoding.GetEncoding("big5"); //網頁為big5編碼
Encoding encoding = Encoding.UTF8;
string postData = "Type=Auth";
postData += "&storeid=50761";
postData += "&ordernumber=123456";
postData += "&amount=100";
postData += "&orderdesc=訂單說明";
postData += "&pan=1234567890123456";
postData += "&expiry=1608";
postData += "&depositflag=0";
postData += "&queryflag=0";
byte[] data = encoding.GetBytes(postData);
//準備以POST方式傳送網頁表單內容至遠端伺服器
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://localhost:4642/OrderTicket1B.aspx");
myRequest.Method = "POST";
myRequest.Proxy = null;
//設置是否允許自動轉址
myRequest.AllowAutoRedirect = true;
//設置UserAgent,某些網站中有做限制,UserAgent為空,則不能訪問:
myRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.1.4322; .NET CLR 2.0.50215; fqSpider)";
//設置ContentType的內容,如果為POST,設置成application/x-www-form-urlencoded,如果是GET設置成text/html:
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream = myRequest.GetRequestStream();
//傳送參數內容
newStream.Write(data, 0, data.Length);
newStream.Close();
//取得遠端伺服器回傳的結果
WebResponse response = myRequest.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 --]
public static void Mail(string Subject, string Body)
{
string UserMails = WebConfigurationManager.AppSettings["UserMails"]; //aaa@@ftstour.com.tw;bbb@ftstour.com.tw
//發送信件
MailMessage newMail = new MailMessage();
newMail.From = new MailAddress("良友旅行社-訊息通知<service@ftstour.com.tw>");
newMail.Priority = MailPriority.Low;
newMail.BodyEncoding = System.Text.Encoding.UTF8;
newMail.IsBodyHtml = true;
newMail.Body = Body;
string[] arrMailAddress = UserMails.Split(';');
foreach (string mailAddress in arrMailAddress)
{
if (mailAddress.Length > 0)
{
//加入指定的發信對象
newMail.To.Add(new MailAddress(mailAddress));
}
}
//當Log檔存在時附加檔案至信件中
string FolderPath = HttpContext.Current.Server.MapPath(WebConfigurationManager.AppSettings["FolderPath"]);
string FileName = DateTime.Today.ToString("yyyyMMdd");
string SourceFile = Path.Combine(FolderPath, FileName + ".txt");
if (File.Exists(SourceFile))
{
newMail.Attachments.Add(new Attachment(SourceFile));
}
newMail.Subject = Subject + " - " + DateTime.Now.ToString();
SmtpClient sc = new SmtpClient(WebConfigurationManager.AppSettings["SmtpServer"]);
sc.Send(newMail);
}
[-- 網頁快取,單位為秒 end --]
[-- 建立Datatable及匯出Excel start --]
#region 建立Datatable
//建立Datatable
DataTable dt = new DataTable();
//宣告欄位名稱
dt.Columns.Add(new DataColumn("會計科目", typeof(string)));
dt.Columns.Add(new DataColumn("科目代碼", typeof(string)));
dt.Columns.Add(new DataColumn("分公司小計", typeof(Int32)));
dt.Columns.Add(new DataColumn("合計", typeof(Int32)));
//新增一筆資料
DataRow dr = dt.NewRow();
dr["會計科目"] = "小計:";
dr["科目代碼"] = "1001";
dr["分公司小計"] = 12345;
dr["合計"] = 12345;
dt.Rows.Add(dr);
//排序
dt.DefaultView.Sort = "科目代碼,會計科目";
//過濾出分公司小計有不為零的才呈現該筆資料
dt.DefaultView.RowFilter = "ISNULL(分公司小計, 0) <> 0";
//刪除多餘欄位
dt.Columns.Remove("完整科目代碼");
dt.Columns.Remove("科目代碼前四碼");
dt.Columns.Remove("分公司代碼");
//匯出EXCEL
GridView gv = new GridView();
gv.DataSource = dt;
gv.DataBind();
ExportToFile(gv, "表單名稱");
#endregion
#region 匯出Excel ExportToFile
/// <summary>
/// 匯出Excel ExportToFile
/// </summary>
public static void ExportToFile(GridView gv, string ExcelName)
{
try
{
//建立 WorkBook 及試算表
HSSFWorkbook workbook = new HSSFWorkbook();
MemoryStream ms = new MemoryStream();
HSSFSheet mySheet1 = (HSSFSheet)workbook.CreateSheet(ExcelName);
mySheet1.DefaultColumnWidth = 15; //預設的字元寬度
//建立標題列 Header
HSSFRow rowHeader = (HSSFRow)mySheet1.CreateRow(0);
for (int i = 0; i < gv.HeaderRow.Cells.Count; i++)
{
//若有啟用排序,Header會變成 LinkButton
LinkButton lb = null;
if (gv.HeaderRow.Cells[i].Controls.Count > 0)
{
lb = gv.HeaderRow.Cells[i].Controls[0] as LinkButton;
}
string strValue = (lb != null) ? lb.Text : gv.HeaderRow.Cells[i].Text;
HSSFCell cell = (HSSFCell)rowHeader.CreateCell(i);
cell.SetCellValue(HttpUtility.HtmlDecode(strValue).Trim());
NPOI.SS.UserModel.CellStyle cellStyle = workbook.CreateCellStyle();
cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER; //設為居中
cell.CellStyle = cellStyle;
}
//建立內容列 DataRow
for (int i = 0; i < gv.Rows.Count; i++)
{
HSSFRow rowItem = (HSSFRow)mySheet1.CreateRow(i + 1);
for (int j = 0; j < gv.HeaderRow.Cells.Count; j++)
{
string value1 = HttpUtility.HtmlDecode(gv.Rows[i].Cells[j].Text).Trim();
long number1 = 0;
bool isNumeric = long.TryParse(value1, out number1);
if (string.IsNullOrEmpty(value1))
{
//空白
rowItem.CreateCell(j).SetCellValue("");
}
else if (!isNumeric)
{
//文字格式
rowItem.CreateCell(j).SetCellValue(value1);
mySheet1.SetColumnWidth(j, 30 * 256); //欄位寬度設為30
}
else
{
//數字格式
HSSFCell cell = (HSSFCell)rowItem.CreateCell(j);
cell.SetCellValue(number1);
//NPOI.SS.UserModel.CellStyle cellStyle = workbook.CreateCellStyle();
//cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("#,##0");
//cell.CellStyle = cellStyle;
HSSFCellStyle cellStyle = (HSSFCellStyle)workbook.CreateCellStyle();
HSSFDataFormat format = (HSSFDataFormat)workbook.CreateDataFormat();
cellStyle.DataFormat = format.GetFormat("#,##0;[RED](#,##0)");
cell.CellStyle = cellStyle;
}
}
}
//匯出
workbook.Write(ms);
HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("Attachment; Filename=" + HttpUtility.UrlEncode(ExcelName) + ".xls"));
HttpContext.Current.Response.BinaryWrite(ms.ToArray());
//釋放資源
workbook = null;
ms.Close();
ms.Dispose();
}
catch (Exception)
{ }
}
#endregion
[-- 建立Datatable及匯出Excel end --]
[-- 利用控制項集合,使用 for 廻圈讓 TextBox1 到 TextBox10 的Text 值為 1 到 10 start --]
// this.Controls[控制項名稱],可以取得表單中的控制項集合
// 假如想要讓 TextBox1.Text = "1" => 可以這樣寫 this.Controls[TextBox1].Text = "1"
// 所以可以透過以下寫法,讓 TextBox1 到 10 的 Text值 為 1 到 10
for (int index = 1; index <= 10; index++)
{
this.Controls["TextBox" + index.ToString()].Text =index.ToString();
}
[-- 利用控制項集合,使用 for 廻圈讓 TextBox1 到 TextBox10 的Text 值為 1 到 10 end --]
[-- DropDownList.Items的常用方法 start --]
在最後一個項目添加:
DropDownList.Items.Add("text");
or
DropDownList.Items.Add(new ListItem("text","value"));
在指定的位置添加一項目:
DropDownList.Items.Insert(index, new ListItem("text","value"));
移除指定的項目:
DropDownList.Items.Remove("text");
or
DropDownList.Items.RemoveAt(index);
移除所有的項目:
DropDownList.Items.Clear();
項目的總數:
DropDownList.Items.Count();
[-- DropDownList.Items的常用方法 end --]
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言