2011年10月17日 星期一

以檔案總管開啟URL瀏覽資料夾(使用WebDAV架構)

1. IIS 網頁服務延伸將WebDAV設為允許
2. IIS 建立虛擬目錄並將瀏覽打勾,驗證存取勾選整合式windows及摘要式windows
3. 網頁加入以下程式
<style>
.httpFolder {behavior: url(#default#httpFolder);}
</style>
<script type="text/javascript">
function fnOpenFolderView(url) {
oDAV.navigateFrame(url, "_self");
}
</script>
<div id = "oDAV" class = "httpFolder" />
<a href="#" onclick = "fnOpenFolderView('http://...');">...</a>

註: WebDAV 只支援 IE

2011年8月1日 星期一

四捨五入or四捨六入五成雙

Math.Round <= 四捨六入五成雙
Math.Round(5.7,MidpointRounding.AwayFromZero) <= 四捨五入到整數
ToString("0.00") <= 四捨五入到兩位小數

2011年7月29日 星期五

禁用輸入法

System.Windows.Input.InputMethod.SetIsInputMethodEnabled([要禁用的控制項], false);

2011年7月22日 星期五

解決包在 updatepanel 中的textbox 如果在 server 端呼叫 .focus() 會造成失效或無法輸入中文

改用下面這段取代 focus()
var sScript = "setTimeout(\"$get('" + TextBox1.ClientID + "').focus(); \", 100);";
ScriptManager.RegisterStartupScript(this, this.GetType(), "focus", sScript, true);

PS. 記得不要把ClientIDMode設為"Static",否則會造成整頁刷新的bug
PS. "focus" 針對不同控制項要取不同名稱

2011年5月23日 星期一

使用 smtpclient 發送郵件之附件處理方式

// 以二進位傳送
mail.Attachments.Add(new Attachment(filename, MediaTypeNames.Application.Octet));
// 檔名避免亂碼(或只需安裝 .net framework 4.5?)
foreach (var att in mail.Attachments)
att.NameEncoding = System.Text.Encoding.UTF8;

若附件大於3MB 則必須另外安裝hotfix

2011年4月15日 星期五

如何將 clickonce 發布至 windows 2003 x64

1.下載並安裝 FrontPage Server Extensions 2002 for Windows x64
2.設定 Internet Information Services (IIS) 以 32 位元模擬模式執行
2.1.開啟命令提示字元並瀏覽至 c:\inetpub\adminscripts
2.2.執行下列指令:(可能需要執行兩次才會出現成功訊息)
adsutil.vbs set w3svc/AppPools/Enable32bitAppOnWin64 1
2.3.執行 IISRESET 以重新啟動 IIS
3.安裝 .NET framework
4.執行 32 位元版本的 aspnet_regiis -i,位置在 C:\WINDOWS\Microsoft.NET\Framework\[版本目錄]
5.執行 IISRESET 以重新啟動 IIS

2011年4月11日 星期一

設定 ajax CascadingDropDown selected value

於 javascript 中撰寫功能,範例如下

非最後一個:
var cddStdRegionCountry = $find("cddStdRegionCountry");
cddStdRegionCountry.set_SelectedValue(countryid);
cddStdRegionCountry._onParentChange(null, true);

最後一個:
document.getElementById("ddlStdRegion").value="1"
var cddStdRegion = $find("cddStdRegion");
cddStdRegion.set_SelectedValue(document.getElementById("ddlStdRegion").value);

注意!
請勿將 dropdownlist autopostback 設為 true 然後在 server 端撰寫功能
否則會有錯誤訊息
推測是 CascadingDropDown 和 autopostback=true 不相容導致

2011年3月22日 星期二

網頁中按下enter 自動跳下一個文字方塊

<script language="JavaScript">
var isNN = (navigator.appName.indexOf("Netscape") != -1);
document.onkeyup = autoTab;
document.onkeydown = blockEnter;
function autoTab() {
var e = event;
var input = event.srcElement;
var keyCode = (isNN) ? e.which : e.keyCode;
if (keyCode == 13 && input.type!="textarea") {
if (getNextIndex(input) > -1)
input.form[(getNextIndex(input)) % input.form.length].focus();
}
}
function containsElement(arr, ele) {
var found = false, index = 0;
while (!found && index < arr.length)
if (arr[index] == ele)
found = true;
else
index++;
return found;
}
function getNextIndex(input) {
var index = -1, i = 0,j=0, found = false;
while (i < input.form.length && index == -1)
if (input.form[i] == input) {
j = i + 1;
while (j < input.form.length && index == -1) {
if (input.form[j].type == "text" || input.form[j].type == "textarea") index = j;
else j++;
}
return index;
}
else i++;
}
function blockEnter(evt) {
evt = (evt) ? evt : event;
var charCode = (evt.charCode) ? evt.charCode :

((evt.which) ? evt.which : evt.keyCode);
if (charCode == 13) {
var input = event.srcElement;
if (input.type != "textarea") return false;
} else {
return true;
}
}
</script>

2011年2月21日 星期一

Kill Excel.exe Process in C# .NET

使用 Interop.Excel 時就算相關資源都已釋放,但除非 winform 關閉否則還是會殘留一個process
這裡有一篇文章教你強制關閉process

以下為釋放資源範例
for (int i = 1; i <= sheets.Count; i++) Marshal.FinalReleaseComObject(sheets[i]);
Marshal.FinalReleaseComObject(sheets);
Marshal.FinalReleaseComObject(xlsbook);
xlsbooks.Close();
Marshal.FinalReleaseComObject(xlsbooks);
xlsapp.Quit();
Marshal.FinalReleaseComObject(xlsapp);
GC.Collect();

2011年1月31日 星期一

正確處理 combobox 的 lostfocus

於 LostKeyboardFocus 事件函數中判斷
if (!(e.NewFocus is ComboBoxItem) && e.OldFocus == sender)
{
// 要處理的事情
}

2011年1月28日 星期五

使用 AJAX 的 cascadingdropdown 於下拉選單出現 [方法錯誤500]

因為下拉選單的資料量超出預設的限制造成
必須於 web.config 增加一段設定以便擴充限制

<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="500000" />
</webServices>
</scripting>
</system.web.extensions>

2011年1月27日 星期四

SQL Server 填補字串右邊字元函數

create FUNCTION dbo.PadRight
(
@PadChar char(1),
@PadToLen int,
@BaseString varchar(100)
)
RETURNS varchar(1000)
AS
BEGIN
DECLARE @Padded varchar(1000)
DECLARE @BaseLen int
SET @BaseLen = datalength(@BaseString)
IF @BaseLen >= @PadToLen
BEGIN
SET @Padded = @BaseString
END
ELSE
BEGIN
SET @Padded = @BaseString + REPLICATE(@PadChar, @PadToLen - @BaseLen)
END
RETURN @Padded
END

註 : 此函數會將中文當作兩個字元看待,以便使用固定寬度字型時能夠正確對齊中英文混雜的資料

2011年1月20日 星期四

ListView 搭配資料庫中的圖片

1. 在ListView中放置顯示圖片及上傳圖片的控制項,圖片網址為一泛行處理常式
<asp:Image ID="picAlbum" runat="server" ImageUrl='<%# "ShowImage.ashx?id=" + Eval("id") %>' />
<asp:FileUpload ID="imgUpload" runat="server" />

2. 撰寫泛行處理常式顯示資料庫中的圖片欄位
public class ShowImage : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
int id;
if (context.Request.QueryString["id"] != null)
id = Convert.ToInt32(context.Request.QueryString["id"]);
else
throw new ArgumentException("No parameter specified");

context.Response.ContentType = "image/jpeg";
Stream strm = GetImage(id);
byte[] buffer = new byte[4096];
int byteSeq = strm.Read(buffer, 0, 4096);

while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 4096);
}
//context.Response.BinaryWrite(buffer);
}

private Stream GetImage(int id)
{
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT 照片 FROM 照片表格 WHERE ID = @ID";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@ID", id);
object img = cmd.ExecuteScalar();
try
{
return new MemoryStream((byte[])img);
}
catch
{
return null;
}
}
}
}

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

3. 於datasource的inserting、updating事件函數中取得使用者選擇的檔案作為參數值
private Byte[] getImage(FileUpload img)
{
Byte[] imgByte = null;
if (img.HasFile && img.PostedFile != null)
{
//To create a PostedFile
HttpPostedFile File = img.PostedFile;
//Create byte Array with file len
imgByte = new Byte[File.ContentLength];
//force the control to load data in array
File.InputStream.Read(imgByte, 0, File.ContentLength);
}
return imgByte;
}

4. 針對updating或inserting事件必須考慮使用者未選取任何檔案時會遇到資料型別不符問題,因為null會當作nvarchar型態造成語法錯誤問題,所以必須抽換參數改用SqlParameter並指定型別為Image,因為原本的參數型別不包含image
e.Command.Parameters.Remove(e.Command.Parameters["@照片"]);
e.Command.Parameters.Add(new SqlParameter("@照片", System.Data.SqlDbType.Image));

Entity Framework 建立新物件並儲存後馬上取得關聯資料

使用 CreateProxy 建立物件,不要直接 new var newmodel = _contextXXX.CreateProxy<yyy>(); ... _contextXXX.yyy.Add(newmodel); await _contextXXX.SaveC...