星期一, 2月 01, 2010
Windows 2008 R2 安裝遇到的問題!!
今天開始換用server 2008R2,
真是不習慣呀,終於把SQL 2005 裝好了Orz
一直偵測不到需求的IIS Feature Requirement,
參考這篇大俠的就解決了(附圖) SQL Server 2005在Windows 2008 R2的安裝
不過最後SQL Server Management Studio竟然不見了。
解決方式如下:
執行此檔案路徑\SQL Server x86\Tools\Setup\SqlRun_Tools.msi 的檔案重新安裝
ps:如果有裝SQL Server Management Studio Express要先移除。
請參考安裝好SQL Server,卻找不到「SQL Server Management Studio」
有n篇以上完全跟上述的文章內容一模一樣XD。
可以在G大神下打『找不到sql server management studio』第一頁就一堆了。
真是不習慣呀,終於把SQL 2005 裝好了Orz
一直偵測不到需求的IIS Feature Requirement,
參考這篇大俠的就解決了(附圖) SQL Server 2005在Windows 2008 R2的安裝
不過最後SQL Server Management Studio竟然不見了。
解決方式如下:
執行此檔案路徑\SQL Server x86\Tools\Setup\SqlRun_Tools.msi 的檔案重新安裝
ps:如果有裝SQL Server Management Studio Express要先移除。
請參考安裝好SQL Server,卻找不到「SQL Server Management Studio」
有n篇以上完全跟上述的文章內容一模一樣XD。
可以在G大神下打『找不到sql server management studio』第一頁就一堆了。
星期日, 1月 31, 2010
asp.net 不可以在 DropDownList 中選取多個項目。
今天遇到這個奇怪的bug,
不可以在 DropDownList 中選取多個項目。
上網查了一下,蠻多人有遇過這樣的問題:
不可以在 DropDownList 中選取多個項目 ?
OOP Pass by Value OR Reference ?
不過我的情形跟上述的不太一樣,
原來是我在DropDownList的item中已指定Selected="True"
又在程式指定一次
if (hwCategory == "True")
{
this.ddlPaidLimit.Items[1].Selected = true;
}
else
{
this.ddlPaidLimit.Items[0].Selected = true;
}
結果就發生這樣的錯誤,拿掉Selected="True"即可解決。
不可以在 DropDownList 中選取多個項目。
上網查了一下,蠻多人有遇過這樣的問題:
不可以在 DropDownList 中選取多個項目 ?
OOP Pass by Value OR Reference ?
不過我的情形跟上述的不太一樣,
原來是我在DropDownList的item中已指定Selected="True"
又在程式指定一次
if (hwCategory == "True")
{
this.ddlPaidLimit.Items[1].Selected = true;
}
else
{
this.ddlPaidLimit.Items[0].Selected = true;
}
結果就發生這樣的錯誤,拿掉Selected="True"即可解決。
星期六, 1月 30, 2010
asp.net 無效的回傳或回呼引數處理
今天使用listview上的button進行delete的動作,
一postback就產生error,
錯誤訊息:「無效的回傳或回呼引數。已在組態中使用 或在網頁中使用 <%@ Page EnableEventValidation="true" %> 啟用事件驗證。基於安全性理由,這項功能驗證回傳或回呼引數是來自原本呈現它們的伺服器控制項。如果資料為有效並且是必需的,請使用 ClientScriptManager.RegisterForEventValidation 方法註冊回傳或回呼資料,以進行驗證。」
原因在於我在page_load中,有將資料動態繫結至listview,
導致postback就產生上述錯誤,
所以再綁定之前判斷資料是否為第一次載入即可。
if (!IsPostBack){
this.InitCoursePlans();
}
一postback就產生error,
錯誤訊息:「無效的回傳或回呼引數。已在組態中使用
原因在於我在page_load中,有將資料動態繫結至listview,
導致postback就產生上述錯誤,
所以再綁定之前判斷資料是否為第一次載入即可。
if (!IsPostBack){
this.InitCoursePlans();
}
星期日, 1月 24, 2010
DataList 自動編號
<div>
<asp:DataList ID="DataListTestPaper" runat="server" DataKeyField="TestPaperItemID" DataSourceID="SqlDataSourceTestPaper" OnItemDataBound="DataList1_ItemDataBound" Width="736px" CellPadding="4" ForeColor="#333333">
<ItemTemplate>
(<%# Container.ItemIndex + 1%>)
<!--試題id之後對答案要用到-->
<asp:Label ID="TestPaperItemIDLabel" runat="server" Text='<%# Eval("TestPaperItemID") %>' style="display: none;"></asp:Label>
<asp:Label ID="TestPaerContentLabel" runat="server" Text='<%# Eval("TestPaerContent") %>'></asp:Label>
<asp:RadioButtonList ID="RadioButtonList1" runat="server" DataSourceID="SqlDataSourceOptions" DataTextField="TestPaperOptionsText" DataValueField="TestPaperOptionsID" RepeatDirection="Horizontal">
</asp:RadioButtonList>
<asp:SqlDataSource ID="SqlDataSourceOptions" runat="server" ConnectionString="<%$ ConnectionStrings:ELTestPaperConnectionString %>"
SelectCommand="SELECT TestPaperOptionsText, TestPaperOptionsID FROM TestPaperOptions WHERE (TestPaperOptionsPID = @pid) order by newid() ">
<SelectParameters>
<asp:ControlParameter ControlID="TestPaperItemIDLabel" Name="pid" PropertyName="Text" />
</SelectParameters>
</asp:SqlDataSource>
</ItemTemplate>
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<SelectedItemStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<AlternatingItemStyle BackColor="White" />
<ItemStyle BackColor="#E3EAEB" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
</asp:DataList><asp:SqlDataSource ID="SqlDataSourceTestPaper" runat="server" ConnectionString="<%$ ConnectionStrings:ELTestPaperConnectionString %>"
SelectCommand="SELECT * FROM [TestPaper] where TestPaperCategoryID = @cid order by newid() ">
<SelectParameters>
<asp:QueryStringParameter DefaultValue="1" Name="cid" QueryStringField="cid" />
</SelectParameters>
</asp:SqlDataSource>
</div>
星期二, 1月 19, 2010
C# DataTable Compute method 一行解決Sum問題
剛好需用到將datatable中的某一列做sum,
原來使用裡面提供的Compute就可以達到了Oops~
//課程作業已佔用的百分比
string hwPercentSum = this.dtHWList.Compute("sum(HomeWorkPercent)","").ToString();
原來使用裡面提供的Compute就可以達到了Oops~
//課程作業已佔用的百分比
string hwPercentSum = this.dtHWList.Compute("sum(HomeWorkPercent)","").ToString();
Ubuntu ConnectTo WILE Using Iphon
ation:
Install the bluez-compat package.
Edit /etc/default/bluetooth to add the following lines:
1
PAND_ENABLED=1
2
PAND_OPTIONS="--role=PANU"
Restart the Bluetooth service: /etc/init.d/bluetooth restart
Add the BNEP network adapter to the /etc/network/interfaces file by appending the following line: iface bnep0 inet dhcp
Get the Bluetooth address of your phone by running hcitool scan and jotting down the address next to your phone’s name.
Now the bits and pieces that need to be done each time:
Pair your computer with your iPhone. If you’re using GNOME, the standard Bluetooth applet can handle that; presumably that’s true of the other flavours of Ubuntu as well.
To connect, run these commands in your favourite shell, replacing 00:aa:bb:cc:dd:ee with the Bluetooth address you jotted down earlier:
1
sudo pand --connect 00:aa:bb:cc:dd:ee -n
2
sudo ifup bnep0
At that point, life should be good and you should be connected. To disconnect later:
1
sudo ifdown bnep0
2
sudo pand -K
Install the bluez-compat package.
Edit /etc/default/bluetooth to add the following lines:
1
PAND_ENABLED=1
2
PAND_OPTIONS="--role=PANU"
Restart the Bluetooth service: /etc/init.d/bluetooth restart
Add the BNEP network adapter to the /etc/network/interfaces file by appending the following line: iface bnep0 inet dhcp
Get the Bluetooth address of your phone by running hcitool scan and jotting down the address next to your phone’s name.
Now the bits and pieces that need to be done each time:
Pair your computer with your iPhone. If you’re using GNOME, the standard Bluetooth applet can handle that; presumably that’s true of the other flavours of Ubuntu as well.
To connect, run these commands in your favourite shell, replacing 00:aa:bb:cc:dd:ee with the Bluetooth address you jotted down earlier:
1
sudo pand --connect 00:aa:bb:cc:dd:ee -n
2
sudo ifup bnep0
At that point, life should be good and you should be connected. To disconnect later:
1
sudo ifdown bnep0
2
sudo pand -K
星期六, 1月 16, 2010
CIH套件
binutils
gcc
diffutils
gdb
util-linux-ng
mc
main()
{
asm("nop");
asm("nop");
asm("nop");
while("1");
asm("nop");
asm("nop");
}
gcc
diffutils
gdb
util-linux-ng
mc
main()
{
asm("nop");
asm("nop");
asm("nop");
while("1");
asm("nop");
asm("nop");
}
星期四, 1月 14, 2010
C# StreamReader 逐行讀取txt file資料
今天又用到了XD,記錄一下。
using(StreamReader sr = new StreamReader(ckipPath,Encoding.Default))
{
while ((termTemp = sr.ReadLine()) != null)
{
termTemp = termTemp.Substring(0,termTemp.IndexOf(" "));
}
}
星期三, 1月 13, 2010
C# Base64 Convert
////// base64convert 的摘要描述 /// public class base64convert { public base64convert() { } public string ConvertStringToBase64(string s) { byte[] ToByte = System.Text.Encoding.Default.GetBytes(s.ToString().Trim()); string str = Convert.ToBase64String(ToByte); return str; } public string ConvertBase64ToString(string s) { byte[] strbyte = Convert.FromBase64String(s.ToString().Trim()); string str = System.Text.Encoding.Default.GetString(strbyte); return str; } }
星期一, 1月 11, 2010
SQL 選擇資料後馬上插入資料表XD
INSERT INTO MembersRole
(MembersRoleMemberID, MembersRoleOrgRoleID)
SELECT MemberID, MemberRoleID
FROM Members
(MembersRoleMemberID, MembersRoleOrgRoleID)
SELECT MemberID, MemberRoleID
FROM Members
星期六, 1月 02, 2010
星期五, 1月 01, 2010
c# MD5
string hashPassword = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(password, "MD5");
星期六, 12月 26, 2009
星期五, 12月 25, 2009
windows的 stack、heap記憶體(內存)管理重點筆記
1/ windows的flat 模式: 這題目要講起來可以很深,包含許多的組合語言的東西。但在此我只想說一個結果,就是因為windows是使用這樣的一個記憶體管理位址模式,所以使得每個process都可以有私有的4G的「定址」能力,但因為windows當初要相容MIPS R4000 architecture,所以高位址的2G部份放的是kernel code,而我們的ap只能用低部份的2G,所以正確的來講,我們的程式能夠使用2G的定址能力。
2/虛擬記憶體: 在80386處理器後,cup support 保護模式,paging 模式。我們都知道windows會使用硬碟來充當ram使用,當ram不足的時候。這就是用paging的cpu功能。有了這個功能,os就可以讓每個process都可以使用2G的data,即使ram只有幾MB。在標題1我們有提到「定址」的這個詞,這只是說cpu的register(暫存器)有能力讓我們定出那麼大的空間。但是可以定出那麼大麼大的空間並不表示你一定先要有那麼大的ram在電腦上。定址是一回事,配置(allocate)又是另一回事,但二者都很重要。比如在dos 80286前的時代,有所謂的640k的限制(那是指定址能力先天不足),所以你就算是買了4MB的ram插在電腦上,還是浪費。回到主題,因為386以後有paging的能力,加上register是32位元,所以就組合出一種相當完美的記憶體管理方法: 每個process都有虛擬的4G記憶體,且可以真的使用到4G,即使你的ram沒有4G,windows會把你的虛擬記憶體資料放到硬碟上。為何說是「虛擬」?就是指你不一定真的有那麼多的真實的ram。比如說你真實的ram有128MB,而你的程式超大,用到512MB,那麼當程式在跑的時候,只會把正需要的code往128MB的ram上放,而把尚不用的放(paging)在硬碟上。
3/ stack: 何謂stack? 是用來放function上auto級的變數(這樣的說法較專業),所謂auto級的就是變數是宣告在function內,它的生命(life time/ extent)在function結束後就無效了! stack的大小是由 linker來決定,以bcb為例,最大可以到0x1000000,即約16MB,你可以在project option上改。由多程式人員喜歡把object放在stack上,即用下面的宣告方式
ClassT object; 這樣整個object的資料都會配在stack上,若class小還好,大則容易overflow。故一般建議用new的方式來create objcet,只留下4byte的指標在stack上。又如這些天許多玩matalab的人問到2維array overflow的問題,也是因為把array宣告在stack上所造成。要解決的方式還是一樣,把它用new的方式create到heap上(稍後會講)。但二維的動態產生array需要一些技巧,可查一下我的文章。還有,使用recursive function的人也要特別注意overfolw的問題。必要的話可以改寫演算法不要用遞回。stack的使用很方便,因為不用僅管使用,無需去自行清理,唯不要overflow就很棒!
4/ heap: 是用來動態使用記憶體的方式,使用的自由度最高,但需要自行善後清理。通常是用malloc/free或是new/delete來處理。heap在windows下可以分為二種,1為default heap2為dynamic heap。default heap 可以是windows dll 等api使用,也可以app自己使用。我們開發的ap是如何來使用這個default heap呢? 可透過下面的三個api來使用GlobalAlloc 或 LocalAlloc 或GetProcessHeap來使用。事實上這個heap還再細分為fixed和movable二種。一般我們都是使用fixed。而vc++的malloc等c run time就是用這個default heap。這個default heap的大小限制為何? 這是一個很重要的題目,我們下個主題講。另一種heap稱為 dynamic heap,這個heap就全然是我們的ap自由使用的地方。它和default heap有個不同? dynamic heap 全都是自己程式用,沒有別的api使用,另外還有一個重要的地方是這個heap可以控制多緒(multithread)同步共享heap的管理。可由HeapCreate等相關api還有VirtualXxx api來建立。bcb本身的malloc等c run time 聽說是使用這種heap,與vc++有所不同。
5/heap size(一): 這是一個很重要的題目。到底 heap size的限制為何? 答案是… 無論是dynamic 或是 defualt heap都是限制在定址能力上,即以windwos來說,就是2G。但是奇怪了,project option的linker選項中有提到一個heap size的地方,就像stack也在那設定一樣。而這個選項裡的最大值一樣只能到0x1000000,即16MB左右。而實際上許多人都曾在程式中要求超過百mb以上的heap,怎都沒事?? 而這個設定值有啥用? 答案是 : 所謂的min size的值是指commit的值,max size是reserve的值。commit / reserve這二個詞在windows api 與vc++中常用。我大概講一下…所謂的reserve是指程式可以「要求註冊」保留虛擬位址的大小。請注意是「虛擬位址」,比個喻,就像是先向政府預定門牌號1-100號都將是我家所用,但還沒建好房子。而commit size則是每次我建房子都是以幾個門牌為單位建立,比如說,commit=4,即表每次都以4間房子來建,直到100個門牌都用完。所有windows的記憶管理都是用reserve/commit的方式在處理。都是先要求將有多少位址會用到,然後等實值用到時再依commit的大小來一單位一單位的分配實值記憶體給你用。
6/ heap size (二) : 之前有提到像vc++ 的malloc都是用heap。最早我說它的限制是2G,但剛在上面又說linker設定上只能最大是16mb,若真的是16mb,那malloc早就應該overflow n次了,很茅盾! 事實上… heap的大小是真的限制在2G,即使用都不去改option中的值,它還是2G。哇~~那那設定是假的? 不…那設定正確講是為了效能。怎說呢? 雖然最大可使用是2G,但windows並非一開始就拿2G等著你用。它是在需要的時候先行要求位址(門牌),在一一的配給你。在option上設定就好比你打電話去餐聽先定位,先定個15個位子(reserve size),並且向服務生說我們會分批進去,而每批都是3個人為單位(commit size)。服務人員想講完電話後想…我們這個時間的生意這麼好,若事先就空著15個位子,那就少賺了…於是先空3個位子,反正每一批都是3人來。於是第一批到後,餐廳再空3人位子出來等,直到15人都到了! 這種預先定位的好處就是你進去餐廳後不必多廢話,進去就入座! 很有效能!
7/ heap size(三): 把剛的比喻故事延申下去…萬一我臨時又有6個朋友也要一起去吃飯,而我剛只定了15位,餐廳能否再開6位給我呢? 當然沒問題! 只是餐聽的人員說,你要稍等一下,等我再補登記新人數後再配位子入座! 所以事實上defult heap 非靜態的只到你reserve的大小就停了,它可以再自動的變大,只是需要一點時間和資源。記住! 是可以到2G沒問題的! 而從這比喻中你應該可以了解,若是開始的時候我們就正確的預定好人數,就不會多花一點時間補登記。反過來說,即使亂預定也沒關係,都還是有位子可以座,只是要多補n次的登記時間!
8/ 何時該使用default heap,何時用dynamic heap? 這問題其實不是很重要,為了portable,用malloc/ new來處理就好,compiler會選用其中一種來處理。除了在開發multithead的程式時,當你不希望主thread中的heap被二個以上的thead同時存取,你可以用dynamic heap來建立,即用HeapCreate( )的預設建立方法。當然你也可以用這個function建立出一般的fixed的heap,只要將參數1改為HEAP_NO_SERIALIZE,就可以!
9/ 補一下commit值的重要性,若每次你new的東西是很大的,而你把commit值又設很小,那麼每new一次就要補手續n次。比如說每次要new 40k 的資料,但你commit只設4k,那…new一次就配置手續10次。當然,若你說把commit設成100k,那麼一次就搞定,但…也有個小缺點 : 剩下的配給你的真實的60k浪費在那裡了。給別的process用那60k不好嗎? 所以…設成40-50k是不是比較折衷的好設定呢?!
轉貼作者: 蕭沖 qs.xiao@gmail.com
http://delphi.ktop.com.tw/board.php?cid=168&fid=912&tid=83727
2/虛擬記憶體: 在80386處理器後,cup support 保護模式,paging 模式。我們都知道windows會使用硬碟來充當ram使用,當ram不足的時候。這就是用paging的cpu功能。有了這個功能,os就可以讓每個process都可以使用2G的data,即使ram只有幾MB。在標題1我們有提到「定址」的這個詞,這只是說cpu的register(暫存器)有能力讓我們定出那麼大的空間。但是可以定出那麼大麼大的空間並不表示你一定先要有那麼大的ram在電腦上。定址是一回事,配置(allocate)又是另一回事,但二者都很重要。比如在dos 80286前的時代,有所謂的640k的限制(那是指定址能力先天不足),所以你就算是買了4MB的ram插在電腦上,還是浪費。回到主題,因為386以後有paging的能力,加上register是32位元,所以就組合出一種相當完美的記憶體管理方法: 每個process都有虛擬的4G記憶體,且可以真的使用到4G,即使你的ram沒有4G,windows會把你的虛擬記憶體資料放到硬碟上。為何說是「虛擬」?就是指你不一定真的有那麼多的真實的ram。比如說你真實的ram有128MB,而你的程式超大,用到512MB,那麼當程式在跑的時候,只會把正需要的code往128MB的ram上放,而把尚不用的放(paging)在硬碟上。
3/ stack: 何謂stack? 是用來放function上auto級的變數(這樣的說法較專業),所謂auto級的就是變數是宣告在function內,它的生命(life time/ extent)在function結束後就無效了! stack的大小是由 linker來決定,以bcb為例,最大可以到0x1000000,即約16MB,你可以在project option上改。由多程式人員喜歡把object放在stack上,即用下面的宣告方式
ClassT object; 這樣整個object的資料都會配在stack上,若class小還好,大則容易overflow。故一般建議用new的方式來create objcet,只留下4byte的指標在stack上。又如這些天許多玩matalab的人問到2維array overflow的問題,也是因為把array宣告在stack上所造成。要解決的方式還是一樣,把它用new的方式create到heap上(稍後會講)。但二維的動態產生array需要一些技巧,可查一下我的文章。還有,使用recursive function的人也要特別注意overfolw的問題。必要的話可以改寫演算法不要用遞回。stack的使用很方便,因為不用僅管使用,無需去自行清理,唯不要overflow就很棒!
4/ heap: 是用來動態使用記憶體的方式,使用的自由度最高,但需要自行善後清理。通常是用malloc/free或是new/delete來處理。heap在windows下可以分為二種,1為default heap2為dynamic heap。default heap 可以是windows dll 等api使用,也可以app自己使用。我們開發的ap是如何來使用這個default heap呢? 可透過下面的三個api來使用GlobalAlloc 或 LocalAlloc 或GetProcessHeap來使用。事實上這個heap還再細分為fixed和movable二種。一般我們都是使用fixed。而vc++的malloc等c run time就是用這個default heap。這個default heap的大小限制為何? 這是一個很重要的題目,我們下個主題講。另一種heap稱為 dynamic heap,這個heap就全然是我們的ap自由使用的地方。它和default heap有個不同? dynamic heap 全都是自己程式用,沒有別的api使用,另外還有一個重要的地方是這個heap可以控制多緒(multithread)同步共享heap的管理。可由HeapCreate等相關api還有VirtualXxx api來建立。bcb本身的malloc等c run time 聽說是使用這種heap,與vc++有所不同。
5/heap size(一): 這是一個很重要的題目。到底 heap size的限制為何? 答案是… 無論是dynamic 或是 defualt heap都是限制在定址能力上,即以windwos來說,就是2G。但是奇怪了,project option的linker選項中有提到一個heap size的地方,就像stack也在那設定一樣。而這個選項裡的最大值一樣只能到0x1000000,即16MB左右。而實際上許多人都曾在程式中要求超過百mb以上的heap,怎都沒事?? 而這個設定值有啥用? 答案是 : 所謂的min size的值是指commit的值,max size是reserve的值。commit / reserve這二個詞在windows api 與vc++中常用。我大概講一下…所謂的reserve是指程式可以「要求註冊」保留虛擬位址的大小。請注意是「虛擬位址」,比個喻,就像是先向政府預定門牌號1-100號都將是我家所用,但還沒建好房子。而commit size則是每次我建房子都是以幾個門牌為單位建立,比如說,commit=4,即表每次都以4間房子來建,直到100個門牌都用完。所有windows的記憶管理都是用reserve/commit的方式在處理。都是先要求將有多少位址會用到,然後等實值用到時再依commit的大小來一單位一單位的分配實值記憶體給你用。
6/ heap size (二) : 之前有提到像vc++ 的malloc都是用heap。最早我說它的限制是2G,但剛在上面又說linker設定上只能最大是16mb,若真的是16mb,那malloc早就應該overflow n次了,很茅盾! 事實上… heap的大小是真的限制在2G,即使用都不去改option中的值,它還是2G。哇~~那那設定是假的? 不…那設定正確講是為了效能。怎說呢? 雖然最大可使用是2G,但windows並非一開始就拿2G等著你用。它是在需要的時候先行要求位址(門牌),在一一的配給你。在option上設定就好比你打電話去餐聽先定位,先定個15個位子(reserve size),並且向服務生說我們會分批進去,而每批都是3個人為單位(commit size)。服務人員想講完電話後想…我們這個時間的生意這麼好,若事先就空著15個位子,那就少賺了…於是先空3個位子,反正每一批都是3人來。於是第一批到後,餐廳再空3人位子出來等,直到15人都到了! 這種預先定位的好處就是你進去餐廳後不必多廢話,進去就入座! 很有效能!
7/ heap size(三): 把剛的比喻故事延申下去…萬一我臨時又有6個朋友也要一起去吃飯,而我剛只定了15位,餐廳能否再開6位給我呢? 當然沒問題! 只是餐聽的人員說,你要稍等一下,等我再補登記新人數後再配位子入座! 所以事實上defult heap 非靜態的只到你reserve的大小就停了,它可以再自動的變大,只是需要一點時間和資源。記住! 是可以到2G沒問題的! 而從這比喻中你應該可以了解,若是開始的時候我們就正確的預定好人數,就不會多花一點時間補登記。反過來說,即使亂預定也沒關係,都還是有位子可以座,只是要多補n次的登記時間!
8/ 何時該使用default heap,何時用dynamic heap? 這問題其實不是很重要,為了portable,用malloc/ new來處理就好,compiler會選用其中一種來處理。除了在開發multithead的程式時,當你不希望主thread中的heap被二個以上的thead同時存取,你可以用dynamic heap來建立,即用HeapCreate( )的預設建立方法。當然你也可以用這個function建立出一般的fixed的heap,只要將參數1改為HEAP_NO_SERIALIZE,就可以!
9/ 補一下commit值的重要性,若每次你new的東西是很大的,而你把commit值又設很小,那麼每new一次就要補手續n次。比如說每次要new 40k 的資料,但你commit只設4k,那…new一次就配置手續10次。當然,若你說把commit設成100k,那麼一次就搞定,但…也有個小缺點 : 剩下的配給你的真實的60k浪費在那裡了。給別的process用那60k不好嗎? 所以…設成40-50k是不是比較折衷的好設定呢?!
轉貼作者: 蕭沖 qs.xiao@gmail.com
http://delphi.ktop.com.tw/board.php?cid=168&fid=912&tid=83727
有關.net的垃圾文章回收機制Garbage Collection(GC)
Reference:[NET framework]一些有關Garbage Collection(GC)的資料
星期一, 12月 21, 2009
Webclient Using Python
Http GET
Http Request
>>> import httplib
>>> conn = httplib.HTTPConnection("www.python.org")
>>> conn.request("GET", "/index.html")
>>> r1 = conn.getresponse()
>>> print r1.status, r1.reason
200 OK
>>> data1 = r1.read()
>>> conn.request("GET", "/parrot.spam")
>>> r2 = conn.getresponse()
>>> print r2.status, r2.reason
404 Not Found
>>> data2 = r2.read()
>>> conn.close()
Http Request
>>> import httplib, urllib
>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>>> headers = {"Content-type": "application/x-www-form-urlencoded",
... "Accept": "text/plain"}
>>> conn = httplib.HTTPConnection("musi-cal.mojam.com:80")
>>> conn.request("POST", "/cgi-bin/query", params, headers)
>>> response = conn.getresponse()
>>> print response.status, response.reason
200 OK
>>> data = response.read()
>>> conn.close()
星期四, 12月 17, 2009
Sql In
使用Sql In 找出自已好友所建立的事件列表
SELECT UserDataUniversitySchool, UserDataDepartment, UserDataSex, UserDataPhoto, EventDataName, EventDataEstablishDate, EventDataAssemblePosition, EventDataID, EventDataUID, UserDataNickName FROM dbo.vw_EventDataTimeLine WHERE (EventDataUID IN (SELECT UserFriendsAddUID FROM dbo.vw_FriendsShipDetail WHERE (UserFriendsUID = @uid) AND (UserFriendsIsConfirm = 1)))
星期三, 12月 16, 2009
C# 取得目前時間為星期幾
DateTime.DayOfWeek 屬性
DayOfWeek 列舉的常數,表示一週天數。
這個屬性值的範圍從 0 開始 (表示星期日) 到 6 (表示星期六)
DayOfWeek 列舉的常數,表示一週天數。
這個屬性值的範圍從 0 開始 (表示星期日) 到 6 (表示星期六)
DateTime dt = new DateTime(2009, 12, 17);
string tmp = dt.DayOfWeek.ToString();//tmp = Thursday
string tmp2 = dt.DayOfWeek.ToString("d");//tmp2 = 4
星期二, 12月 15, 2009
Backup System Using tar
backup:
cd /mnt/linux && tar -jcvf /mnt/bak/linux.tar.bz2 *
restore:
tar -jxvpf /mnt/bak/linux.tar.bz2 -C /mnt/linux
/mnt/linux 備份目錄
星期一, 12月 14, 2009
PHP XML Receive
<?xml version="1.0" encoding="UTF-8"?>
<inventory>
<book>
<author>Nick Chase</author>
<title>XML Primer Plus</title>
<publisher>Sams</publisher>
</book>
<book>
<author>Earth</author>
<title>David Brin</title>
<publisher>Spectra</publisher>
</book>
<movie>
<director>Steven Spielberg</director>
<title>Raiders of the Lost Ark</title>
<actor>Harrison Ford</actor>
<actor>Karen Allen</actor>
</movie>
<movie>
<director>Rob Reiner</director>
<title>The American President</title>
<actor>Michael Douglas</actor>
<actor>Annette Bening</actor>
<actor>Martin Sheen</actor>
</movie>
</inventory>
if (!isset($HTTP_RAW_POST_DATA))
$HTTP_RAW_POST_DATA = file_get_contents("php://input");
header("Content-type: text/plain");
echo $HTTP_RAW_POST_DATA;
?>
if (!isset($HTTP_RAW_POST_DATA))
$HTTP_RAW_POST_DATA = file_get_contents("php://input");
$doc = new DOMDocument();
$doc->loadXML($HTTP_RAW_POST_DATA);
$allBooks = $doc->getElementsByTagName('book');
$numBooks = $allBooks->length;
$allMovies = $doc->getElementsByTagName('movie');
$numMovies = $allMovies->length;
echo "There are ".$numBooks." books and ".$numMovies." movies.";
?>
acer Ferrari 1100 wifi setting
1. 安裝 ndiswrapper
2. 安裝 bcmwl5.inf
3.
sudo modprobe -r b43 b44 ssb wl
sudo modprobe wl
sudo modprobe b44
sudo /etc/init.d/networking restart
sudo iwlist scan
2. 安裝 bcmwl5.inf
3.
sudo modprobe -r b43 b44 ssb wl
sudo modprobe wl
sudo modprobe b44
sudo /etc/init.d/networking restart
sudo iwlist scan
星期六, 12月 12, 2009
FCKEditor Asp.net
原本使用.net ajaxcontroltoolkit內的editor元件,
由於頁面會載入太多東西,簡單來說就是太肥,
於是找了網上大家最常用的FCKEditor,還有一些優化方法。
可參考以下二篇教學
Reference:
FCKeditor 超強html線上編輯器應用於ASP.NET
ASP Fckeditor 優化技巧教學
由於頁面會載入太多東西,簡單來說就是太肥,
於是找了網上大家最常用的FCKEditor,還有一些優化方法。
可參考以下二篇教學
Reference:
FCKeditor 超強html線上編輯器應用於ASP.NET
ASP Fckeditor 優化技巧教學
星期三, 12月 09, 2009
用PHP 做HTTP Request
$fields = array(
'__VIEWSTATE'=>'0IZf2tvjZxs7aeq7Tx7mFkZBB62iWgsCq3zbL%2BTnYZZ%2FXfeXgvDJNEEd3b3Z7COD',
'__EVENTVALIDATION'=>'YAJy6SEjjCbcu4df21JN%2BhAtGvApqKxJhDeS%2FE5s24EVBRHYEIqypa9hS%2BdTo%2FS%2F%2By8GO8Zu%2FS0%3D',
'Login1%24UserName'=>urlencode($StuNo),
'Login1%24Password'=>urlencode($StuPwd),
'Login1%24LoginButton'=>'%E7%99%BB%E5%85%A5'
);//POST的東西
foreach($fields as $key=>$value)
{
$fields_string .= $key.'='.$value;
if(sizeof($fields)-1!=$count)
$fields_string.="&";
}//組成POST STRING
$curl = curl_init("YOUR REQUEST URL");
$ckfile = tempnam ("/tmp", "CURLCOOKIE");//建立Cookie文件
curl_setopt($ch, CURLOPT_COOKIEJAR, "./cookie.txt");//寫入指定的Cookie
curl_setopt($curl, CURLOPT_POST, 1);//post資料給指定網頁
curl_setopt($curl, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-TW; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5");//UserAgent
$Result = curl_exec($curl);//Html String
curl_close($curl);
星期日, 12月 06, 2009
使用mysqldump
mysqldump最常見的用法是:
shell>; mysqldump --opt -u user --password="password" db_name >; backup-file.sql
或者壓縮備份文件:
#mysqldump --opt -u user --password="password" database | bzip2 -c >; database.sql.bz2
在dbname已經存在的情況下,讀入備份文件恢復數據庫,
shell>; mysql db_name < backup-file.sql (備註:建議使用--database選項)
或者
shell>; mysql -e "source /path-to-backup/backup-file.sql" db_name
mysqldump 還可以用於在兩個mysql server之間複製數據:
shell>; mysqldump --opt db_name | mysql --host=remote_host -C db_name
也可以同時備份多個數據庫:
shell>; mysqldump --databases db_name1 [db_name2 ...] >; my_databases.sql
如果想一次備份整個數據庫使用 --all-databases 選項:
shell>; mysqldump --all-databases >; all_databases.sql
常見選項:
--add-drop-table:添加DROP TABLE語句
--add-locks:用LOCK TABLES 和 UNLOCK TABLES 語句封裝插入每個表格的語句,能加速數據導入速度
--all-databases, -A: 備份所有數據庫
--compress, -C:用於在兩個server之間複製時壓縮數據
--databases, -B: 用於備份多個數據庫,如果沒有該選項,mysqldump 把第一個名字參數作為數據庫名,後面的作為表名。使用該選項,mysqldum把每個名字都當作為數據庫名。CREATE DATABASE IF NOT EXISTS db_name and USE db_name 會被添加到導出文件裡。
--force, -f:即使發現sql錯誤,仍然繼續備份
--host=host_name, -h host_name:備份主機名,默認為localhost
--no-data, -d:只導出表結構
--opt:等同於激活--add-drop-table --add-locks --create-options --disable-keys --extended-insert --lock-tables --quick --set-charset這些選項
--password[=password], -p[password]:密碼
--port=port_num, -P port_num:制定TCP/IP連接時的端口號
--protocol={TCP | SOCKET | PIPE | MEMORY}:制定連接所用的協議
--quick, -q:快速導出
--socket=path, -S path:當連接至localhost時,制定socket文件
--tables:覆蓋 --databases or -B選項,後面所跟參數被視作表名
--user=user_name, -u user_name:用戶名
--xml, -X:導出為xml文件
shell>; mysqldump --opt -u user --password="password" db_name >; backup-file.sql
或者壓縮備份文件:
#mysqldump --opt -u user --password="password" database | bzip2 -c >; database.sql.bz2
在dbname已經存在的情況下,讀入備份文件恢復數據庫,
shell>; mysql db_name < backup-file.sql (備註:建議使用--database選項)
或者
shell>; mysql -e "source /path-to-backup/backup-file.sql" db_name
mysqldump 還可以用於在兩個mysql server之間複製數據:
shell>; mysqldump --opt db_name | mysql --host=remote_host -C db_name
也可以同時備份多個數據庫:
shell>; mysqldump --databases db_name1 [db_name2 ...] >; my_databases.sql
如果想一次備份整個數據庫使用 --all-databases 選項:
shell>; mysqldump --all-databases >; all_databases.sql
常見選項:
--add-drop-table:添加DROP TABLE語句
--add-locks:用LOCK TABLES 和 UNLOCK TABLES 語句封裝插入每個表格的語句,能加速數據導入速度
--all-databases, -A: 備份所有數據庫
--compress, -C:用於在兩個server之間複製時壓縮數據
--databases, -B: 用於備份多個數據庫,如果沒有該選項,mysqldump 把第一個名字參數作為數據庫名,後面的作為表名。使用該選項,mysqldum把每個名字都當作為數據庫名。CREATE DATABASE IF NOT EXISTS db_name and USE db_name 會被添加到導出文件裡。
--force, -f:即使發現sql錯誤,仍然繼續備份
--host=host_name, -h host_name:備份主機名,默認為localhost
--no-data, -d:只導出表結構
--opt:等同於激活--add-drop-table --add-locks --create-options --disable-keys --extended-insert --lock-tables --quick --set-charset這些選項
--password[=password], -p[password]:密碼
--port=port_num, -P port_num:制定TCP/IP連接時的端口號
--protocol={TCP | SOCKET | PIPE | MEMORY}:制定連接所用的協議
--quick, -q:快速導出
--socket=path, -S path:當連接至localhost時,制定socket文件
--tables:覆蓋 --databases or -B選項,後面所跟參數被視作表名
--user=user_name, -u user_name:用戶名
--xml, -X:導出為xml文件
[Asp.Net] master page 事件處理順序
1.主版頁面控制項 Init 事件。
2.內容控制項 Init 事件。
3.主版頁面 Init 事件。
4.內容頁面 Init 事件。
7.內容控制項 Load 事件。
8.內容頁面 PreRender 事件。
9.主版頁面 PreRender 事件。
10.主版頁面控制項 PreRender 事件。
11.內容控制項 PreRender 事件。
2.內容控制項 Init 事件。
3.主版頁面 Init 事件。
4.內容頁面 Init 事件。
5.內容頁面 Load 事件。
6.主版頁面 Load 事件。
6.主版頁面 Load 事件。
7.內容控制項 Load 事件。
8.內容頁面 PreRender 事件。
9.主版頁面 PreRender 事件。
10.主版頁面控制項 PreRender 事件。
11.內容控制項 PreRender 事件。
處理查詢運算式中的例外狀況
class ExceptionsOutsideQuery
{
static void Main()
{
// DO THIS with a datasource that might
// throw an exception. It is easier to deal with
// outside of the query expression.
IEnumerable<int> dataSource;
try
{
dataSource = GetData();
}
catch (InvalidOperationException)
{
// Handle (or don't handle) the exception
// in the way that is appropriate for your application.
Console.WriteLine("Invalid operation");
goto Exit;
}
// If we get here, it is safe to proceed.
var query = from i in dataSource
select i * i;
foreach (var i in query)
Console.WriteLine(i.ToString());
//Keep the console window open in debug mode
Exit:
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
// A data source that is very likely to throw an exception!
static IEnumerable<int> GetData()
{
throw new InvalidOperationException();
}
}
LINQ 查詢運算式
class LINQQueryExpressions
{
static void Main()
{
// Specify the data source.
int[] scores = new int[] { 97, 92, 81, 60 };
// Define the query expression.
IEnumerable<int> scoreQuery =
from score in scores
where score > 80
select score;
// Execute the query.
foreach (int i in scoreQuery)
{
Console.Write(i + " ");
}
}
}
Using LINQ To Create Custom Datatable And Travel Table
IEnumerable<DataRow> SubenumTable =
from goodTable in dt.AsEnumerable()
where goodTable.Field<string>("TravelRegion") == row.col1.ToString()
select goodTable;
//sr.Append(row.col1.ToString()+"<br>");
foreach (DataRow goodsrow in SubenumTable)
{
SiteNode Subn1 = new SiteNode();
Subn1.ParentID = count.ToString();
Subn1.ID = goodsrow["TravelID"].ToString();
Subn1.Title = goodsrow["TravelAttractions"].ToString();
Subn1.Pos = goodsrow["TravelLat"].ToString() + "," + goodsrow["TravelLng"].ToString();
nodes.Add(Subn1);
}
使用 LINQ 擷取 dataTable 部份列數的寫法
IEnumerable<DataRow> source = dt.AsEnumerable().Take((this.page) * pageSize);
Creating a Custom CopyToDataTable Method
// Fill the DataSet.
DataSet ds = new DataSet();
ds.Locale = CultureInfo.InvariantCulture;
FillDataSet(ds);
DataTable orders = ds.Tables["SalesOrderHeader"];
DataTable details = ds.Tables["SalesOrderDetail"];
var query =
from order in orders.AsEnumerable()
join detail in details.AsEnumerable()
on order.Field<int>("SalesOrderID") equals
detail.Field<int>("SalesOrderID")
where order.Field<bool>("OnlineOrderFlag") == true
&& order.Field<DateTime>("OrderDate").Month == 8
select new
{
SalesOrderID =
order.Field<int>("SalesOrderID"),
SalesOrderDetailID =
detail.Field<int>("SalesOrderDetailID"),
OrderDate =
order.Field<DateTime>("OrderDate"),
ProductID =
detail.Field<int>("ProductID")
};
DataTable orderTable = query.CopyToDataTable();
Creating a DataTable From a Query
dataGridView.DataSource = bindingSource;
// Fill the DataSet.
DataSet ds = new DataSet();
ds.Locale = CultureInfo.InvariantCulture;
FillDataSet(ds);
DataTable orders = ds.Tables["SalesOrderHeader"];
// Query the SalesOrderHeader table for orders placed
// after August 8, 2001.
IEnumerable<DataRow> query =
from order in orders.AsEnumerable()
where order.Field<DateTime>("OrderDate") > new DateTime(2001, 8, 1)
select order;
// Create a table from the query.
DataTable boundTable = query.CopyToDataTable<DataRow>();
// Bind the table to a System.Windows.Forms.BindingSource object,
// which acts as a proxy for a System.Windows.Forms.DataGridView object.
bindingSource.DataSource = boundTable;
星期四, 12月 03, 2009
mstsc 指令
mstsc /console 會連到session 0
意即跟遠端電腦同一個畫面,
不會新開一個登入帳號,
但windows server 都會新開一個session。
改用mstsc /admin即可連到session 0
PS:mstsc 開啟遠端連線,連xp與vista都也是連session 0
意即跟遠端電腦同一個畫面,
不會新開一個登入帳號,
但windows server 都會新開一個session。
改用mstsc /admin即可連到session 0
PS:mstsc 開啟遠端連線,連xp與vista都也是連session 0
PHP XML Build
<?php
$doc = new DOMDocument('1.0', 'UTF-8');
$root = $doc->createElement('songs');
$doc->appendChild($root);
for($i=0;$i<10;$i++){
$root_child = $doc->createElement('song');
$root->appendChild($root_child);
$root_attr1 = $doc->createAttribute('url');
$root_child->appendChild($root_attr1);
$root_text = $doc->createTextNode('This is the root element!');
$root_attr1->appendChild($root_text);
$root_attr2= $doc->createAttribute('artist');
$root_child->appendChild($root_attr2);
$root_text = $doc->createTextNode('This is the root element!');
$root_attr2->appendChild($root_text);
$root_attr3 = $doc->createAttribute('track');
$root_child->appendChild($root_attr3);
$root_text = $doc->createTextNode('This is the root element!');
$root_attr3->appendChild($root_text);
}
print $doc->saveXML();
?>
星期三, 12月 02, 2009
C# 取得本機ip
string strHostIP = "";
IPHostEntry oIPHost = Dns.GetHostEntry(Environment.MachineName);
if (oIPHost.AddressList.Length > 0)
{
strHostIP = oIPHost.AddressList[0].ToString();
}
IPHostEntry oIPHost = Dns.GetHostEntry(Environment.MachineName);
if (oIPHost.AddressList.Length > 0)
{
strHostIP = oIPHost.AddressList[0].ToString();
}
Asp.net Regex.Matches
在parser html時使用正則表示式當然是最方便不過了,
如果再加上groups使用就便方便!!,用括號來分割你要的group
html content :
<span id="ctl00_ContentPlaceHolder1_ctl00_FormView1_preschoolLabel">市立中正高工</span>
註:\s+表示空白間隔
如果再加上groups使用就便方便!!,用括號來分割你要的group
html content :
<span id="ctl00_ContentPlaceHolder1_ctl00_FormView1_preschoolLabel">市立中正高工</span>
註:\s+表示空白間隔
Mathc = Regex.Matches(profileHtml, "<span\\s+id=\"(ctl00_ContentPlaceHolder1_ctl00_FormView1.*)\">(.*)</span>");
for (int i = 0; i < Mathc.Count; i++)
{
//get regex group
string g1 = Mathc[i].Groups[1].Value;
//ctl00_ContentPlaceHolder1_ctl00_FormView1_preschoolLabel
string g2 = Mathc[i].Groups[2].Value;
//市立中正高工
}
星期二, 12月 01, 2009
[jQuery API] div 左右分割長短腳的問題
#divContainer
{
float:left;
width:400px;
height:auto;
overflow:inherit;
}
#divLeft
{
width:200px; float:left;
}
#divRight
{
width:200px; float:right;
}
$("#divRight , #divLeft").css("height", Math.max($("#divRight ").height(), $("#divLeft").height()));
Reference:
網頁教學-解決Div排版長短腳的問題
uploadify session null
uploadify flash 本身上傳自己的 session 和 browser 不會共用,
: 就連 user agnet 名稱也不同,所以會有登入驗證失敗的問題。
: 這部份的解法不會太難:
: 1. 新增一個資料表裡面有一個 hashkey 對應 user_id, album_id 之類的欄位
: 2. 每次上傳的時候,先新增一個 hashkey, user_id 及其它你需要的資料
: 3. 當上傳的時候,取回剛剛新增的 hashkey 一併然後 post 到妳的 controller 裡面
: 4. 根據 hashkey 去找 user_id..等等,加上上傳的照片路徑(或照片),插入新資料
: 5. 上傳完畢。
: 這是一個簡單的解法,很有用。
Reference[分享]CakePHP+uploadify => Ajax uploader
: 就連 user agnet 名稱也不同,所以會有登入驗證失敗的問題。
: 這部份的解法不會太難:
: 1. 新增一個資料表裡面有一個 hashkey 對應 user_id, album_id 之類的欄位
: 2. 每次上傳的時候,先新增一個 hashkey, user_id 及其它你需要的資料
: 3. 當上傳的時候,取回剛剛新增的 hashkey 一併然後 post 到妳的 controller 裡面
: 4. 根據 hashkey 去找 user_id..等等,加上上傳的照片路徑(或照片),插入新資料
: 5. 上傳完畢。
: 這是一個簡單的解法,很有用。
Reference[分享]CakePHP+uploadify => Ajax uploader
星期日, 11月 29, 2009
[Asp.net] 在content page擷取master page的事件
在content page 新建master page 控制項事件(這範例是button),原文內以下內容需注意:
Reference:
Capture Master Page Events in Content Pages - ASP.NET 2.0
@ MasterType 指示詞
- TypeName:為主版頁面指定類型名稱。
VirtualPath:指定產生強型別之檔案的路徑。
Reference:
Capture Master Page Events in Content Pages - ASP.NET 2.0
@ MasterType 指示詞
星期五, 11月 27, 2009
asp.net 使用多個以上的sitemap
由於使用sitemap可以快速建立menu選單,
又可以加上securityTrimmingEnabled="true"來依成員角色顯示不同的選單,
但是用了這個安全機制又會讓網站的選單空空的,
所以就不加上這個屬性,
改用二個sitemap檔案來自動切換(二個sitemap的節點數不一樣)
以下是web.config
由於管理者與未登入及登入會員的頁面都是使用不同的master page,
於是就新增一個繼承System.Web.UI.MasterPage的 BaseMaster物件
接著在網站內master加入以下code,
透過 this.SiteMapDataSource1.SiteMapProvider切換不同的SiteMapProvider
又可以加上securityTrimmingEnabled="true"來依成員角色顯示不同的選單,
但是用了這個安全機制又會讓網站的選單空空的,
所以就不加上這個屬性,
改用二個sitemap檔案來自動切換(二個sitemap的節點數不一樣)
以下是web.config
<!--
sitemap角色權限讀取 securityTrimmingEnabled="true"
-->
<siteMap defaultProvider="XmlSiteMapProvider" enabled="true">
<providers>
<add name="XmlSiteMapProvider" description="未登入與登入"
type="System.Web.XmlSiteMapProvider,System.Web,Version=2.0.3600.0, Culture= neutral,PublicKeyToken=b03f5f7f11d50a3a"
siteMapFile="common-map.sitemap" securityTrimmingEnabled="false" />
<add name="XmlSiteMapProviderForAdmin" description="登入管理員"
type="System.Web.XmlSiteMapProvider,System.Web,Version=2.0.3600.0, Culture= neutral,PublicKeyToken=b03f5f7f11d50a3a"
siteMapFile="admin-map.sitemap" securityTrimmingEnabled="false" />
</providers>
</siteMap>
由於管理者與未登入及登入會員的頁面都是使用不同的master page,
於是就新增一個繼承System.Web.UI.MasterPage的 BaseMaster物件
///
/// BaseMaster 的摘要描述
///
public class BaseMaster : System.Web.UI.MasterPage
{
public BaseMaster()
{
//
// TODO: 在此加入建構函式的程式碼
//
}
///
/// 切換不同的sitemap
///
///
///
public string SitemapHelper(string username)
{
string provider = "XmlSiteMapProvider";
string[] roleTmp = System.Web.Security.Roles.GetRolesForUser(username);
for (int i = 0; i < roleTmp.Length; i++)
{
if (roleTmp[i] == "Admin")
{
provider = "XmlSiteMapProviderForAdmin";
break;
}
}
return provider;
}
}
接著在網站內master加入以下code,
透過 this.SiteMapDataSource1.SiteMapProvider切換不同的SiteMapProvider
public partial class guest_mp : BaseMaster
{
protected void Page_Load(object sender, EventArgs e)
{
if (this.Page.User.Identity.IsAuthenticated)
{
if (!IsPostBack)
{
this.SiteMapDataSource1.SiteMapProvider = this.SitemapHelper(this.Page.User.Identity.Name);
}
}
}
}
星期四, 11月 26, 2009
星期一, 11月 23, 2009
C# WebClient Post
使用webclient來做post,
很方便使用。
要能正確取得post的結果,
就要看各個網站的驗證的方法如何了。
方法如下:
如果又要讓Session能夠保存的話,
可參考這篇的做法:
C# 實現Webclient保持Session的方法
很方便使用。
要能正確取得post的結果,
就要看各個網站的驗證的方法如何了。
方法如下:
System.Net.WebClient wc = new System.Net.WebClient();
string url = "http://www.thsrc.com.tw/tc/ticket/tic_time_result.asp";
string postData = "rom=1&to=5&sDate=2009%2F11%2F23&TimeTable=21%3A00&FromOrDest=From&x=33&y=10";
wc.Encoding = Encoding.UTF8;
byte[] sendData = Encoding.GetEncoding("utf-8").GetBytes(postData.ToString());
wc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-TW; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5");
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
wc.Headers.Add("Referer", "http://www.thsrc.com.tw/tc/index.asp");
byte[] recData = wc.UploadData(url, "POST", sendData);
string tmp = Encoding.UTF8.GetString(recData);
如果又要讓Session能夠保存的話,
可參考這篇的做法:
C# 實現Webclient保持Session的方法
Shell.Applicatio Using C#
1,直接添加引用 %windir%\system32\Shell32.dll
Shell32.ShellClass sc = new Shell32.ShellClass();
sc.FileRun();
2,不用添加任何引用直接用反射 C#
//通过 ProgID 取得 com 对象类型
Type tShell =Type.GetTypeFromProgID("Shell.Application");
//实列对象
object oShell = Activator.CreateInstance(tShell);
//反射调用
tShell.InvokeMember("FileRun"
, BindingFlags.InvokeMethod | BindingFlags.Default
, null
, oShell
, null //如果有参数在这里 new object[]{参数一,参数二,参数三,....}
);
//释放对象
System.Runtime.InteropServices.Marshal.ReleaseComObject(oShell);
上面二個方式都可以實作,
不過比較起來的話,第一種的方法比較容易撰寫,
瞬間跟CCN大師請教一下就有了結果,
不過是神之手,不過還是記錄一下,避免忘記
以下是利用shell32控制網路連線自動連線方法,
不過只適用32位元以及繁體中文os,自已用的小工具就不考慮太多了XD,
用個timer就可以一直監控了!!
PS:記得加入參考 COM->Microsoft Shell Controls And Automation(SHELL32.dll)
以下是G大神提供的資料~
Reference:
C#调用dll文件中的函数的问题
minimizes all windows..
[VB.NET/ C#.Net / VC++.Net] 如何由程式開啟 IE 並進行會員登入
[C#][VB.NET]顯示桌面
C#怎么实现启用和禁用本地网卡?
Shell32.ShellClass sc = new Shell32.ShellClass();
sc.FileRun();
2,不用添加任何引用直接用反射 C#
//通过 ProgID 取得 com 对象类型
Type tShell =Type.GetTypeFromProgID("Shell.Application");
//实列对象
object oShell = Activator.CreateInstance(tShell);
//反射调用
tShell.InvokeMember("FileRun"
, BindingFlags.InvokeMethod | BindingFlags.Default
, null
, oShell
, null //如果有参数在这里 new object[]{参数一,参数二,参数三,....}
);
//释放对象
System.Runtime.InteropServices.Marshal.ReleaseComObject(oShell);
上面二個方式都可以實作,
不過比較起來的話,第一種的方法比較容易撰寫,
瞬間跟CCN大師請教一下就有了結果,
不過是神之手,不過還是記錄一下,避免忘記
以下是利用shell32控制網路連線自動連線方法,
不過只適用32位元以及繁體中文os,自已用的小工具就不考慮太多了XD,
用個timer就可以一直監控了!!
PS:記得加入參考 COM->Microsoft Shell Controls And Automation(SHELL32.dll)
/// <summary>
/// 保持連線
/// </summary>
/// <param name="connectionName">連線的裝置名稱</param>
void KeepConnection(string connectionName)
{
Shell32.ShellClass shell = new ShellClass();
//列出namespace代碼
//for (int i = 0; i < 100; i++)
//{
// if (shell.NameSpace(i) != null)
// this.listBox1.Items.Add("[" + i.ToString() + "]" + shell.NameSpace(i).Title);
//}
Folder applicationObj = shell.NameSpace(3);
//取得控制台清單
foreach (FolderItem fItem in applicationObj.Items())
{
//this.listBox1.Items.Add(fItem.Name);
if (fItem.Name == "網路連線")
{
if (fItem.IsFolder)
{
//這裡的轉換要注意一下
Folder network = (Folder)fItem.GetFolder;
//取得網路連線清單
foreach (FolderItem fItem2 in network.Items())
{
//this.listBox1.Items.Add(fItem2.Name);
if (fItem2.Name == connectionName)
{
//列出該項目右鍵選單
foreach (FolderItemVerb fivb in fItem2.Verbs())
{
//this.listBox1.Items.Add(fivb.Name);
if (fivb.Name.IndexOf("連線") > -1 && fivb.Name.IndexOf("預設") == -1 && fivb.Name.IndexOf("中斷") == -1)
fivb.DoIt();
}
}
}
}
}
}
}
以下是G大神提供的資料~
Reference:
C#调用dll文件中的函数的问题
minimizes all windows..
[VB.NET/ C#.Net / VC++.Net] 如何由程式開啟 IE 並進行會員登入
[C#][VB.NET]顯示桌面
C#怎么实现启用和禁用本地网卡?
星期日, 11月 22, 2009
asp.net using memcache
安裝Memcache
Step1:下載Memcache (memcached for Win32)
Step2:安裝與啟動Memcache
sc create memcached binPath= "C:\memcached-1.2.1-win32\memcached.exe -p 8888 -l 127.0.0.1 -m 512 -d runservice" DisplayName= "memcached server" start= auto depend= TCPIP
相關參數:
Asp.net設定
1.將取得的MemCache用戶端(download)解壓縮內的三個dll加入參考Enyim.Caching.dll, log4net.dll, MemcachedProviders.dll
2.設定web.config內的configsection加入以下tags
3.然後在configuration區塊裡加入下面的詳細設定
*.aspx 範例
檢查物件是否有存在memcache
Telnet 到你的伺服器(ex:telnet 127.0.0.1 ),輸入指令'stats',就可以看到目前memcached的狀態。
curr_items 是目前memcached裡暫存物件的數量。
Reference:
在.NET應用程式裡使用memcached暫存Linq資料
MSDNDataContractSerializer Class
如何用 C# 撰寫序列化(Serialize)與反序列化(Deserialize)
用 C# 撰寫序列化(Serialize)與反序列化(Deserialize) - Part 2
.NET 筆記:序列化
Step1:下載Memcache (memcached for Win32)
Step2:安裝與啟動Memcache
sc create memcached binPath= "C:\memcached-1.2.1-win32\memcached.exe -p 8888 -l 127.0.0.1 -m 512 -d runservice" DisplayName= "memcached server" start= auto depend= TCPIP
相關參數:
Asp.net設定
1.將取得的MemCache用戶端(download)解壓縮內的三個dll加入參考Enyim.Caching.dll, log4net.dll, MemcachedProviders.dll
2.設定web.config內的configsection加入以下tags
在web.config或app.config裡的<configSections>區塊加入下列設定: <section name="cacheProvider" type="MemcachedProviders.Cache.CacheProviderSection, MemcachedProviders" allowDefinition="MachineToApplication" restartOnExternalChanges="true"/> <sectionGroup name="enyim.com"> <section name="memcached" type="Enyim.Caching.Configuration.MemcachedClientSection, Enyim.Caching"/> </sectionGroup> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
3.然後在configuration區塊裡加入下面的詳細設定
<!--Memcatch 詳細設定-->
<cacheProvider defaultProvider="MemcachedCacheProvider">
<providers>
<add name="MemcachedCacheProvider" type="MemcachedProviders.Cache.MemcachedCacheProvider, MemcachedProviders"
keySuffix="_MySuffix_" defaultExpireTime="2000"/>
</providers>
</cacheProvider>
<enyim.com>
<memcached>
<servers>
<!--Memcatch default port 11211-->
<add address="127.0.0.1" port="8888" />
</servers>
<socketPool minPoolSize="10" maxPoolSize="100" connectionTimeout="00:00:10" deadTimeout="00:02:00" />
</memcached>
</enyim.com>
<log4net>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}]- %message%newline" />
</layout>
</appender>
<root>
<priority value="WARN"/>
<appender-ref ref="ConsoleAppender">
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="WARN"/>
<levelMax value="FATAL"/>
</filter>
</appender-ref>
</root>
</log4net>
*.aspx 範例
DataTable dt = (DataTable)MemcachedProviders.Cache.DistCache.Get("SearchKey3");
if (dt == null)
{
Response.Write("without cache");
Module_Command.GetMenuList obj = new Module_Command.GetMenuList(3);
dt = (System.Data.DataTable)obj.Execute();
MemcachedProviders.Cache.DistCache.Add("SearchKey3", dt, TimeSpan.FromSeconds(5));
}
this.GridView1.DataSource = dt;
this.GridView1.DataBind();
檢查物件是否有存在memcache
Telnet 到你的伺服器(ex:telnet 127.0.0.1 ),輸入指令'stats',就可以看到目前memcached的狀態。
curr_items 是目前memcached裡暫存物件的數量。
Reference:
在.NET應用程式裡使用memcached暫存Linq資料
MSDNDataContractSerializer Class
如何用 C# 撰寫序列化(Serialize)與反序列化(Deserialize)
用 C# 撰寫序列化(Serialize)與反序列化(Deserialize) - Part 2
.NET 筆記:序列化
星期三, 11月 18, 2009
jquery get tagname
今天剛好需要retrieve element,
要判斷某一元素時,該元素剛好沒有其他屬性,
只剩tagname可以使用XD,
所以以下是利用jquery取得取得元素的tagname。
回傳的tagName是"大寫"
要判斷某一元素時,該元素剛好沒有其他屬性,
只剩tagname可以使用XD,
所以以下是利用jquery取得取得元素的tagname。
回傳的tagName是"大寫"
$(chirdObj).parent().attr("tagName") == "UL"
星期一, 11月 16, 2009
c# 日期運算 timespan
string lateTime = this.itemsAgent.GetLateTestLog(this.UserID);
DateTime lateDT = DateTime.Parse(lateTime);
//string currentTime = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss");
//日期相減
TimeSpan ts = DateTime.Now.Subtract(lateDT);
int subMin = ts.Minutes;
//日期比較
//DateTime.Compare(t1,t2),回傳一個整數小於0,则t1小於t2,大於0,则t1大於t2, =0,则t1=t2
int compareVal = DateTime.Compare(t1, t2) ;
DateTime lateDT = DateTime.Parse(lateTime);
//string currentTime = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss");
//日期相減
TimeSpan ts = DateTime.Now.Subtract(lateDT);
int subMin = ts.Minutes;
//日期比較
//DateTime.Compare(t1,t2),回傳一個整數小於0,则t1小於t2,大於0,则t1大於t2, =0,则t1=t2
int compareVal = DateTime.Compare(t1, t2) ;
div 內圖片置中(相簿封面效果)
每個網站常用到的div照片封面置中的方法,
我的每張thumb為100*100大小內的等比例縮圖。
所以最外圍的div.albumCover設定110*110大小,
就可以很漂亮的顯示了!!。
我的每張thumb為100*100大小內的等比例縮圖。
所以最外圍的div.albumCover設定110*110大小,
就可以很漂亮的顯示了!!。
#listDiv
{
width:100%;
background:#fff;
padding:10px;
}
#listDiv:after
{
content: ".";
display: block;
clear: both;
height: 0;
overflow: hidden;
visibility: hidden;
}
#listDiv ol li
{
display: inline;
float: left;
text-align: center;
margin-right: 15px;
margin-bottom: 10px;
overflow: hidden;
background-color:#FFFFFF;
}
#listDiv ol li a
{
}
#listDiv ol li a:hover
{
}
/*album title desc*/
#listDiv ol li a span.albumTitle
{
font-size : 12px;
display: block;
text-align: left;
padding-left: 3px;
padding-top: 3px;
padding-bottom: 3px;
}
/*album cover*/
#listDiv ol li div.albumCover
{
display: table-cell;
border:1px solid #CCCCCC;
width:110px;
height:110px;
vertical-align:middle;
text-align:center;
}
#listDiv ol li div.albumCover:hover
{
background-color:#B0C4DE;
}
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<h2>相簿標題:<asp:Label ID="lblAlbumTitle" runat="server"></asp:Label></h2>
<div id="photoList">
<asp:ListView ID="ListView1" runat="server"
DataSourceID="SqlDataSourcePhotoList" >
<EmptyDataTemplate>
<div class="icon-yellow">Sorry 目前相簿無照片</div>
</EmptyDataTemplate>
<ItemTemplate>
<li>
<a href="activity-photo-show.aspx?aid=<%#Eval("ActivityPhotoAID")%>&pid=<%#Eval("ActivityPhotoID")%>">
<div class="albumCover">
<img src="<%#AlbumCover(Eval("ActivityAlbumDirectory").ToString(),Eval("ActivityPhotoFile").ToString())%>" alt="<%#Eval("ActivityAlbumTitle")%>"/>
<%-- <img src="photo/default.gif" />--%>
</div>
</a>
</li>
</ItemTemplate>
<AlternatingItemTemplate>
<li>
<a href="activity-photo-show.aspx?aid=<%#Eval("ActivityPhotoAID")%>&pid=<%#Eval("ActivityPhotoID")%>">
<div class="albumCover">
<img src="<%#AlbumCover(Eval("ActivityAlbumDirectory").ToString(),Eval("ActivityPhotoFile").ToString())%>" alt="<%#Eval("ActivityAlbumTitle")%>"/>
<%--<img src="photo/default.gif" />--%>
</div>
</a>
</li>
</AlternatingItemTemplate>
<LayoutTemplate>
<div id="listDiv">
<ol>
<asp:PlaceHolder ID="itemPlaceholder" runat="server" />
</ol>
</div>
<div class="Pagination">
<asp:DataPager ID="_moviesGridDataPager" runat="server" PageSize="20">
<Fields>
<asp:NumericPagerField CurrentPageLabelCssClass="pagerlabel" NextPageText="..."
NextPreviousButtonCssClass="pagerlink" NumericButtonCssClass="pagerlink"
PreviousPageText="..."/>
</Fields>
</asp:DataPager>
</div>
</LayoutTemplate>
</asp:ListView>
<asp:SqlDataSource ID="SqlDataSourcePhotoList" runat="server"
ConnectionString="<%$ ConnectionStrings:CSIEFriendsConnectionString %>"
SelectCommand="SELECT ActivityAlbumTitle,ActivityPhotoID, ActivityPhotoAID, ActivityPhotoFile,ActivityAlbumDirectory FROM vw_ActivityPhotoList
Where ActivityPhotoAID=@aid">
<SelectParameters>
<asp:QueryStringParameter Name="aid" QueryStringField="aid" />
</SelectParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSourceGetAlbumTitle" runat="server"
ConnectionString="<%$ ConnectionStrings:CSIEFriendsConnectionString %>"
SelectCommand="SELECT [ActivityAlbumTitle] FROM [ActivityAlbum] WHERE ([ActivityAlbumID] = @ActivityAlbumID)">
<SelectParameters>
<asp:QueryStringParameter Name="ActivityAlbumID" QueryStringField="aid"
Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
</div>
</asp:Content>
Treeview 蒐集
Treeview 蒐集
Reference:
Context Menu on TreeView
ASP.NET 2.0 使用資料表動態產生TreeView的樹狀結構
Graphic JavaScript Tree with Layout
[asp.net] 簡單秀Treeview, 使用 jQuery
Building Trees from Lists in .NET
PS:Printing Out All Nodes using Nested HTML ul and li Tags
Hierarchical Treeview with ASP.NET MVC & jQuery
Reference:
Context Menu on TreeView
ASP.NET 2.0 使用資料表動態產生TreeView的樹狀結構
Graphic JavaScript Tree with Layout
[asp.net] 簡單秀Treeview, 使用 jQuery
Building Trees from Lists in .NET
PS:Printing Out All Nodes using Nested HTML ul and li Tags
Hierarchical Treeview with ASP.NET MVC & jQuery
Jquery plugin : Uploadify 多檔上傳
好用的多檔上傳元件,
伺服端語言可用asp.net或php,
以下範例是一個將相片上傳至相本的的動作~
更多說明請參考網站文件
http://www.uploadify.com/
*.aspx
uploadHandler.ashx接收上傳的檔案
伺服端語言可用asp.net或php,
以下範例是一個將相片上傳至相本的的動作~
更多說明請參考網站文件
http://www.uploadify.com/
<!--uploader-->
<script type="text/javascript" src="../js/swfobject.js"></script>
<script type="text/javascript" src="../js/jquery.uploadify.v2.1.0.min.js"></script>
<link rel="stylesheet" type="text/css" href="../css/uploadify.css"/>
//限制上傳的檔案格式一定要指定fileDesc
<script type="text/javascript">
$(document).ready(function() {
$("#uploadify").uploadify({
"uploader": "../js/uploadify.swf",
"script": "../uploadHandler.ashx",
"cancelImg": "../images/cancel.png",
"sizeLimit": 1024000,
"queueID": "fileQueue",
"auto": false,
"fileDesc":"選取上傳的照片",
"fileExt": "*jpeg;*.jpg;*.gif;*.png",
"multi": true,
"onComplete": function(event, queueID, fileObj, response, data) {
if (response == "0")
alert("上傳發生錯誤");
else {
$("#uploadSet").append("<div id=\"fileitem\" >file:" + fileObj.name + " size:" + fileObj.size + "</div>");
}
}
});
});
function Upload() {
$("#uploadSet").html("");
$("#uploadify").uploadifySettings("scriptData", { "aid": $("#ctl00_ContentPlaceHolder1_hiddenAlbum").val() });
$("#uploadify").uploadifyUpload();
}
function CancelUpload() {
$("#uploadify").uploadifyClearQueue();
}
</script>
需注意的是:.net預設的上傳大小為上限值 4096 (4 MB)
因此會產生超出最大要求長度的exception,
要再webconfig加入以下設定
例如, Web.config 設定會允許最大 10 MB 的檔案上傳(設跟uploadifyg sizeLimit一樣大):
<System.Web>
<httpRuntime maxRequestLength="10240" />
</System.Web>
*.aspx
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<h2>照片上傳</h2>
<p class="help">請上傳小於 1MB 的圖片,僅支援.jpg、.gif、.png等圖片格式</p>
<p>支援多檔上傳</p>
<div id="fileQueue"></div>
<input type="file" name="uploadify" id="uploadify" />
<a href="javascript:Upload()" runat="server">上傳圖片</a>
<a href="javascript:CancelUpload()" >取消選取圖片</a>
<input id="hiddenAlbum" type="hidden" runat="server" />
<div id="uploadSet"></div>
</asp:Content>
uploadHandler.ashx接收上傳的檔案
<%@ WebHandler Language="C#" Class="uploadHandler" %>
using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using BigdControls;
using System.Drawing;
using System.Drawing.Drawing2D;
public class uploadHandler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
if (context.Request["aid"] == null)
{
context.Response.Write("0");
return;
}
//uploadifySettings post 的 album id
string aid = context.Request["aid"].ToString();
//album directory
string aDirectory = this.GetAlbumDirectory(aid);
if (String.IsNullOrEmpty(aDirectory))
return;//無相簿目錄
string fullFileName = context.Server.MapPath("Album/" + aDirectory + "/");
string fullFileNameThumb = context.Server.MapPath("Album/" + aDirectory + "/thumb/");
for (int i = 0; i < context.Request.Files.Count; i++)
{
HttpPostedFile postedFile = context.Request.Files[i];
string fileFormat = Path.GetExtension(postedFile.FileName);
if (ModuleSecurity.ModuleSecurity.FileChecker(fileFormat,new string[] { ".jpg", ".gif", ".png" }))
{
string orgFileName = Path.GetFileNameWithoutExtension(postedFile.FileName);
//string fileName = orgFileName + "-" + DateTime.Now.ToString("yyyyMMddhhmmss") + fileFormat;
Random rn = new Random((int)DateTime.Now.Ticks);
string fileName = rn.Next().ToString() + "-" + DateTime.Now.ToString("yyyyMMddhhmmss") + fileFormat;
fullFileName = fullFileName + fileName;
fullFileNameThumb = fullFileNameThumb + fileName;
//save photo
postedFile.SaveAs(fullFileName);
//縮圖
postedFile.SaveAs(fullFileNameThumb);
ImageProcessing.Save(fullFileNameThumb,
ImageProcessing.ImagePreviewThumb(fullFileNameThumb, 100, 100, Color.White, InterpolationMode.High, SmoothingMode.HighQuality));
//add photo
this.AddAlbumPhoto(aid, fileName);
}
}
context.Response.Write("1");
}
public bool IsReusable {
get {
return false;
}
}
/// <summary>
/// 取得相簿目錄
/// </summary>
/// <param name="aid">相簿id</param>
/// <returns></returns>
public string GetAlbumDirectory(string aid)
{
SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["CSIEFriendsConnectionString"].ConnectionString);
sqlConn.Open();
SqlCommand sqlCmd = new SqlCommand("select ActivityAlbumDirectory from ActivityAlbum where ActivityAlbumID=@aid",sqlConn);
sqlCmd.Parameters.Add("aid", SqlDbType.Int).Value = aid;
string direcdtory = sqlCmd.ExecuteScalar().ToString();
sqlConn.Close();
return direcdtory;
}
/// <summary>
/// 新增相片
/// </summary>
/// <param name="aid">相簿id</param>
/// <param name="photo">相本檔名</param>
public void AddAlbumPhoto(string aid, string photo)
{
SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["CSIEFriendsConnectionString"].ConnectionString);
sqlConn.Open();
SqlCommand sqlCmd = new SqlCommand("insert into ActivityPhoto(ActivityPhotoAID,ActivityPhotoFile)values(@aid,@photo) ", sqlConn);
sqlCmd.Parameters.Add("aid", SqlDbType.Int).Value = aid;
sqlCmd.Parameters.Add("photo", SqlDbType.NVarChar).Value = photo;
sqlCmd.ExecuteNonQuery();
sqlConn.Close();
}
}
星期日, 11月 15, 2009
[jQuery plugin] Validator addMethod Func
由於預設的Validator裡面的驗證欄位的方法可能不夠我們使用,
所以可以透過addMethod來自訂我們的驗證規格,
剛好用到記錄一下。
Reference:
客户端驗證的極品--jQuery.validator
利用 jQuery.Validate 驗證中華民國身份證字號
所以可以透過addMethod來自訂我們的驗證規格,
剛好用到記錄一下。
jQuery.validator.addMethod("projSN", function(value, element) {
var length = value.length;
return this.optional(element) || (length == 5 && /^[A-Z]{5}$/.test(value));
}, "專案代碼僅限英文大寫五碼");
jQuery.validator.addMethod("number", function(value, element) {
var length = value.length;
return this.optional(element) || (/^[1-9]{1}[0-9]*$/.test(value));
}, "欄位只能為數字,且第一位數不能為 0");
//
Reference:
客户端驗證的極品--jQuery.validator
利用 jQuery.Validate 驗證中華民國身份證字號
星期三, 11月 11, 2009
jQuery plugin : Validation in ASP.NET Master Pages
剛好要在asp.net master page 下使用jquery validation plugin來做欄位驗證,
但我的button又是使用ajax的方式,
是不能將表單產生sumbit的動作Orz,
所以有了以下的解決方法:
頁面上配置鈕
但我的button又是使用ajax的方式,
是不能將表單產生sumbit的動作Orz,
所以有了以下的解決方法:
頁面上配置鈕
<input id="btnProdcut" type="button" value="送出" runat="server" onclick="MySubmit()"/>
首先先初始化驗證控制項
<script type="text/javascript">
$(document).ready(function() {
$("#aspnetForm").validate({
event:"keyup",
rules: {
<%=tbDesignName.UniqueID %>: {
minlength: 2,
maxlength:10,
required: true
},
<%=tbDesignNameEnglish.UniqueID %>: {
minlength: 2,
maxlength:10,
required: true,
},
<%=tbDesignDesc.UniqueID %>: {
minlength: 2,
maxlength:10,
required: true,
},
<%=tbDesignDescEnglish.UniqueID %>: {
minlength: 2,
maxlength:50,
required: true,
}
},
messages: {
<%=tbDesignName.UniqueID %>: {
required: "設計名稱尚未填寫",
minlength: "設計名稱最小長度為 2",
maxlength: "設計名稱最大長度為 10"
},
<%=tbDesignDesc.UniqueID %>: {
required: "設計描述尚未填寫",
minlength: "設計描述最小長度為 2",
maxlength: "設計描述最大長度為 10"
}
}
});
});
</script>
按鈕執行的鈕
function MySubmit() {
CancelSumbit();
if (FormValidate()) {
if (FileValidate()) {
//驗證成功
else {
//驗證失敗
}
});
}
else
alert("驗證失敗");
}
改由檢查錯誤訊息元素的css屬性 display:none確認驗證是否成功,
function FormValidate() {
var displayChecker = false;
//找出class=error的錯誤訊息元素
$("td .error").each(function(i, obj) {
//alert($(this).css("display"));
if ($(this).css("display") == "none")
displayChecker = true;//表示欄位都通過驗證
else
displayChecker = false;
});
if (displayChecker == true)
return true;
else
return false;
}
摸擬submit的動作來檢查欄位
function CancelSumbit() {
$("input:[type=submit]").submit();
return false;
}
星期二, 11月 10, 2009
Asp.net FindControl
以前沒用FindControl時都習慣把元素的id全列出來
然後就可以找出欲取得值的控制項位置
由於上面的方法會因控制項往後的位置變更又需要修改程式碼,
非常不好,所以改用FindControl(元素的id)是比較適合的
int allControl = this.ListView1.Items[e.ItemIndex].Controls.Count;
for (int i = 0; i < allControl; i++)
{
this.Response.Write(this.ListView1.Items[e.ItemIndex].Controls[i].ClientID + "<br/>");
}
然後就可以找出欲取得值的控制項位置
this.SqlDataSourceActivityAlbumList.UpdateParameters["ActivityAlbumID"].DefaultValue = ((ImageButton)this.ListView1.Items[e.ItemIndex].Controls[1]).CommandArgument;
由於上面的方法會因控制項往後的位置變更又需要修改程式碼,
非常不好,所以改用FindControl(元素的id)是比較適合的
this.SqlDataSourceActivityAlbumList.UpdateParameters["ActivityAlbumTitle"].DefaultValue = ((TextBox)this.ListView1.Items[e.ItemIndex].FindControl("tbAlbumTitle")).Text;
this.SqlDataSourceActivityAlbumList.UpdateParameters["ActivityAlbumDesc"].DefaultValue = ((TextBox)this.ListView1.Items[e.ItemIndex].FindControl("tbAlbumDesc")).Text;
星期日, 11月 08, 2009
Jquery Plugin: Star Rating
jQuery Star Rating Plugin
Star Rating widget(目前使用,直接有大顆星星的樣式表)
demo6 code
Star Rating widget(目前使用,直接有大顆星星的樣式表)
demo6 code
// Create stars
$("#rat").stars({
// starWidth: 28, // only needed in "split" mode
cancelShow: false,
callback: function(ui, type, value)
{
// Hide Stars while AJAX connection is active
$("#rat").hide();
$("#loader").show();
// Send request to the server using POST method
/* NOTE:
The same PHP script is used for the FORM submission when Javascript is not available.
The only difference in script execution is the returned value.
For AJAX call we expect an JSON object to be returned.
The JSON object contains additional data we can use to update other elements on the page.
To distinguish the AJAX request in PHP script, check if the $_SERVER['HTTP_X_REQUESTED_WITH'] header variable is set.
(see: demo6.php)
*/
$.post("demo6.php", {rate: value}, function(db)
{
// Select stars to match "Average" value
ui.select(Math.round(db.avg));
// Update other text controls...
$("#avg").text(db.avg);
$("#votes").text(db.votes);
// Show Stars
$("#loader").hide();
$("#rat").show();
}, "json");
}
});
星期二, 10月 27, 2009
Create Google Maps
function CreatMap(address)
{
alert(address);
if (GBrowserIsCompatible())
{
var map = new GMap2(document.getElementById("map_canvas"));
var geocoder = new GClientGeocoder();
map.addControl(new GSmallMapControl());
geocoder.getLatLng(address, function(point) {
if (!point)
{
alert('Google Maps 可能發生問題或無法顯示該地區的地圖!'); //如果Google Maps無法顯示該地址的警示文字
}
else
{
map.setCenter(point, 13);
var marker = new GMarker(point);
map.addOverlay(marker);
marker.openInfoWindowHtml(address);
}
});
}
}
星期一, 10月 26, 2009
星期四, 10月 22, 2009
asp.net 會員機制
今天在找相關的asp.net會員機制的相關資料,
找到一些文章就暫時記錄起來。
Reference:
小喵
ASP.NET的驗證與授權機制(動態錄影說明)
ASP.NET 2.0 如何將MemberShip的資料庫建立在自己的資料庫上
Will保哥
ASP.NET MVC 實做登入機制
ASP.NET 自訂角色的方式(不用實做 Role Provider)
概略解釋 Forms Authentication 的運作
使用ASP.NET會員和角色,顯示不同導覽相關介紹
找到一些文章就暫時記錄起來。
Reference:
小喵
ASP.NET的驗證與授權機制(動態錄影說明)
ASP.NET 2.0 如何將MemberShip的資料庫建立在自己的資料庫上
Will保哥
ASP.NET MVC 實做登入機制
ASP.NET 自訂角色的方式(不用實做 Role Provider)
概略解釋 Forms Authentication 的運作
使用ASP.NET會員和角色,顯示不同導覽相關介紹
星期三, 10月 21, 2009
星期二, 10月 20, 2009
星期日, 10月 18, 2009
免費樣版
http://www.oswd.org
http://www.openwebdesign.org
http://www.opendesigns.org
http://www.opensourcetemplates.org
http://www.free-css.com
http://www.opensourcedesign.com
http://www.oswt.co.uk
Reference:
http://pignet.wordpress.com/2008/07/03/free_templates/
星期六, 10月 17, 2009
WINDOWS API大全
Reference WINDOWS API大全
1. API之網路函數
WNetAddConnection 新增同一個網路資源的永久性連接
WNetAddConnection2 新增同一個網路資源的連接
WNetAddConnection3 新增同一個網路資源的連接
WNetCancelConnection 結束一個網路連接
WNetCancelConnection2 結束一個網路連接
WNetCloseEnum 結束一次枚舉操作
WNetConnectionDialog 啟動一個標準對話視窗,以便建立同網路資源的連接
WNetDisconnectDialog 啟動一個標準對話視窗,以便中斷連線同網路資源的連接
WNetEnumResource 枚舉網路資源
WNetGetConnection 獲取本機或已連接的一個資源的網路名稱
WNetGetLastError 獲取網路錯誤的增強錯誤訊息
WNetGetUniversalName 獲取網路中一個文件的遠端名稱以及/或者UNC(統一命名規範)名稱
WNetGetUser 獲取一個網路資源用以連接的名字
WNetOpenEnum 啟動對網路資源進行枚舉的程序
1. API之網路函數
WNetAddConnection 新增同一個網路資源的永久性連接
WNetAddConnection2 新增同一個網路資源的連接
WNetAddConnection3 新增同一個網路資源的連接
WNetCancelConnection 結束一個網路連接
WNetCancelConnection2 結束一個網路連接
WNetCloseEnum 結束一次枚舉操作
WNetConnectionDialog 啟動一個標準對話視窗,以便建立同網路資源的連接
WNetDisconnectDialog 啟動一個標準對話視窗,以便中斷連線同網路資源的連接
WNetEnumResource 枚舉網路資源
WNetGetConnection 獲取本機或已連接的一個資源的網路名稱
WNetGetLastError 獲取網路錯誤的增強錯誤訊息
WNetGetUniversalName 獲取網路中一個文件的遠端名稱以及/或者UNC(統一命名規範)名稱
WNetGetUser 獲取一個網路資源用以連接的名字
WNetOpenEnum 啟動對網路資源進行枚舉的程序
星期日, 10月 11, 2009
asp.net 會員機制 取得當前使用者的Profile
利用Profile.GetProfile取得當前使用者的資訊
///
/// 取得profile 暱稱
///
public string GetNickName(string username)
{
MembershipUser currecter;
currecter = Membership.GetUser(username);
string nickname = "未設暱稱";
//string tmp = currecter.ProviderUserKey.ToString();
ProfileCommon pc = Profile.GetProfile(username);
string tmp = pc.個人資訊.暱稱;
if (tmp != "")
nickname = tmp;
return nickname;
}
asp.net 會員機制 取得當前使用者所屬的成員角色
//角色可為多個,因此回傳陣列
string[] tmp = Roles.GetRolesForUser(this.Page.User.Identity.Name.ToString());
星期四, 10月 08, 2009
星期三, 10月 07, 2009
UrlRewrite in Asp.net
Google到的Url Rewriteing Solution,記錄不時之需。
2012/04/08更新
請直接參考這篇[Asp.Net] URL Rewrite 懶人包心得
Reference:
ASP.NET 的 Url Rewrite
A Complete URL Rewriting Solution for ASP.NET 2.0
簡易的 Url Rewriting 隱藏 Querystring
簡易的 Url Rewriting 隱藏 Querystring (二) IIS 注意事項
在 URL Rewrite 後保持 PostBack 地址
2012/04/08更新
請直接參考這篇[Asp.Net] URL Rewrite 懶人包心得
Reference:
ASP.NET 的 Url Rewrite
A Complete URL Rewriting Solution for ASP.NET 2.0
簡易的 Url Rewriting 隱藏 Querystring
簡易的 Url Rewriting 隱藏 Querystring (二) IIS 注意事項
在 URL Rewrite 後保持 PostBack 地址
在ashx 中如何取得 SESSION
常常會用到ashx來處理圖片的顯示處理,
除了用querystring來傳遞參數之外,
有時候會利用到session來傳值,
為了能在ashx能讀到session則
需引用 IReadOnlySessionState,
這才能有足夠的權限進行SESSION讀取。
Reference:
http://www.allenkuo.com/EBook5/view.aspx?TreeNodeID=83&id=378
除了用querystring來傳遞參數之外,
有時候會利用到session來傳值,
為了能在ashx能讀到session則
需引用 IReadOnlySessionState,
這才能有足夠的權限進行SESSION讀取。
Reference:
http://www.allenkuo.com/EBook5/view.aspx?TreeNodeID=83&id=378
經典SQL語句集錦(收藏版)
Reference:經典SQL語句集錦(收藏版)
下列語句部分是MsSql語句,不可以在access中使用。
SQL分類:
DDL—資料定義語言(CREATE,ALTER,DROP,DECLARE)
DML—資料操縱語言(SELECT,DELETE,UPDATE,INSERT)
DCL—資料控制語言(GRANT,REVOKE,COMMIT,ROLLBACK)
SQL分類:
DDL—資料定義語言(CREATE,ALTER,DROP,DECLARE)
DML—資料操縱語言(SELECT,DELETE,UPDATE,INSERT)
DCL—資料控制語言(GRANT,REVOKE,COMMIT,ROLLBACK)
星期一, 10月 05, 2009
星期六, 10月 03, 2009
星期三, 9月 30, 2009
DateTime using C#
整理一下datatime常用到的方法
DateTime dt = DateTime.Now;
Label1.Text = dt.ToString();//2005-11-5 13:21:25
Label2.Text = dt.ToFileTime().ToString();//127756416859912816
Label3.Text = dt.ToFileTimeUtc().ToString();//127756704859912816
Label4.Text = dt.ToLocalTime().ToString();//2005-11-5 21:21:25
Label5.Text = dt.ToLongDateString().ToString();//2005年11月5日
Label6.Text = dt.ToLongTimeString().ToString();//13:21:25
Label7.Text = dt.ToOADate().ToString();//38661.5565508218
Label8.Text = dt.ToShortDateString().ToString();//2005-11-5
Label9.Text = dt.ToShortTimeString().ToString();//13:21
Label10.Text = dt.ToUniversalTime().ToString();//2005-11-5 5:21:25
Label1.Text = dt.Year.ToString();//2005
Label2.Text = dt.Date.ToString();//2005-11-5 0:00:00
Label3.Text = dt.DayOfWeek.ToString();//Saturday
Label4.Text = dt.DayOfYear.ToString();//309
Label5.Text = dt.Hour.ToString();//13
Label6.Text = dt.Millisecond.ToString();//441
Label7.Text = dt.Minute.ToString();//30
Label8.Text = dt.Month.ToString();//11
Label9.Text = dt.Second.ToString();//28
Label10.Text = dt.Ticks.ToString();//632667942284412864
Label11.Text = dt.TimeOfDay.ToString();//13:30:28.4412864
Label1.Text = dt.ToString();//2005-11-5 13:47:04
Label2.Text = dt.AddYears(1).ToString();//2006-11-5 13:47:04
Label3.Text = dt.AddDays(1.1).ToString();//2005-11-6 16:11:04
Label4.Text = dt.AddHours(1.1).ToString();//2005-11-5 14:53:04
Label5.Text = dt.AddMilliseconds(1.1).ToString();//2005-11-5 13:47:04
Label6.Text = dt.AddMonths(1).ToString();//2005-12-5 13:47:04
Label7.Text = dt.AddSeconds(1.1).ToString();//2005-11-5 13:47:05
Label8.Text = dt.AddMinutes(1.1).ToString();//2005-11-5 13:48:10
Label9.Text = dt.AddTicks(1000).ToString();//2005-11-5 13:47:04
Label10.Text = dt.CompareTo(dt).ToString();//0
Label11.Text = dt.Add(?).ToString();//问号为一个时间段
Label1.Text = dt.Equals("2005-11-6 16:11:04").ToString();//False
Label2.Text = dt.Equals(dt).ToString();//True
Label3.Text = dt.GetHashCode().ToString();//1474088234
Label4.Text = dt.GetType().ToString();//System.DateTime
Label5.Text = dt.GetTypeCode().ToString();//DateTime
Label1.Text = dt.GetDateTimeFormats('s')[0].ToString();//2005-11-05T14:06:25
Label2.Text = dt.GetDateTimeFormats('t')[0].ToString();//14:06
Label3.Text = dt.GetDateTimeFormats('y')[0].ToString();//2005年11月
Label4.Text = dt.GetDateTimeFormats('D')[0].ToString();//2005年11月5日
Label5.Text = dt.GetDateTimeFormats('D')[1].ToString();//2005 11 05
Label6.Text = dt.GetDateTimeFormats('D')[2].ToString();//星期六 2005 11 05
Label7.Text = dt.GetDateTimeFormats('D')[3].ToString();//星期六 2005年11月5日
Label8.Text = dt.GetDateTimeFormats('M')[0].ToString();//11月5日
Label9.Text = dt.GetDateTimeFormats('f')[0].ToString();//2005年11月5日 14:06
Label10.Text = dt.GetDateTimeFormats('g')[0].ToString();//2005-11-5 14:06
Label11.Text = dt.GetDateTimeFormats('r')[0].ToString();//Sat, 05 Nov 2005 14:06:25 GMT
Label1.Text = string.Format("{0:d}",dt);//2005-11-5
Label2.Text = string.Format("{0:D}",dt);//2005年11月5日
Label3.Text = string.Format("{0:f}",dt);//2005年11月5日 14:23
Label4.Text = string.Format("{0:F}",dt);//2005年11月5日 14:23:23
Label5.Text = string.Format("{0:g}",dt);//2005-11-5 14:23
Label6.Text = string.Format("{0:G}",dt);//2005-11-5 14:23:23
Label7.Text = string.Format("{0:M}",dt);//11月5日
Label8.Text = string.Format("{0:R}",dt);//Sat, 05 Nov 2005 14:23:23 GMT
Label9.Text = string.Format("{0:s}",dt);//2005-11-05T14:23:23
Label10.Text string.Format("{0:t}",dt);//14:23
Label11.Text = string.Format("{0:T}",dt);//14:23:23
Label12.Text = string.Format("{0:u}",dt);//2005-11-05 14:23:23Z
Label13.Text = string.Format("{0:U}",dt);//2005年11月5日 6:23:23
Label14.Text = string.Format("{0:Y}",dt);//2005年11月
Label15.Text = string.Format("{0}",dt);//2005-11-5 14:23:23
Label16.Text = string.Format("{0:yyyyMMddHHmmssffff}",dt);String Format for DateTime [C#]
C# datetime 操作
C#如何判断两个日期是否相等
C# 如何取得兩個 DateTime 日期之間的天數
DateTime dt = DateTime.Now;
Label1.Text = dt.ToString();//2005-11-5 13:21:25
Label2.Text = dt.ToFileTime().ToString();//127756416859912816
Label3.Text = dt.ToFileTimeUtc().ToString();//127756704859912816
Label4.Text = dt.ToLocalTime().ToString();//2005-11-5 21:21:25
Label5.Text = dt.ToLongDateString().ToString();//2005年11月5日
Label6.Text = dt.ToLongTimeString().ToString();//13:21:25
Label7.Text = dt.ToOADate().ToString();//38661.5565508218
Label8.Text = dt.ToShortDateString().ToString();//2005-11-5
Label9.Text = dt.ToShortTimeString().ToString();//13:21
Label10.Text = dt.ToUniversalTime().ToString();//2005-11-5 5:21:25
Label1.Text = dt.Year.ToString();//2005
Label2.Text = dt.Date.ToString();//2005-11-5 0:00:00
Label3.Text = dt.DayOfWeek.ToString();//Saturday
Label4.Text = dt.DayOfYear.ToString();//309
Label5.Text = dt.Hour.ToString();//13
Label6.Text = dt.Millisecond.ToString();//441
Label7.Text = dt.Minute.ToString();//30
Label8.Text = dt.Month.ToString();//11
Label9.Text = dt.Second.ToString();//28
Label10.Text = dt.Ticks.ToString();//632667942284412864
Label11.Text = dt.TimeOfDay.ToString();//13:30:28.4412864
Label1.Text = dt.ToString();//2005-11-5 13:47:04
Label2.Text = dt.AddYears(1).ToString();//2006-11-5 13:47:04
Label3.Text = dt.AddDays(1.1).ToString();//2005-11-6 16:11:04
Label4.Text = dt.AddHours(1.1).ToString();//2005-11-5 14:53:04
Label5.Text = dt.AddMilliseconds(1.1).ToString();//2005-11-5 13:47:04
Label6.Text = dt.AddMonths(1).ToString();//2005-12-5 13:47:04
Label7.Text = dt.AddSeconds(1.1).ToString();//2005-11-5 13:47:05
Label8.Text = dt.AddMinutes(1.1).ToString();//2005-11-5 13:48:10
Label9.Text = dt.AddTicks(1000).ToString();//2005-11-5 13:47:04
Label10.Text = dt.CompareTo(dt).ToString();//0
Label11.Text = dt.Add(?).ToString();//问号为一个时间段
Label1.Text = dt.Equals("2005-11-6 16:11:04").ToString();//False
Label2.Text = dt.Equals(dt).ToString();//True
Label3.Text = dt.GetHashCode().ToString();//1474088234
Label4.Text = dt.GetType().ToString();//System.DateTime
Label5.Text = dt.GetTypeCode().ToString();//DateTime
Label1.Text = dt.GetDateTimeFormats('s')[0].ToString();//2005-11-05T14:06:25
Label2.Text = dt.GetDateTimeFormats('t')[0].ToString();//14:06
Label3.Text = dt.GetDateTimeFormats('y')[0].ToString();//2005年11月
Label4.Text = dt.GetDateTimeFormats('D')[0].ToString();//2005年11月5日
Label5.Text = dt.GetDateTimeFormats('D')[1].ToString();//2005 11 05
Label6.Text = dt.GetDateTimeFormats('D')[2].ToString();//星期六 2005 11 05
Label7.Text = dt.GetDateTimeFormats('D')[3].ToString();//星期六 2005年11月5日
Label8.Text = dt.GetDateTimeFormats('M')[0].ToString();//11月5日
Label9.Text = dt.GetDateTimeFormats('f')[0].ToString();//2005年11月5日 14:06
Label10.Text = dt.GetDateTimeFormats('g')[0].ToString();//2005-11-5 14:06
Label11.Text = dt.GetDateTimeFormats('r')[0].ToString();//Sat, 05 Nov 2005 14:06:25 GMT
Label1.Text = string.Format("{0:d}",dt);//2005-11-5
Label2.Text = string.Format("{0:D}",dt);//2005年11月5日
Label3.Text = string.Format("{0:f}",dt);//2005年11月5日 14:23
Label4.Text = string.Format("{0:F}",dt);//2005年11月5日 14:23:23
Label5.Text = string.Format("{0:g}",dt);//2005-11-5 14:23
Label6.Text = string.Format("{0:G}",dt);//2005-11-5 14:23:23
Label7.Text = string.Format("{0:M}",dt);//11月5日
Label8.Text = string.Format("{0:R}",dt);//Sat, 05 Nov 2005 14:23:23 GMT
Label9.Text = string.Format("{0:s}",dt);//2005-11-05T14:23:23
Label10.Text string.Format("{0:t}",dt);//14:23
Label11.Text = string.Format("{0:T}",dt);//14:23:23
Label12.Text = string.Format("{0:u}",dt);//2005-11-05 14:23:23Z
Label13.Text = string.Format("{0:U}",dt);//2005年11月5日 6:23:23
Label14.Text = string.Format("{0:Y}",dt);//2005年11月
Label15.Text = string.Format("{0}",dt);//2005-11-5 14:23:23
Label16.Text = string.Format("{0:yyyyMMddHHmmssffff}",dt);String Format for DateTime [C#]
C# datetime 操作
C#如何判断两个日期是否相等
C# 如何取得兩個 DateTime 日期之間的天數
Pass NULL as a Parameter Value to SQLParameter
The following c# code sample shows how to pass Null as a parameter value.
SqlParameter ParamValue= new SqlParameter("@Address", SqlDbType.NVarChar, 20);
ParamValue.Value = DBNull.Value;
Reference:Pass NULL as a Parameter Value to SQLParameter
星期二, 9月 29, 2009
jQuery Intellisense in VS 2008
jQuery的官方下載區(http://docs.jquery.com/Downloading_jQuery#Download_jQuery),在原本的Minified, Packed, Uncompressed版檔案連結下方,多了一個Documentation項目,裡面有Visual Studio的專用文件說明檔: jquery-1.2.x-vsdoc.js。
Reference:
jQuery Intellisense in VS 2008
TIPS-為VS2008加入完整jQuery Intellisense
Reference:
jQuery Intellisense in VS 2008
TIPS-為VS2008加入完整jQuery Intellisense
星期日, 9月 27, 2009
星期五, 9月 25, 2009
星期四, 9月 24, 2009
MS SQL 重覆性資料表處理 Repeat rows ,Group by
第一篇:
--出現多筆時抓取最大值 Select 欄位一,max(欄位二) 欄位二 From Table Group By 欄位一 --出現多筆時抓取最小值 Select 欄位一,min(欄位二) 欄位二 From Table Group By 欄位一
星期三, 9月 23, 2009
MS SQL DATEDIFF(計算兩時間差)
使用Convert、DATEDIFF 函數求得時間差
SELECT design_product_comment_id, design_product_comment_pid, design_product_comment_username, design_product_comment_text,
design_product_comment_category,
CONVERT(varchar(4), DATEDIFF(day, design_product_comment_date, GETDATE())) AS Days, CONVERT(varchar(4), DATEDIFF(hour, design_product_comment_date, GETDATE()) % 24) AS Hours,
CONVERT(varchar(4), DATEDIFF(minute, design_product_comment_date, GETDATE()) % 60) AS Mins
FROM design_product_comment
WHERE (design_product_comment_pid = @dpid) AND (design_product_comment_category = @cid)"
SELECT design_product_comment_id, design_product_comment_pid, design_product_comment_username, design_product_comment_text,
design_product_comment_category,
CONVERT(varchar(4), DATEDIFF(day, design_product_comment_date, GETDATE())) AS Days, CONVERT(varchar(4), DATEDIFF(hour, design_product_comment_date, GETDATE()) % 24) AS Hours,
CONVERT(varchar(4), DATEDIFF(minute, design_product_comment_date, GETDATE()) % 60) AS Mins
FROM design_product_comment
WHERE (design_product_comment_pid = @dpid) AND (design_product_comment_category = @cid)"
星期一, 9月 21, 2009
MS Sql 迴圈
ALTER proc [dbo].[sp_showDesignProducts]
as
/*宣告cursor*/
declare dpid_set CURSOR FOR
SELECT DISTINCT design_product_id FROM design_product
/*開啟cursor連結*/
open dpid_set
declare @dpid nvarchar(50)
/*清單將第一筆資料存入@dpid*/
fetch next from dpid_set into @dpid
/*檢查是否有資料,0代表有*/
while(@@fetch_status=0)
begin
/*取出每一筆專案id其所屬的上傳圖片的第一張圖*/
SELECT allResult.* FROM (
SELECT row_number() OVER (ORDER BY design_product_pictures_id) AS rid, * FROM design_product_pictures WHERE (design_product_pictures_pid = @dpid)) as allResult
where allResult.rid = 1
fetch NEXT from dpid_set into @dpid
end
/*關閉cursor連結*/
close dpid_set
/*移除cursor連結*/
deallocate dpid_set
as
/*宣告cursor*/
declare dpid_set CURSOR FOR
SELECT DISTINCT design_product_id FROM design_product
/*開啟cursor連結*/
open dpid_set
declare @dpid nvarchar(50)
/*清單將第一筆資料存入@dpid*/
fetch next from dpid_set into @dpid
/*檢查是否有資料,0代表有*/
while(@@fetch_status=0)
begin
/*取出每一筆專案id其所屬的上傳圖片的第一張圖*/
SELECT allResult.* FROM (
SELECT row_number() OVER (ORDER BY design_product_pictures_id) AS rid, * FROM design_product_pictures WHERE (design_product_pictures_pid = @dpid)) as allResult
where allResult.rid = 1
fetch NEXT from dpid_set into @dpid
end
/*關閉cursor連結*/
close dpid_set
/*移除cursor連結*/
deallocate dpid_set
JQUERY-Each
//jquery each func 初試
//btn set,找出表格被勾選的checkbox
$("#btnCommentDelete").click(function() {
var valSet = "";
$("#ctl00_ContentPlaceHolder1_gvComment input:enabled[type=checkbox]").each(function(i, obj) {
if ($(obj).attr("id") == "cbAllComment") {
}
else {
valSet += $(obj).attr("value") + ',';
//移除表格列
$(obj).parents("#ctl00_ContentPlaceHolder1_gvComment tr").remove();
}
});
alert(valSet);
if (valSet != "") {
$.get("comment_delete.aspx", { cidset: valSet }, function(data) {
alert(data);
});
}
else {
Boxy.alert("No Data");
}
});
String Split
//1,2,3,4,5
string[] commentSet = commentValStr.Split(new char[]{','});//['1','2','3','4','5']
string[] commentSet = commentValStr.Split(new char[]{','});//['1','2','3','4','5']
星期日, 9月 20, 2009
使用Profile.GetProfile()取得指定帳戶的Profile
///
/// 取得profile 暱稱
///
///
///
public string GetNickName(string username)
{
//MembershipUser currecter;
//currecter = Membership.GetUser(username);
string nickname = "未公開";
ProfileCommon pc = Profile.GetProfile(username);
string tmp = pc.個人資訊.暱稱;
if (tmp != "")
nickname = tmp;
return nickname;
}
/// 取得profile 暱稱
///
///
///
public string GetNickName(string username)
{
//MembershipUser currecter;
//currecter = Membership.GetUser(username);
string nickname = "未公開";
ProfileCommon pc = Profile.GetProfile(username);
string tmp = pc.個人資訊.暱稱;
if (tmp != "")
nickname = tmp;
return nickname;
}
星期五, 9月 18, 2009
Calendar Extender for select month
選擇月份的月曆Calendar Extender ~
How to show and select month/year in Calendar Extender by aghausman
測試結果一切正常,有需要的朋友參考吧~
Reference:
http://www.aghausman.net/asp/how-to-show-and-select-monthyear-in-calendar-extender.html
MSSQL 取得目前新增資料的索引(PK)
取出當前新增資料的索引。
語法如下:
string sql = "insert into pictures_annotation (pictures_annotation_top,pictures_annotation_left,pictures_annotation_width,pictures_annotation_height,pictures_annotation_text,pictures_annotation_pid,pictures_annotation_username,pictures_annotation_date)values(@top,@left,@width,@height,@text,@pid,@username,@date);select @NewPK = @@IDENTITY";
this.sqlConn.Open();
this.sqlCmd = new SqlCommand(sql, this.sqlConn);
this.sqlCmd.Parameters.Add("top", SqlDbType.Int).Value = (int)Convert.ToDouble(top);
this.sqlCmd.Parameters.Add("left", SqlDbType.Int).Value = (int)Convert.ToDouble(left);
....
.......省略
SqlParameter pkPara = new SqlParameter("NewPK",SqlDbType.Int);
pkPara.Direction = ParameterDirection.Output;
this.sqlCmd.Parameters.Add(pkPara);
this.sqlCmd.ExecuteNonQuery();
this.sqlConn.Close();
//get current aid
aid = this.sqlCmd.Parameters["NewPK"].Value.ToString();
語法如下:
string sql = "insert into pictures_annotation (pictures_annotation_top,pictures_annotation_left,pictures_annotation_width,pictures_annotation_height,pictures_annotation_text,pictures_annotation_pid,pictures_annotation_username,pictures_annotation_date)values(@top,@left,@width,@height,@text,@pid,@username,@date);select @NewPK = @@IDENTITY";
this.sqlConn.Open();
this.sqlCmd = new SqlCommand(sql, this.sqlConn);
this.sqlCmd.Parameters.Add("top", SqlDbType.Int).Value = (int)Convert.ToDouble(top);
this.sqlCmd.Parameters.Add("left", SqlDbType.Int).Value = (int)Convert.ToDouble(left);
....
.......省略
SqlParameter pkPara = new SqlParameter("NewPK",SqlDbType.Int);
pkPara.Direction = ParameterDirection.Output;
this.sqlCmd.Parameters.Add(pkPara);
this.sqlCmd.ExecuteNonQuery();
this.sqlConn.Close();
//get current aid
aid = this.sqlCmd.Parameters["NewPK"].Value.ToString();
有關SiteMap SiteMapNode Root問題
今天為了讓menu control能套上美美的css,
使用了ASP.NET 2.0 CSS Friendly Control Adapters 1.0,
因為第一次使用sitemap,雖然知道根節點只能設一個,但我要能一開始就能秀很多選項,
原來是要設定將根節點hidden就好啦~
Reference:
TreeView使用SiteMapNode製作結點,root只能有一個嗎?
淺介 ASP.NET 2.0 CSS Friendly Control Adapters 1.0
使用了ASP.NET 2.0 CSS Friendly Control Adapters 1.0,
因為第一次使用sitemap,雖然知道根節點只能設一個,但我要能一開始就能秀很多選項,
原來是要設定
<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
<siteMapNode url="#" title="根節點" description="不會顯示">
....
</siteMap>
<!--
sitemap角色權限讀取 securityTrimmingEnabled="true"
-->
<siteMap defaultProvider="XmlSiteMapProvider" enabled="true">
<providers>
<add name="XmlSiteMapProvider" description="SiteMap provider which reads in .sitmap XML files."
type="System.Web.XmlSiteMapProvider,System.Web,Version=2.0.3600.0, Culture= neutral,PublicKeyToken=b03f5f7f11d50a3a"
siteMapFile="Web.sitemap" securityTrimmingEnabled="true"/>
</providers>
</siteMap>
Reference:
TreeView使用SiteMapNode製作結點,root只能有一個嗎?
淺介 ASP.NET 2.0 CSS Friendly Control Adapters 1.0
[Javascript 茶包筆記] setTimeout 倒數計數
專案需用到倒數計數的功能,
以下是一個簡單的測試版本,
另外又在網上找到一個將秒數轉時分秒(TimeToHMS)
javascript func。
script範例程式如下:
//20分鐘
var allTime = 1200000;
$(document).ready(function(){
$("#myDiv").css("border","3px solid red");
DoTestCount();
});
function DoTestCount()
{
if(allTime <= 0){
//dopostback
__doPostBack(this.btnSubmit,"")
}
else
{
var timeTmp = allTime/1000;
var currentTimeHMS = TimeToHMS(timeTmp)
$("#myDiv").text(currentTimeHMS)
setTimeout("DoTestCount()",1000);
}
allTime-=1000;
}
/* convert seconds value to H:MM:SS format */
function TimeToHMS(seconds)
{
sec = seconds % 60;
temp = ( seconds - sec ) / 60;
minute = temp % 60;
hour = (temp - minute) / 60;
if(!(isFinite(sec) && isFinite(minute) && isFinite(hour))) /* invalid time */
{
return ("");
}
time_str = hour;
time_str += ":";
time_str+=(minute<10)?("0"+minute):minute;
time_str+=":";
time_str+=(sec<10)?("0"+sec):sec;
return (time_str);
}
網頁配置如下:
以下是一個簡單的測試版本,
另外又在網上找到一個將秒數轉時分秒(TimeToHMS)
javascript func。
script範例程式如下:
//20分鐘
var allTime = 1200000;
$(document).ready(function(){
$("#myDiv").css("border","3px solid red");
DoTestCount();
});
function DoTestCount()
{
if(allTime <= 0){
//dopostback
__doPostBack(this.btnSubmit,"")
}
else
{
var timeTmp = allTime/1000;
var currentTimeHMS = TimeToHMS(timeTmp)
$("#myDiv").text(currentTimeHMS)
setTimeout("DoTestCount()",1000);
}
allTime-=1000;
}
/* convert seconds value to H:MM:SS format */
function TimeToHMS(seconds)
{
sec = seconds % 60;
temp = ( seconds - sec ) / 60;
minute = temp % 60;
hour = (temp - minute) / 60;
if(!(isFinite(sec) && isFinite(minute) && isFinite(hour))) /* invalid time */
{
return ("");
}
time_str = hour;
time_str += ":";
time_str+=(minute<10)?("0"+minute):minute;
time_str+=":";
time_str+=(sec<10)?("0"+sec):sec;
return (time_str);
}
網頁配置如下:
Asp.NET buttom doPostBack
今天剛好要用到倒數時間來觸發button 的click事件,
才發現原來頁面上配置button時,
原來是不會自動產生__doPoskBack這個func
要自已加入
if(!IsPostBack)
this.Page.GetPostBackEventReference(this.btnSubmit, "");
MS SQL 更改SA帳號密碼
開啟SQL Server Management Studio,「安全性」->「登入」->右邊的「SA」按右鍵,選屬性,就可以改了。
1. sp_droplogin:移除 Microsoft SQL Server 登入,防止以該登入名稱存取 SQL Server 的執行個體。
2. sp_addlogin:建立一項新的 SQL Server 登入,讓使用者利用 SQL Server 驗證來連接 SQL Server 的執行個體。
3. sp_grantdbaccess:將資料庫使用者加入目前資料庫中。
4. sp_revokedbaccess:從目前資料庫移除資料庫使用者。
Reference:
http://msdn.microsoft.com/zh-tw/library/ms174428.aspx
http://msdn.microsoft.com/zh-tw/library/ms162806.aspx
1. sp_droplogin:移除 Microsoft SQL Server 登入,防止以該登入名稱存取 SQL Server 的執行個體。
2. sp_addlogin:建立一項新的 SQL Server 登入,讓使用者利用 SQL Server 驗證來連接 SQL Server 的執行個體。
3. sp_grantdbaccess:將資料庫使用者加入目前資料庫中。
4. sp_revokedbaccess:從目前資料庫移除資料庫使用者。
Reference:
http://msdn.microsoft.com/zh-tw/library/ms174428.aspx
http://msdn.microsoft.com/zh-tw/library/ms162806.aspx
星期三, 9月 02, 2009
Url Rewriting Survey
URL rewrite 的幾種做法 By 艾倫郭
以下為Url Rewriting的幾種做法:
Approach 1: Use Request.PathInfo Parameters Instead of QueryStrings
Approach 2: Using an HttpModule to Perform URL Rewriting
Approach 3: Using an HttpModule to Perform Extension-Less URL Rewriting with IIS7
Approach 4: ISAPIRewrite to enable Extension-less URL Rewriting for IIS5 and IIS6
簡易的 Url Rewriting 隱藏 Querystring
訂閱:
意見 (Atom)
