2015年12月29日 星期二

ASP.NET 加上 MS SQL IF判斷式、update指令

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click

Dim int_sql As Integer = -1
Dim str_sql As String = String.Empty
str_sql = "if exists (select tid,cname from test_table1 where tid=@tid) " & _
" BEGIN " & _
" update test_table1 set cname=@cname where tid=@tid " & _
" END"
Using conn As New SqlConnection("Server=.;uid=test;pwd=test;Database=school")
 conn.Open()
 Using command As SqlCommand = New SqlCommand(str_sql, conn)
  command.Parameters.AddWithValue("@tid", "2")
  command.Parameters.AddWithValue("@cname", "李四")
  int_sql = command.ExecuteNonQuery() '回傳影響的筆數 -1
 End Using
 conn.Close()
End Using
Response.Write(int_sql)

End Sub

2015年12月25日 星期五

ASP.NET TextBox 加上 jquery autocomplete(自動完成)

參考資料:AutoComplete using JQuery Ajax and Asp.Net WCF Service–C# and Vb.Net

本篇參考以上資料,並作部分修改。

結果:















A.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>jquery autocomplete</title>
    <link rel="stylesheet" href="themes/base/jquery.ui.all.css">
    <script type="text/javascript" src="Scripts/jquery-1.8.2.min.js"></script>
    <script type="text/javascript" src="ui/jquery.ui.core.js"></script>
 <script type="text/javascript" src="ui/jquery.ui.widget.js"></script>
 <script type="text/javascript" src="ui/jquery.ui.position.js"></script>
 <script type="text/javascript" src="ui/jquery.ui.menu.js"></script>
 <script type="text/javascript" src="ui/jquery.ui.autocomplete.js"></script>
    <script type="text/javascript">
         $(function () {
             $("#TextBox1").autocomplete({
                 source: function (request, response) {
                     var val = request.term;
                     $.ajax({
                         url: 'loadData.aspx', method: 'post', dataType: 'json',
                         data: { sd: 'txtaut', p1: val },
                         error: function (XMLHttpRequest, textStatus, errorThrown) {
                             if ((XMLHttpRequest.status == 0) || (textStatus == 'error')) {
                                 alert('執行時發生錯誤\n請重新執行'); 
                             } else {
                                 alert('發生例外錯誤'); 
                                };
                         },
                         success: function (data) {
                             if (data != null) {
                                 var total = data.length;
                                 if (total > 0) {
                                     response($.map(data, function (item) {
                                         return { value: item.text };
                                     }));
                                 } else if (total == 0) {
                                     //查無資料
                                 };
                             };
                         }
                     });
                 },
                 minLength: 1    // MINIMUM 1 CHARACTER TO START WITH.
             });
         });
 </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    jquery autocomplete TextBox自動完成<br/>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="送出" />
    </div>
    </form>
</body>
</html>

loadData.aspx
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="loadData.aspx.vb" Inherits="WebApplication1.loadData" %>

loadData.aspx.vb
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
 If Not Page.IsPostBack Then
  If (Not Request("sd") Is Nothing) Then
   Dim sd() As String = Request("sd").ToString.Split(";")
   Dim str_data As StringBuilder = Nothing

   If sd(0).Equals("txtaut") = True Then
    If Not Request("p1") Is Nothing Then
     str_data = New StringBuilder()
     Dim str_sql As String = String.Empty
     str_sql = "select rtrim(cname) as text from test_staff where cname like @cname+'%'"
     Dim ds As New DataSet()
     Using conn As New SqlConnection("Server=.;uid=test;pwd=test;Database=temp_db")
      Using command As SqlCommand = New SqlCommand(str_sql, conn)
       '避免 SQL Injection(資料隱碼)攻擊
       If command.Parameters.Contains("@cname") Then
        command.Parameters("@cname").Value = Request("p1").ToString
       Else
        command.Parameters.AddWithValue("@cname", Request("p1").ToString) '讓ADO.NET自行判斷型別轉換
       End If
       
       Using da As New SqlDataAdapter()
        da.SelectCommand = command
        da.Fill(ds)
       End Using
      End Using
     End Using
     str_data.Append(JsonConvert.SerializeObject(ds.Tables(0), Formatting.Indented))
     Response.Write(str_data.ToString)
    Else
     Response.Write("[]")
    End If
   Else
    Response.Write("[]")
   End If

  Else
   Response.Write("[]")
  End If
 End If
End Sub

ASP.NET DropDownList 加上 jquery chosen,送出後保留原本的值






aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link rel="stylesheet" href="css/chosen.css">
    <!--JQuery使用v1.8.2-->
    <script type="text/javascript" src="Scripts/jquery.js"></script>
    <script type="text/javascript" src="Scripts/chosen.jquery.js"></script>
    <script type="text/javascript" src="docsupport/prism.js" charset="utf-8"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var config = {
                '.chosen-select': {},
                '.chosen-select-deselect': { allow_single_deselect: true },
                '.chosen-select-no-single': { disable_search_threshold: 10 },
                '.chosen-select-no-results': { no_results_text: 'Oops, nothing found!' },
                '.chosen-select-width': { width: "95%" }
            };
            for (var selector in config) {
                $(selector).chosen(config[selector]);
            };
            //$('.chosen-select').chosen().change(function (event) {
            $('#<%=DropDownList1.ClientID %>[class="chosen-select"]').chosen().change(function (event) {
                var strval = $(this).val();
                if (strval == null) { $('#<%=HF_DDL1.ClientID %>').val(''); } else { $('#HF_DDL1').val(strval); };
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    以下為範例<br/>
          <select data-placeholder="Your Favorite Types of Bear" multiple class="chosen-select" style="width:350px;" tabindex="18" id="multiple-label-example">
            <option value=""></option>
            <option>American Black Bear</option>
            <option>Asiatic Black Bear</option>
            <option selected>Brown Bear</option>
            <option>Giant Panda</option>
            <option>Sloth Bear</option>
            <option>Sun Bear</option>
            <option>Polar Bear</option>
            <option>Spectacled Bear</option>
          </select>
          <br/>
          <br/>
        <asp:DropDownList ID="DropDownList1" runat="server" Width="80%"
              CssClass="chosen-select" >
        </asp:DropDownList>
        <asp:HiddenField ID="HF_DDL1" runat="server" />
        <asp:Button ID="Button1" runat="server" Text="送出" />
    </div>
    </form>
</body>
</html>

aspx.vb
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            Dim str_sql As String = String.Empty
            str_sql = "select id_no+'-'+rtrim(cname) as html_text,id_no as val from test_staff"
            Dim ds As New DataSet()
            Using conn As New SqlConnection("Server=.;uid=test;pwd=test;Database=temp_db")
                Using command As SqlCommand = New SqlCommand(str_sql, conn)
                    Using da As New SqlDataAdapter()
                        da.SelectCommand = command
                        da.Fill(ds)
                    End Using
                End Using
            End Using

            DropDownList1.DataTextField = "html_text"
            DropDownList1.DataValueField = "val"
            DropDownList1.DataSource = ds.Tables(0)
            DropDownList1.DataBind()

            DropDownList1.Attributes.Add("data-placeholder", "請選擇學生")
            DropDownList1.Attributes.Add("multiple", "")
        End If
    End Sub

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
        Dim str_js As StringBuilder = New StringBuilder()
        str_js.Append("$(document).ready(function () {")
        str_js.Append("var HF_val=$('#" & HF_DDL1.ClientID & "').val();")
        str_js.Append("if (HF_val!=''){")
        str_js.Append("$.each(HF_val.split(','),function (index,value) {")
        str_js.Append("$('#" & DropDownList1.ClientID & " option[value=" & Chr(34) & "' + value + '" & Chr(34) & "]').prop('selected', true);")
        str_js.Append("});")
        str_js.Append("$('#" & DropDownList1.ClientID & "[class=" & Chr(34) & "chosen-select" & Chr(34) & "]').trigger('" & "chosen:updated" & "');")
        str_js.Append("};")
        str_js.Append("});")
        WJS2(str_js.ToString, Page, "js1")
    End Sub

    Public Sub WJS2(ByVal str_js As String, ByVal Pa As System.Web.UI.Page, ByVal str_js_name As String)
        If ScriptManager.GetCurrent(Pa) Is Nothing Then
            '未啟用asp.net ajax功能
            '有些情況下會需要以動態的方式加入用戶端指令碼。 若要動態加入指令碼,請使用 RegisterClientScriptBlock 方法、RegisterClientScriptInclude 方法、RegisterStartupScript 方法或 RegisterOnSubmitStatement 方法,視您要加入指令碼的時間和方式而定。
            '最後面插入JS程式碼
            Pa.ClientScript.RegisterStartupScript(Me.GetType(), str_js_name, str_js.ToString, True)
        Else
            '啟用asp.net ajax功能
            ScriptManager.RegisterStartupScript(Pa, Me.GetType(), str_js_name, str_js.ToString, True)
        End If
    End Sub

2015年10月27日 星期二

VB.NET 建立自己的錯誤紀錄檔



Imports System.IO
Public Class TEST1

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Dim plog As String = Application.StartupPath & "\sqlexe_error\"
        Dim fileName As String = plog & "err" & DateTime.Now.ToString("yyyy-MM-dd_HHmmssff") & ".txt"

        '判斷是否有記錄檔資料夾
        If Directory.Exists(plog) = False Then
            Directory.CreateDirectory(plog)
        End If

        Try
            '紀錄瀏覽選擇的路徑
            Dim sw As StreamWriter = New StreamWriter(fileName)
            sw.WriteLine("錯誤測試")
            sw.Write("建檔日期:")
            sw.WriteLine(DateTime.Now)
            sw.Close()
            sw.Dispose()
        Catch ex As Exception
            MsgBox("發生錯誤")
        End Try

    End Sub

End Class

2015年7月28日 星期二

ASP.NET 由於該物件目前的狀態,導致作業無效。

參考資料:ASP.NET 發現重大資安弱點影響範圍涵蓋 ASP.NET 1.1 ~ 4.0

我碰到這個問題是在GridView顯示大量資料時,當我點擊GridView中的按鈕,就會發生(由於該物件目前的狀態,導致作業無效)這個錯誤。要解決這個問題,可以在web.config檔中,在<appSettings>...</appSettings>之間加上aspnet:MaxHttpCollectionKeys就可以解決這個問題,如下:

<appSettings> 
  <add key="aspnet:MaxHttpCollectionKeys" value="2000" /> 
</appSettings>

但是這樣還是會有問題(我想),就是當使用者因為查詢條件的關係,查詢出來的資料有可能又超過MaxHttpCollectionKeys的設定值,又會發生這個錯誤。所以另外一個解決的辦法,就是透過分頁再加上SQL指令的配合,就可以解決這個問題,但是方法比較麻煩ㄧ些。

以下為 分頁+SQL指令 範例
test_paging.aspx
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="test_paging.aspx.vb" Inherits="testdb_mssql.test_paging" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
        <div id="gv_p1" runat="server" style=" width:500px;">
        分頁顯示在此處
        </div>
    </div>
    </form>
</body>
</html>

test_paging.aspx.vb
Imports System.Data.SqlClient

Public Class test_paging
    Inherits System.Web.UI.Page
    Dim prows As Integer = 100 '每一頁多少筆數(此處100筆分成一頁)
    Dim this_page As Integer = 1 '目前在第幾頁
    Dim maxpage As Integer = 10 '最多顯示頁數(不變動)
    Dim showpage As Integer = 10 '最多顯示頁數
    Dim str_sql As String = String.Empty
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            If (Not Request("p") Is Nothing) Then
                If Regex.IsMatch(Request("p").ToString, "^\d+$") = False Then '數字會回傳true
                    '不是數字,設定回1
                    this_page = 1
                Else
                    this_page = CInt(Request("p").ToString)
                End If
            Else
                this_page = 1
            End If
            Dim dt1 As DataTable = Nothing, tot_dt As DataTable = Nothing
            Dim rows_count As Integer = 0 '資料的總筆數
            str_sql = "select TOP " & prows & " * from (" & _
            "select ROW_NUMBER() OVER(Order by t1.stud_id) as sec,t1.stud_id,t1.stud_name from Student as t1 where t1.stud_id like '401%'" & _
            ") as ta1 where ta1.sec>" & (CInt(this_page) - 1) * prows
            dt1 = queryDataTable(str_sql)
            GridView1.DataSource = dt1
            GridView1.DataBind()

            str_sql = "select count(t1.stud_id) as tot from Student as t1 where t1.stud_id like '401%'"
            tot_dt = queryDataTable(str_sql)
            If Not tot_dt Is Nothing Then
                If tot_dt.Rows.Count = 1 Then
                    rows_count = tot_dt.Rows(0).Item("tot").ToString() '資料的總筆數
                End If
                tot_dt.Clear()
                tot_dt.Dispose()
            End If
            If rows_count > 0 Then
                Dim str_temp1 As String = String.Empty
                's1開始頁數;tot_x1 全部的頁數
                Dim s1 As Integer = 1, tot_x1 As Integer = 0
                tot_x1 = Fix(rows_count / prows) '總筆數/每一頁多少筆數
                '總筆數 求餘數,餘數>0就加1頁
                If (CInt(rows_count) Mod prows) > 0 Then
                    tot_x1 = tot_x1 + 1
                End If
                '==========================
                '頁數變動
                If this_page >= 7 Then
                    If ((tot_x1 + 1) - ((this_page - 6) + 1)) >= maxpage Then
                        s1 = (this_page - 6) + 1
                        showpage = maxpage + (this_page - 6)
                    Else
                        s1 = ((this_page - 6) + 1) + (((tot_x1 + 1) - ((this_page - 6) + 1)) - maxpage)
                        showpage = tot_x1
                    End If
                Else
                    '預設
                    s1 = 1 '第一頁開始
                    showpage = maxpage '顯示的頁數
                End If
                '==========================
                Dim str_ago As String = String.Empty, str_back As String = String.Empty, str_num As String = String.Empty
                For i As Integer = s1 To tot_x1
                    str_num = CStr(i)
                    If str_num.Length = 1 Then
                        str_num = "0" & str_num
                    End If
                    If i = this_page Then
                        str_temp1 = str_temp1 & "<a style=" & Chr(34) & "text-decoration:none" & Chr(34) & ">" & str_num & "</a>&nbsp;"
                        If i > 1 Then
                            str_ago = "<a href=" & Chr(34) & "test_paging.aspx?p=" & (i - 1) & Chr(34) & " style=" & Chr(34) & "text-decoration:none" & Chr(34) & ">&lt;</a>&nbsp;"
                        End If
                        If i < tot_x1 Then
                            str_back = "<a href=" & Chr(34) & "test_paging.aspx?p=" & (i + 1) & Chr(34) & " style=" & Chr(34) & "text-decoration:none" & Chr(34) & ">&gt;</a>&nbsp;"
                        End If
                    Else
                        str_temp1 = str_temp1 & "<a href=" & Chr(34) & "test_paging.aspx?p=" & i & Chr(34) & ">" & str_num & "</a>&nbsp;"
                    End If
                    If i = showpage Then
                        Exit For
                    End If
                Next
                Me.gv_p1.InnerHtml = str_ago & str_temp1 & str_back
            Else
                Me.gv_p1.InnerHtml = ""
            End If
        End If
    End Sub

    Function queryDataTable(ByVal sql_str As String) As DataTable
        Dim ds As New DataSet()
        Using conn As New SqlConnection("Server=127.0.0.1;Database=test1;uid=test;pwd=test")
            Dim command As SqlCommand = New SqlCommand(sql_str, conn)

            Dim da As New SqlDataAdapter()
            da.SelectCommand = command

            da.Fill(ds)
        End Using
        If ds.Tables.Count > 0 Then
            Return ds.Tables(0)
        Else
            Return New DataTable()
        End If
    End Function
End Class

P.S SQL指令中的stud_id為學號,sec是自行自訂編號

ASP.NET 手寫分頁

test_paging.aspx
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="test_paging.aspx.vb" Inherits="testdb_mssql.test_paging" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <div id="gv_p1" runat="server" style=" width:500px;">
        分頁顯示在此處
        </div>
    </div>
    </form>
</body>
</html>

test_paging.aspx.vb
Public Class test_paging
    Inherits System.Web.UI.Page
    Dim this_page As Integer = 1 '目前在第幾頁
    Dim maxpage As Integer = 10 '最多顯示頁數(不變動)
    Dim showpage As Integer = 10 '最多顯示頁數

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            If (Not Request("p") Is Nothing) Then
                If Regex.IsMatch(Request("p").ToString, "^\d+$") = False Then '數字會回傳true
                    '不是數字,設定回1
                    this_page = 1
                Else
                    this_page = CInt(Request("p").ToString)
                End If
            Else
                this_page = 1
            End If
            Dim rows_count As Integer = 2701 '假設此變數是資料的總筆數
            Dim str_temp1 As String = String.Empty
            's1開始頁數;tot_x1 全部的頁數
            Dim s1 As Integer = 1, tot_x1 As Integer = 0
            tot_x1 = Fix(rows_count / 100) '總筆數/每一頁多少筆數
            '總筆數 求餘數,餘數>0就加1頁
            If (CInt(rows_count) Mod 100) > 0 Then
                tot_x1 = tot_x1 + 1
            End If
            '==========================
            '頁數變動
            If this_page >= 7 Then
                If ((tot_x1 + 1) - ((this_page - 6) + 1)) >= maxpage Then
                    s1 = (this_page - 6) + 1
                    showpage = maxpage + (this_page - 6)
                Else
                    s1 = ((this_page - 6) + 1) + (((tot_x1 + 1) - ((this_page - 6) + 1)) - maxpage)
                    showpage = tot_x1
                End If

            Else
                '預設
                s1 = 1 '第一頁開始
                showpage = maxpage '顯示的頁數
            End If
            '==========================
            Dim str_ago As String = String.Empty, str_back As String = String.Empty, str_num As String = String.Empty
            For i As Integer = s1 To tot_x1
                str_num = CStr(i)
                If str_num.Length = 1 Then
                    str_num = "0" & str_num
                End If
                If i = this_page Then
                    str_temp1 = str_temp1 & "<a style=" & Chr(34) & "text-decoration:none" & Chr(34) & ">" & str_num & "</a>&nbsp;"
                    If i > 1 Then
                        str_ago = "<a href=" & Chr(34) & "test_paging.aspx?p=" & (i - 1) & Chr(34) & " style=" & Chr(34) & "text-decoration:none" & Chr(34) & ">&lt;</a>&nbsp;"
                    End If
                    If i < tot_x1 Then
                        str_back = "<a href=" & Chr(34) & "test_paging.aspx?p=" & (i + 1) & Chr(34) & " style=" & Chr(34) & "text-decoration:none" & Chr(34) & ">&gt;</a>&nbsp;"
                    End If
                Else
                    str_temp1 = str_temp1 & "<a href=" & Chr(34) & "test_paging.aspx?p=" & i & Chr(34) & ">" & str_num & "</a>&nbsp;"
                End If
                If i = showpage Then
                    Exit For
                End If
            Next
            Me.gv_p1.InnerHtml = str_ago & str_temp1 & str_back
        End If
    End Sub
End Class

2015年7月11日 星期六

跑跑卡丁車 劇場 KOIN幣

最近朋友邀約回流回去玩跑跑卡丁車,但因跟人玩競速沒有車實在沒辦法跟上別人,所以到網路上看能不能取得比較好的車子,發現有KOIN幣,以前過劇場都沒發現,網路上也有人提供一些情報,哪些關卡可以拿KOIN,而陸續又出了很多劇場,到網路上找,好像比較少人提到,在此分享。

1.機械戰爭
正義海盜船長-第7關 7 KOIN
機械鬥士的衝擊-第6關 7 KOIN

2.WKC冠軍賽
F1 世界盃冠軍賽-第4關 3 KOIN

3.極速熱浪
熱浪馬汀的挑戰!迎向勝利!-第1關 7 KOIN
街頭極速賽車-第2關 3 KOIN

4.闇影勢力
尋找星石碎片! -第2關 3 KOIN
闇黑勢力降臨-第2關 3 KOIN

5.奇幻精靈
奇幻精靈:精靈國度~阿克納 第7關 10 KOIN

6.月不落城
永夜的繁華城市-第8關 3 KOIN

7.黃金文明
黃金文明 高狄的復活-第7關 5 KOIN

8.海盜紀元
危機重重! 海賊島大冒險!-第12關 3 KOIN

9.繁榮山丘大冒險
新朋友!新挑戰!-第10關 7 KOIN

P.S以上拿到後KOIN,就沒有繼續玩下去了。

---------

以下是沒有KOIN可以拿的
1.侏儸紀大冒險
2.勞迪雷諾的秘密!
3.流星睏寶
4.夢幻樂園

以上如有錯誤指正,謝謝。如有過新劇場會持續更新。

巴哈姆特參考情報:http://forum.gamer.com.tw/C.php?bsn=08936&snA=141631