.NET FRAMEWORK 寫一個WinForm程式來監控自己的電腦狀態(WMI)

使用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

.NET FRAMEWORK WMI TOOLS 下載

WMI 是作業系統提供來監控與管理系統, 驅動程式與應用程式的一種技術.簡單來說就是監控作業系統相關的所有資訊.

wmi tools 下載點
http://www.microsoft.com/downloads/details.aspx?familyid=6430F853-1120-48DB-8CC5-F2ABDC3ED314&displaylang=en
wql 語言詳細範例介紹
http://msdn.microsoft.com/en-us/library/aa394054(VS.85).aspx

PHP 的 STRING FUNCTION

PHP 的 STRING FUNCTION

php 的string function 一直是處理字串的好幫手. 對於各種需求都可以在這個列表中找到.
以下列表取自: http://tw2.php.net/manual/en/ref.strings.php

Table of Contents

addcslashes — Quote string with slashes in a C style
addslashes — Quote string with slashes
bin2hex — Convert binary data into hexadecimal representation
chop — Alias of rtrim
chr — Return a specific character
chunk_split — Split a string into smaller chunks
convert_cyr_string — Convert from one Cyrillic character set to another
convert_uudecode — Decode a uuencoded string
convert_uuencode — Uuencode a string
count_chars — Return information about characters used in a string
crc32 — Calculates the crc32 polynomial of a string
crypt — One-way string encryption (hashing)
echo — Output one or more strings
explode — Split a string by string
fprintf — Write a formatted string to a stream
get_html_translation_table — Returns the translation table used by htmlspecialchars and htmlentities
hebrev — Convert logical Hebrew text to visual text
hebrevc — Convert logical Hebrew text to visual text with newline conversion
html_entity_decode — Convert all HTML entities to their applicable characters
htmlentities — Convert all applicable characters to HTML entities
htmlspecialchars_decode — Convert special HTML entities back to characters
htmlspecialchars — Convert special characters to HTML entities
implode — Join array elements with a string
join — Alias of implode
lcfirst — Make a string’s first character lowercase
levenshtein — Calculate Levenshtein distance between two strings
localeconv — Get numeric formatting information
ltrim — Strip whitespace (or other characters) from the beginning of a string
md5_file — Calculates the md5 hash of a given file
md5 — Calculate the md5 hash of a string
metaphone — Calculate the metaphone key of a string
money_format — Formats a number as a currency string
nl_langinfo — Query language and locale information
nl2br — Inserts HTML line breaks before all newlines in a string
number_format — Format a number with grouped thousands
ord — Return ASCII value of character
parse_str — Parses the string into variables
print — Output a string
printf — Output a formatted string
quoted_printable_decode — Convert a quoted-printable string to an 8 bit string
quotemeta — Quote meta characters
rtrim — Strip whitespace (or other characters) from the end of a string
setlocale — Set locale information
sha1_file — Calculate the sha1 hash of a file
sha1 — Calculate the sha1 hash of a string
similar_text — Calculate the similarity between two strings
soundex — Calculate the soundex key of a string
sprintf — Return a formatted string
sscanf — Parses input from a string according to a format
str_getcsv — Parse a CSV string into an array
str_ireplace — Case-insensitive version of str_replace.
str_pad — Pad a string to a certain length with another string
str_repeat — Repeat a string
str_replace — Replace all occurrences of the search string with the replacement string
str_rot13 — Perform the rot13 transform on a string
str_shuffle — Randomly shuffles a string
str_split — Convert a string to an array
str_word_count — Return information about words used in a string
strcasecmp — Binary safe case-insensitive string comparison
strchr — Alias of strstr
strcmp — Binary safe string comparison
strcoll — Locale based string comparison
strcspn — Find length of initial segment not matching mask
strip_tags — Strip HTML and PHP tags from a string
stripcslashes — Un-quote string quoted with addcslashes
stripos — Find position of first occurrence of a case-insensitive string
stripslashes — Un-quote string quoted with addslashes
stristr — Case-insensitive strstr
strlen — Get string length
strnatcasecmp — Case insensitive string comparisons using a “natural order” algorithm
strnatcmp — String comparisons using a “natural order” algorithm
strncasecmp — Binary safe case-insensitive string comparison of the first n characters
strncmp — Binary safe string comparison of the first n characters
strpbrk — Search a string for any of a set of characters
strpos — Find position of first occurrence of a string
strrchr — Find the last occurrence of a character in a string
strrev — Reverse a string
strripos — Find position of last occurrence of a case-insensitive string in a string
strrpos — Find position of last occurrence of a char in a string
strspn — Find length of initial segment matching mask
strstr — Find first occurrence of a string
strtok — Tokenize string
strtolower — Make a string lowercase
strtoupper — Make a string uppercase
strtr — Translate certain characters
substr_compare — Binary safe comparison of 2 strings from an offset, up to length characters
substr_count — Count the number of substring occurrences
substr_replace — Replace text within a portion of a string
substr — Return part of a string
trim — Strip whitespace (or other characters) from the beginning and end of a string
ucfirst — Make a string’s first character uppercase
ucwords — Uppercase the first character of each word in a string
vfprintf — Write a formatted string to a stream
vprintf — Output a formatted string
vsprintf — Return a formatted string
wordwrap — Wraps a string to a given number of characters

使用IFRAME的方法

甚麼情況下要是用IFRAME呢?
當你的網頁想在某個欄位放上其他網頁, 這樣在固定的範圍就會動態更新.
也就不用一直去更新某些資料了.

SOURCE CODE:

<iframe src=”news.html” width=”40%” height=”80″ align=”right”>
<p>See our <a href=”news.html”>newsflashes</a>.</p> <!–若IE不支援IFRAME則顯示這行–>
</iframe>

以下網站對IFRAME有更詳細的教學:

http://www.cs.tut.fi/~jkorpela/html/iframe.html

ASP.NET 利用GDI+ 產生圖片,並附加文字

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

這裡教你怎麼把版權宣告文字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

 

ASP.NET 建構自己的Culture

 

用.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

VB vs C#

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

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

這個網址列出了一些VB及C#語法的比較:
http://www.harding.edu/fmccown/vbnet_csharp_comparison.html

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

ASP.NET(VB) Cache, Log.txt 的寫法

為了讓資料存取的速度加快, 我們可以設定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>