Archive for the ‘.NET’ Category

  1. Hello, COM(VB.NET) World!

    Posted on 5月 18th, 2012 by cx20

    COM(VB.NET)

    COM(Component Object Model)はマイクロソフトの提唱するプログラム部品の仕様である。
    COM を用いて開発された部品であれば言語を問わず利用することができる。
    以下は VB.NET による COM クライアント(事前バインディングならびに実行時バインディング)の例となっている。

    ソースコード(事前バインディング)

    Imports System
    Imports System.Runtime.InteropServices
    Imports Shell32
     
    Module Hello
        Sub Main()
            Dim shell As New Shell
            Dim folder As Folder
            Dim vRootFolder As Object = ShellSpecialFolderConstants.ssfWINDOWS
            folder = shell.BrowseForFolder(0, "Hello, COM(VB.NET) World!", 0, vRootFolder)
            If Not folder Is Nothing Then
                Marshal.ReleaseComObject(folder)
            End If
            Marshal.ReleaseComObject(shell)
        End Sub
    End Module

    コンパイル方法(事前バインディング)

    C:¥> SET PATH=C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin;%PATH%
    C:¥> tlbimp %SystemRoot%\system32\shell32.dll /out:Shell32.dll
    C:¥> vbc /r:Shell32.dll Hello.vb

    ソースコード(実行時バインディング)

    Imports System
    Imports System.Runtime.InteropServices
     
    Module Hello
        Sub Main()
            Dim shell As Object
            Dim folder As Object
            shell = CreateObject("Shell.Application")
            folder = shell.BrowseForFolder(0, "Hello, COM(VB.NET) World!", 0, 36)
            If Not folder Is Nothing Then
                Marshal.ReleaseComObject(folder)
            End If
            Marshal.ReleaseComObject(shell)
        End Sub
    End Module

    コンパイル方法(実行時バインディング)

    C:¥> vbc Hello.vb

    実行結果

    +----------------------------------------+
    |Browse For Folder                    [X]|
    +----------------------------------------+
    | Hello, COM(VB.NET) Wolrd!              |
    |                                        |
    | +------------------------------------+ |
    | |[Windows]                           | |
    | | +[addins]                          | |
    | | +[AppCompat]                       | |
    | | +[AppPatch]                        | |
    | | +[assembly]                        | |
    | |     :                              | |
    | |     :                              | |
    | |     :                              | |
    | +------------------------------------+ |
    | [Make New Folder]    [  OK  ] [Cancel] |
    +----------------------------------------+
  2. Hello, COM(C#) World!

    Posted on 5月 17th, 2012 by cx20

    COM(C#)

    COM(Component Object Model)はマイクロソフトの提唱するプログラム部品の仕様である。
    COM を用いて開発された部品であれば言語を問わず利用することができる。
    以下は C# による COM クライアント(事前バインディングならびに実行時バインディング)の例となっている。

    ソースコード(事前バインディング)

    using System;
    using System.Runtime.InteropServices;
    using Shell32;
     
    class Hello
    {
        static void Main(String[] args)
        {
            Shell shell = new Shell();
            Object vRootFolder = (long)ShellSpecialFolderConstants.ssfWINDOWS;
            Folder folder = shell.BrowseForFolder(0, "Hello, COM(C#) World!", 0, vRootFolder);
            if (folder != null)
            {
                Marshal.ReleaseComObject(folder);
            }
            Marshal.ReleaseComObject(shell);
        }
    }

    コンパイル方法(事前バインディング)

    C:¥> SET PATH=C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin;%PATH%
    C:¥> tlbimp %SystemRoot%\system32\shell32.dll /out:Shell32.dll
    C:¥> csc /r:Shell32.dll Hello.cs

    ソースコード(実行時バインディング)

    using System;
    using System.Reflection;
    using System.Runtime.InteropServices;
     
    class Hello
    {
        static void Main(String[] args)
        {
            Type objType = Type.GetTypeFromProgID("Shell.Application"); 
            Object shell = Activator.CreateInstance(objType);
            Object[] param = { 0, "Hello, COM(C#) World!", 0, 36 };
            Object folder = shell.GetType().InvokeMember( 
                "BrowseForFolder", BindingFlags.InvokeMethod, null, shell, param );
            if (folder != null)
            {
                Marshal.ReleaseComObject(folder);
            }
            Marshal.ReleaseComObject(shell);
        }
    }

    コンパイル方法(実行時バインディング)

    C:¥> csc Hello.cs

    実行結果

    +----------------------------------------+
    |Browse For Folder                    [X]|
    +----------------------------------------+
    | Hello, COM(C#) Wolrd!                  |
    |                                        |
    | +------------------------------------+ |
    | |[Windows]                           | |
    | | +[addins]                          | |
    | | +[AppCompat]                       | |
    | | +[AppPatch]                        | |
    | | +[assembly]                        | |
    | |     :                              | |
    | |     :                              | |
    | |     :                              | |
    | +------------------------------------+ |
    | [Make New Folder]    [  OK  ] [Cancel] |
    +----------------------------------------+
  3. Hello, Win32 API(MSIL) World!

    Posted on 4月 26th, 2012 by cx20

    Win32 API(MSIL)

    Win32 API は、Windows の機能にアクセスする為の API(Application Programming Interface)である。
    以下は MSIL による呼出し例である。

    ソースコード

    //  Microsoft (R) .NET Framework IL Disassembler.  Version 4.0.30319.1
    //  Copyright (c) Microsoft Corporation. All rights reserved.
     
    // Metadata version: v2.0.50727
    .module extern user32.dll
    .assembly extern mscorlib
    {
      .publickeytoken = (B7 7A 5C 56 19 34 E0 89 )                         // .zV.4..
      .ver 2:0:0:0
    }
    .assembly Hello
    {
      .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilationRelaxationsAttribute::.ctor(int32) = ( 01 00 08 00 00 00 00 00 ) 
      .custom instance void [mscorlib]System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::.ctor() = ( 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78   // ....T..WrapNonEx
                                                                                                                 63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 )       // ceptionThrows.
      .hash algorithm 0x00008004
      .ver 0:0:0:0
    }
    .module Hello.exe
    // MVID: {412A0088-7664-4361-B59D-98DD5760B045}
    .imagebase 0x00400000
    .file alignment 0x00000200
    .stackreserve 0x00100000
    .subsystem 0x0003       // WINDOWS_CUI
    .corflags 0x00000001    //  ILONLY
    // Image base: 0x00360000
     
    // =============== CLASS MEMBERS DECLARATION ===================
    .class private auto ansi beforefieldinit Hello
           extends [mscorlib]System.Object
    {
      .method private hidebysig static pinvokeimpl("user32.dll" winapi) 
              uint32  MessageBox(uint32 hWnd,
                                 string lpText,
                                 string lpTitle,
                                 uint32 uType) cil managed preservesig
      {
      }
      .method private hidebysig static void  Main(string[] args) cil managed
      {
        .entrypoint
        // コード サイズ       20 (0x14)
        .maxstack  8
        IL_0000:  nop
        IL_0001:  ldc.i4.0
        IL_0002:  ldstr      "Hello, Windows API(MSIL) World!"
        IL_0007:  ldstr      "Hello, World!"
        IL_000c:  ldc.i4.0
        IL_000d:  call       uint32 Hello::MessageBox(uint32,
                                                      string,
                                                      string,
                                                      uint32)
        IL_0012:  pop
        IL_0013:  ret
      } // end of method Hello::Main
     
      .method public hidebysig specialname rtspecialname 
              instance void  .ctor() cil managed
      {
        // コード サイズ       7 (0x7)
        .maxstack  8
        IL_0000:  ldarg.0
        IL_0001:  call       instance void [mscorlib]System.Object::.ctor()
        IL_0006:  ret
      } // end of method Hello::.ctor
     
    } // end of class Hello

    上記のコードは、以下の C# のプログラムを ildasm.exe で逆アセンブルしたものである。

    ソースコード

    using System.Runtime.InteropServices;
     
    class Hello
    {
         [DllImport("user32.dll")]
         private extern static uint MessageBox(uint hWnd, string lpText, string lpTitle, uint uType);
         static void Main(string[] args)
        {
            MessageBox( 0, "Hello, Win32 API(MSIL) World!", "Hello, World!", 0 );
        }
    }

    コンパイル方法

    C:¥> ilasm Hello.il

    実行結果

    ---------------------------
    Hello, World!
    ---------------------------
    Hello, Win32 API(MSIL) World!
    ---------------------------
    OK   
    ---------------------------
  4. Hello, Win32 API(F#) World!

    Posted on 4月 25th, 2012 by cx20

    Win32 API(F#)

    Win32 API は、Windows の機能にアクセスする為の API(Application Programming Interface)である。
    以下は F# にて DllImport 属性を用いた呼出し例である。

    ソースコード

    open System
    open System.Runtime.InteropServices
     
    [<DllImport("user32.dll")>]
    extern int MessageBox( UInt32 hWnd, String lpText, String lpCaption, UInt32 uType)
     
    let x = MessageBox( 0u, "Hello, Win32 API(F#) World!", "Hello, World!", 0u )

    コンパイル方法

    C:¥> fsc Hello.fs

    実行結果

    ---------------------------
    Hello, World!
    ---------------------------
    Hello, Win32 API(F#) World!
    ---------------------------
    OK   
    ---------------------------
  5. Hello, Win32 API(VB.NET) World!

    Posted on 4月 24th, 2012 by cx20

    Win32 API(VB.NET)

    Win32 API は、Windows の機能にアクセスする為の API(Application Programming Interface)である。
    以下は VB.NET にて Declare ステートメントを用いた呼出し例である。

    ソースコード

    Imports System
    Imports System.Runtime.InteropServices
     
    Module Hello
        Declare Auto Function MessageBox Lib "user32.dll" Alias "MessageBox" ( _
            ByVal hWnd As IntPtr, _
            ByVal lpText As String, _
            ByVal lpCaption As String, _
            ByVal nType As UInteger _
        ) As Integer
     
        Sub Main()
            MessageBox( New IntPtr(0), "Hello, Win32 API(VB.NET) World!", "Hello, World!", 0 )
        End Sub
    End Module

    「文字セット」に「Auto」を指定した場合は「エイリアス名」「プラットフォーム」に応じて、呼び出される API 関数名が自動判別される。
    「文字セット」に「Ansi」もしくは「Unicode」を指定した場合は「エイリアス名」が API 関数名として使用される為、”A” / “W” のどちらのバージョンであるか明示的に指定する必要がある。(指定を行わない場合、関数名が見つからずエラーとなる)

    文字セット指定 エイリアス名 プラットフォーム 文字変換 判別 API関数名
    Auto MessageBox Windows 9x系 ANSI “A” MessageBoxA
    Auto MessageBox Windows NT系 Unicode “W” MessageBoxW
    Ansi または 省略 MessageBox ANSI Not Found
    Ansi または 省略 MessageBoxA ANSI MessageBoxA
    Unicode MessageBox Unicode Not Found
    Unicode MessageBoxW Unicode MessageBoxW

    また、Win32 データ型と VB.NET データ型の対応は主に以下のようになっている。「(2.0)」は、.NET Framework 2.0 で追加された型を示す。文字関連の型に関しては文字セット指定が必要なことに注意。

    Win32 データ型 C/C++ データ型 .NET データ型 VB.NET データ型
    HANDLE void * IntPtr
    BYTE unsigned char Byte Byte
    SHORT short Int16 Short
    WORD unsigned short UInt16 UShort (2.0)
    INT int Int32 Integer
    UINT unsigned int UInt32 UInteger (2.0)
    LONG long Int32 Integer
    BOOL int Int32 Integer
    DWORD unsigned long UInt32 UInteger (2.0)
    ULONG unsigned long UInt32 UInteger (2.0)
    CHAR char Char (Ansi) Char (Ansi)
    WCHAR wchar_t Char (Unicode) Char (Unicode)
    LPSTR char * StringBuilder (Ansi)
    LPCSTR const char * String (Ansi) String (Ansi)
    LPWSTR wchar_t * StringBuilder (Unicode)
    LPCWSTR const wchar_t * String (Unicode) String (Unicode)
    FLOAT float Single Single
    DOUBLE double Double Double

    コンパイル方法

    C:¥> vbc Hello.vb

    実行結果

    ---------------------------
    Hello, World!
    ---------------------------
    Hello, Win32 API(VB.NET) World!
    ---------------------------
    OK   
    ---------------------------
  6. Hello, Win32 API(C#) World!

    Posted on 4月 23rd, 2012 by cx20

    Win32 API(C#)

    Win32 API は、Windows の機能にアクセスする為の API(Application Programming Interface)である。
    以下は C# にて DllImport 属性を用いた呼出し例である。

    ソースコード

    using System;
    using System.Runtime.InteropServices;
     
    class Hello
    {
         [DllImport("user32.dll", CharSet=CharSet.Auto)]
         private extern static uint MessageBox(IntPtr hWnd, string lpText, string lpCaption, uint uType);
         static void Main(string[] args)
        {
            MessageBox( new IntPtr(0), "Hello, Win32 API(C#) World!", "Hello, World!", 0 );
        }
    }

    「文字セット」に「Auto」を指定した場合は「関数定義」「プラットフォーム」に応じて、呼び出される API 関数名が自動判別される。
    「文字セット」に「Ansi」もしくは「Unicode」を指定した場合それぞれ、末尾が “A” / “W” の API 関数名として自動判別される。

    文字セット指定 関数定義 プラットフォーム 文字変換 判別 API関数名
    Auto MessageBox Windows 9x系 ANSI “A” MessageBoxA
    Auto MessageBox Windows NT系 Unicode “W” MessageBoxW
    Ansi または 省略 MessageBox ANSI “A” MessageBoxA
    Ansi または 省略 MessageBoxA ANSI MessageBoxA
    Unicode MessageBox Unicode “W” MessageBoxW
    Unicode MessageBoxW Unicode MessageBoxW

    また、Win32 データ型と C# データ型の対応は主に以下のようになっている。文字関連の型に関しては文字セット指定が必要なことに注意。

    Win32 データ型 C/C++ データ型 .NET データ型 C# データ型
    HANDLE void * IntPtr
    BYTE unsigned char Byte byte
    SHORT short Int16 short
    WORD unsigned short UInt16 ushort
    INT int Int32 int
    UINT unsigned int UInt32 uint
    LONG long Int32 int
    BOOL int Int32 int
    DWORD unsigned long UInt32 uint
    ULONG unsigned long UInt32 uint
    CHAR char Char (Ansi) char (Ansi)
    WCHAR wchar_t Char (Unicode) char (Unicode)
    LPSTR char * StringBuilder (Ansi)
    LPCSTR const char * String (Ansi) string (Ansi)
    LPWSTR wchar_t * StringBuilder (Unicode)
    LPCWSTR const wchar_t * String (Unicode) string (Unicode)
    FLOAT float Single float
    DOUBLE double Double double

    コンパイル方法

    C:¥> csc Hello.cs

    実行結果

    ---------------------------
    Hello, World!
    ---------------------------
    Hello, Win32 API(C#) World!
    ---------------------------
    OK   
    ---------------------------
  7. Hello, Win32 API(PowerShell) World!

    Posted on 4月 22nd, 2012 by cx20

    Win32 API(PowerShell)

    Win32 API は、Windows の機能にアクセスする為の API(Application Programming Interface)である。
    以下は PowerShell での P/Invoke による呼出し例である。

    ソースコード

    function Main
    {
       MessageBox 0 "Hello, Win32 API(PowerShell)!" "Hello, World!" 0
    }
     
    ## Invoke a Win32 P/Invoke call. 
    ## http://www.leeholmes.com/blog/2006/07/21/get-the-owner-of-a-process-in-powershell-%e2%80%93-pinvoke-and-refout-parameters/
    function Invoke-Win32([string] $dllName, [Type] $returnType, [string] $methodName,  
       [Type[]] $parameterTypes, [Object[]] $parameters) 
    { 
       ## Begin to build the dynamic assembly 
       $domain = [AppDomain]::CurrentDomain 
       $name = New-Object Reflection.AssemblyName 'PInvokeAssembly' 
       $assembly = $domain.DefineDynamicAssembly($name, 'Run') 
       $module = $assembly.DefineDynamicModule('PInvokeModule') 
       $type = $module.DefineType('PInvokeType', "Public,BeforeFieldInit") 
     
       ## Define the actual P/Invoke method
       $method = $type.DefineMethod($methodName, 'Public,HideBySig,Static,PinvokeImpl',  
          $returnType, $parameterTypes) 
     
       ## Apply the P/Invoke constructor 
       $ctor = [Runtime.InteropServices.DllImportAttribute].GetConstructor([string]) 
       $attr = New-Object Reflection.Emit.CustomAttributeBuilder $ctor, $dllName 
       $method.SetCustomAttribute($attr) 
     
       ## Create the temporary type, and invoke the method. 
       $realType = $type.CreateType() 
       $realType.InvokeMember($methodName, 'Public,Static,InvokeMethod', $null, $null,  
          $parameters) 
    } 
     
    function MessageBox([Int32] $hWnd, [String] $lpText, [String] $lpCaption, [Int32] $uType) 
    { 
       $parameterTypes = [Int32], [String], [String], [Int32]
       $parameters = $hWnd, $lpText, $lpCaption, $uType
     
       Invoke-Win32 "user32.dll" ([Int32]) "MessageBoxA" $parameterTypes $parameters
    } 
     
    . Main

    実行方法

    C:¥> PowerShell -file hello.ps1

    実行結果

    ---------------------------
    Hello, World!
    ---------------------------
    Hello, Win32 API(PowerShell) World!
    ---------------------------
    OK   
    ---------------------------
  8. Hello, LINQ World!

    Posted on 4月 8th, 2012 by cx20

    LINQ

    LINQ(Language Integrated Query : 統合言語クエリ)は、.NET 言語から DBMS や XML にアクセスする為の汎用クエリ機能である。
    LINQ プロバイダとして、以下のようなものがある。

    LINQ プロバイダ 説明
    LINQ to SQL SQL Server
    LINQ to XML XML ドキュメント
    LINQ to Dataset ADO.NET データセット
    LINQ to Objects .NET コレクション、ファイル、文字列など

    ソースコード(C# + LINQ to Objects)

    using System;
    using System.Linq;
    using System.Collections.Generic;
     
    class Record
    {
        public string Message;
        public Record(string message)
        {
            this.Message = message;
        }
    }
     
    class Hello
    {
        static void Main(string[] args)
        {
            Record[] records = new Record[]
            {
                new Record("Hello, LINQ World!")
            };
     
            IEnumerable<Record> query =
                from n in records
                select n;
     
            foreach (Record r in query)
            {
                Console.WriteLine(r.Message);
            }
        }
    }

    ソースコード(C# + LINQ to SQL)

    /**
    -- <事前準備>
    -- 1. テーブル作成
    CREATE TABLE HELLO
    (
        ID      INT         NOT NULL,
        MESSAGE VARCHAR(50) NULL,
        PRIMARY KEY (ID)
    );
    -- 2. データ投入
    INSERT HELLO ( ID, MESSAGE ) VALUES ( 1, 'Hello, LINQ World' );
    -- 3. データ表示
    SELECT * FROM HELLO;
    -- ------------------
    ID MESSAGE
    -- ------------------
     1 Hello, LINQ World!
    -- ------------------
    */
     
    using System;
    using System.Linq;
    using System.Data.Linq;
    using System.Data.Linq.Mapping;
     
    public class HelloDataContext : DataContext
    {
        public HelloDataContext(string connectionString) : base(connectionString) { }
        public Table<HelloTable> Hello;
    }
     
    [Table(Name = "Hello")]
    public class HelloTable
    {
        [Column(IsPrimaryKey = true)]
        public int Id;
        [Column]
        public string Message;
    }
     
    class Hello
    {
        static void Main(string[] args)
        {
            string conStr = "SERVER=(local);"
                + "DATABASE=Hello;"
                + "UID=sa;"
                + "PWD=P@ssW0rd";
            var db = new HelloDataContext( conStr );
            var q = 
                from h in db.Hello
                select h;
            foreach (var h in q)
            {
                Console.WriteLine(h.Message);
            }
        }
    }

    ソースコード(VB.NET + LINQ to SQL)

    ''' -- <事前準備>
    ''' -- 1. テーブル作成
    ''' CREATE TABLE HELLO
    ''' (
    '''     ID      INT         NOT NULL,
    '''     MESSAGE VARCHAR(50) NULL,
    '''     PRIMARY KEY (ID)
    ''' );
    ''' -- 2. データ投入
    ''' INSERT HELLO ( ID, MESSAGE ) VALUES ( 1, 'Hello, LINQ World' );
    ''' -- 3. データ表示
    ''' SELECT * FROM HELLO;
    ''' -- ------------------
    ''' ID MESSAGE
    ''' -- ------------------
    '''  1 Hello, LINQ World!
    ''' -- ------------------
     
    Imports System
    Imports System.Linq
    Imports System.Data.Linq
    Imports System.Data.Linq.Mapping
     
    Public Class HelloDataContext 
        Inherits DataContext
        Public Sub New( ByVal connectionString As String )
            MyBase.New(connectionString)
        End Sub
        Public Hello As Table( Of HelloTable )
    End Class
     
    <Table(Name := "Hello")> _
    Public Class HelloTable
        <Column(IsPrimaryKey := True)> _
        Public Id As Integer
        <Column()> _
        Public Message As String
    End Class
     
    Class Hello
        Shared Sub Main()
            Dim conStr As String = "SERVER=(local);" _
                & "DATABASE=Hello;" _
                & "UID=sa;" _
                & "PWD=P@ssW0rd"
            Dim db = New HelloDataContext( conStr )
     
            Dim q = 
                from h In db.Hello
                Select h
     
            For Each h In q
                Console.WriteLine(h.Message)
            Next
        End Sub
    End Class

    コンパイル方法(C# + LINQ to Objects)

    C:¥> csc Hello.cs

    コンパイル方法(C# + LINQ to SQL)

    C:¥> csc Hello.cs

    コンパイル方法(VB.NET + LINQ to SQL)

    C:¥> vbc Hello.vb

    実行結果

    Hello, LINQ World!
  9. Hello, ODP.NET World!

    Posted on 4月 3rd, 2012 by cx20

    ODP.NET

    ODP.NET(Oracle Data Provider for .NET)は、.NET ベースの Oracle Database 接続用 API である。ODAC(Oracle Data Access Component)と呼ばれるパッケージに含まれる。
    .NET 環境での Oracle Database 用データプロバイダとしては、マイクロソフト社が提供する「Microsoft Oracle Client」とオラクル社が提供する「ODP.NET」があるが、現在、「Microsoft Oracle Client」はマイクロソフト社自身が非推奨としており、今後は ODP.NET の使用が推奨されている。

    データプロバイダ 説明
    System.Data.OracleClient .NET Framework Data Provider for Oracle
    Oracle.DataAccess.Client Oracle Data Provider for .NET

    ソースコード(C# + ODP.NET + Oracle)

    using System;
    using Oracle.DataAccess.Client;
     
    class Hello
    {
        static void Main( String[] args )
        {
            string conStr = "Data Source=ORCL;"
                + "User Id=scott;"
                + "Password=tiger";
     
            string sqlStr = "SELECT 'Hello, ODP.NET World!' AS Message FROM DUAL";
     
            OracleConnection con = new OracleConnection(conStr);
            OracleCommand cmd = new OracleCommand(sqlStr, con);
            con.Open();
            OracleDataReader reader = cmd.ExecuteReader();
            while( reader.Read() )
            {
                Console.WriteLine( reader.GetName(0) );
                Console.WriteLine( "---------------------" );
                Console.WriteLine( reader[0] );
            }
            reader.Close();
            con.Close();
        }
    }

    コンパイル方法(C#)

    C:¥> csc /r:Oracle.DataAccess.dll Hello.cs

    実行結果

    MESSAGE
    ---------------------
    Hello, ODP.NET World!
  10. Hello, ADO.NET World!

    Posted on 3月 24th, 2012 by cx20

    ADO.NET

    ADO.NET(ActiveX Data Objects .NET)は、ADO の後継で .NET ベースの DBMS 接続用 API である。
    .NET データプロバイダを介することで様々な DBMS への接続が可能となっている。
    .NET Framework 標準で使用できる .NET データプロバイダとしては、以下のようなプロバイダがある。

    データプロバイダ名 説明
    System.Data.SqlClient Microsoft SQL Server
    System.Data.OleDb OLE DB
    System.Data.Odbc ODBC
    System.Data.OracleClient Oracle

    ソースコード(C# + ADO.NET + OLE DB + Jet データベース)

    using System;
    using System.Data.OleDb;
     
    class Hello
    {
        static void Main( String[] args )
        {
            string conStr = "Provider=Microsoft.Jet.OLEDB.4.0;"
                + "Data Source=hello.mdb";
            string sqlStr = "SELECT 'Hello, ADO.NET World!' AS Message";
     
            OleDbConnection con = new OleDbConnection(conStr);
            OleDbCommand  cmd = new OleDbCommand(sqlStr, con);
            con.Open();
            OleDbDataReader reader = cmd.ExecuteReader();
            while( reader.Read() )
            {
                Console.WriteLine( reader.GetName(0) );
                Console.WriteLine( "---------------------" );
                Console.WriteLine( reader[0] );
            }
            reader.Close();
            con.Close();
        }
    }

    ソースコード(C# + ADO.NET + OLE DB + ACE データベース)

    using System;
    using System.Data.OleDb;
     
    class Hello
    {
        static void Main( String[] args )
        {
            string conStr = "Provider=Microsoft.ACE.OLEDB.12.0;"
                + "Data Source=.\hello.accdb";
            string sqlStr = "SELECT 'Hello, ADO.NET World!' AS Message";
     
            OleDbConnection con = new OleDbConnection(conStr);
            OleDbCommand  cmd = new OleDbCommand(sqlStr, con);
            con.Open();
            OleDbDataReader reader = cmd.ExecuteReader();
            while( reader.Read() )
            {
                Console.WriteLine( reader.GetName(0) );
                Console.WriteLine( "---------------------" );
                Console.WriteLine( reader[0] );
            }
            reader.Close();
            con.Close();
        }
    }

    ソースコード(C# + ADO.NET + SQL Server)

    using System;
    using System.Data.SqlClient;
     
    class Hello
    {
        static void Main( String[] args )
        {
            string conStr = "SERVER=(local);"
                + "DATABASE=master;"
                + "UID=sa;"
                + "PWD=P@ssW0rd";
            string sqlStr = "SELECT 'Hello, ADO.NET World!' AS Message";
     
            SqlConnection con = new SqlConnection(conStr);
            SqlCommand cmd = new SqlCommand(sqlStr, con);
            con.Open();
            SqlDataReader reader = cmd.ExecuteReader();
            while( reader.Read() )
            {
                Console.WriteLine( reader.GetName(0) );
                Console.WriteLine( "---------------------" );
                Console.WriteLine( reader[0] );
            }
            reader.Close();
            con.Close();
        }
    }

    ソースコード(C# + ADO.NET + Oracle)

    using System;
    using System.Data.OracleClient;
     
    class Hello
    {
        static void Main( String[] args )
        {
            string conStr = "Data Source=ORCL;User ID=scott;Password=tiger";
            string sqlStr = "SELECT 'Hello, ADO.NET World!' AS Message FROM DUAL";
     
            OracleConnection con = new OracleConnection(conStr);
            OracleCommand cmd = new OracleCommand(sqlStr, con);
            con.Open();
            OracleDataReader reader = cmd.ExecuteReader();
            while( reader.Read() )
            {
                Console.WriteLine( reader.GetName(0) );
                Console.WriteLine( "---------------------" );
                Console.WriteLine( reader[0] );
            }
            reader.Close();
            con.Close();
        }
    }

    ソースコード(C# + ADO.NET + ODBC + MySQL)

    using System;
    using System.Data.Odbc;
     
    class Hello
    {
        static void Main( String[] args )
        {
            string conStr = "Driver={MySQL ODBC 5.1 Driver};Server=localhost;UID=root;PWD=P@ssW0rd";
            string sqlStr = "SELECT 'Hello, ADO.NET World!' AS Message";
     
            OdbcConnection con = new OdbcConnection(conStr);
            OdbcCommand  cmd = new OdbcCommand(sqlStr, con);
            con.Open();
            OdbcDataReader reader = cmd.ExecuteReader();
            while( reader.Read() )
            {
                Console.WriteLine( reader.GetName(0) );
                Console.WriteLine( "---------------------" );
                Console.WriteLine( reader[0] );
            }
            reader.Close();
            con.Close();
        }
    }

    コンパイル方法(32bit OLE DB 使用時)

    C:¥> csc Hello.cs /platform:x86

    コンパイル方法(上記以外)

    C:¥> csc Hello.cs

    実行結果

    Message
    ---------------------
    Hello, ADO.NET World!