顯示具有 vb 標籤的文章。 顯示所有文章
顯示具有 vb 標籤的文章。 顯示所有文章

[程式]VB.Net2.0資料庫通用存取函式

序言

在VS2005建立VB專案(或Web網站)後,若要進行資料庫存取,我個人比較習慣將連線字串寫在設定檔app.config(或web.config)下。

不過VB專案預設是不會產生這個檔,而且在程式中若要取得連線字串的設定也要對專案的參考進行設定。

以下記錄下我做的設定,並把資料庫存取程式簡化為函式。

開發環境

  • VB.Net 2.0 (VS2005)
  • MSSQL2005 Express

專案設定

  • 建立專案後預設的專案屬性下,參考的元件如下圖:

  • 下面的程式中會用到【ConfigurationManager】這個物件來取得設定檔的連線字串,所以我們需要加入【System.Configuration】這個元件:

    點選加入,在.Net分頁下找到【System.Configuration】這個元件
  • 再來要在專案加入新項目【應用程式組態】,名稱用預設的【app.config】就可以了:

  • 編輯app.config,在【configuration】標籤內加入連線字串的設定如:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
    ...
    <connectionStrings>
    <add name="MSSQLDB1"
    connectionString="Data Source=localhost;Initial Catalog=MyTestDB;Integrated Security=True"
    providerName="System.Data.SqlClient" />
    <add name="MSSQLDB2"
    connectionString="Data Source=127.0.0.1;Initial Catalog=MyTestDB;User ID=sa;Password=1234"
    providerName="System.Data.SqlClient" />
    </connectionStrings>
    ...

通用存取函式類別


Imports System.Data.SqlClient
Imports System.Configuration
Public Class DBAccessFunc
    ''' <summary>
    ''' 從ConfigurationManager中的ConnectionStrings找出Initial Catalog
    ''' </summary>
    ''' <param name="ConnName">ConnectionStrings名稱(String)</param>
    ''' <returns>回傳資料庫名稱</returns>
    ''' <remarks>從ConfigurationManager中的ConnectionStrings找出Initial Catalog</remarks>
    Public Shared Function getDBName(ByVal ConnName As String) As String
        Dim val As String = ""
        Dim ConnString As String = ConfigurationManager.ConnectionStrings(ConnName).ConnectionString
        Dim i As Integer = ConnString.IndexOf("Initial Catalog=")
        If i > -1 Then
            val = ConnString.Substring(i + "Initial Catalog=".Length)
            i = val.IndexOf(";")
            If i > -1 Then
                val = val.Substring(0, i)
            End If
        End If
        Return val
    End Function

    Public Shared Function getConnString(ByVal ConnName As String) As String
        Return ConfigurationManager.ConnectionStrings(ConnName).ConnectionString
    End Function


    Public Shared Function getConn(ByVal ConnName As String) As SqlConnection
        Return New SqlConnection(getConnString(ConnName))
    End Function
    ''' <summary>
    ''' 查詢資料庫
    ''' </summary>
    ''' <param name="cn">連線</param>
    ''' <param name="sql">查詢內容</param>
    ''' <returns>回傳查詢結果的DataTable</returns>
    ''' <remarks>查詢資料庫並回傳查詢結果的DataTable</remarks>
    Public Shared Function getTable(ByRef cn As SqlConnection, ByRef sql As String, Optional ByVal isColseConn As Boolean = True) As Data.DataTable
        Dim da As New SqlDataAdapter(sql, cn)
        Dim dt As New Data.DataTable("dt_xml")
        Try
            If cn.State = ConnectionState.Closed Then cn.Open()
            da.SelectCommand.CommandTimeout = 36000000
            da.Fill(dt)
        Catch ex As Exception
            If isColseConn And cn.State = ConnectionState.Open Then cn.Close()
            Throw ex
        End Try
        If isColseConn And cn.State = ConnectionState.Open Then cn.Close()
        Return dt
    End Function

    ''' <summary>
    ''' 執行命令
    ''' </summary>
    ''' <param name="cn">連線</param>
    ''' <param name="sql">查詢內容</param>
    ''' <returns>回傳受影響的資料筆數</returns>
    ''' <remarks>執行命令並回傳受影響的資料筆數</remarks>
    Public Shared Function doCmd(ByRef cn As SqlConnection, ByRef sql As String, Optional ByRef param() As SqlParameter = Nothing, Optional ByVal isColseConn As Boolean = True) As Integer
        Dim result As Integer = 0
        Dim cmd As New SqlCommand
        Try
            cmd.Connection = cn
            cmd.CommandText = sql
            If Not param Is Nothing Then
                cmd.Parameters.AddRange(param)
            End If
            cmd.CommandTimeout = 36000000
            If cn.State = ConnectionState.Closed Then cn.Open()
            result = cmd.ExecuteNonQuery()
        Catch ex As Exception
            cmd.Parameters.Clear()
            If isColseConn And cn.State = ConnectionState.Open Then cn.Close()
            Throw ex
        Finally
            cmd.Parameters.Clear()
            If isColseConn And cn.State = ConnectionState.Open Then cn.Close()
        End Try
        Return result
    End Function


    ''' <summary>
    ''' 取得單一資料
    ''' </summary>
    ''' <param name="cn">連線</param>
    ''' <param name="sql">查詢內容</param>
    ''' <returns>回傳受影響的資料筆數</returns>
    ''' <remarks>執行命令並回傳受影響的資料筆數</remarks>
    Public Shared Function doScalar(ByRef cn As SqlConnection, ByRef sql As String, Optional ByRef param() As SqlParameter = Nothing, Optional ByVal isColseConn As Boolean = True) As Object
        Dim result As Object = Nothing
        Dim cmd As New SqlCommand
        Try
            cmd.Connection = cn
            cmd.CommandText = sql
            If Not param Is Nothing Then
                cmd.Parameters.AddRange(param)
            End If
            cmd.CommandTimeout = 36000000
            If cn.State = ConnectionState.Closed Then cn.Open()
            result = cmd.ExecuteScalar()
        Catch ex As Exception
            cmd.Parameters.Clear()
            If isColseConn And cn.State = ConnectionState.Open Then cn.Close()
            Throw ex
        Finally
            cmd.Parameters.Clear()
            If isColseConn And cn.State = ConnectionState.Open Then cn.Close()
        End Try
        Return result
    End Function

    Public Function executeStoredProcedure(ByRef cn As SqlConnection, ByVal procedure As String, Optional ByRef param As SqlParameter() = Nothing, Optional ByRef output As SqlParameter() = Nothing, Optional ByVal isColseConn As Boolean = True) As Integer
        Dim result As Integer = 0
        Dim cmd As New SqlCommand(procedure, cn)
        Try

            cmd.CommandText = procedure
            cmd.CommandTimeout = 36000000
            cmd.CommandType = CommandType.StoredProcedure
            If Not param Is Nothing Then cmd.Parameters.AddRange(param)
            If Not output Is Nothing Then
                For Each o As SqlParameter In output
                    o.Direction = ParameterDirection.Output
                Next
                cmd.Parameters.AddRange(output)
            End If

            '開啟資料庫連線
            If cn.State = ConnectionState.Closed Then cn.Open()
            '設定變數儲存受影響資料列
            result = cmd.ExecuteNonQuery()
        Catch ex As Exception
            cmd.Parameters.Clear()
            If isColseConn And cn.State = ConnectionState.Open Then cn.Close()
            Throw ex
        Finally
            cmd.Parameters.Clear()
            If isColseConn And cn.State = ConnectionState.Open Then cn.Close()
        End Try
        Return result
    End Function
End Class


使用範例程式

Dim connStr1 As String = DBGenFunc.getConnStr("MSSQLDB1")
Dim sourceTable As String() = {"[" & DBGenFunc.getDBName("MSSQLDB1") & "].[dbo].[" & "MyTestTab" & "]", _
"[" & DBGenFunc.getDBName("MSSQLDB1") & "].[dbo].[" & "MyContentTab" & "]"}
Dim param() As SqlClient.SqlParameter = {New SqlClient.SqlParameter("P0", SqlDbType.VarChar)}
Dim sql As String

Dim title As String

Console.WriteLine("doCmdScalar Start:")
sql = "SELECT Title" & vbCrLf & _
" FROM " & sourceTable(0) & "" & vbCrLf & _
" WHERE SN=@P0"
param(0).Value = 1
title = DBGenFunc.doCmdScalar(connStr1, sql, param)
Console.WriteLine("doCmdScalar" & vbTab & title)

Console.WriteLine("getTable Start:")
sql = "SELECT Title" & vbCrLf & _
" FROM " & sourceTable(0) & "" & vbCrLf
Dim dt As DataTable = DBGenFunc.getTable(connStr1, sql)
For Each r As DataRow In dt.Rows
title = r.Item(0)
Console.WriteLine("getTable" & vbTab & title)
Next

Console.WriteLine("getTableToArray Start:")
Dim data As String() = DBGenFunc.dataTableToArray(Of String)(dt, 0)
For Each r As String In data
title = r
Console.WriteLine("getTable" & vbTab & title)
Next

Console.WriteLine("doCmd Start:")
sql = "INSERT INTO " & sourceTable(0) & "" & vbCrLf & _
"VALUES(@P0,@P1)"
param = New SqlClient.SqlParameter() {New SqlClient.SqlParameter("P0", SqlDbType.VarChar), _
New SqlClient.SqlParameter("P1", SqlDbType.VarChar)}
param(0).Value = "TNew"
param(1).Value = "SNew"
title = DBGenFunc.doCmd(connStr1, sql, param)
Console.WriteLine("doCmd" & vbTab & title)

Console.WriteLine("getReader Start:")
sql = "SELECT Title, Subject" & vbCrLf & _
" FROM " & sourceTable(0) & "" & vbCrLf
Dim dr As SqlClient.SqlDataReader = DBGenFunc.getReader(connStr1, sql)
While dr.Read()
title = dr.Item(0)
Console.WriteLine("getReader" & vbTab & title & vbTab & dr.Item(1))
End While
DBGenFunc.closeReader()

執行結果

doCmdScalar Start:
doCmdScalar T1
getTable Start:
getTable T1
getTable T2
getTable T3
getTable TNew
getTableToArray Start:
getTable T1
getTable T2
getTable T3
getTable TNew
doCmd Start:
doCmd 1
getReader Start:
getReader T1 S1
getReader T2 S2
getReader T3 S3
getReader TNew SNew
getReader TNew SNew

以尋找控制項的方式取得大量控制項的值

最近在寫VB的視窗程式時~因為一拉了一堆控制項讓使用者將值填進去,結果就要寫程式一個一個把值讀進來~

由於不是陣列型的控制項(我也不知怎麼讓這些控制項變陣列),所以就以命名的方式,將這些控制項命名為TXT1、TXT2...

這時就須要以名字找控制項了,所以我寫了個小函式來輔助我~

程式

將以下這段程式擺在控制項所在的Form的程式碼中~

    Public Function findControl(ByVal name As String) As Control
       Dim result As Control = Nothing
       Dim find As Control() = Me.Controls.Find(name, True)
       If find.Length > 0 Then
           result = find(0)
       End If
       Return result
   End Function

呼叫

這時呼叫findControl("控制項名稱"),有找到就會傳回該控制項,沒找到就會傳回Nothing。

利用這樣的函式,只要控制項命名得當,就能動態依照控制項數量將資料讀進來。例如,

        Dim txtName As TextBox = Nothing
       Dim SA As new ArrayList
       Dim i As Integer = 1
       Do
           txtName = findControl("SA" + i.ToString)
           If Not txtName Is Nothing Then
              SA.Add(txtName.Text)
           End If
           i = i + 1
       Loop Until txtName Is Nothing

這樣我就取得了一個文字陣列,這個文字陣列的值都來自以SA開頭為名的文字方塊囉

用VB.Net寫的RSS Feed產生函式

我自己是很喜歡用RSS的服務的人,所以寫網站或是做一些事時常會想到要弄個RSS Feed,最起碼自己會用的到~

不過VB中並沒有直接提供RSS Feed的產生函式,國外有些網站好像有提供類似的東西,不過不是要註冊就是有些複雜,所以我就自己寫了一個~

作法

我原本是用FileIO那篇的寫文字檔的方式,用比較笨的方法產生RSS Feed~

不過後來我改用以下的內容,將RSS的內容,以Xml.XmlDocument這個類別來產生XML的結構,順便學習在VB.Net下怎麼自己產生XML結構,並且它會自己將HTML編碼的問題解決

RSS 2.0的規格則是參考RSS 2.0 Specification中的規定,來設計RSS feed的元素,不過我剔除掉了一些我覺得沒用或是我看不出來功能的標籤,來產生結果

模組程式碼

Imports System
Module RSSGenModule
   ''' 
   ''' RSSGenerator V1.0 is builded by Allen
   ''' Please get the newest information at
   ''' http://allen080.blogspot.com/
   ''' 
   Public Class RSSGenerator
       Public Sub createRSS(ByRef rssfeed As RSSFeed, ByVal path As String)
           'RSS 2.0 specification is Reference at
           'http://www.rssboard.org/rss-specification/
           Dim x As New Xml.XmlDocument
           x.LoadXml("" + "" + "")

           Dim channel As Xml.XmlElement = x.CreateElement("channel")
           x.DocumentElement.AppendChild(channel)

           Dim element As Xml.XmlElement
           Dim subElement As Xml.XmlElement
           'set channel start
           element = x.CreateElement("title")
           channel.AppendChild(element)
           element.InnerText = rssfeed.title
           If Not rssfeed.link Is Nothing Then
               element = x.CreateElement("link")
               channel.AppendChild(element)
               element.InnerText = rssfeed.link
           End If
           If Not rssfeed.description Is Nothing Then
               element = x.CreateElement("description")
               channel.AppendChild(element)
               element.InnerText = rssfeed.description
           End If
           If Not rssfeed.language Is Nothing Then
               element = x.CreateElement("language")
               channel.AppendChild(element)
               element.InnerText = rssfeed.language
           End If
           If Not rssfeed.copyright Is Nothing Then
               element = x.CreateElement("copyright")
               channel.AppendChild(element)
               element.InnerText = rssfeed.copyright
           End If
           If Not rssfeed.managingEditor Is Nothing Then
               element = x.CreateElement("managingEditor")
               channel.AppendChild(element)
               element.InnerText = rssfeed.managingEditor
           End If

           If Not rssfeed.webMaster Is Nothing Then
               element = x.CreateElement("webMaster")
               channel.AppendChild(element)
               element.InnerText = rssfeed.webMaster
           End If

           element = x.CreateElement("pubDate")
           channel.AppendChild(element)
           element.InnerText = (rssfeed.pubDate.AddHours(-8)).ToString("r")

           element = x.CreateElement("lastBuildDate")
           channel.AppendChild(element)
           element.InnerText = (rssfeed.lastBuildDate.AddHours(-8)).ToString("r")

           If Not rssfeed.category Is Nothing Then
               element = x.CreateElement("category")
               channel.AppendChild(element)
               element.InnerText = rssfeed.category
           End If
           If Not rssfeed.generator Is Nothing Then
               element = x.CreateElement("generator")
               channel.AppendChild(element)
               element.InnerText = rssfeed.generator
           End If
           If Not rssfeed.docs Is Nothing Then
               element = x.CreateElement("docs")
               channel.AppendChild(element)
               element.InnerText = rssfeed.docs
           End If


           If Not rssfeed.image Is Nothing Then
               element = x.CreateElement("image")
               channel.AppendChild(element)
               'set image start
               If Not rssfeed.image.title Is Nothing Then
                   subElement = x.CreateElement("title")
                   element.AppendChild(subElement)
                   subElement.InnerText = rssfeed.image.title
               End If
               If Not rssfeed.image.link Is Nothing Then
                   subElement = x.CreateElement("link")
                   element.AppendChild(subElement)
                   subElement.InnerText = rssfeed.image.link
               End If
               subElement = x.CreateElement("url")
               element.AppendChild(subElement)
               subElement.InnerText = rssfeed.image.url
               If Not rssfeed.image.description Is Nothing Then
                   subElement = x.CreateElement("description")
                   element.AppendChild(subElement)
                   subElement.InnerText = rssfeed.image.description
               End If
               'set image end
           End If
           If Not rssfeed.itmes Is Nothing Then
               For Each item As RSSElement In rssfeed.itmes
                   element = x.CreateElement("item")
                   channel.AppendChild(element)
                   'set item start
                   subElement = x.CreateElement("title")
                   element.AppendChild(subElement)
                   subElement.InnerText = item.title
                   If Not item.link Is Nothing Then
                       subElement = x.CreateElement("link")
                       element.AppendChild(subElement)
                       subElement.InnerText = item.link
                   End If
                   If Not item.description Is Nothing Then
                       subElement = x.CreateElement("description")
                       element.AppendChild(subElement)
                       subElement.InnerText = item.description
                   End If
                   If Not item.author Is Nothing Then
                       subElement = x.CreateElement("author")
                       element.AppendChild(subElement)
                       subElement.InnerText = item.author
                   End If
                   If Not item.category Is Nothing Then
                       subElement = x.CreateElement("category")
                       element.AppendChild(subElement)
                       subElement.InnerText = item.category
                   End If
                   If Not item.comments Is Nothing Then
                       subElement = x.CreateElement("comments")
                       element.AppendChild(subElement)
                       subElement.InnerText = item.comments
                   End If
                   If Not item.guid Is Nothing Then
                       subElement = x.CreateElement("guid")
                       subElement.SetAttribute("isPermaLink", "false")
                       element.AppendChild(subElement)
                       subElement.InnerText = item.guid
                   End If

                   subElement = x.CreateElement("pubDate")
                   element.AppendChild(subElement)
                   subElement.InnerText = (item.pubDate.AddHours(-8)).ToString("r")
                   'set item end
               Next
           End If
           'set channel end

           'write to file
           Dim settings As New Xml.XmlWriterSettings()
           settings.Indent = True
           settings.IndentChars = "    "
           settings.Encoding = System.Text.Encoding.UTF8
           Using writer As Xml.XmlWriter = Xml.XmlWriter.Create(path, settings)
               x.WriteTo(writer)
               writer.Flush()
           End Using
       End Sub
   End Class

   Public Class RSSElement
       Private _title As String
       Private _link As String
       Private _description As String
       Private _author As String
       Private _category As String
       Private _comments As String
       Private _guid As String
       Private _pubDate As Date
       Public Property pubDate() As Date
           Get
               Return _pubDate
           End Get
           Set(ByVal value As Date)
               _pubDate = value
           End Set
       End Property

       Public Property guid() As String
           Get
               Return _guid
           End Get
           Set(ByVal value As String)
               _guid = value
           End Set
       End Property

       ''' 
       ''' 回應的URL
       ''' 
       Public Property comments() As String
           Get
               Return _comments
           End Get
           Set(ByVal value As String)
               _comments = value
           End Set
       End Property
       Public Property category() As String
           Get
               Return _category
           End Get
           Set(ByVal value As String)
               _category = value
           End Set
       End Property

       ''' 
       ''' E-Mail
       ''' 
       Public Property author() As String
           Get
               Return _author
           End Get
           Set(ByVal value As String)
               _author = value
           End Set
       End Property

       Public Property description() As String
           Get
               Return _description
           End Get
           Set(ByVal value As String)
               _description = value
           End Set
       End Property

       Public Property title() As String
           Get
               Return _title
           End Get
           Set(ByVal value As String)
               _title = value
           End Set
       End Property
       Public Property link() As String
           Get
               Return _link
           End Get
           Set(ByVal value As String)
               _link = value
           End Set
       End Property
   End Class

   Public Class RSSImage
       Private _title As String
       Private _link As String
       Private _url As String
       Private _description As String
       Public Property description() As String
           Get
               Return _description
           End Get
           Set(ByVal value As String)
               _description = value
           End Set
       End Property

       Public Property url() As String
           Get
               Return _url
           End Get
           Set(ByVal value As String)
               _url = value
           End Set
       End Property

       Public Property link() As String
           Get
               Return _link
           End Get
           Set(ByVal value As String)
               _link = value
           End Set
       End Property

       Public Property title() As String
           Get
               Return _title
           End Get
           Set(ByVal value As String)
               _title = value
           End Set
       End Property
   End Class

   Public Class RSSFeed
       Private _title As String
       Private _link As String
       Private _description As String
       Private _language As String = "zh-tw"
       Private _copyright As String
       Private _managingEditor As String
       Private _webMaster As String
       Private _guid As String
       Private _pubDate As Date = Now
       Private _lastBuildDate As Date = Now
       Private _category As String
       Private _generator As String
       Private _docs As String = "http://www.rssboard.org/rss-specification"
       Private _image As RSSImage
       Private _items As ArrayList

       ''' 
       ''' 元素型態是RSSElement
       ''' 
       Public Property itmes() As ArrayList
           Get
               Return _items
           End Get
           Set(ByVal value As ArrayList)
               _items = value
           End Set
       End Property
       Public Property image() As RSSImage
           Get
               Return _image
           End Get
           Set(ByVal value As RSSImage)
               _image = value
           End Set
       End Property

       ''' 
       ''' URL
       ''' 
       Public Property docs() As String
           Get
               Return _docs
           End Get
           Set(ByVal value As String)
               _docs = value
           End Set
       End Property

       Public Property generator() As String
           Get
               Return _generator
           End Get
           Set(ByVal value As String)
               _generator = value
           End Set
       End Property

       Public Property category() As String
           Get
               Return _category
           End Get
           Set(ByVal value As String)
               _category = value
           End Set
       End Property

       Public Property lastBuildDate() As Date
           Get
               Return _lastBuildDate
           End Get
           Set(ByVal value As Date)
               _lastBuildDate = value
           End Set
       End Property
       Public Property pubDate() As Date
           Get
               Return _pubDate
           End Get
           Set(ByVal value As Date)
               _pubDate = value
           End Set
       End Property

       Public Property guid() As String
           Get
               Return _guid
           End Get
           Set(ByVal value As String)
               _guid = value
           End Set
       End Property

       ''' 
       ''' E-Mail
       ''' 
       Public Property managingEditor() As String
           Get
               Return _managingEditor
           End Get
           Set(ByVal value As String)
               _managingEditor = value
           End Set
       End Property

       ''' 
       ''' E-Mail
       ''' 
       Public Property webMaster() As String
           Get
               Return _webMaster
           End Get
           Set(ByVal value As String)
               _webMaster = value
           End Set
       End Property

       Public Property copyright() As String
           Get
               Return _copyright
           End Get
           Set(ByVal value As String)
               _copyright = value
           End Set
       End Property

       Public Property language() As String
           Get
               Return _language
           End Get
           Set(ByVal value As String)
               _language = value
           End Set
       End Property

       Public Property description() As String
           Get
               Return _description
           End Get
           Set(ByVal value As String)
               _description = value
           End Set
       End Property

       Public Property title() As String
           Get
               Return _title
           End Get
           Set(ByVal value As String)
               _title = value
           End Set
       End Property
       Public Property link() As String
           Get
               Return _link
           End Get
           Set(ByVal value As String)
               _link = value
           End Set
       End Property
   End Class

End Module

使用方法

這個模組中主要有4個類別,分別是

  • RSSFeed:整個RSS的資料都存在這裡面,如果沒有被設定到的屬性,就不會被寫入檔案中(日期除外)
  • RSSImage:用來顯示Logo的資訊,如果沒有Logo就不要把它設定給RSSFeed就好了
  • RSSElement:用來存每一筆新資訊的地方,在RSSFeed中是被ArrayList存起來的
  • RSSGenerator:將路徑與RSSFeed交給其中的createRSS函式,就能產生一個RSS feed檔

使用範例

            Dim rssfeed As New RSSFeed
           rssfeed.title = title
           rssfeed.link = url
           rssfeed.description = title
           rssfeed.generator = "倫倫3號"
           rssfeed.webMaster = "allen080+Tech@gmail.com"
           Dim rssimage As New RSSImage
           rssfeed.image = rssimage
           rssimage.title = title
           rssimage.link = url
           rssimage.url = url + "images/fslogo.jpg"
           rssfeed.itmes = New ArrayList
           Dim notes As ArrayList = gbdatas
           For Each item As GuestBookData In notes
               Dim rsselement As New RSSElement
               rsselement.title = item.title
               rsselement.author = item.eMail + " (" + item.name + ")"
               rsselement.link = item.url
               rsselement.description = item.content
               rsselement.pubDate = item.time
               rsselement.guid = item.url
               rssfeed.itmes.Add(rsselement)
           Next

           Dim rssgen As New RSSGenerator
           rssgen.createRSS(rssfeed, path)

總結

有這樣的一個類別就可以很快的產生出屬於自己的RSS Feed,當然這個xml檔要放在網頁伺服器上,我通常是用IIS就解決了~

完成的檔案可以透過Feed Validator for Atom and RSS這樣的網站來做驗證,不過如果只是一些小警告、小錯誤不理他也沒關係,只要你的RSS Reader不會讀不出來就好了

寫完這個RSS產生函式,如果有空我會找時間看看Atom的不同,如果有必要,也會寫Atom的版本~

參考連結

用VB讀寫文字檔的簡單函式

以下是我常用的VB檔案讀寫函式,我自己覺得還滿方便的

程式碼

丟給它路徑與new好的ArrayList就可以讀檔了,讀出來後ArrayList中會都是String,每個String代表一行,寫入也是反向動作,如果寫入的路徑不存在會自己產生目錄

修改encoding就可以設定寫入的編碼,預設用UTF8

Imports System.IO
Public Class MyFileIO
Public encoding As System.Text.Encoding = System.Text.Encoding.UTF8

Public Sub fileReadLine(ByRef path As String, ByRef fileData As ArrayList)
    If Not fileData Is Nothing And Not path.Equals("") And System.IO.File.Exists(path) Then
        Dim readfile As New System.IO.StreamReader(path, encoding)
        Dim str As String
        str = readfile.ReadLine()
        While Not str Is Nothing
            fileData.Add(str)
            str = readfile.ReadLine
        End While
        readfile.Close()
    End If
End Sub

Public Sub fileWriteLine(ByRef path As String, ByRef fileData As ArrayList)
    If Not fileData Is Nothing And Not path.Equals("") Then
        Directory.CreateDirectory(path.Substring(0, path.LastIndexOf("\")))
        Dim writefile As New System.IO.StreamWriter(path, False, encoding)
        Dim i As Integer
        Dim str As String
        For i = 0 To fileData.Count - 1
            str = fileData.Item(i)
            writefile.WriteLine(str)
        Next
        writefile.Close()
    End If
End Sub
End Class

相關

如果要取得應用程式所在路徑可用:

 Dim path as String = System.Windows.Forms.Application.StartupPath + "\"

如果是Web App的話則使用

 Dim path As String = Server.MapPath("~/")

相關連結

VS2005(.Net)非同步呼叫Web Services

.Net Framework 2.0所提供的開發環境中,提供了簡單的方式讓你用非同步的方法呼叫Web Services

它使用MothodName後方加上Async名稱的函式當做呼叫方法,然後另外寫一個函式處理呼叫的回傳值

我想背後原理應該不脫離使用執行序(Thread)來達到這樣的功能。

參考資料中有微軟的範例,但它的做法如果用在連續呼叫的話可能會有些問題,而且沒有C#的範例,

所以我稍做修改成我需要的版本

開發環境

  • Microsoft Visual Studio 2005 (.Net Framework 2.0)
  • 專案類型:Windows 應用程式
  • 已有一個簡單的Web Service,該Service中有個函式: Function hello(ByVal name As String) As String
  • 我將Web Service加到名為wsServer的Web參考中
  • 我在畫面中用一個多行的TextBox叫resultOut來顯示呼叫與回應的資訊

C#

  //CallMyWSAsync用來New起Web service的實體,指定處理回應的函式,然後呼叫Web Service
 private void CallMyWSAsync(string value)
 {
  //New起Web service的實體
  wsServer.WebService ws = new wsServer.WebService();
  //指定處理回應的函式
  ws.helloCompleted += new wsServer.helloCompletedEventHandler(getCompletedHandler);
  //resultOut來顯示呼叫的資訊
  string o = "ID=" + ws.GetHashCode() + " Start, value=" + value;
  o = DateTime.Now.ToString() + "\r\n" + o;
  resultOut.Text = o + "\r\n" + resultOut.Text;
  resultOut.Text = "\r\n" + resultOut.Text;
  //呼叫Web Service
  ws.helloAsync(value);

 }

 //getCompletedHandler用來處理回應
 private void getCompletedHandler(object sender, wsServer.helloCompletedEventArgs e)
 {
  string o;
  if (e.Error == null)
  {
   o = "ID=" + sender.GetHashCode() + " Done, Result: " + e.Result; //e.Result可取得回應的物件
  }
  else
  {
   o = e.Error.Message;
  }
  //resultOut來顯示回應的資訊
   o = DateTime.Now.ToString() + "\r\n" + o;
  resultOut.Text = o + "\r\n" + resultOut.Text;
  resultOut.Text = "\r\n" + resultOut.Text;
 } 

VB


   'CallMyWSAsync用來New起Web service的實體,指定處理回應的函式,然後呼叫Web Service
   Sub CallMyWSAsync(ByVal value As String)
       'New起Web service的實體
       Dim ws As New wsServer.WebService
       '指定處理回應的函式
       AddHandler ws.helloCompleted, AddressOf getCompletedHandler
       'resultOut來顯示呼叫的資訊
       Dim o As String = "ID=" + ws.GetHashCode() + " Start, value=" + value
       o = DateTime.Now.ToString() + vbCrLf + o
       resultOut.Text = o + vbCrLf + resultOut.Text
       resultOut.Text = vbCrLf + resultOut.Text
       '呼叫Web Service
       ws.helloAsync(value)

   End Sub
   'getCompletedHandler用來處理回應
   Private Sub getCompletedHandler(ByVal sender As Object, ByVal e As wsServer.helloCompletedEventArgs)
       Dim o As String
       If e.Error Is Nothing Then
           o = "ID=" + sender.GetHashCode() + " Done, Result: " + e.Result 'e.Result可取得回應的物件
           o = DateTime.Now.ToString() + vbCrLf + o
           resultOut.Text = o + vbCrLf + resultOut.Text
           resultOut.Text = vbCrLf + resultOut.Text
       Else
           o = e.Error.Message
       End If
       'resultOut來顯示回應的資訊
       o = DateTime.Now.ToString() + vbCrLf + o
       resultOut.Text = o + vbCrLf + resultOut.Text
       resultOut.Text = vbCrLf + resultOut.Text
   End Sub

後言

這是我第一次寫C#的程式,因為我想順便體驗C#開發起來有何不同,

我在查資料時,還有看到ASP.Net的網頁也可以設為Async,不過會有什麼結果我沒試過,下回有空再寫寫札記吧

參考資料

這裡是關於技術的手札~

也歡迎大家到

倫與貓的足跡



到噗浪來

關心一下我唷!
by 倫
 
Copyright 2009 倫倫3號Beta-Log All rights reserved.
Blogger Templates created by Deluxe Templates
Wordpress Theme by EZwpthemes