當我們在撰寫物件導向程式的時候, 難免會需要將參數傳入Method裡面, 若傳入的參數是陣列, 格式如下:

static void Main(string[] args)
{

int[] a = new int[2]{5,7};

Util util = new Util();

Console.WriteLine(util.Min(a));

}

class Util
{

public int Min(int[] param)
{
if (param == null || param.Length == 0)
{
throw new ArgumentException("Util.Min: not enough arguments");
}

int currentmin = param[0];

foreach (int i in param)
{
if (i < currentmin)
{
currentmin = i;
}
}

return currentmin;
}

}

這種寫法應該很直觀吧, 但如果傳入的參數是Integer豈不是出現Error? 要怎麼解決呢? 其實要解決這個問題非常簡單, 就是在Method的參數部分加入 "params"這個關鍵字, 寫法如下:

class Util
{

public int Min(params int[] param)
{
if (param == null || param.Length == 0)
{
throw new ArgumentException("Util.Min: not enough arguments");
}

int currentmin = param[0];

foreach (int i in param)
{
if (i < currentmin)
{
currentmin = i;
}
}

return currentmin;
}

}

這樣一來傳入的參數會經過compiler做以下的動作:

int min = Util.Min(first, second);
int[] array = new int[2];
array[0] = first;
array[1] = second;
int min = Util.Min(array);

你的主程式就可以彈性傳入參數, 夠方便吧?

static void Main(string[] args)
{

int[] a = new int[2]{5,7};

Util util = new Util();

Console.WriteLine(util.Min(a));//可以傳入陣列型態的變數

int b = util.Min(2, 10); //同時可以傳入多個Integer

Console.WriteLine(b);

}

使用params有幾個注意事項:

  • 陣列不能是multidimensional
  • 使用params的method不能Overloading (多載)
  • 使用params的method不能是ref 或這 out
  • method傳入的參數只能有一個params array
  • 為了避免使用者取得他們不應該存取的資料,

    .NET FRAMEWORK提供了安全性的物件, 限制使用者的存取權限.
    這跟Windows本身的帳戶安全性有些不同, 是針對程式而言.

    SecurityAction 屬性有三種:

    • RequestMinimum(M) 正常執行的最小權限
    • RequestOptional(O) 可有可無的權限
    • RequestRefuse(R) 絕對不能有的權限

    *P = Security Policy (也就是Enterprise, Machine, User三者的交集)

    最終權限的決定放程式為:  (P 交 ((M 聯 O) – R))

    以下範例顯示:只允許使用者存取特定的資料表, 如果不是指定的資料表, 就無法執行程式:

    注: RequestOptional, Unrestricted應設為False, 才表示不允許給予其他的權限; 如果設為True, 則表示沒有限制, 所有權限的給了(很危險, 容易造成駭客的入侵).

    Imports System.Security.Permissions
    Imports System.Data.SqlClient

    <Assembly: UIPermission(SecurityAction.RequestMinimum, Window:=UIPermissionWindow.SafeTopLevelWindows)>
    <Assembly: SqlClientPermission(SecurityAction.RequestMinimum, _
             ConnectionString:="server=.;database=pubs;integrated security=true")>

    <Assembly: SecurityPermission(SecurityAction.RequestOptional, Unrestricted:=False)>

    Public Class Form1

        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim cn As New SqlConnection(TextBox1.Text)
            Try
                cn.Open()
                MessageBox.Show("連線成功")
            Catch ex As Exception
                MessageBox.Show(ex.Message)
            End Try
        End Sub

    End Class

    方法的權限安全種類:

    有六種SecurityAction 可用再宣告式或命令式安全性

    • Assert
    • Demand
    • InheritanceDemand
    • LinkDemand
    • PermitOnly
    • Deny

    Imports System.Security.Permissions
    Imports System.IO

    Public Class Form1

        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        End Sub

        <FileIOPermission(SecurityAction.Demand)> _
        Sub CreateFile()
            Try
                File.CreateText("C:\test\b.txt")
                MessageBox.Show("b.txt has been created")
            Catch ex As Exception
                MessageBox.Show(ex.Message)
            End Try
        End Sub

        ‘DENY表示不允許使用這個METHOD
        <FileIOPermission(SecurityAction.Deny, Write:="C:\test")> _
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            CreateFile()
        End Sub

        ‘SecurityAction.Demand的另一種寫法
        Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
            Dim fp As New FileIOPermission(FileIOPermissionAccess.Write, "C:\test")
            fp.Demand()
            CreateFile()
        End Sub
    End Class

    使用Visual Studio 來開發程式, 不只在ASPX有很不錯的功能, 再WINFORM方面也是學幾年都學不完.

    以下是一個簡單的範例程式, 作用是監控自己的電腦如果建立一個帳號了, 就會顯示一個對話框, 告訴你所建立的帳號名稱及SID.

    當然如果你會舉一反三, 也可以寫類似的程式(利用System.Management的namespace)來玩很多的花樣.

    WinForm 程式:

    Imports System.Management

    Public Class Form1

        Dim watcher As ManagementEventWatcher

        Private Sub Form1_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
            Button2.PerformClick()
        End Sub
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        End Sub

        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim equery As New WqlEventQuery("__InstanceCreationEvent", New TimeSpan(0, 0, 2), "TargetInstance isa ""Win32_Account""")
            watcher = New ManagementEventWatcher(equery)
            AddHandler watcher.EventArrived, AddressOf watcher_EventArrived
            watcher.Start()
            Button1.Enabled = False
        End Sub

        Sub watcher_EventArrived(ByVal sender As Object, ByVal e As EventArrivedEventArgs)

            Dim mbo As ManagementBaseObject
            mbo = CType(e.NewEvent, ManagementBaseObject)

            Dim serviceMO As ManagementBaseObject
            serviceMO = CType(mbo("TargetInstance"), ManagementBaseObject)
            MessageBox.Show(String.Format("Create a New Account: {0}" & vbCrLf & "SID:{1}", serviceMO("Name"), serviceMO("SID")))
        End Sub

        Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
            If watcher Is Nothing Then

                Exit Sub

            End If
            watcher.Stop()

            Button1.Enabled = True
            Button2.Enabled = False
        End Sub
    End Class

    用程式碼產生圖片是很常用的需求,

    這裡教你怎麼把版權宣告文字PRINT在圖片上,

    再用IMG CONTROL把它抓出來, 然後不留垃圾在Server.

    "Defautlt.aspx

    <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

    <!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>Untitled Page</title>
    </head>
    <body>
        <form id="form1″ runat="server">
        <div>
             <!– 用IMAGECONTROL把它抓出來 –>
             <asp:Image ID="Image1″ runat="server" ImageUrl="~/getImage.aspx" />
        </div>
        </form>
    </body>
    </html>

    " getImage.aspx

    Imports System.Drawing
    Imports System.Drawing.Imaging

    Partial Class getImage
        Inherits System.Web.UI.Page
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            Dim s As String = "NewtonStudio"
           ‘若不要固定圖片路徑, 可以用querystring來抓.
           ’Dim bmpFile As String = Server.MapPath(Request.QueryString("id").ToString())
            Dim bmpFile As String = Server.MapPath("ADONETx.jpg")
            Dim img As System.Drawing.Image = System.Drawing.Image.FromFile(bmpFile)
            Dim g As Graphics = Graphics.FromImage(img)
            Dim f As New Font("Courier New", 10)
            Dim b As New SolidBrush(Color.Black)
            g.DrawString(s, f, b, 0, 0)
            img.Save(Response.OutputStream, ImageFormat.Jpeg)

            img.Dispose()
        End Sub
    End Class

     

     

    用.NET FRAMEWORK 2.0可以針對不同的語系去展示網頁.
    而culture都是預設的zh-TW, en-US, 如果要自訂Culture呢? 方法如下, 使用Console 端做例子

    Imports System.Globalization
    Imports System.Threading

    Module Module1

        Sub Main()

            CultureAndRegionInfoBuilder.Unregister("zh-TW-adams")

            Dim DemoBuilder As New CultureAndRegionInfoBuilder("zh-TW-adams", CultureAndRegionModifiers.None)

            Dim TWCulture As New CultureInfo("zh-TW")
            Dim TWRegion As New RegionInfo("zh-TW")
            DemoBuilder.LoadDataFromCultureInfo(TWCulture)
            DemoBuilder.LoadDataFromRegionInfo(TWRegion)

            Dim NumberInfo As New NumberFormatInfo()
            NumberInfo.CurrencySymbol = "##"
            NumberInfo.CurrencyDecimalDigits = "4″
            DemoBuilder.NumberFormat = NumberInfo

            Dim DateInfo As New DateTimeFormatInfo
            DateInfo.DateSeparator = "."
            DemoBuilder.GregorianDateTimeFormat = DateInfo

            DemoBuilder.Register()
            Thread.CurrentThread.CurrentCulture = New CultureInfo("zh-TW-adams")
            Thread.CurrentThread.CurrentCulture.NumberFormat = NumberInfo
            Thread.CurrentThread.CurrentCulture.DateTimeFormat = DateInfo
            Console.WriteLine("Culture: " & Thread.CurrentThread.CurrentCulture.Name)
            Console.WriteLine("DateTime: " & DateTime.Now.ToString)
            Console.WriteLine("Currency: " & 1000.ToString("c"))
            Console.Read()
        End Sub

    End Module

    不知道有沒有人像我一樣常常會去比較每個語言的差異性以及實用性,
    有人跟我說Visual Basic很容易學, 比較快得到成就, 但他的發展空間有限.
    也有人跟我說Visual C#很難學, 比較難得到成就, 但他可以做比較大的發展.
    也有講師級的人說其實兩者可以做到的事情是一樣的.
    最主要是看你比較喜歡甚麼..

    既然Visual Studio 內兩種語言的CLASS是可以互相使用的,
    那使用哪種語言就顯得沒那麼重要的了吧? 就完全看你個人的習慣囉…
    但根據我的觀察, 似乎只要會其中一種, 另一種就比較容易上手吧~

    這個網址列出了一些VB及C#語法的比較:

    http://www.harding.edu/fmccown/vbnet_csharp_comparison.html

    沒有說誰比誰好,
    能夠幫你達成目的,解決方案的就是好物就對啦~

    為了讓資料存取的速度加快, 我們可以設定CACHE把資料站存在伺服器的記憶體.\
    如下:

    <%@ Page Language="VB" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <script runat="server">

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
            Label1.Text = Now
        End Sub

        Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs)
            If Not IsNothing(Cache("data")) Then
                Label2.Text = Cache("data").ToString()
            Else
                Label2.Text = "不存在…"
            End If
        End Sub

        Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
            Cache.Insert("data", TextBox1.Text & " – " & Now, Nothing, Now.AddSeconds(10), System.Web.Caching.Cache.NoSlidingExpiration)
           
        End Sub

        Protected Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs)
            Cache.Insert("data", TextBox1.Text & " – " & Now, Nothing, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(10))
        End Sub

        Protected Sub Button4_Click(ByVal sender As Object, ByVal e As System.EventArgs)
            Cache.Insert("data", TextBox1.Text & " – " & Now, New CacheDependency(Server.MapPath("~/Mod05/Books.xml")))
        End Sub

        Protected Sub Button5_Click(ByVal sender As Object, ByVal e As System.EventArgs)
            Cache.Insert("data", TextBox1.Text & " – " & Now, Nothing, Now.AddSeconds(10), System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.Default, New CacheItemRemovedCallback(AddressOf RemovedCallback))
        End Sub
       
        ‘當cache 被移除的時候, 寫一個TXT檔在C:\
        Public Sub RemovedCallback(ByVal k As String, ByVal v As Object, ByVal r As CacheItemRemovedReason)
            Dim sw As New IO.StreamWriter("c:\2544\log.txt", True)
            sw.WriteLine("快取物件 " & k & " 已經移除, 原因是 : " & r.ToString)
            sw.Close()
        End Sub

    </script>

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>Untitled Page</title>
    </head>
    <body>
        <form id="form1″ runat="server">
        <div>
            Now =
            <asp:Label ID="Label1″ runat="server" Text="Label"></asp:Label><br />
            <br />
            Data :
            <asp:TextBox ID="TextBox1″ runat="server"></asp:TextBox>
            <asp:Button ID="Button1″ runat="server" Text="絕對過期" OnClick="Button1_Click" />
            <asp:Button ID="Button3″ runat="server" OnClick="Button3_Click" Text="相對過期" />
            <asp:Button ID="Button4″ runat="server" OnClick="Button4_Click" Text="相依檔案" />
            <asp:Button ID="Button5″ runat="server" OnClick="Button5_Click" Text="快取釋放回呼" /><br />
            <br />
            <br />
            <br />
            <br />
            <asp:Button ID="Button2″ runat="server" OnClick="Button2_Click" Text="取得快取資料" />
            <asp:Label ID="Label2″ runat="server" Text="Label"></asp:Label></div>
        </form>
    </body>
    </html>

    UserControl是 .NET FRAMEWORK 2.0 非常好用的功能,
    一旦物件建立之後, 包裝起來. 就可以重複使用.

    testQuery.aspx

    <%@ Page Language="VB" %>

    <%@ Register Src="ucQueryCustomers.ascx" TagName="ucQueryCustomers" TagPrefix="uc1″ %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <script runat="server">

        Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
            UcQueryCustomers1.Visible = True
        End Sub

        ’3, 使用事件
        Protected Sub UcQueryCustomers1_Selected(ByVal sender As Object, ByVal e As System.EventArgs)
            TextBox1.Text = UcQueryCustomers1.CustomerID
            UcQueryCustomers1.Visible = False
        End Sub
    </script>

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>Untitled Page</title>
    </head>
    <body>
        <form id="form1″ runat="server">
        <div>
            訂單<br />
            <br />
            Customer ID :
            <asp:TextBox ID="TextBox1″ runat="server"></asp:TextBox>
            <asp:Button ID="Button1″ runat="server" OnClick="Button1_Click" Text="…" /><br />
            <br />
            <uc1:ucQueryCustomers ID="UcQueryCustomers1″ runat="server" Visible="false" OnSelected="UcQueryCustomers1_Selected" />
       
        </div>
        </form>
    </body>
    </html>

    ———

    (User Control: UcQueryCustomers1.ascx)

    ———

    <%@ Control Language="VB" ClassName="ucQueryCustomers" %>

    <script runat="server">

        Public ReadOnly Property CustomerID() As String
            Get
                Return GridView1.SelectedValue
            End Get
        End Property
       
        ’1, 對外宣告事件
        Public Event Selected As EventHandler
       
        ’2, 在正確時間點觸發事件給外界
        Protected Sub GridView1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
            RaiseEvent Selected(sender, e)
        End Sub
    </script>

    <div>
        查詢 :
        <asp:TextBox ID="TextBox1″ runat="server"></asp:TextBox>
        <asp:Button ID="Button1″ runat="server" Text="查詢" /><br />
        <asp:GridView ID="GridView1″ runat="server" AllowPaging="True" AutoGenerateColumns="False"
            CellPadding="4″ DataKeyNames="CustomerID" DataSourceID="SqlDataSource1″ EmptyDataText="There are no data records to display."
            ForeColor="#333333″ GridLines="None" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
            <FooterStyle BackColor="#1C5E55″ Font-Bold="True" ForeColor="White" />
            <Columns>
                <asp:CommandField ShowSelectButton="True" />
                <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" ReadOnly="True" SortExpression="CustomerID" />
                <asp:BoundField DataField="ContactTitle" HeaderText="ContactTitle" SortExpression="ContactTitle" />
                <asp:BoundField DataField="CompanyName" HeaderText="CompanyName" SortExpression="CompanyName" />
                <asp:BoundField DataField="ContactName" HeaderText="ContactName" SortExpression="ContactName" />
            </Columns>
            <RowStyle BackColor="#E3EAEB" />
            <EditRowStyle BackColor="#7C6F57″ />
            <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333″ />
            <PagerStyle BackColor="#666666″ ForeColor="White" HorizontalAlign="Center" />
            <HeaderStyle BackColor="#1C5E55″ Font-Bold="True" ForeColor="White" />
            <AlternatingRowStyle BackColor="White" />
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1″ runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString1 %>"
            DeleteCommand="DELETE FROM [Customers] WHERE [CustomerID] = @CustomerID" InsertCommand="INSERT INTO [Customers] ([CustomerID], [ContactTitle], [CompanyName], [ContactName]) VALUES (@CustomerID, @ContactTitle, @CompanyName, @ContactName)"
            ProviderName="<%$ ConnectionStrings:NorthwindConnectionString1.ProviderName %>"
            SelectCommand="SELECT [CustomerID], [ContactTitle], [CompanyName], [ContactName] FROM [Customers] WHERE ([CompanyName] LIKE ‘%’ + @CompanyName + ‘%’)"
            UpdateCommand="UPDATE [Customers] SET [ContactTitle] = @ContactTitle, [CompanyName] = @CompanyName, [ContactName] = @ContactName WHERE [CustomerID] = @CustomerID">
            <DeleteParameters>
                <asp:Parameter Name="CustomerID" Type="String" />
            </DeleteParameters>
            <UpdateParameters>
                <asp:Parameter Name="ContactTitle" Type="String" />
                <asp:Parameter Name="CompanyName" Type="String" />
                <asp:Parameter Name="ContactName" Type="String" />
                <asp:Parameter Name="CustomerID" Type="String" />
            </UpdateParameters>
            <SelectParameters>
                <asp:ControlParameter ControlID="TextBox1″ Name="CompanyName" PropertyName="Text"
                    Type="String" />
            </SelectParameters>
            <InsertParameters>
                <asp:Parameter Name="CustomerID" Type="String" />
                <asp:Parameter Name="ContactTitle" Type="String" />
                <asp:Parameter Name="CompanyName" Type="String" />
                <asp:Parameter Name="ContactName" Type="String" />
            </InsertParameters>
        </asp:SqlDataSource>
    </div>

    —————-

     

    <%@ Page Language="VB" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <script runat="server">

        Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
            Label1.Text = WebConfigurationManager.AppSettings(TextBox1.Text)
        End Sub

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
            If Not Page.IsPostBack Then
                DropDownList1.DataSource = WebConfigurationManager.AppSettings.Keys
                DropDownList1.DataBind()
                TextBox2.Text = WebConfigurationManager.AppSettings(DropDownList1.SelectedValue)
            End If
        End Sub

        Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
            TextBox2.Text = WebConfigurationManager.AppSettings(DropDownList1.SelectedValue)
        End Sub

        Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs)
            ’1, 寫入Runtimeg設定
            ‘WebConfigurationManager.AppSettings.Set(DropDownList1.SelectedValue, TextBox2.Text)
            ’2, 修改Web.config
            ’2-1, 開啟web.config
            Dim cfg As System.Configuration.Configuration = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath)
            ’2-2, 修改設定
            cfg.AppSettings.Settings(DropDownList1.SelectedValue).Value = TextBox2.Text
            ’2-3, 存檔
            cfg.Save()
        End Sub

        Protected Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs)
            ’1, 開啟web.config
            Dim cfg As System.Configuration.Configuration = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath)
            ’2, 取得appSettings設定區段
            Dim cs As ConfigurationSection = cfg.GetSection("appSettings")
            ’3, 判斷是否有加密過, 以決定加密或解密
            If cs.SectionInformation.IsProtected Then
                cs.SectionInformation.UnprotectSection()
                Response.Write("已解密…")
            Else
                cs.SectionInformation.ProtectSection("DataProtectionConfigurationProvider")
                Response.Write("已加密…")
            End If
            ’4, 存檔
            cfg.Save()
        End Sub
    </script>

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>Untitled Page</title>
    </head>
    <body>
        <form id="form1″ runat="server">
        <div>
            key :
            <asp:TextBox ID="TextBox1″ runat="server"></asp:TextBox>
            <asp:Button ID="Button1″ runat="server" OnClick="Button1_Click" Text="Get Value" />
            <asp:Label ID="Label1″ runat="server" Text="Label"></asp:Label><br />
            <br />
            <br />
            keys :
            <asp:DropDownList ID="DropDownList1″ runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
            </asp:DropDownList>
            <asp:TextBox ID="TextBox2″ runat="server"></asp:TextBox>
            <asp:Button ID="Button2″ runat="server" Text="修改" OnClick="Button2_Click" />
            <asp:Button ID="Button3″ runat="server" OnClick="Button3_Click" Text="加密/解密" /></div>
        </form>
    </body>
    </html>