2016年9月2日金曜日

ASP.NET MVC5(VB) 【Entity Frame Workを使用しないでCRUD】

Entity Frame Workを使用しないで、昔ながらのADO.NETの記述方法でデータベースの基本操作をしようと、チュートリアルを探したところ、以下のサイトがありました。(英語サイト)

CRUD Operations In ASP.NET MVC5 Using ADO.NET

同様の内容を、VBでコーディングしてみました。

開発環境:Visual Studio Community 2015(VB)、SQLServer2008R2



  1. 新しいプロジェクトの作成

    「ASP.NET Webアプリケーション」を選択して「OK」、


    テンプレートとして「Empty」を選択し、フォルダー及びコア参照の部分で「MVC」にのみチェックを入れて「OK」


    ソリューションが作成されます。
  2. モデルクラスの作成

    モデルフォルダを右クリックし、「追加」、「クラス」の順に選択します。


    「EmpModel.vb」と名前を付けて、空のクラスを作成します。


    以下のコードを入力します。
    Imports System.ComponentModel
    Imports System.ComponentModel.DataAnnotations
    
    Public Class EmpModel
    
        <DisplayName("ID")>
        Public Property Empid As Integer
    
        <Required(ErrorMessage:="名前を入力して下さい")>
        Public Property Name As String
    
        <Required(ErrorMessage:="都市名を入力して下さい")>
        Public Property City As String
    
        <Required(ErrorMessage:="住所を入力して下さい")>
        Public Property Address As String
    
    End Class
    
    
  3. コントローラークラスの作成

    コントローラーフォルダを右クリックし、「追加」、「コントローラー」の順に選択します。


    「読み取り/書き込みアクションがある MVC5コントローラー」を選択します。


    「EmproyeeContoroller」と名付けます。


    CRUDを行うテンプレートのコードが、自動生成されます。
  4. テーブルの作成

    接続先のSQLServerのデータベースにテーブルを作成します。
    テーブル名は「Emproyee」とします。
    ※SQLServerManagementStudioを用いてテーブルを作成しました。

    CREATE TABLE [dbo].[Employee](
     [Id] [int] NOT NULL PRIMARY KEY,
     [Name] [varchar](50) NULL,
     [City] [varchar](50) NULL,
     [Address] [varchar](50) NULL
     )
    

    元のチュートリアルではレコード操作用のストアドプロシージャを作成していますが、ここではストアドプロシージャは作成せず、SQL文を都度発行するスタイルで作ります。
  5. レポジトリの作成
    データベース関連の処理をするレポジトリクラスを作成します。
    まずはソリューションに「Repository」フォルダを作成します。


    続いて、「Repository」フォルダを右クリックし、「追加」、「クラス」の順に選択し、「EmpRepository.vb」と名前を付けてクラスを作成します。


    レポジトリクラスに、データの一覧取得、追加、更新、削除のメソッドを記述します。

    Imports System.Data.SqlClient
    
    Public Class EmpRepository
    
        Private con As SqlConnection
    
        '-----------------------------------------------
        '   SqlConnection                               
        '-----------------------------------------------
        Private Sub connection()
            Dim constr As String = ConfigurationManager.ConnectionStrings("getconn").ToString
            con = New SqlConnection(constr)
        End Sub
    
        '-----------------------------------------------
        '   データの追加
        '-----------------------------------------------
        Public Function AddEmployee(obj As EmpModel) As Boolean
    
            connection()
    
            Dim strSQL As String = String.Empty
            strSQL &= "INSERT   INTO    Employee    " & vbCrLf
            strSQL &= "VALUES(  @ID,                " & vbCrLf
            strSQL &= "         @NAME,              " & vbCrLf
            strSQL &= "         @CITY,              " & vbCrLf
            strSQL &= "         @ADDRESS            " & vbCrLf
            strSQL &= "         )                   " & vbCrLf
    
            Dim com As New SqlCommand(strSQL, con)
            com.CommandType = CommandType.Text
    
            'パラメータをセット
            com.Parameters.AddWithValue("@ID", obj.Empid)
            com.Parameters.AddWithValue("@NAME", obj.Name)
            com.Parameters.AddWithValue("@CITY", obj.City)
            com.Parameters.AddWithValue("@ADDRESS", obj.Address)
    
            con.Open()
            Dim i As Integer = com.ExecuteNonQuery
            con.Close()
    
            If i >= 1 Then
                Return True
            Else
                Return False
            End If
    
        End Function
    
        '-----------------------------------------------
        '   データの一覧
        '-----------------------------------------------
        Public Function GetAllEmployees() As List(Of EmpModel)
    
            connection()
    
            Dim EmpList As List(Of EmpModel) = New List(Of EmpModel)
            Dim strSQL As String = String.Empty
            strSQL &= "SELECT   Id,Name,City,Address" & vbCrLf
            strSQL &= "FROM     Employee            " & vbCrLf
            strSQL &= "ORDER BY ID                  " & vbCrLf
    
            Dim com As New SqlCommand(strSQL, con)
            com.CommandType = CommandType.Text
    
            Dim da As New SqlDataAdapter(com)
            Dim dt As DataTable = New DataTable
    
            con.Open()
            da.Fill(dt)
            con.Close()
    
            '読み込んだ値をListにセット
            For Each dr As DataRow In dt.Rows
                Dim Record As New EmpModel
                With Record
                    .Empid = CInt(dr.Item("Id"))
                    .Name = dr.Item("Name").ToString
                    .City = dr.Item("City").ToString
                    .Address = dr.Item("Address").ToString
                End With
                EmpList.Add(Record)
            Next
    
            Return EmpList
    
        End Function
    
        '-----------------------------------------------
        '   既存データの更新
        '-----------------------------------------------
        Public Function UpdateEmployee(Id As Integer, obj As EmpModel) As Boolean
    
            connection()
    
            Dim strSQL As String = String.Empty
            strSQL &= "UPDATE   Employee                  " & vbCrLf
            strSQL &= "SET      Id = @ID ,                " & vbCrLf
            strSQL &= "         Name = @NAME,             " & vbCrLf
            strSQL &= "         City = @CITY,             " & vbCrLf
            strSQL &= "         Address = @ADDRESS        " & vbCrLf
            strSQL &= "WHERE    Id = @UPDID               " & vbCrLf
    
            Dim com As New SqlCommand(strSQL, con)
            com.CommandType = CommandType.Text
    
            'パラメータをセット
            com.Parameters.AddWithValue("@ID", obj.Empid)
            com.Parameters.AddWithValue("@NAME", obj.Name)
            com.Parameters.AddWithValue("@CITY", obj.City)
            com.Parameters.AddWithValue("@ADDRESS", obj.Address)
            com.Parameters.AddWithValue("@UPDID", Id)
    
            con.Open()
            Dim i As Integer = com.ExecuteNonQuery
            con.Close()
    
            If i >= 1 Then
                Return True
            Else
                Return False
            End If
    
        End Function
    
        '-----------------------------------------------
        '   既存データの削除
        '-----------------------------------------------
        Public Function DeleteEmployee(Id As Integer) As Boolean
    
            connection()
    
            Dim strSQL As String = String.Empty
            strSQL &= "DELETE   Employee    " & vbCrLf
            strSQL &= "WHERE    Id = @ID    " & vbCrLf
    
            Dim com As New SqlCommand(strSQL, con)
            com.CommandType = CommandType.Text
    
            'パラメータをセット
            com.Parameters.AddWithValue("@ID", Id)
    
            con.Open()
            Dim i As Integer = com.ExecuteNonQuery
            con.Close()
    
            If i >= 1 Then
                Return True
            Else
                Return False
            End If
    
        End Function
    
    End Class
    
    ルートフォルダの「Web.config」に"getconn"の名前で接続文字列を定義します。 ※各自の環境に合わせて記述して下さい。
  6. コントローラーにメソッドを記述

    Option Strict Off   '※OnだとViewBagの記述時に遅延バインディングエラー
    
    Imports System.Web.Mvc
    
    Namespace Controllers
        Public Class EmployeeController
            Inherits Controller
    
            '-----------------------------------------------
            '   データの一覧画面表示
            '-----------------------------------------------
            ' GET: Employee
            Function Index() As ActionResult
                Dim EmpRepo As New EmpRepository
                ModelState.Clear()
                Return View(EmpRepo.GetAllEmployees)
            End Function
    
            '-----------------------------------------------
            '   データの詳細取得
            '-----------------------------------------------
            ' GET: Employee/Details/5
            Function Details(ByVal id As Integer) As ActionResult
                Dim EmpRepo As New EmpRepository
                Return View(EmpRepo.GetAllEmployees().Find(Function(a) a.Empid = id))
            End Function
    
            '-----------------------------------------------
            '   データの追加画面表示
            '   ※入力画面=空データ
            '-----------------------------------------------
            ' GET: Employee/Create
            Function Create() As ActionResult
                Return View()
            End Function
    
            '-----------------------------------------------
            '   データの追加
            '-----------------------------------------------
            ' POST: Employee/Create
            
            Function Create(Emp As EmpModel) As ActionResult
                Try
                    ' TODO: Add insert logic here
                    If ModelState.IsValid Then
                        Dim EmpRepo As New EmpRepository
                        If EmpRepo.AddEmployee(Emp) Then
                            ViewBag.Message = "データの登録に成功しました"
                        End If
                    End If
                    Return RedirectToAction("Index")
                Catch
                    Return View()
                End Try
            End Function
    
            '-----------------------------------------------
            '   既存データの編集画面表示
            '-----------------------------------------------
            ' GET: Employee/Edit/5
            Function Edit(ByVal id As Integer) As ActionResult
                Dim EmpRepo As New EmpRepository
                Return View(EmpRepo.GetAllEmployees().Find(Function(a) a.Empid = id))
            End Function
    
            '-----------------------------------------------
            '   既存データの更新
            '-----------------------------------------------
            ' POST: Employee/Edit/5
            <HttpPost()>
            Function Edit(ByVal id As Integer, Emp As EmpModel) As ActionResult
                Try
                    ' TODO: Add update logic here
                    Dim EmpRepo As New EmpRepository
                    EmpRepo.UpdateEmployee(id, Emp)
                    Return RedirectToAction("Index")
                Catch
                    Return View()
                End Try
            End Function
    
            '-----------------------------------------------
            '   データの削確認除画面表示
            '-----------------------------------------------
            ' GET: Employee/Delete/5
            Function Delete(ByVal id As Integer) As ActionResult
                Dim EmpRepo As New EmpRepository
                Return View(EmpRepo.GetAllEmployees().Find(Function(a) a.Empid = id))
            End Function
    
            '-----------------------------------------------
            '   データの削除
            '-----------------------------------------------
            ' POST: Employee/Delete/5
            
            Function Delete(ByVal id As Integer, ByVal collection As FormCollection) As ActionResult
                Try
                    ' TODO: Add delete logic here
                    Dim EmpRepo As New EmpRepository
                    If EmpRepo.DeleteEmployee(id) Then
                        ViewBag.AlertMsg = "データを削除しました。"
                    End If
                    Return RedirectToAction("Index")
                Catch
                    Return View()
                End Try
            End Function
    
        End Class
    
    End Namespace
    
  7. ビューの作成

    作成したコントローラーに対応するビューを作成(自動生成)します。
    コントローラーのメソッド内で右クリックし「ビューを追加」を選択します。


    ビューの追加画面が表示されるので、
    テンプレート欄には
    ・Indexメソッドには「Create」
    ・Deteilsメソッドには「Details」
    ・Createメソッドには「Create」
    ・Editメソッドには「Edit」
    ・Deleteメソッドには「Delete」
    をそれぞれ選択します。

    また、モデルクラス欄には「EmpModel」を選択し、オプションの「部分ビューとして作成」にチェックを入れて「追加」を押します。


    Index、Details、Create、Edit、Deleteの5つのメソッドに対してビューを作成します。
  8. ビュー「Index.vbhtml」の修正
    初期状態ではコメントアウトされているEdit、Details、Editのリンク部分を修正します。

    初期状態


    修正後
                @Html.ActionLink("Edit", "Edit", New With {.id = item.Empid}) |
                @Html.ActionLink("Details", "Details", New With {.id = item.Empid}) |
                @Html.ActionLink("Delete", "Delete", New With {.id = item.Empid})



  9. ルーティング設定
    「App_Start」フォルダ内の「RouteConfig.vb」を修正します。


    デフォルトのコントローラーを「Employee」にし、デフォルトアクションを「Index」にします。


    Imports System
    Imports System.Collections.Generic
    Imports System.Linq
    Imports System.Web
    Imports System.Web.Mvc
    Imports System.Web.Routing
    
    Public Module RouteConfig
        Public Sub RegisterRoutes(ByVal routes As RouteCollection)
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}")
    
            routes.MapRoute(
                name:="Default",
                url:="{controller}/{action}/{id}",
                defaults:=New With {.controller = "Employee", .action = "Index", .id = UrlParameter.Optional}
            )
        End Sub
    End Module
    
ここまでで一通り完成です。
実行して、動作を確認してみて下さい。


2016年8月31日水曜日

「ASP.NET MVC5 実践プログラミング」 VBでコーディング(Chapter1~3)

「ASP.NET MVC5 実践プログラミング」 (山田祥寛 著 秀和システム)を学習中。
C#での開発経験がないため、C#のコードをVBに置き換えながらテキストを読み進めた。
VBのコードのメモを残す。

以下のサイトを参考にさせていただきました。



Chapter1 イントロダクション

概要や、環境構築の説明部分。
テキストではVisual Studio 2013 Expressを用いているが、こちらではVisual Studio 2015 Communityをインストールした。


Chapter2 ASP.NET MVCの基本

※プロジェクトの参照設定の「インポートされた名前空間」にSystem.Data.Entityを追加しておくこと

リスト2-1 Controllers/BeginController.vb

Option Strict Off

Namespace Controllers
    Public Class BeginController
        Inherits Controller

        ' GET: Begin
        Function Index() As ActionResult
            Return Content("こんにちは、世界!")
        End Function

    End Class
End Namespace

リスト2-4 Controllers/BeginController.vb

Option Strict Off

Namespace Controllers
    Public Class BeginController
        Inherits Controller
...中略...

        Function Show() As ActionResult
            ViewBag.Message = "こんにちは、世界!"
            Return View()
        End Function

    End Class
End Namespace

リスト2-5 Views/Begin/Show.vbhtml

@Code
    ViewData("Title") = "Show"
End Code

<h2>Show</h2>

<p>@ViewBag.Message</p>

リスト2-7 Models/Member.vb

Public Class Member
    Public Property Id As Integer
    Public Property Name As String
    Public Property Email As String
    Public Property Birth As DateTime
    Public Property Married As Boolean
    Public Property Memo As String
End Class

リスト2-8 Models/MvcBasicContext.vb

Public Class MvcBasicContext
    Inherits DbContext
    Public Property Members As DbSet(Of Member)
End Class

リスト2-9 Web.config

  <connectionStrings>
    ...中略...
    <add name="MvcBasicContext" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\MvcBasic.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />
  </connectionStrings>

リスト2-10 Models/MvcBasicInitializer.vb

Public Class MvcBasicInitializer
    Inherits DropCreateDatabaseAlways(Of MvcBasicContext)

    Protected Overrides Sub Seed(context As MvcBasicContext)

        Dim members As New List(Of Member) _
            From {
            New Member() With {
                .Name = "山田太郎",
                .Email = "yamada@example.com",
                .Birth = DateTime.Parse("1970-04-01"),
                .Married = False,
                .Memo = "メモ欄です。"
            },
            New Member() With {
                .Name = "佐藤花子",
                .Email = "sato@example.com",
                .Birth = DateTime.Parse("1972-12-12"),
                .Married = False,
                .Memo = "備考欄です。"
            }
        }
        members.ForEach(Function(b) context.Members.Add(b))
        context.SaveChanges()
    End Sub

End Class

リスト2-11 Global.asax

Imports System.Web.Optimization

Public Class MvcApplication
    Inherits System.Web.HttpApplication

    Protected Sub Application_Start()
        ...中略...
        Database.SetInitializer(Of MvcBasicContext)(New MvcBasicInitializer())
    End Sub
End Class


リスト2-12 Controllers/BeginController.vb

Option Strict Off

Namespace Controllers
    Public Class BeginController
        Inherits Controller

        Private db As New MvcBasicContext

        ...中略...

        Function List() As ActionResult
            Return View(db.Members)
        End Function

    End Class
End Namespace


リスト2-13 Views/Begin/List.vbhtml

@ModelType IEnumerable(Of MvcBasic.Member) 
@Code
    ViewData("Title") = "List"
End Code
<h2>List</h2>
<table class="table">
    <tr>
        <th>氏名</th>
        <th>メールアドレス</th>
        <th>誕生日</th>
        <th>既婚</th>
        <th>備考</th>
    </tr>
    @For Each item In Model
        @<tr>
            <td>@item.Name</td>
            <td>@item.Email</td>
            <td>@item.Birth</td>
            <td>@item.Married</td>
            <td>@item.Memo</td>
        </tr>
    Next
</table>

リスト2-14 Controllers/BeginController.vb

Option Strict Off

Namespace Controllers
    Public Class BeginController
        Inherits Controller

        ...中略...

        Sub New()
            db.Database.Log = Sub(sql) Debug.Write(sql)
        End Sub

        ...中略...

    End Class
End Namespace


2016年8月24日水曜日

ASP.NET MVC5 (VB) + SQLServer 【その1】

ASP.NET MVC5 (VB) + SQLServer 【その1 プロジェクト作成~CRUD生成】

<やりたいこと>
ASP.NET NVC5にて、
・データのメンテナンス機能
・データの帳票出力機能
を作ってみたい。

<本投稿で行うこと>
特定のテーブルのメンテナンス画面を作成(自動生成)する。
いわゆる「コードファースト」のスタイルではなく、すでにテーブルが定義されていて、データも存在するデータベース(SQLServer)を操作する。

<開発環境>
・Visual Studio 2015 Community 2015
・SQLServer2008R2

<手順>
  1. プロジェクトの作成
    新しいプロジェクトを作成「ASP.NET Web アプリケーション」


    「MVC」のテンプレートを選択。Azureへの配置はしない。
  2. モデルを生成
    ソリューションエクスプローラーの「Models」のフォルダを右クリック => 「追加」 => 「新しい項目」 =>「ADO.NET Entity Data Model」を選択



    「データベースからCode First」を選択


    データ接続の選択 「新しい接続」を押す


    データベースの接続情報を入力して「OK」


    作成したデータ接続を選択。重要情報は接続文字列に含めてみた。「次へ」を押す


    対象とするテーブルを選択して「完了」


    モデルが自動生成された。
    ここで一旦ビルドしておく。
  3. CRUD自動生成
    ソリューションエクスプローラーのControllersフォルダを右クリックし「追加」 => 「新規スキャフォールディングアイテム」


    「Entity Framework を使用した、ビューがある MVC 5 コントローラー」を選択


    モデルクラスに先ほど作成したModelの任意のものをチョイス。
    データコンテキストクラスにもModelの項で作成したものをチョイス。
    「追加」を押す。上手くいけば、コントローラーとビューが自動生成されます。
  4. 動作確認
    再生ボタンを押して、プログラムを実行jしブラウザで動作確認します。


    ブラウザにトップページが表示されます。


    先ほど作成したコントローラーのパスを開きます。
    もともと「http://localhost:○○○○○/」と出ていたURLに、コントローラー名(名前の「Controller」の部分を除く)を加え「http://localhost:○○○○○/コントローラー名」を入力します。


    テーブルの一覧が表示されたら成功です。Create、Edit、Details、Deleteが動作することが確認できます。

2014年6月17日火曜日

Android Studio 外部ライブラリ(.jar)の参照設定

Android Studioにて、外部ライブラリ(.jar)を参照設定する手順のメモ

ADTで作られたサンプルプログラムをAndroidStudio上で動作させようと、プロジェクトをインポートしたが、外部ライブラリの参照設定を別途行う必要があった。
外部ライブラリの参照設定の手順をメモする。

<環境>
Android Studio(Preview) 0.6.1 MAC

<手順>

  1. アプリケーションのフォルダにlibsフォルダを作成し、libsフォルダに外部ライブラリファイルを入れる
  2. プロジェクトの設定を行う。
    [File] => [ProjectStructure] を押してプロジェクトの設定を開く
    画面左側のModules内のアプリケーションを選択
    Dependenciesタブを選択
    画面下側の[+]を押す
    [2 File Dependency]を押す。
    手順1で追加した外部ライブラリファイルを選択して[OK]を押す


2014年5月15日木曜日

Android Studio プロジェクト作成後にアイコンを再設定する方法

Android Studioにて、一旦プロジェクトを作成した後に、アイコンを再作成する手順を示す。

<環境>
Android Studio(Preview)0.5.8 MAC

<手順>
  1. プロジェクトのモジュールフォルダを右クリックして、New→Image Assetの順にクリック
  2. アイコンを指定するウィザードが表示されるので、任意のImage fileを指定してNext





2014年4月16日水曜日

UbuntuにRails4の開発環境をセットアップ

Ruby on Rails Tutorial を学習するための、Rails4の開発環境をセットアップする
VirtualBoxにてUbuntu(12.04)を動作させ、Ubuntu上にセットアップすることにした。
Ubuntuにrbenv + BundlerでRails4をインストールする
  1. VirtualBoxのインストール
    https://www.virtualbox.org/wiki/Downloads
    ダウンロードしてインストール
  2. Ubuntuのディスクイメージをダウンロード
    https://www.ubuntulinux.jp/download/ja-remix-vhd
    Ubuntu12.04の仮想ハードディスクのイメージを取得する
  3. VirtualBoxのセットアップ
    メモリを1GBに、ネットワークアダプタの設定は「ブリッジ」モードにしてUbuntuを立ち上げる。
  4. SublimeText3 のインストール
    GUIのエディタを入れておく。
    http://www.sublimetext.com/3
    Ubuntu 32 bit
    ダウンロードしたものを実行するだけでとりあえずインストールできるようだが、日本語入力なんかはうまくいかない。
    ここは別の機会に設定手順を示す。

    この後はUbuntuのターミナルからコマンドを叩いていく。
  5. パッケージのインストール
    事前準備
    sudo apt-get update
    sudo apt-get upgrade
    

  6. パッケージをインストール
    sudo apt-get install build-essential git curl zlib1g-dev libssl-dev libreadline-dev libyaml-dev libxml2-dev libxslt-dev sqlite3 libsqlite3-dev nodejs 
    
  7. rbenvをインストール
    cd
    git clone git://github.com/sstephenson/rbenv.git .rbenv
    
    パスを通す
    echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bash_profile
    echo 'eval "$(rbenv init -)"' >> ~/.bash_profile
    
  8. ruby-buildをインストール
    mkdir -p ~/.rbenv/plugins
    cd ~/.rbenv/plugins
    git clone git://github.com/sstephenson/ruby-build.git
    cd ruby-build
    git pull
    sudo ./install.sh
    
  9. rubyのインストール
    ここでは2.0.0 p195をインストール
    rbenv install 2.0.0-p195
    rbenv rehash
    rbenv global 2.0.0-p195
    
    バージョンの確認
    ruby - v
    
  10. RubyGemsのgemインストール時にドキュメントをインストールしないオプションをデフォルトに
    echo "install: --no-rdoc --no-ri" >> ~/.gemrc
    echo "update: --no-rdoc --no-ri" >> ~/.gemrc
    
  11. Bundlerのインストール
    gem update
    gem install bundler
    
  12. Rails(4.0.2)のインストール
    gem install rails --version 4.0.2
    rbenv rehash
    
以上です!

2014年3月7日金曜日

始めてみよっと

アウトプットの練習をする。
そうすることで、自分の書くことや話すことに一貫性を持たせることができるのかもしれないから。