2016年9月9日 星期五

[Oracle][PL/SQL]動態執行Cursor-Dynamic Cursor

說明:在寫PL/SQL時,遇到需要在Function或Stored Procedure中,動態宣告Cursor以及取得Cursor欄位及值。
文中我們使用Function來做範例:
image
1.定義一個Function,F_Dynamic_Cursor_Demo
CREATE OR REPLACE PROCEDURE F_DYNAMIC_CURSOR_DEMO AS 

    --宣告Type

    TYPE TYPE_CUR IS RECORD ( 

      V_SQL VARCHAR(1000),

      V_CUR NUMBER,

      V_DTBL DBMS_SQL.DESC_TAB,

      V_CNT NUMBER,

      V_STATUS NUMBER,

      V_VAL VARCHAR2(200)); 

    

    REC_CUR TYPE_CUR;

BEGIN

    --查詢SQL語法

    REC_CUR.V_SQL:='SELECT ''GOOGLE'' AS NAME,18 AS AGE FROM DUAL';

    --動態設定CURSOR';

    REC_CUR.V_CUR:= DBMS_SQL.OPEN_CURSOR;

    DBMS_SQL.PARSE(REC_CUR.V_CUR,REC_CUR.V_SQL,DBMS_SQL.NATIVE);

    DBMS_SQL.DESCRIBE_COLUMNS(REC_CUR.V_CUR,REC_CUR.V_CNT,REC_CUR.V_DTBL);

    --動態定義CURSOR欄位;

    FOR I IN 1..REC_CUR.V_CNT LOOP

      --定義欄位及值還有Size

      DBMS_SQL.DEFINE_COLUMN(REC_CUR.V_CUR,I,REC_CUR.V_VAL,200);

    END LOOP;

    --動態執行CURSOR;

    REC_CUR.V_STATUS := DBMS_SQL.EXECUTE(REC_CUR.V_CUR);

    --動態取得CURSOR資料,巡覽每一筆資料

    WHILE ( DBMS_SQL.FETCH_ROWS(REC_CUR.V_CUR) > 0 ) LOOP

        --動態取得CURSOR欄位名稱及值

        FOR I IN 1..REC_CUR.V_CNT LOOP             

                  DBMS_SQL.COLUMN_VALUE(REC_CUR.V_CUR,I,REC_CUR.V_VAL);

                  DBMS_OUTPUT.PUT_LINE(REC_CUR.V_DTBL(I).COL_NAME||' --> '||REC_CUR.V_VAL);

        END LOOP;    

     END LOOP;

     DBMS_SQL.CLOSE_CURSOR(REC_CUR.V_CUR);       

END F_DYNAMIC_CURSOR_DEMO;

2.執行F_Dynamic_Cursor_Demo
begin

  F_DYNAMIC_CURSOR_DEMO;

end;

3.結果
NAME --> GOOGLE
AGE –> 18


2014年4月30日 星期三

[VB.NET][XML]使用XPATH查詢含有前置詞的XML

使用.NET的XmlDocument類別要處理XML檔非常方便,但是遇到有XmlNamespace的XML要怎麼處理?
一般會有常見的像是Soap描述檔,節點前面都有前置詞,例如:xsd:節點名稱
Test.xml
 
 

  
    
      
        A
        
          
            A1
            A2
          
        
      
      
        B
        
          B1
          B2
          B3
        
      
    
  

VB.NET
    Sub Main()
        Dim oXml As New XmlDocument
        Dim nsmgr As XmlNamespaceManager = New XmlNamespaceManager(oXml.NameTable)
        oXml.Load("Test.xml")
        '這裡要對應XML內容的真正使用的Namespace如:xmlns:xsd="http://www.w3.org/2001/XMLSchema"
        nsmgr.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema")
        '回傳單一節點
        Console.WriteLine(oXml.SelectSingleNode("//xsd:anyType[1]", nsmgr).InnerText)
        '回傳多個節點
        For Each Note As XmlNode In oXml.SelectNodes("//xsd:anyType", nsmgr)
            Console.WriteLine(Note.InnerText)
        Next
        Console.ReadKey()
    End Sub

2014年1月25日 星期六

[VB.NET]Console程式,接收外部傳入的參數雙引號消失問題

1.狀況:A程式呼叫外部Console程式,並傳入JOSN格式給Console程式,如果此時JSON格式中有雙引號("),

Console程式接受後雙引號會消失,因此造成JOSN無法反序列化。

解決方式:再傳入參數時,先將雙引號前加入反斜線\,用來脫逸雙引號。

例如:"你好嗎?" –>\"你好嗎?\"

[VB.NET][JSON]將物件序列化成Json格式

1.在專案中加入參考System.Runtime.Serialization命名空間

2.在類別中加入Imports System.Runtime.Serialization.Json

 
'''
''' 物件序列化成Json格式
'''

''' 物件型別
''' 物件
''' Json格式
Public Shared Function JsonSerialize(Of T)(ByVal o As T) As String
Return JsonSerialize(Of T)(o, Encoding.Default)
End Function
'''
''' 物件序列化成Json格式
'''

''' 物件型別
''' 物件
''' 編碼
''' Json格式
Public Shared Function JsonSerialize(Of T)(ByVal o As T, ByVal encoding As Encoding) As String
Using ms As New MemoryStream
Dim json As New DataContractJsonSerializer(GetType(T))
json.WriteObject(ms, o)
Using sr As New StreamReader(ms, encoding)
ms.Position = 0
Return sr.ReadToEnd()
End Using
End Using
End Function
'''
''' Json格式反序列化成物件
'''

''' 物件型別
''' Json格式
''' 物件
Public Shared Function JsonDeserialize(Of T)(ByVal s As String) As T
Return JsonDeserialize(Of T)(s, Encoding.Default)
End Function
'''
''' Json格式反序列化成物件
'''

''' 物件型別
''' Json格式
''' 編碼
''' 物件
Public Shared Function JsonDeserialize(Of T)(ByVal s As String, ByVal encoding As Encoding) As T
Using ms As New MemoryStream(encoding.GetBytes(s))
Dim json As New DataContractJsonSerializer(GetType(T))
ms.Position = 0
Return json.ReadObject(ms)
End Using
End Function

2014年1月23日 星期四

[VB.NET][MVC]DataTable物件顯示於View

Controller
 
         Function Index() As ActionResult
            Dim dt As New DataTable
            dt.Columns.Add("Name")
            dt.Columns.Add("Age")
            Dim dr As DataRow
            dr = dt.NewRow()
            dr("Name") = "Aaron"
            dr("Age") = 19
            dt.Rows.Add(dr)
            dr = dt.NewRow()
            dr("Name") = "Justin"
            dr("Age") = 19
            dt.Rows.Add(dr)
            Return View(dt)
        End Function
View
 

@Code
    ViewData("Title") = "MyTest"
    Layout = "~/Views/Shared/_Layout.vbhtml"
    Dim dt As Data.DataTable = Model
End Code
<table>
    <tr>
        @For Each row As System.Data.DataRow In dt.Rows
            @<td>
                <th>@row(0)</th>
            </td>
        Next
    </tr>
</table>

2013年11月27日 星期三

[VB.NET]Get IP Address取得本機IP

一,使用電腦名稱取得本機IP
 
    ''' 
    ''' 取得本機IPAddress
    ''' 
    ''' IPAddress
    Public Shared Function GetIPaddress() As String
        Dim myHost As String = System.Net.Dns.GetHostName
        Dim myIPs As System.Net.IPHostEntry = System.Net.Dns.GetHostEntry(myHost)
        For Each ipAddress As System.Net.IPAddress In myIPs.AddressList
            Return ipAddress.ToString()
        Next
        Return String.Empty
    End Function 

二,取得本機所有網卡IPAddress
 
    Private Function GetIPaddress() As List(Of String)
        Dim IpAddressList As New List(Of String)
        Try
            '取得本機上ipv4及非Loopback的IP Address
            For Each nic As System.Net.NetworkInformation.NetworkInterface In System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()
                For Each ipInfo As System.Net.NetworkInformation.IPAddressInformation
                     In nic.GetIPProperties().UnicastAddresses
                    If System.Net.IPAddress.IsLoopback(ipInfo.Address) = False _
                        AndAlso ipInfo.Address.AddressFamily <> Net.Sockets.AddressFamily.InterNetworkV6 Then
                        '取得IP Address
                        IpAddressList.Add(ipInfo.Address.ToString())
                    End If
                Next
            Next
            Return IpAddressList 
        Finally
            IpAddressList = Nothing
        End Try
    End Function

2013年9月13日 星期五

[VB.NET]Oracle Client連線發生錯誤,當與具有 32 位元的 Oracle 用戶端元件執行 64 位元模式安裝時,會出現此問題。

開發工具:VS2010

DB Driver:Oracle Client 11gR2 64bit

OS:Win7 64bit .NET Framework 4.0 

使用Oracle Provider發生:System.InvalidOperationException 嘗試載入 Oracle 用戶端程式庫時傳出 BadImageFormatException。當與具有 32 位元的 Oracle 用戶端元件執行 64 位元模式安裝時,會出現此問題。 

在網路上許多文章是說只要將VS的組態設定成X86即可。但是此方法對我的狀況沒有改善 

解決方法:
 1.將Oracle Client移除
 2.OS重新開機
 3.重裝Oracle Client 64bit(依OS的版本)
 4.解決

2013年5月22日 星期三

[系統]製作USB開機碟+NoName XPE

一,需事先準備下面幾項工具
1.HP USB Disk Storage Format Tool (製作開機區)。
2.Grub4dos Installer (設定開機檔)。
3.grldr 及 grub.exe 二個檔案 (Grub4Dos內的二個檔案) (下載)。
4.NoName XPE (自製XP精簡版 ISO檔)。
5.準備一支USB 2.0/3.0 1G 以上的隨身碟。
二,開始製作
注意:USB隨身碟在第一步驟時會作格式化,所以裡面原本有檔案的話會被清除。
1.先將USB插入。
2.執行HP USB Disk Storage Format Tool 程式。
3.選擇USB裝置,快速格式,建立一個DOS開機作業磁碟,DOS系統檔案位置。
4.開始(Start)。
1
5.執行Grub4dos Installer 工具設定MBR。
6.Disk<-選擇你USB裝置(如果抓不到請用管理員權限來執行此程式)。
7.Options<-勾選No backup MBR ,Don’t search floppy ,Disable PrevMBR。
8.Install。
2
9.將下載回來的XPE ISO解壓縮,或者用酒精先掛載起來。
10.將XPE ISO內的檔案複製到USB隨身碟:
  • A.複製整個XPE ISO內的檔案到USB隨身碟。
  • B.將RXPE資料夾內的RXPE.COM及SETUPLDR.BIN檔案複製到USB隨身碟根目錄下。
  • C.將USB隨身碟下的SETUPLDR.BIN檔案更名為NTLDR。
11.USB隨身碟根目錄下會有這些資料夾及檔案。
3
12.恭喜你完成了,快找台電腦來測試吧!

2013年5月20日 星期一

[VB.NET]跨執行緒作業無效-跨執行續操作UI

一,依WindowsForm來說,介面上有二個Button,有一支執行續需要設定這二個Button的Enabled。

如果直接設定會出現跨執行緒作業無效的錯誤訊息。

所以我們可以使用委派來處理跨執行續的問題。

 
Private Delegate Sub MyButtonCallBack(ByVal StartValue As Boolean, ByVal StopValue As Boolean)

Private Sub SetButtonEnabled(ByVal StartValue As Boolean, ByVal StopValue As Boolean)
'判斷是否由執行緒以外的執行緒呼叫,若不是則直接設定Button
If Me.InvokeRequired Then
'實作委派方法
Dim MyButton As New MyButtonCallBack(AddressOf SetButtonEnabled)
'執行委派
Me.Invoke(MyButton, StartValue, StopValue)
Else
Me.btnStart.Enabled = StartValue
Me.btnStop.Enabled = StopValue
End If
End Sub

2013年5月14日 星期二

[VB.NET]Custom Contol自訂控制項事件

一,客製一個控制項是繼承Button,增加一個按下滑鼠右鍵Click事件,事件名稱:RightClick


自訂控制項

 
Public Class SuperButton
    Inherits Button

    Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
        MyBase.OnPaint(e)

        '請在此處加入您自訂的繪製程式碼
    End Sub
    '自訂一個新的事件RightClick
    Dim _handlers As New List(Of EventHandler)

    Public Custom Event RightClick As EventHandler
        AddHandler(value As EventHandler)
            _handlers.Add(value)
        End AddHandler

        RemoveHandler(value As EventHandler)
            If _handlers.Contains(value) Then
                _handlers.Remove(value)
            End If
        End RemoveHandler

        RaiseEvent(sender As Object, e As System.EventArgs)
            For Each handler As EventHandler In _handlers
                Try
                    handler.Invoke(sender, e)
                Catch ex As Exception
                    Debug.WriteLine(ex.ToString())
                End Try
            Next
        End RaiseEvent
    End Event
    '監聽滑鼠事件
    Protected Overrides Sub OnMouseDown(mevent As System.Windows.Forms.MouseEventArgs)
        MyBase.OnMouseDown(mevent)
        '當滑鼠被按下右鍵時則回應自訂事件
        If mevent.Button = Windows.Forms.MouseButtons.Right Then
            RaiseEvent RightClick(Me, mevent)
        End If
    End Sub

End Class

[Web Service]Console Mode 基礎連接已關閉: 無法為SSL/TLS 安全通道 忽略認證

 
Imports System.Net
Imports System.Net.Security
Imports System.Security.Cryptography.X509Certificates

Module Module1

Sub Main()
Dim oWebCilent As New TEST.ReceiveClient
Dim oResponse As TEST.ServiceResponse
'委派認證回呼
ServicePointManager.ServerCertificateValidationCallback = New RemoteCertificateValidationCallback(AddressOf ValidateServerCertificate)
Try
'........
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub
'忽略認證直接回傳True
Public Function ValidateServerCertificate(ByVal sender As [Object], ByVal certificate As X509Certificate, ByVal chain As X509Chain, ByVal sslPolicyErrors As SslPolicyErrors) As Boolean
Return True
End Function
End Module

2013年4月16日 星期二

[VB.NET]使用System.Configuration命名空間處理自訂的應用程式組態檔Config

在WinForm組態檔來說,較常使用的app.config,當專案建置後app.config會被編譯成(xxxx.exe.config)。

但是這樣只有此專案能使用這個app.config而已,如果當有多個專案要共用的話,其他專案也都加入此app.config,才能讀取得到。

當然有很多種方法可以解決這個問題,這裡只提供其中一種方法當作範例。

1.先在專案中加入一個自訂的應用程式組態檔 Sample.config
 


  
    
  
2.加入參考System.Configuration命名空間

3.讀取Sample.config
Imports System.Configuration

Module Module1
    Sub Main()
        Dim configFileMap As ExeConfigurationFileMap
        Dim config As Configuration
        Dim configKeyValue As KeyValueConfigurationElement
        Try
            configFileMap = New ExeConfigurationFileMap
            configFileMap.ExeConfigFilename = "Sample.config"
            config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None)
            configKeyValue = config.AppSettings.Settings("Test")
            If configKeyValue Is Nothing Then
                Console.WriteLine("指定Key錯誤。")
            End If
            Console.WriteLine("Test=" + configKeyValue.Value)
            Console.ReadKey()
        Catch ex As Exception
            Console.WriteLine(ex.Message)
            Console.ReadKey()
        Finally
            configFileMap = Nothing
            config = Nothing
            configKeyValue = Nothing
        End Try
    End Sub
End Module

2012年8月1日 星期三

[VB.NET]程式中使用SQL字串IN參數化設定

 

一,寫程式時在使用SQL字串時,WHERE條件的參數,我們需要參數化,以防止SQL Injection發生,

ADO.Net 有提供相關參數化設定,但是當我們遇到使用IN子句時,要如何使用參數化?

 
Dim parameString As String = "123,456,789"
Dim parameArray() As String
Dim temp As String
comm.CommandText = "SELECT * FROM TEST WHERE ID IN (@ID)"


parameArray = parameString.Split(",")


For i = 0 To parameArray.Length - 1
temp &= String.Format("@ID{0},", i)
Next
comm.CommandText = comm.CommandText.Replace("@ID", temp.Substring(0, temp.Length - 1))
For j = 0 To parameArray.Length - 1
comm.Parameters.Add(String.Format("@ID{0}", j), SqlDbType.VarChar).Value = parameArray(j)
Next
comm.ExecuteReader()

2012年5月30日 星期三

[AOP]Crosscutting Concerns實作

Crosscutting Concerns 使用System.Runtime.Remoting.Proxies.RealProxy類別來實作

一,說明Hello這類別就是用來繼承MarshalByRefObject類別,在AOP中表示Pointcut。
Hello.vb
 
Public Class Hello
    Inherits MarshalByRefObject
End Class

二,說明IHello這類別就是定義一個Interface,在AOP中表示Weave。
IHello.vb
 
Public Interface IHello
    Sub hello(ByVal name As String)
End Interface

三,說明LogHandler這類別就是用來做動態Proxy Pattern,繼承RealProxy類別,在AOP中表示Advices。
LogHandler.vb
 
Imports System.Runtime.Remoting.Proxies
Imports System.Runtime.Remoting.Messaging
Imports System.Runtime.Remoting
Imports System.Runtime.Remoting.Services

Public Class LogHandler
    Inherits RealProxy

    Private myMarshalByRefObject As MarshalByRefObject

    Public Sub New(ByVal myType As Type)
        MyBase.New(myType)
        myMarshalByRefObject = CType(Activator.CreateInstance(myType), MarshalByRefObject)
    End Sub

    Public Overrides Function Invoke(ByVal myIMessage As IMessage) As IMessage
        Dim calls As IMethodCallMessage = myIMessage
        Dim back As IMethodReturnMessage = Nothing

        Console.WriteLine("呼叫方法的名稱:" + calls.MethodName)

        back = RemotingServices.ExecuteMessage(myMarshalByRefObject, calls)

        Console.WriteLine("顯示的結果:" + back.ReturnValue.ToString())

        Return back
    End Function
End Class

四,說明HelloSpeaker這類別就是用來這類別就是用來繼承Hello類別並實作IHello介面,在AOP中表示Joinpoint。
HelloSpeaker.vb
 
Public Class HelloSpeaker
    Inherits Hello
    Implements IHello

    Public Sub hello(name As String) Implements IHello.hello
        Console.WriteLine("Hello:" + name)
    End Sub

End Class

五,執行
ProxyDemo.vb
 
Module ProxyDemo
    Sub Main()
        Dim proxy As LogHandler = New LogHandler(New HelloSpeaker().GetType())
        Dim Hello As IHello = proxy.GetTransparentProxy()
        Hello.hello("123")
        Console.ReadKey()
    End Sub
End Module

SyntaxHighlighter Manual

 
 您的程式碼請貼此處。 
SyntaxHighlighter/manual/brushes/
Brush nameBrush aliasesFile name
ActionScript3as3, actionscript3shBrushAS3.js
Bash/shellbash, shellshBrushBash.js
ColdFusioncf, coldfusionshBrushColdFusion.js
C#c-sharp, csharpshBrushCSharp.js
C++cpp, cshBrushCpp.js
CSScssshBrushCss.js
Delphidelphi, pas, pascalshBrushDelphi.js
Diffdiff, patchshBrushDiff.js
Erlangerl, erlangshBrushErlang.js
GroovygroovyshBrushGroovy.js
JavaScriptjs, jscript, javascriptshBrushJScript.js
JavajavashBrushJava.js
JavaFXjfx, javafxshBrushJavaFX.js
Perlperl, plshBrushPerl.js
PHPphpshBrushPhp.js
Plain Textplain, textshBrushPlain.js
PowerShellps, powershellshBrushPowerShell.js
Pythonpy, pythonshBrushPython.js
Rubyrails, ror, rubyshBrushRuby.js
ScalascalashBrushScala.js
SQLsqlshBrushSql.js
Visual Basicvb, vbnetshBrushVb.js
XMLxml, xhtml, xslt, html, xhtmlshBrushXml.js