2014年12月31日 星期三

[.NET] GridVIew合併儲存格

說明:想讓GridView的某欄合併儲存格(非動態等資料繫結後,再判斷資料是否相符),該怎麼做?


做法:
在GridView的PreRender(GridView載入後與render前)事件中加上:

foreach (GridViewRow gvRow in GridView1.Rows)
        {
            if (gvRow.RowIndex > 0)//DataRow
            {
                //let column index+1 merge cell and assign the rows to across
                GridView1.Rows[0].Cells[index].RowSpan = GridView1.Rows.Count;
                //hide the extra cells
                gvRow.Cells[index].Visible = false;
            }
        }



參考資料:
http://www.dotblogs.com.tw/mis2000lab/archive/2008/04/archive/2008/04/archive/2008/04/24/3452.aspx
http://pramaire.pixnet.net/blog/post/31837470-gridview%E8%B3%87%E6%96%99%E5%88%97row%E5%90%88%E4%BD%B5%E6%AC%84%E4%BD%8D

2014年11月24日 星期一

[ClosedXML] 使用語法紀錄

using ClosedXML.Excel;

var workbook = new XLWorkbook(templateFilePath);
var worksheet = workbook.Worksheets.Worksheet(1);

//set cell value
worksheet.Cell(Row, Col).Value = string;

//set value by using DataTable
for (int j = 0; j < Data.Rows.Count; j++)
{
    for (int k = 0; k < Data.Columns.Count; k++)
    {
          worksheet.Cell(j, k).Value = Data.Rows[j][k].ToString();
     }
}

//set cell value in center
worksheet.Cell(R, C).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
worksheet.Cell(R, C).Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;

//set border line
worksheet.Cell(R, C).Style.Border.SetRightBorder(XLBorderStyleValues.Thin);
worksheet.Cell(R, C).Style.Border.SetTopBorder(XLBorderStyleValues.Thin);
worksheet.Cell(R, C).Style.Border.SetBottomBorder(XLBorderStyleValues.Thin);
worksheet.Cell(R, C).Style.Border.SetLeftBorder(XLBorderStyleValues.Thin);

//column fit
worksheet.Column(columnIndex).AdjustToContents();
worksheet.Column(columnIndex).Width -= 1;

//merging columns
//Merge(true) might cause files error?
worksheet.Range(R, C, R2, C2).Column(1).Merge();

//copying worksheets
worksheet.CopyTo(sheetName);
worksheet.CopyTo(workbook2, sheetName);


workbook.SaveAs(filePath);


參考資料:
http://closedxml.codeplex.com/documentation
https://closedxml.codeplex.com/wikipage?title=Copying%20Worksheets
https://closedxml.codeplex.com/wikipage?title=Merging%20Cells

2014年11月6日 星期四

[Oracle] 在小於1的小數的整數位補0

說明:使用Round函式算百分比到小數位數,可能出現小於1的小數,Oracle不會顯示整數位數的0,如.03,那該如何補0呢?

做法:
使用TO_CHAR函式來將數值轉換成特定字串,語法:TO_CHAR(numeric, text),例:
--轉換為百分比,四捨五入到小數第2位,其中fm可去除首尾的空字元
SELECT TO_CHAR(0.05, 'fm990.09')||'%' FROM DUAL;


參考資料:
http://blog.csdn.net/hj402555749/article/details/8878587

2014年10月1日 星期三

[Oracle] 'OraOLEDB.Oracle' 提供者並未登錄於本機電腦上

說明:先安裝Win32 Oracle 11g R2 client,再安裝Win64 11g R2 client,Toad跟PL/SQL Developer都可存取DB,但執行本機程式卻出現「'OraOLEDB.Oracle' 提供者並未登錄於本機電腦上」的錯誤訊息。


嘗試方法:
1. 解除安裝Oracle,可參考此篇http://iamsbc.blogspot.com/2014/05/oracle-windowsoracle.html。
2. 先裝Win32 11g R2 client。
3. 再裝Win64 11g R2 client。

重裝一遍,程式就可以連了,順序都一樣,猜測可能是第一次安裝不完全吧!
P.S. 但第兩次是裝完整版


參考資料:
https://www.ptt.cc/bbs/Database/M.1393220172.A.E90.html

2014年9月25日 星期四

[.NET] 使用Microsoft.Office.Interop.Excel元件將資料匯出Excel

說明:有許多元件可將資料匯成Excel,這裡使用Excel 2010 PIA來實作,加入參考 -> 選.NET tab -> Microsoft.Office.Interop.Excel 12.0.0.0,namespace為Microsoft.Office.Interop.Excel。


做法:
//避免與Windows.Form.Application衝突
using Excel =  Microsoft.Office.Interop.Excel;

Excel.Application _Excel = null; //起一個Excel.exe
Excel.Workbook _Workbook = null; //活頁簿
Excel.Worksheet _Worksheet1 = null;
Excel.Sheets _Sheets = null;

string strTemplateFilePath = Application.StartupPath + @"\EXCEL\Template.xlsx"; //範本路徑
string strRptPath = Application.StartupPath + @"\EXCEL\Rpt\";
string strFilePath = string.Empty;
string strFileName = string.Empty;
           
try
{
    _Excel = new Excel.Application();
    _Excel.Visible = false;
    _Workbook = _Excel.Workbooks.Open(strTemplateFilePath);
    _Sheets = _Workbook.Worksheets;
    string[,] strTable;
 
    if (有資料)
    {
        _Worksheet1 = _Sheets.get_Item(1);
        _Worksheet1.Name = DateTime.Now.ToString("yyyyMM");

        int iInitialRow = 0; //起始列
        int iInitialCol = 0; //起始欄
        int iRowCnt = 資料來源筆數;
        int iColCnt = 資料來源欄位數;

        for (int x = 0; x < iRowCnt; x++)
        {
            for (int y = 0; y < iColCnt; y++)
            {
                strTable[x, y] = dt.Rows[x][y].ToString();
            }
        }

         Excel.Range _RangeStart = _Worksheet1.Cells[iInitialRow, iInitialCol];
         Excel.Range _RangeEnd = _Worksheet1.Cells[iInitialRow+iRowCnt, iInitialCol+iColCnt];
         Excel.Range _Range = (Excel.Range)_Worksheet1.get_Range(_RangeStart, _RangeEnd);
       
         _Range.Value2 = strTable;
         _Range.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter;
         _Range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
         _Range.Font.Name = "Times New Roman";
         _Range.Font.Size = 10;
         _Range.EntireColumn.AutoFit();
         _Range.Borders.Weight = Excel.XlBorderWeight.xlHairline;

         _Workbook.Application.DisplayAlerts = false;
         _Workbook.Application.AlertBeforeOverwriting = false;
         _Workbook.Saved = true;

         strFileName = "Rpt.xlsx";
         strFilePath = strRptPath + strFileName;
         _Workbook.SaveCopyAs(strFilePath);
    }
}
catch (Exception ex)
{
    throw ex;
}
finally
{
    if (_Range != null)
   {
        Marshal.FinalReleaseComObject(_Range );
    }
    if (_Sheets != null)
    {
        Marshal.FinalReleaseComObject(_Sheets);
    }
    if (_Workbook != null)
    {
        _Workbook.Close(false);
        Marshal.FinalReleaseComObject(_Workbook);
     }
     if (_Excel != null)
     {
         _Excel.Workbooks.Close();
         _Excel.Quit();
         Marshal.FinalReleaseComObject(_Excel);
     }
}

 _Range.Cells.Text; //取得範本上資料
 //合併儲存格
 Excel.Range _RangeStart = _Worksheet1.Cells[int, int];
 Excel.Range _RangeEnd = _Worksheet1.Cells[int, int];
 _Worksheet1.get_Range(_RangeStart, _RangeEnd).Merge(0);
//新增工作表
_Worksheet1 = (Excel.Worksheet)_Workbook.Worksheets.Add(After: (Excel.Worksheet)_Workbook.Sheets[test], Count: 1);
_Worksheet1.Name = test+"_"+k;


參考資料:
http://www.dotblogs.com.tw/yc421206/archive/2012/03/09/70624.aspx
http://www.dotblogs.com.tw/yc421206/archive/2008/12/20/6470.aspx //fill in data
http://blog.darkthread.net/post-2013-05-14-excel-interop-notes.aspx //release
http://www.dotblogs.com.tw/chou/archive/2013/03/26/99016.aspx //Excel.Range.Cells.Text
http://fecbob.pixnet.net/blog/post/38189181-c%23-excel-%E8%A1%8C%E9%AB%98%E3%80%81%E5%88%97%E5%AF%AC%E3%80%81%E5%90%88%E4%BD%B5%E5%84%B2%E5%AD%98%E6%A0%BC%E3%80%81%E5%84%B2%E5%AD%98%E6%A0%BC%E9%82%8A%E6%A1%86 //Excel語法彙集
http://ww0o0ww.pixnet.net/blog/post/64084894-%E3%80%90c%23%E3%80%91%E3%80%8Amicrosoft.office.interop.excel%E3%80%8B%E5%AF%AB%E5%85%A5excel%E6%AA%94

2014年9月21日 星期日

[Reporting Service] 使用CDate函式轉換Date Type為YYYYMMDD

說明:使用Reporting Service繫結Oracle或SQL Server資料庫欄位為Date Type資料時,會出現「上午12:00:00」,該如何去除呢?


做法:
在Reporting Service繫結的欄位 -> properties(找屬性視窗) -> Value -> =Format(CDate(Fields!DATE.Value), "yyyy/MM/dd")


參考資料:
http://stackoverflow.com/questions/9722516/report-builder-3-0-how-to-convert-string-representation-of-dates-in-mm-dd-yy-fo

2014年8月24日 星期日

[UltraEdit] 使用區塊模式(column mode)替一堆字串一次加入單引號

說明:SQL使用IN查詢一堆同一欄位的資料,這些查詢的value需要單引號包起來,資料一多該怎麼處理比較方便呢?


作法:
使用UltraEdit的區塊模式(column mode),功能列->直行->區塊模式,快捷鍵為alt + c,轉換該模式後,將游標移到第一行字串前,按住shift不放再按滑鼠左鍵往下拖曳,此時會出現一條線,按下單引號鍵即可。


參考資料:

2014年7月30日 星期三

[ASP.NET] GridView樣板內控制項文字設定斷行

說明:因GridView內控制項(label)文字太長,想設定斷行。


作法:
1. 在GridView的RowDataBound事件內,找到該控制項。
2. 再設定特定長度或字元斷行,例:
 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        Label lblTest = (Label)e.Row.FindControl("lblTest");
        if (lblTest .Text.Length > 0)
        {
            //1. 直接insert <br/>
            blTest.Text = (lblTestt.Text.IndexOf('.') > 0) ? lblTest.Text.Insert(lblTestt.Text.IndexOf('.') + 1, "<br/>") : blTest.Text;

        
            // 2. 用replace加入<br/>
            lblTest.Text = lblTest.Text.Replace(".", ".<br/>");
        }
    }
}


參考資料:
http://www.dreamincode.net/forums/topic/117242-wrapping-around-a-symbol/
http://msdn.microsoft.com/zh-tw/library/11w09h50(v=vs.110).aspx

2014年7月21日 星期一

[Oracle/Toad] 如何在toad測試function與procedure

說明:在修改完function或procedure (schema Browser -> copy script to an Editor Window)後,要如何測試呢?


作法:
測試function:
1. Menu -> View -> 打開DBMS Output
2. 在Editor視窗輸入如下語法:
begin
    parameter := '測試資料';
    dbms_output.put_line(packagename.functionname(parameter));
commit;
end;
3. return值會顯示於DBMS Output視窗上
或SELECT function FROM dual;

測試procedure:
1. schema Browser -> Tab Source上右鍵 -> Execute Procedure (或copy code到Editor執行)
2. SELECT procedure FROM dual;


參考資料:
http://stackoverflow.com/questions/4827134/how-do-i-get-the-return-value-from-a-function-in-oracle-using-toad
http://www.dotblogs.com.tw/kim/archive/2011/06/01/26827.aspx
http://blog.yam.com/csylvia/article/71505909
http://plsql-tutorial.com/plsql-passing-parameters-procedure-function.htm
http://plsql-tutorial.com/plsql-functions.htm
http://blog.yam.com/csylvia/article/71505909
http://godleon.blogspot.tw/2008/12/oracle-stored-procedures.html

2014年7月17日 星期四

[AJAX] 使用ASP.NET Ajax與jQuery Ajax實作連動下拉式選單

說明:
使用ASP.NET Ajax與jQuery Ajax實作兩個下拉式選單,第一個為地區(id: ddlArea),第二個顯示對應地區的縣市(id: ddlCounty)。


作法:
使用ASP.NET Ajax:
1. .NET 3.5已內建ASP.NET Ajax,若是更舊版本需自行import Ajax Extensions。
2. 從工具箱拉ScriptManager與UpdatePanel控制項,然後將ddlCounty放進UpdatePanel內,
     並設定Triggers為ddlArea,例:
xxx.aspx
<asp:ScriptManager ID="ScriptManager1" runat="server" ScriptMode="Release" >
    </asp:ScriptManager>
<asp:DropDownList ID="ddlArea" runat="server" AutoPostBack="true" onselectedindexchanged="ddlArea_SelectedIndexChanged"></asp:DropDownList>
 <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
     <ContentTemplate>
         <asp:DropDownList ID="ddlCounty" runat="server"></asp:DropDownList>    
     </ContentTemplate>
     <Triggers>
          <asp:AsyncPostBackTrigger ControlID="ddlArea"
                                EventName="SelectedIndexChanged"></asp:AsyncPostBackTrigger>
     </Triggers>
 </asp:UpdatePanel>

xxx.aspx.cs
protected void ddlArea_SelectedIndexChanged(object sender, EventArgs e)
{
        if (this.ddlArea.SelectedIndex > 0)
        {
            DataTable dtCounty = 資料來源;
            this.ddlCounty.DataSource = dtCounty;
            this.ddlCounty.DataTextField = "County_Name";
            this.ddlCounty.DataValueField = "County_No";
            this.ddlCounty.DataBind();
        }
}


使用jQuery Ajax (後端使用webservice):
1. 在webservice新增webmethod供ajax存取,例:
//WebService.cs
public class AreaInfo
{
        public string AreaNo { get; set; }
        public string AreaName { get; set; }
}

public class CountyInfo
{
        public string CountyNo { get; set; }
        public string CountyName { get; set; }
}

[WebMethod]
public List<AreaInfo> LoadArea()
{
        List<AreaInfo> AreaInfo1 = new List<AreaInfo>();

        DataTable dtResult = 資料來源;
        if (dtResult != null && dtResult.Rows.Count > 0)
        {
            for (int i = 0; i < dtResult.Rows.Count; i++)
            {
                AreaInfo1.Add(new AreaInfo()
                {
                    AreaNo = dtResult.Rows[i]["Area_No"].ToString(),
                    AreaName = dtResult.Rows[i]["Area_Name"].ToString()
                });
            }
        }
        return AreaInfo1;
}

[WebMethod]
public List<CountyInfo> LoadCounty(string strAreaNo)
{
        List<CountyInfo> CountyInfo1 = new List<CountyInfo>();

        DataTable dtResult = 資料來源;

        if (dtResult != null && dtResult.Rows.Count > 0)
        {
            for (int i = 0; i < dtResult.Rows.Count; i++)
            {
                CountyInfo1.Add(new CountyInfo()
                {
                    CountyNo = dtResult.Rows[i]["County_No"].ToString(),
                    CountyName = dtResult.Rows[i]["County_Name"].ToString()
                });
            }
        }
        return CountyInfo1;
}

2. include jQuery library並使用jQuery.ajax跟後端要資料(回傳格式使用json),例:
//xxx.aspx
<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
        $(document).ready(function() {
        $.ajax({
                type: 'post',
                contentType: "application/json; charset=utf-8",
                url: "WebService.asmx/LoadArea",
                data: "{}",
                dataType: "json",
                success: function(Result) {
                    $.each(Result.d, function(key, value) {
                        $("#ddlArea").append($("<option></option>").val(value.AreaNo).html(value.AreaName));
                    });
                },
                error: function() { alert('ajax fail'); }
            });
            $('#ddlArea').change(function() {
            $("#ddlCounty").find('option').remove();
                var ID = $(this).val();
                $.ajax({
                    type: 'post',
                    contentType: "application/json; charset=utf-8",
                    url: "WebService.asmx/LoadCounty",
                    data: "{strAreaNo:" + ID + "}",
                    dataType: "json",
                    success: function(Result) {
                        $.each(Result.d, function(key, value) {
                           $("#ddlCounty").append($("<option></option>").val(value.CountyNo).html(value.CountyName));
                        });
                    },
                    error: function() { alert('ajax fail'); }
                });
            });
        });
</script>

<asp:DropDownList ID="ddlArea" runat="server"></asp:DropDownList>
<asp:DropDownList ID="ddlCounty" runat="server"></asp:DropDownList>


參考資料:
http://stackoverflow.com/questions/10477476/why-0-in-textbox10-value-is-used-to-get-scalar-value-in-asp-net-control

http://www.dotblogs.com.tw/hatelove/archive/2009/12/22/jqueryajax.aspx
http://msdn.microsoft.com/zh-tw/dd310332.aspx#jQuery
http://www.dotblogs.com.tw/topcat/category/1656.aspx
http://pastie.org/2356308
http://social.msdn.microsoft.com/Forums/zh-TW/384800f1-d366-484e-bd30-aaeac5d07d85/aspnet-jqueryjqueryajaxashxaspxasmx?forum=236#9125942a-cc8a-41d5-981e-882fe0894f82
https://www.youtube.com/playlist?list=PLNPgPJ-90sSlwfSHvuyafzWJ8jQphAam0
http://www.codeproject.com/Tips/688228/Bind-Dropdownlist-in-ASP-NET-using-jQuery-AJAX
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/

2014年6月11日 星期三

[C#] 加入參考Microsoft.office.core的dll


做法:
加入參考->選取COM tab ->找到Microsoft Office (1x.0) Object Library


參考資料:
http://social.msdn.microsoft.com/Forums/en-US/6fef9910-fed8-4b13-9366-66d24c0966a7/microsoftofficecoredll-location

2014年5月30日 星期五

[ASP.NET] a potentially dangerous request.form value was detected from the client

說明:ASP.NET 4.0,另開新視窗時,出現錯誤訊息:a potentially dangerous request.form value was detected from the client,是避免XSS (Cross-site scripting)攻擊(一種夾帶script語法到網頁的方式)的訊息,所以偵測到post <或>字元,就會出現此訊息。


解決方法:
1.在web.config的<system.web></system.web>標籤中加上 <httpRuntime requestValidationMode="2.0" />與<pages validateRequest="false" />,因為ASP.NET 2.0 request validation的順序會在request processing events之後,若限個別pages,可在各pages加上<@ Page validateRequest="false" %>,但此方法不推薦。

2. 使用HttpUtility.HtmlEncode (Server.HtmlEncode)或AntiXss.HtmlEncode (import AntiXssLibrary.dll),會將特殊字元編碼HTML字元集,如<換為&lt;,"換為&quot;,供HTML正常輸出。



參考資料:
http://stackoverflow.com/questions/81991/a-potentially-dangerous-request-form-value-was-detected-from-the-client
http://www.asp.net/whitepapers/aspnet4/breaking-changes
http://msdn.microsoft.com/en-us/library/hh882339.aspx
http://msdn.microsoft.com/en-us/library/aa973813.aspx
http://msdn.microsoft.com/en-us/library/ms998274.aspx
http://www.dotblogs.com.tw/johnny/archive/2010/03/01/13829.aspx
http://www.dotblogs.com.tw/coca/archive/2011/03/11/21794.aspx
http://blog.darkthread.net/post-2008-06-18-eval-xss.aspx



2014年5月7日 星期三

[Oracle] Windows環境下手動移除Oracle client

作法:
1. 使用Oracle Universal Installer (OUI)移除Oracle全部安裝程式。
2. 開始->執行regedit.exe->刪除HKEY_LOCAL_MACHINE/SOFTWARE/Oracle登錄檔。
3. 如果windows是64位元,需再刪HKEY_LOCAL_MACHINE/SOFTWARE/Wow6432Node/Oracle登錄檔,如果有的話。
4. 刪除HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services/Ora開頭的登錄檔。
5. 重開機。
6. 刪除C:\Oracle (ORACLE BASE目錄)。
7. 刪除C:\Program Files\Oracle目錄,如果windows是64位元,需刪除C:\Program Files (x86)\Oracle目錄。
8. 刪除在C:\ProgramData\Microsoft\Windows\Start Menu\Programs\目錄下與Oracle相關的子目錄。
9. 刪除C:\temp目錄下的所有檔案->再清空資源回收桶(與Oracle相關檔案)->結束。


參考資料:
http://www.oracle-base.com/articles/misc/manual-oracle-uninstall.php

2014年4月28日 星期一

[Oracle] PL/SQL Developer無法載入oci.dll (Could not load oci.dll)的解決辦法

說明:安裝Oracle Client 64 bits版本,使用PL/SQL Developer設定Oracle Home與OCI library後,會出現Could not load oci.dll、OCIDLL forced to oci.dll、LoadLibrary(oci.dll) returned 0的錯誤訊息,這是因為PL/SQL Developer是32 bits的應用程式,無法載入64 bits的oci.dll檔。


找到兩種解法:
1. Oracle官網(http://www.oracle.com/technetwork/database/features/instant-client/index-097480.html)下載Instant Client Downloads for Microsoft Windows (32-bit) -> 解壓縮到某路徑 -> 將PL/SQL Developer(程式->Tools->Preferences)的Oracle Home設為此路徑 -> OCI library設為路徑\oci.dll -> 至系統內容內的環境變數新增一筆TNS_ADMIN = Oracle Client 64 bits放tnsnames.ora的路徑(例: D:\app\xxx\product\11.2.0\client_1\network\admin) -> 再打開PL/SQL Developer即可。

2. 直接安裝Oracle Client 32 bits版本,可與64 bits共存,測試過也可以。


參考資料:
http://www.databaseskill.com/488915/
http://www.oracle.com/technetwork/topics/winsoft-085727.html
http://www.nextofwindows.com/how-to-addedit-environment-variables-in-windows-7/
http://daniel-tu.iteye.com/blog/1276589

2014年4月20日 星期日

[ASP.NET] 在Server端動態加入Client script

說明:想在server端建立client script時,該怎麼做?


作法:
使用Page.ClientScript屬性取得的ClientScriptManager object提供的四個method:
1. RegisterStartupScript(Type type, string key, string script, bool addScriptTags):
    在網頁載入完成後及網頁OnLoad事件觸發前,會執行所加入的script,適用非一開始會用
    到的script。

2. RegisterClientScriptBlock(Type type, string key, string script, bool addScriptTags):
    會將script加入至網頁頂端(<form>下),不保證script可依註冊的順序輸出。

3. RegisterClientScriptInclude(Type type, string key, string url):
    動態加入js 檔的script,在以動態方式加入其他script前就會加入該script,因此可能無法參
    考網頁上的某些項目。

4. RegisterOnSubmitStatement(Type type, string key, string script):
    加入可回應網頁onsubmit 事件的script (ex: confirm),在送出網頁前即執行script,因此可取消送出動作。例:
    ClientScript.RegisterOnSubmitStatement(this.GetType(), "ConfirmSubmit", "return confirm('Do you want to submit the page?')");


參考資料:
http://msdn.microsoft.com/zh-tw/library/system.web.ui.page.clientscript%28v=vs.90%29.aspx
http://msdn.microsoft.com/zh-tw/library/system.web.ui.clientscriptmanager%28v=vs.90%29.aspx
http://msdn.microsoft.com/zh-tw/library/ms178207%28v=vs.100%29.aspx
http://www.dotblogs.com.tw/hatelove/archive/2009/10/28/11325.aspx
http://msdn.microsoft.com/zh-tw/library/7ytf5t7k%28v=vs.100%29.aspx


[C#] 透過WebBrowser控制項與HtmlElement類別自訂填表程式

說明:訂票時可自訂自動填表程式,減少輸入表單時間。


作法:
1. 開啟一winform專案->從工具箱拉WebBrowser進來。
2. 在WebBrowser物件的Url屬性上填上目標網址->選取DocumentCompleted事件。
3. code behind:
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
            HtmlDocument hdTest = webBrowser1.Document;
            foreach (HtmlElement he in hdTest.All)
            {
                if (he.Name == "selectStartStation")
                {
                    he.SetAttribute("value", "1");
                }
                else if (he.Name == "selectDestinationStation")
                {
                    he.SetAttribute("value", "7");
                }
                else if (he.Id == "mobileInputRadio")
                {
                    he.InvokeMember("onClick");
                    he.SetAttribute("checked", "radio47");
                }
            }
}


參考資料:
1. 自動訂票程式
http://blog.xuite.net/tzjvetaj/blog/11653752-%E8%87%AA%E8%A3%BD%E8%A8%82%E7%A5%A8%E7%A8%8B%E5%BC%8F
2. 自動填表
http://rritw.com/a/bianchengyuyan/csharp/2011/0919/129332.html
3. radio
http://social.msdn.microsoft.com/Forums/zh-TW/4deeddb1-ea22-4683-9890-4eed2a0ed233/radio-?forum=236

2014年3月30日 星期日

[JavaScript] BOM (Browser Object Model) methods或properties記錄

BOM function:

1. window object:
1.1 moveBy(dx, dy),dx表水平移動的像素,dy為垂直向下的像素,可為負數。
1.2 moveTo(x, y),將視窗移到螢幕的(x, y)處,可為負數。
1.3 resizeBy(dw, dh),dw表寬度增加的像素,dh為高度增加的像素,可為負數。
1.4 resizeTo(w, h),視窗寬度調為w像素,高度為h像素,不能負數。
1.5 open(URL, name, specs, replace),四個參數皆為optional,name可以為target屬性或式窗的名稱,如_blank, _self, _parent等,specs為特性字串,如height, width, menubar, resizable, scrollbar, toolbar等,replace為是否替代原視窗的bool值。
1.6 close(),關閉新開的視窗。
1.8 alert(), confirm(), prompt()
1.8 history.go(),  history.back(), history.forward()

2. document object:
2.1 write()

3. location object:
3.1 replace(URL),使用者無法back,會移除document history。
3.2 reload(bool),預設false,從暫存reload,反之從server。
3.3 href,導入新頁面。

4. navigator object:
4.1 userAgent,可獲取user agent字串。

5. screen object:
5.1 availHeight,視窗可使用的螢幕高度。
5.2 avaiWidth,視窗可使用的螢幕寬度。


參考資料:
http://www.w3schools.com/jsref/obj_window.asp

2014年3月27日 星期四

[ASP.NET] 套用MasterPage的Button權限控管

說明:有使用MasterPage,想根據用戶的權限代號(Authority)管控頁面上的新增/編輯/刪除等button,無權限則disable該button。


做法:在MasterPage的PreRender事件中使用ContentPlaceHolder控制項的findcontrol找到新增/編輯/刪除等button後,再分別disable該button。例:

//namespace
[Flags]
public enum Privilege
{
            None=0,
            View=1,
            Add=2,
            Edit=4,
            Remove=8,
            All = None|View|Add|Edit|Remove
}

//xxx.master.cs
protected override void OnPreRender(EventArgs e)
{
        try
        {
             Button btnAdd = (Button)ContentPlaceHolder1.FindControl("btnAdd");
             Button btnEdit = (Button)ContentPlaceHolder1.FindControl("btnEdit");
             Button btnDel = (Button)ContentPlaceHolder1.FindControl("btnDel");

             if (Authority == (int)Privilege.View)
             {
                 btnAdd.Disable = false;
                 btnEdit.Disable = false;
                 btnDel.Disable = false;
             }
             else if (Authority == (int)(Privilege.View | Privilege.Add))
             {
                 btnEdit.Disable = false;
                 btnDel.Disable = false;
             }
             ...以此類推
        }
        catch (Exception ex)
        {
            throw ex;
        }
        base.OnPreRender(e);
}


參考資料:

[C#] 判斷DataTable有無該欄位語法紀錄

說明:判斷DataTable有無該欄位。


語法:DataTable.Columns.Contains(欄位名稱);,例:
if (dtTemp.Columns.Contains("test")) {...}
esle {...}


參考資料:
http://www.programmer-club.com/showSameTitleN/csharp/2210.html

2014年3月26日 星期三

[T-SQL] 使用SSMS建立外來鍵(foreign key)

說明:使用SQL Server Management Studio建立外來鍵(FK),FK即關聯外部table的PK,以保持資料完整性。


作法:
1. 在物件總管中,在欲設定FK的table按右鍵->選擇[設計]。
2. 在欄位上按右鍵->選擇[關聯性]->點選[加入]。
3. 按一下[資料表和資料行規格]->再按右邊的省略符號 ([…])。
4. 在對話視窗中[主索引鍵]的下拉式清單中->選擇要關聯外部PK的table與欄位。
5. 對應右邊選擇要設定FK的table與欄位->按確定即可。


參考資料:
http://technet.microsoft.com/zh-tw/library/ms189049.aspx
http://msdn.microsoft.com/zh-tw/library/ms175464.aspx

2014年3月20日 星期四

[Subversion] 更新失敗:解壓縮時發生錯誤 ra_serf: An error occurred during decompression

說明:從subversion上更新資料時,發生更新失敗:ra_serf: An error occurred during decompression,使用collabnet subversion 1.8.8 on Windows 2008 R2 64bits。


解法:
Subversion Edge 4.x configures the server to use mod_deflate which improves performance. I cannot say what the problem is, you could try reporting it at users at subversion dot apache dot org. There are currently not any good ways to gather diagnostics out of the Serf library but if you can do a Wireshark there are people on the list that might be able to see something.

You can disable mod_deflate by renaming the file mod_deflate.so in the lib/modules folder of your server and stopping and starting the Subversion server via the Edge web UI. I would guess this will resolve the problem.



參考資料:
https://subversion.open.collab.net/ds/viewMessage.do?dsForumId=3&viewType=browseAll&dsMessageId=503878#messagefocus

[Subversion] 更新失敗:連線已被您主機上的軟體中止

說明:從subversion更新大量資料時,出現更新失敗:「連線已被您主機上的軟體中止」的訊息。使用collabnet subversion 1.8.8 on Windows 2008 R2 64bits。


解法:
1. 在subversion server上找到httpd.conf檔 (C:\Program Files\CollabNetEdge\data\conf)
2. 在裡面加上SVNAllowBulkUpdates Prefer,儲存後重新啟動subversion apache service即可.


參考資料:
https://groups.google.com/forum/#!topic/tortoisesvn-dev/idsTxNkMMsQ
http://subversion.apache.org/docs/release-notes/1.8.html#serf-skelta-default

2014年3月12日 星期三

[CSS] box-shadow使用記錄

說明:想將網頁刻出一塊對比的版面,使用CSS3的box-shadow。


語法:
box-shadow: x y blur spread color inset;
x: 陰影水平位移距離,必要值。
y: 陰影垂直位移句離,必要值。
blur: 模糊強度,預設為0,不能負值。
spread: 擴散強度,預設為0。
color: 陰影顏色。
inset: 內陰影。

例:
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
搭配width: 來控制盒子寬度。
搭配margin: 控制盒子間隔。


參考資料:
http://boohover.pixnet.net/blog/post/35116159-%E9%99%B0%E5%BD%B1%E6%95%88%E6%9E%9C%E5%8F%8A%E5%85%89%E6%9A%88%E6%95%88%E6%9E%9C%E7%9A%84-box-shadow-(css-property)

2014年3月7日 星期五

[ASP.NET] 動態產生控制項TextBox、CalendarExtender與DropDownList並取值

說明:動態產生控制項TextBox、CalendarExtender與DropDownList並取值,其中產生控制項最好放在事件OnInit裡,可透過ViewState來更新控制項的屬性值。本例已有一列靜態控制項,並搭配HiddenField來紀錄資料列數。


語法:
//code behind
using AjaxControlToolkit;

protected void Page_Load(object sender, EventArgs e)
{
        if (IsPostBack)
        {
            int iNum = 0;
            if (!string.IsNullOrEmpty(hidNum.Value))
                iNum = int.Parse(hidNum.Value);
            AddRecord(iNum, false);
        }
}

protected void btnMore_Click(object sender, EventArgs e)
{
        int iNum = 0;
        if (!string.IsNullOrEmpty(hidNum.Value))
            iNum = int.Parse(hidNum.Value);
        iNum++;
        hidNum.Value = iNum.ToString();
        AddRecord(int.Parse(hidInvoiceNum.Value), true);
}

private void AddRecord(int iNum, bool blFlag)
{
        int iTemp = 1;
        if (blFlag) iTemp = iNum;
        for (int i=iTemp; i <= iNum; i++)
        {
            TableRow tr = new TableRow();

            TableCell tc1 = new TableCell();
            TextBox txtNo = new TextBox();
            txt.ID = "txtNo" + i;
            tc1.Controls.Add(txtNo);
            tr.Cells.Add(tc1);

            TableCell tc2 = new TableCell();
            TextBox txtDate = new TextBox();
            CalendarExtender ce = new CalendarExtender();
            txtDate.ID = "txtDate" + i;
            ce.TargetControlID = "txtDate" + i;
            ce.Format = "yyyy/MM/dd";
            this.PlaceHolder1.Controls.Add(ce);
            tc2.Controls.Add(txtDate);
            tr.Cells.Add(tc2);

            TableCell tc3 = new TableCell();
            DropDownList ddlType = new DropDownList();
            ddlType.ID = "ddlType" + i;
            ddlType.DataSource = datasource;
            ddlType.DataTextField = "Text";
            ddlType.DataValueField = "Value";
            ddlType.DataBind();
            tc3.Controls.Add(ddlType);
            tr.Cells.Add(tc3);

            //Add Server Control Table
            this.tbTest.Rows.Add(tr);
}

//取值
for (int i = 0; i <= int.Parse(hidNum.Value); i++)
{
        txtNo = (TextBox)tbTest.FindControl("txtNo" + i);
        txtDate = (TextBox)tbTest.FindControl("txtDate" + i);
        ddlType = (DropDownList)tbTest.FindControl("ddlType" + i);
}

[VB.NET] 三元運算子IIF

說明:
VB中的三元運算子該怎麼寫?C#為 value = condition ? first_expression : first_expression;


語法:
value = IIF (condition, first_expression, first_expression)


參考資料:
http://itgroup.blueshop.com.tw/shian/blog?n=convew&i=1770

[ASP.NET] 控制項tooltip與html title屬性文字斷行

說明:若使用html tag的title屬性,文字使用&#10;(ASCII的\n)或&#13;(ASCII的\r)來斷行,若用server control要做到同樣效果,如Panel的tooltip文字使用\n或\r或\r\n。

例:
//html title
<div id="pic" title="1. test1 &#10; 2. test2"></div>
//server control
this.Panel1.ToolTip = "1. test1 \n2. test2";


參考資料:
http://www.dotblogs.com.tw/aquarius6913/archive/2011/02/01/21179.aspx


2014年3月2日 星期日

[T-SQL] 調整維護計畫Log路徑 maintenance plan log file path

說明:常用維護計畫來設定執行資料庫的優化或備份作業,在新增維護計畫時,可設定「將報表寫入文字檔」,也就是寫log的路徑,一般皆預設在SQL Server目錄中的Log下,如果日後想調整,該怎麼改?


作法:
1. 打開SSMS->點開物件總管的維護計畫->在要修改的維護計畫名稱上->右鍵選修改->畫面上方找一個看起來像兩個報表的小圖示(在管理連線右邊)->點開即看到修改路徑。


參考資料:
http://www.sqlserver-dba.com/2012/07/sql-server-find-the-maintenance-plan-log-file-path.html
http://stackoverflow.com/questions/3290531/change-sql-server-maintenance-plan-report-location
http://ithelp.ithome.com.tw/question/10030033

2014年2月25日 星期二

[ASP.NET] Server Control Table使用記錄

命名空間:
System.Web.UI.WebControls


語法:
<asp:Table borderwidth="1" id="tbTest" runat="server">
           <asp:TableRow>
               <asp:TableCell>
                   <asp:Label ID="lblUserNo" runat="server" Text="" />
               </asp:TableCell>
               <asp:TableCell>
                   <asp:Label ID="lblBirthday" runat="server" Text="" />
               </asp:TableCell>
           </asp:TableRow>
           <asp:TableRow>
               <asp:TableCell>
                   <asp:TextBox ID="txtUserNo" runat="server"></asp:TextBox>
               </asp:TableCell>
               <asp:TableCell>
                   <asp:TextBox ID="txtBirthday" runat="server"></asp:TextBox>
                   <asp:CalendarExtender ID="txtBirthday_CalendarExtender" runat="server"
                        Enabled="True" TargetControlID="txtBirthday" Format="yyyy/MM/dd">
                   </asp:CalendarExtender>
               </asp:TableCell>
           </asp:TableRow>
</asp:Table>


參考資料:
http://msdn.microsoft.com/zh-tw/library/system.web.ui.webcontrols.table(v=vs.110).aspx
http://imagine-code.blogspot.tw/2013/07/aspnet_3.html

[ASP.NET] 連接Oracle

問題:
大部分ASP.NET網站搭配SQL Server較多,若DB使用Oracle,該怎麼做?


作法(使用oleDb):
0. 主機或local需安裝Oracle client,在tnsname.ora設定連Oracle Server服務資訊。

1. 在web.config的connectionStrings標籤內加入連線資訊,例:
<add name="OracleDBConn" connectionString="Provider=MSDAORA(OraOLEDB.Oracle);Data Source=service_name;Persist Security Info=True;User ID=user_id;Password=password"/>

2. 在DB存取class中,引用System.Data.OleDb命名空間;

3. 擷取連線字串(需引用System.Configuration命名空間):
private static string OracleDBConn = ConfigurationManager.ConnectionStrings["OracleDBConn"].ConnectionString;

4. 撰寫操作method,例:
public static DataTable ExecuteDataTable(string strQuery)
{
    try
    {
        DataTable dtReturn = new DataTable();
        using (OleDbConnection conn = new OleDbConnection(OracleDBConn))
        {
            using (OleDbDataAdapter sda = new OleDbDataAdapter(strQuery, conn))
            {
                sda.Fill(dtReturn);
                return dtReturn;
            }
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}


參考資料:
http://msdn.microsoft.com/zh-tw/library/system.data.oledb(v=vs.110).aspx
http://c.ittoolbox.com/groups/technical-functional/csharp-l/connection-string-for-ms-access-in-c-3271615

[Oracle] DDL/alter table schema

說明:想增加或刪除欄位、調整欄位長度或名稱時,該怎麼做?


語法:
1. 增加欄位:ALTER TABLE table_name ADD column_name column-definition;
    例:ALTER TABLE account ADD user_id VARCHAR2(10);

2. 刪除欄位:ALTER TABLE table_name DROP COLUMN column_name;
    例:ALTER TABLE account DROP COLUMN user_id;

3. 調整欄位:ALTER TABLE table_name MODIFY column_name column-definition;
                        ALTER TABLE table_name MODIFY
                        (column_name1 column-definition,
                         column_name2 column-definition);
    例:ALTER TABLE account MODIFY user_id VARCHAR2(20);

4. 調整欄位名稱:ALTER TABLE table_name RENAME COLUMN old_name to new-name;
    例:ALTER TABLE account RENAME COLUMN user_id to user;


參考資料:
http://www.techonthenet.com/sql/tables/alter_table.php
http://www.dba-oracle.com/t_alter_table_modify_column_syntax_example.htm
http://www.dotblogs.com.tw/dc690216/archive/2011/02/23/21534.aspx
http://docs.oracle.com/cd/E17952_01/refman-5.0-en/alter-table.html
http://blog.xuite.net/f8789/DCLoveEP/43020770-PLSQL+%26+SQL+-+%E4%BF%AE%E6%94%B9%E8%B3%87%E6%96%99%E8%A1%A8%E4%B8%AD%E7%9A%84%E6%AC%84%E4%BD%8D%E9%95%B7%E5%BA%A6

2014年2月7日 星期五

[Crystal Report] 應用程式中發生伺服器錯誤。無法載入檔案或組件 'CrystalDecisions.Web, Version=10.5.3700.0, Culture=neutral, PublicKeyToken=692fbea5521e1304' 或其相依性的其中之一。系統找不到指定的檔案。

說明:用VS 2008 (.NET Framework 3.5)內建的Crystal Report開發web-based報表 (import CrystalDecisions.CrystalReports.Engine),將ASP.NET佈到.NET Framework 2.0的Server上,出現該錯誤訊息:

應用程式中發生伺服器錯誤。
無法載入檔案或組件 'CrystalDecisions.CrystalReports.Engine, Version=10.5.3700.0, Culture=neutral, PublicKeyToken=692fbea5521e1304' 或其相依性的其中之一。 系統找不到指定的檔案。

也就是web.config裡註記要載入Crystal Report的相關dll找不到。


解決方法:
到網路上下載CRRedist2008_x86.msi檔案,並安裝到Server上,確認C:\Windows\assembly內相關dll安裝成功後,重試即可。


參考資料:
http://social.msdn.microsoft.com/Forums/zh-TW/80764698-46a4-43ba-87fb-094911442fea/aspnet-crystal-reports-vs-2008-ok-iisruntime?forum=236
http://code.google.com/p/crystaldelivery/downloads/detail?name=CRRedist2008_x86.zip&can=2&q

[IIS] 伺服器應用程式無法使用 您嘗試在此 Web 伺服器上存取的 Web 應用程式目前無法使用。請按 Web 瀏覽器中的 [重新整理] 按鈕,再試一次。 系統管理員注意: Web 伺服器的應用程式事件記錄檔中的錯誤訊息詳細說明了這項特定要求失敗原因。請檢閱這個記錄項目,查看造成錯誤的原因為何。

說明:將ASP.NET程式佈上IIS,出現錯誤訊息:

伺服器應用程式無法使用
您嘗試在此 Web 伺服器上存取的 Web 應用程式目前無法使用。請按 Web 瀏覽器中的 [重新整理] 按鈕,再試一次。
系統管理員注意: Web 伺服器的應用程式事件記錄檔中的錯誤訊息詳細說明了這項特定要求失敗原因。請檢閱這個記錄項目,查看造成錯誤的原因為何。

因我網站虛擬目錄有使用.NET 2.0與.NET 3.5的專案,皆使用同一個應用程式集區,而同一個IIS process不能執行不同版本的ASP.NET,因此出現該錯誤。


解決方法:
依ASP.NET版本調整虛擬目錄使用的應用程式集區即可。


參考資料:
http://www.dotblogs.com.tw/rainmaker/archive/2013/03/07/95717.aspx
http://blog.xuite.net/wallaces528/blog/28604194

2014年2月4日 星期二

[C#] 取得執行中的method name

說明:想取得執行的method name,該怎麼做?


作法:
1. 使用System.Reflection.MethodBase.GetCurrentMethod().Name
2. 使用this.GetType().Name
兩者皆是利用reflection來取得執行中object的型別屬性,其中MSDN提到若執行中method是泛型method,GetCurrentMethod()會回傳泛型method的定義。


參考資料:
http://msdn.microsoft.com/en-us/library/system.reflection.methodbase(v=vs.90).aspx
http://msdn.microsoft.com/zh-tw/library/ms173183(v=vs.90).ASPX
http://stackoverflow.com/questions/2652460/c-sharp-how-to-get-the-name-of-the-current-method-from-code
http://stackoverflow.com/questions/2113069/c-sharp-getting-its-own-class-name
http://stackoverflow.com/questions/44153/can-you-use-reflection-to-find-the-name-of-the-currently-executing-method
http://blogs.msdn.com/b/webdevelopertips/archive/2009/06/23/tip-83-did-you-know-you-can-get-the-name-of-the-calling-method-from-the-stack-using-reflection.aspx
http://joelabrahamsson.com/getting-property-and-method-names-using-static-reflection-in-c/

2014年1月26日 星期日

[.NET] 取得Server或Client IP

1. 取得Server IP語法:
using System.Net;
IPAddress ServerIP = IPAddress(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].Address);
Response.Write("Server IP=" + ServerIP.ToString());

2. 取得Client IP
string strClientIP = Request.ServerVariables["REMOTE_ADDR"].ToString();
string strClientIP = Request.UserHostAddress;
//使用代理伺服器
string strClientIP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();



參考資料:
http://blog.xuite.net/sunnysoap/r/25283108-C%23+%E5%A6%82%E4%BD%95%E5%8F%96%E5%BE%97%E6%9C%AC%E6%A9%9F(Server)%E7%9A%84IP
http://www.dotblogs.com.tw/jimmyyu/archive/2009/05/21/8493.aspx


http://bytes.com/topic/asp-net/answers/848515-how-get-client-ip-address-assigned-isp
http://dotnetstock.com/technical/how-to-get-ip-address-of-a-client-system-using-asp-net
http://csharpdotnetfreak.blogspot.com/2008/12/finding-ip-address-behind-proxy-using-c.html
http://forums.asp.net/t/1780050.aspx

[C#] 這個資料列已經屬於其他資料表

說明:
從DataTable依條件篩選出一些DataRow,想匯入另一DataTable object,卻出現Exception:這個資料列已經屬於其他資料表,例:
DataTable dtTemp = dtSource.Clone();
dtTemp.Rows.add(dr);

解決方法:
使用DataTable的ImportRow方法,例:
DataTable dtTemp = dtSource.Clone();
dtTemp.ImportRow(dr);


參考資料:
http://blog.mu1979.idv.tw/2007/10/datatabledatarowdatatable.html

[Cystal Report] DateAdd與DateDiff函式使用記錄

語法:
DateDiff (intervalType, startDateTime, endDateTime)
DateAdd (intervalType, nIntervals, startDateTime)
Year (CurrentDate) //取得Date之西元年

例:
DateDiff ("m", CDate (Mid({?Cycle}, 1, 10)), DateAdd ("d", 1, CDate (Mid({?Cycle}, 12, 10))))


參考資料:
http://pic.dhe.ibm.com/infocenter/rsawshlp/v7r5m0/index.jsp?topic=%2Fcom.businessobjects.integration.eclipse.designer.doc%2Fhtml%2Ftopic682.html


2014年1月20日 星期一

[T-SQL] REPLICATE與{fn LENGTH(string)}函數使用記錄

說明:依照table某欄位字串長度,加上某長度的特定字元。


作法:
1. 使用ODBC純量函數中的LENGTH函數。
    語法:SELECT {fn <function_name> [ (<argument>,.... n) ] }
    例: SELECT {fn LENGTH(Function_ID)}

2. 使用REPLICATE函數。
    語法:REPLICATE ( string_expression ,integer_expression )
    例:REPLICATE('=', {fn LENGTH(Function_ID)}-1)


參考資料:
http://msdn.microsoft.com/zh-tw/library/ms174383.aspx
http://jengting.blogspot.tw/2011/08/sql.html
http://www.dotblogs.com.tw/atowngit/archive/2010/10/04/18077.aspx
http://technet.microsoft.com/zh-tw/library/bb630290.aspx
http://msdn.microsoft.com/zh-tw/library/ms710249.aspx




2014年1月1日 星期三

[ASP.NET] 網頁導向Response.Redirect與Server.Transfer

說明:網頁導向有Response.Redirect與Server.Transfer兩種方法,有什麼不同?


說明:
Response.Redirect不會保留表單值,可導向外部網站,但送出兩次Request,一次給Source.aspx,一次給Destination.aspx。可用在get傳值。
例:
Response.Redirect("Destination.aspx?Value="+strValue);

Server.Transfer恰好相反,可保留表單值,但只限同一網站,Request一次效能較佳。


參考資料:
http://www.dotblogs.com.tw/jimmyyu/archive/2009/11/10/11503.aspx