跳到主要內容

VB.NET 語法 1

> Class Inherits Class
Public Class ApiService
    Inherits PageBase

--------------------------------------------------------------------------
> Class Implements Interface
Interface Interface1
    Sub sub1(ByVal i As Integer)
End Interface

Public Class ImplementationClass1
    Implements Interface1
    Sub Sub1(ByVal i As Integer) Implements Interface1.sub1
        ' Insert code here to implement this method.
    End Sub
End Class

--------------------------------------------------------------------------
>Interface > abstract class > Class 

(c#)
interface ITheseSchedule
{
        void DoWork();       
}

abstract class BaseThese : DbBase , ITheseSchedule
{
        public abstract void DoWork();
        public TheseBLCHService.BLCHService blchService;

        public void InitWs()
        {
            blchService = new TheseBLCHService.BLCHService();
            blchService.Timeout = 600000;
        }
}
   
class ARS010 : BaseThese
{
        public override void DoWork()
        {
            InitWs();
            ...........
        }



(vb.net)

Public Interface IFoo
    Property Description() As String
End Interface

Public MustInherit Class FooBase
    Implements IFoo

    Public MustOverride Property Description As String Implements IFoo.Description
End Class

Public Class MyFoo
    Inherits FooBase

    Private description As String

    Public Overrides Property Description As String
        Get
            Return description
        End Get
        Set(value As String)
            description = value
        End Set
    End Property
End Class
 
--------------------------------------------------------------------------
> 基底Class 執行繼承Class的Fucntion
Public MustInherit Class ConsultationPageBase
    Inherits PageBase
    Public Event UpdateCustOrderFinish As EventHandler
   
    Sub Update_Cust_Order
         RaiseEvent UpdateCustOrderFinish(Me, New EventArgs) 被繼承Class執行繼承Class的Fucntion
    End Sub
End Class
   
Partial Public Class EQ022
    Inherits ConsultationPageBase 
    AddHandler Me.UpdateCustOrderFinish, AddressOf BindGrid  註冊繼承Class要被執行的Fucntion
   
    Sub BindGrid()
        ..........
    End Sub
End Class       
--------------------------------------------------------------------------
>for each
For Each de As DictionaryEntry In htSeparatedGroup
            Dim Sum As Decimal = de.Value
            Dim Group As Decimal = de.Key.ToString().Split("_")(1)
            If Sum > Group Then
                ProportionTotal_MRI += Group
            Else
                ProportionTotal_MRI += Sum
            End If
Next
--------------------------------------------------------------------------
>for
For n = UBound(cpno) To LBound(cpno) Step -1   'For i As Integer = 0 To dt.Rows.Count - 1
            If n > 0 Then
                If CInt(cpno(n)) - (CInt(cpno(n - 1)) + 4) > 40 Then
                    insrt_point = insrt_point & Trim((CInt(cpno(n - 1)) + 4) + 40) & ","
                End If
                'Exit For
            ElseIf n = 0 Then
                If CInt(cpno(n)) > 40 Then
                    insrt_point = insrt_point & "40,"
                End If
                'Continue For
            End If
Next
--------------------------------------------------------------------------
>Do While
Do While source.EndsWith(s)
            source = source.Remove(source.Length - s.Length)
Loop
--------------------------------------------------------------------------
>Do Loop
Do
           read = responseStream.Read(buffer, 0, buffer.Length)
           fs.Write(buffer, 0, read)
Loop Until read = 0
--------------------------------------------------------------------------
>While
While Not Client.GetStream.DataAvailable()
            i = i + 1
            If i >= 1500000 Then
                Do_Socket_Put = False
                Exit While
            End If
End While
--------------------------------------------------------------------------
>Select Case
Protected Function GetActionType() As ActionType
        Dim at As ActionType
        If Request("action") <> Nothing Then
            Select Case Request("action").ToString
                Case "i"
                    at = ActionType.Insert
                Case "s"
                    at = ActionType.Search
                Case "u"
                    at = ActionType.Update
            End Select
            Return at
        End If
End Function

Dim action As Nullable(Of ActionType) = GetActionType()
--------------------------------------------------------------------------
>Function / Optional Parameter
Public Function ExecSqlTrans(ByVal al As ArrayList , Optional ByVal TableName As String = "") As Boolean
    Dim conn As New OleDbConnection(HMCIS_DB_ConnectStr)
    Dim sqlTran As OleDbTransaction
    Dim cmd As New OleDbCommand
    conn.Open()

    sqlTran = conn.BeginTransaction()
    cmd.Transaction = sqlTran
    cmd.Connection = conn

    Try
        Dim i As Integer
        For i = 0 To al.Count - 1
            cmd.CommandText = al(i)
            cmd.ExecuteNonQuery()
        Next
        sqlTran.Commit()
        Return True
    Catch err As Exception
        sysvar.myLog(err.Message)
        sqlTran.Rollback()
        'Exit Function
        Return False
    Finally
        conn.Close()
    End Try
End Function
--------------------------------------------------------------------------
>Function
Function LogicAnd(ByVal x As Integer, ByVal y As Integer) As Boolean
        Return (x And y) = y
End Function
--------------------------------------------------------------------------
>Sub
Public Sub GetTraceData(ByVal alSql As ArrayList)
        If Not Session("listItems") Is Nothing Then
            Dim items = From x In CType(Session("listItems"), List(Of String)) Select x
            For Each strSql As String In items
                alSql.Add(strSql)
            Next
        End If
End Sub
--------------------------------------------------------------------------
>construct
Public Class   
    Public Sub New()

    End Sub
End Class
--------------------------------------------------------------------------
>IIf
Return IIf(New DBComponent().Execute(ExecStr) > 0, True, False)
--------------------------------------------------------------------------
>Using
Using rs As Stream = ftp.GetRequestStream
           Do
              dataRead = fs.Read(content, 0, BufferSize)
              rs.Write(content, 0, dataRead)
           Loop Until dataRead < BufferSize
           rs.Close()
End Using
--------------------------------------------------------------------------
>Get Set
Public ht As Hashtable
Public Property Items() As Hashtable
  Get
      Return ht
  End Get
  Set(ByVal value As Hashtable)
      ht = value
  End Set
End Property
--------------------------------------------------------------------------
>With
Dim newMail As New System.Net.Mail.MailMessage
With newMail
            .From = New System.Net.Mail.MailAddress(from_email, from_name)
            .Body = body
            .Subject = subject
            .To.Add(New System.Net.Mail.MailAddress(email))
            .IsBodyHtml = True
            .Priority = Net.Mail.MailPriority.Normal
End With

tmpCell.Controls.Add(New Literal() With {.Text = "<br/>"})
--------------------------------------------------------------------------
>Enum
Private Enum CheckType As Integer
        isReceive = 0
        isReturn = 1
        isAll = 2
End Enum

Enum.Parse(Type, String)
CType(Enum.Parse(GetType(CheckType), "2"), CheckType)
--------------------------------------------------------------------------
>ParamArray
Protected Sub SetOpenerValue(ByVal ParamArray idValuePaires As IdValuePaire())
        Dim strScript As String = String.Empty
        For Each ivp As IdValuePaire In idValuePaires
            strScript &= " window.opener.document.getElementById('" & Request.QueryString(ivp.Id).ToString() & "').value= '" & ivp.Value & "' ; "
        Next
        strScript &= "self.close();"
        Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "close", strScript, True)
End Sub

Dim ivps(1) As IdValuePaire
If strSelectedValueEng.Length() > 0 Then
    strSelectedValueEng = strSelectedValueEng.Substring(0, strSelectedValueEng.Length - 1)
    ivps(0) = New IdValuePaire()
    ivps(0).Id = "tempEngId"
    ivps(0).Value = strSelectedValueEng
End If
If strSelectedValueCh.Length() > 0 Then
    strSelectedValueCh = strSelectedValueCh.Substring(0, strSelectedValueCh.Length - 1)
    ivps(1) = New IdValuePaire()
    ivps(1).Id = "tempChId"
    ivps(1).Value = strSelectedValueCh
End If
SetOpenerValue(ivps(0), ivps(1))  'or SetOpenerValue(ivps)
--------------------------------------------------------------------------
>Extension Method
Imports System.Runtime.CompilerServices
Module StringExtensions
    <Extension()> _
    Public Function ToShowDateString(ByVal x As String) As String
        Return x.Split(New Char() {" "})(0).Replace("-", "/")
    End Function
End Module
--------------------------------------------------------------------------
>List<T>  Sort()
Dim list As List(Of String) = New List(Of String)
list.Add(strSql)
For Each strSql As String In list
  alSql.Add(strSql)
Next
--------------------------------------------------------------------------
>HashSet 自動替除重複
--------------------------------------------------------------------------
>Queue 先進先出
Enqueue()  Dequeue()
--------------------------------------------------------------------------
>Stack 後進先出
Push()  Pop()
--------------------------------------------------------------------------
>Dictionary<TKey,TValue>
Dim dict As New Dictionary(Of String, Integer)()
dict.Add("one", 1)
dict.Add("two", 2)
dict.Add("three", 3)
dict.Add("four", 4)

For Each pair As KeyValuePair(Of String, Integer) In dict
    MsgBox(pair.Key & "  -  " & pair.Value)
Next

If dict.ContainsKey("four") = True Then
    MessageBox.Show(dict("four").ToString())
End If
--------------------------------------------------------------------------
>DateTime
formatdatetime(now,DateFormat.ShortDate) "2014/1/3" String
datediff(DateInterval.Day,New Date(2013,1,15),New Date(2013,1,8)) -7 Long
math.Round(now.Subtract(New Date(2014,1,6)).TotalDays) -2.0 Double
new DateTime().Now.ToShortDateString "2014/1/3" String

datetime.ParseExact("20141115","yyyyMMdd", nothing, Globalization.DateTimeStyles.AllowWhiteSpaces).ToShortDateString() "2014/11/15" String

Dim xDate As Date
If Not DateTime.TryParseExact(tmpCDate, "yyyyMMdd", Nothing, Globalization.DateTimeStyles.AllowWhiteSpaces, xDate) Then
   ErrMsg = "日期不符合"
End If
--------------------------------------------------------------------------
other:
字串換行 & _
程式換行 _
數字連加 +=
字串連加 &= 

Imports DB = DbComponent.DBComponent
   alias name = Namespace.Class
--------------------------------------------------------------------------
>SqlParameters And SqlTransaction
Dim SQL As String
Dim conn As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("DAAN9FSqlServer_HMCDB").ConnectionString)
Dim sqlTran As SqlTransaction
Dim cmd As New SqlCommand
conn.Open()

sqlTran = conn.BeginTransaction()
cmd.Transaction = sqlTran
cmd.Connection = conn

Try
     SQL = "insert into hc_file_log... "     
     cmd.CommandText = SQL
     cmd.ExecuteNonQuery()

     Dim ParameterFileName As SqlParameter
     Dim ParameterImageData As SqlParameter
     Dim ParameterUpdateTime As SqlParameter
     Dim ParameterUpuser As SqlParameter

     cmd.CommandText = String.Format("update {0} set HC_Report_Nm=@HC_Report_Nm ,HC_Report_Data =@HC_Report_Data , _
     ED_Login_ID=@ED_Login_ID , Ed_Tm=@Ed_Tm where chart_no='{1}' and ex_dt='{2}'", reportTableName, _
     Trim(l_chart_no), Trim(l_ex_dt))
   
     ParameterFileName = New SqlParameter
     ParameterFileName.ParameterName = "@HC_Report_Nm"
     ParameterFileName.Value = new_filenm
     cmd.Parameters.Add(ParameterFileName)

     ParameterImageData = New SqlParameter
     ParameterFileName.ParameterName = "@HC_Report_Data"
     ParameterImageData.Value = ByteBuffer
     cmd.Parameters.Add(ParameterImageData)

     ParameterUpuser = New SqlParameter
     ParameterFileName.ParameterName = "@ED_Login_ID"
     ParameterUpuser.Value = Session("Login_ID")
     cmd.Parameters.Add(ParameterUpuser)

     ParameterUpdateTime = New SqlParameter
     ParameterFileName.ParameterName = "@Ed_Tm"
     ParameterUpdateTime.Value = FormatDateTime(Now,vbShortDate) & " " & FormatDateTime(Now, vbShortTime)
     cmd.Parameters.Add(ParameterUpdateTime)

     cmd.ExecuteNonQuery()

     'Commit()
     sqlTran.Commit()
Catch err As Exception
     'Rollback()
     sqlTran.Rollback()
Finally
     conn.Close()
End Try
--------------------------------------------------------------------------
>Get Image from db
Dim BufferSize As Integer = 10000
Dim OutByte(BufferSize - 1) As Byte
Dim RetVal As Long
Dim StartIndex As Long = 0

Try
  Dim SQL As String
  Dim Reader As IDataReader 'As OleDbDataReader
  Dim ImageIndex As Integer

  SQL = "select * from Chart_Diagram_Record "
  Reader = DB.QueryGetDataReader(SQL)
  If Reader.Read() Then
      Dim i As Integer
     
      For i = 0 To Reader.FieldCount - 1
          If UCase(Trim(Reader.GetName(i))) = "IMAGE" Then
              ImageIndex = i
          End If
      Next i
  End If
  Reader.Close()

  SQL = "select * from Chart_Diagram_Record "
  Reader = DB.QueryGetDataReader(SQL)
  Do While Reader.Read()

      Dim fStream As FileStream = New FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write)
      Dim bWriter As BinaryWriter = New BinaryWriter(fStream)

      StartIndex = 0
      RetVal = Reader.GetBytes(ImageIndex, StartIndex, OutByte, 0, BufferSize) '將Binary讀出

      Do While RetVal = BufferSize
          bWriter.Write(OutByte)
          bWriter.Flush()

          StartIndex = StartIndex + BufferSize
          RetVal = Reader.GetBytes(ImageIndex, StartIndex, OutByte, 0, BufferSize)
      Loop

      bWriter.Write(OutByte)
      bWriter.Flush()


      bWriter.Close()
      fStream.Close()

  Loop
  Reader.Close()
Catch ex As Exception
 
End Try
--------------------------------------------------------------------------


--------------------------------------------------------------------------


--------------------------------------------------------------------------
>Delegate 代理型別

Delegate Function ConvertMethod(ByVal inString As String) As String  '定義一個傳入一個參數的代理型別
Module DelegateExample
   Public Sub Main()
      ' 宣告一個變數,型別為定義的代理型別; 並且指向實際執行的 Function
      Dim convertMeth As ConvertMethod = AddressOf UppercaseString
      Dim name As String = "Dakota"
      ' 使用該變數執行Function
      Console.WriteLine(convertMeth(name))
   End Sub

   Private Function UppercaseString(inputString As String) As String
      Return inputString.ToUpper()
   End Function
End Module


--Func(Of String, String) 傳入參數型別,回傳參數型別
Module GenericFunc
   Public Sub Main()
      ' 不定義代理型別,定義一個變數直接指向 實際執行的 Function
      Dim convertMethod As Func(Of String, String) = AddressOf UppercaseString
      Dim name As String = "Dakota"
      ' 使用該變數執行Function
      Console.WriteLine(convertMethod(name))
   End Sub

   Private Function UppercaseString(inputString As String) As String
      Return inputString.ToUpper()
   End Function
End Module


Module LambdaExpression
   Public Sub Main()
      ' 不定義代理型別,不定義實際執行的 Function;定義一個變數且直接定義要執行的程式
      Dim convert As Func(Of String, String) = Function(s) s.ToUpper()
      Dim name As String = "Dakota"
      Console.WriteLine(convert(name)) 
   End Sub
End Module
--------------------------------------------------------------------------
>Recursive 在父控制項中,找出指定id的子控制項
Public Function FindControlRecursively(ByVal parentControl As System.Web.UI.Control, ByVal controlId As String) As System.Web.UI.Control

        If String.IsNullOrEmpty(controlId) = True OrElse controlId = String.Empty Then
            Return Nothing
        End If

        If parentControl.ID = controlId Then
            Return parentControl
        End If

        If parentControl.HasControls Then
            For Each c As System.Web.UI.Control In parentControl.Controls
                Dim child As System.Web.UI.Control = FindControlRecursively(c, controlId)
                If child IsNot Nothing Then
                    Return child
                End If
            Next
        End If

        Return Nothing

End Function
--------------------------------------------------------------------------
>Lamdba

>Function(num, index)
Public Sub DataSetLinq12()
    Dim numbers As IEnumerable(Of DataRow) = TestDS.Tables("Numbers").AsEnumerable()
    Dim numsInPlace = numbers.Select( _
                        Function(num, index) New With {.Num = num("number"), _
                                                       .InPlace = (num("number") = index)})

    Console.WriteLine("Number: In-place?")
    For Each n In numsInPlace
        Console.WriteLine("{0}: {1}", n.Num, n.InPlace)
    Next
End Sub

Dim nameList =
 myFacade.GetData().
 Where( Function(x) x.ID = 42 ).
 Select( Function(x) x.Name ).
 ToList()

Dim nameList =
 myFacade.GetData().
 Where( Function(x As MyClass) x.ID = 42 ).
 Select( Function(x As MyClass) x.Name ).
 ToList()
--------------------------------------------------------------------------
>Linq

>Select New With
Public Sub DataSetLinq9()
    Dim words = TestDS.Tables("Words").AsEnumerable()
    Dim upperLowerWords = From w In words _
        Select New With {.Upper = CStr(w("word")).ToUpper(), .Lower = CStr(w("word")).ToLower()}

    For Each ul In upperLowerWords
        Console.WriteLine("Uppercase: " & ul.Upper & ", Lowercase: " & ul.Lower)
    Next
End Sub
--------------------------------------------------------------------------
>o.Field(Of Decimal)("Total")  inner join
Public Sub DataSetLinq17()
    Dim customers = TestDS.Tables("Customers").AsEnumerable()
    Dim orders = TestDS.Tables("Orders").AsEnumerable()

    Dim myOrders = From c In customers, o In orders _
                   Let Total = o.Field(Of Decimal)("Total") _
                   Where c.Field(Of String)("CustomerID") = o.Field(Of String)("CustomerID") AndAlso Total >= 2000.0# _
                   Select CustomerID = c.Field(Of String)("CustomerID"), OrderID = o.Field(Of Integer)("OrderID"), Total

    ObjectDumper.Write(myOrders)
End Sub
--------------------------------------------------------------------------
> left join
Dim query = From A In ds.Tables("dtShelfs").AsEnumerable _
Join B In ds.Tables("dtBooks").AsEnumerable On _
A.Field(Of Integer)("shelfID") Equals B.Field(Of Integer)("shelfUsed") _
Select New With { _
ShelfID = A.Field(Of Integer)("shelfID"), _
ShelfLocation = A.Field(Of String)("shelfLocation"), _
ShelfClassification = A.Field(Of String)("shelfClassification"), _
BookName = B.Field(Of String)("bookName")}
--------------------------------------------------------------------------
>left outer join    DefaultIfEmpty()
Public Sub Linq105()
    Dim categories() = {"Beverages", "Condiments", "Vegetables", "Dairy Products", "Seafood"}
    Dim productList = GetProductList()
    Dim query = From c In categories _
                Group Join p In productList On c Equals p.Category Into Group _
                From p In Group.DefaultIfEmpty() _
                Select Category = c, ProductName = If(p Is Nothing, "(No products)", p.ProductName)

    For Each v In query
        Console.WriteLine(v.ProductName + ": " + v.Category)
    Next
End Sub
--------------------------------------------------------------------------
>group by
Public Sub GroupBySample()
  Dim customers = GetCustomerList()
  Dim customersByCountry = From cust In customers
                           Order By cust.City   -- 分組前排序
                           Group By CountryName = cust.Country Into RegionalCustomers = Group, Count()
                           Order By CountryName   --分組後排序

  For Each country In customersByCountry    --所有群組
    Console.WriteLine(country.CountryName &
                      " (" & country.Count & ")" & vbCrLf)

    For Each customer In country.RegionalCustomers    --每一個別群組
      Console.WriteLine(vbTab & customer.CompanyName &
                        " (" & customer.City & ")")
    Next
  Next
End Sub


-- group x by x.yyy into g  (g 為分組後的集合)
Dim query = from p in subjectresults where id= 12
group p by p.subjectId  into myGroup
select new _
SubjectId = myGroup.Key , _
Total = myGroup.Count() )


-- group by z = x.yyy into g = Group  (z 為分組後的集合,Group為關鍵字)
Dim query1 = From queryItem In dc1.SubjectResults Where queryItem.ID = 12
 Group By SubjectId = queryItem.SubjectId Into SIds = Group
 Select _
 SubId = SubjectId, _
 Total = SubjectId.Count()
--------------------------------------------------------------------------