始めに
前回までの2記事でsoapAPIを使うためにSFやvisual studioの準備をしてきました。
今回はいよいよログインやDB操作をSFのsoapAPIを使って行います。
準備や環境設定が不十分な方は下記の2記事を参照ください。
SalesForceでsoap APIを利用するための前準備
SalesforceのsoapAPIを使う(Visual Studio環境設定)
テーブル = オブジェクト
カラム = 項目
レコード = レコードこちらの記事ではSFのDB用語に合わせて記述します。
SOAP API
下記のソースコードは言語は全てVB.netです。
C#にしたい方はこちらのコンバータをお使いください
SforceService()というクラスにSFを操作するメソッドが定義されています。
1 2 |
' SFに接続するためのインスタンス Dim binding As New SforceService() |
ログイン(login)
下記のソースコードにメソッド呼び出しの制御をするMain()を記述しているので、
必要なメソッドを追加しましたら、こちらにメソッド呼び出しを追加してください。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
Module Module1 ' SFに接続するためのインスタンス Dim binding As New SforceService() ' コントローラ Sub Main() binding.Timeout = 30000 ' ログインメソッド呼び出し Login() End Sub ' ログインメソッド Function Login() As Boolean ' SFのユーザ名 Dim username As String = "SFのログイン名" ' SFのパスワード Dim password As String = "SFのログインパスワード + セキュリティトークン" Dim loginResult Try ' ログインする loginResult = binding.login(username, password) ' ログインが失敗した場合 Catch e As SoapException Console.WriteLine("失敗") Return False End Try ' パスワード失効している場合 If loginResult.passwordExpired Then ' binding.setPassword(userId, newPassword) で更新が必要 Return False End If ' エンドポイント更新 Dim authEndPoint As String = binding.Url binding.Url = loginResult.serverUrl ' セッションヘッダ追加 binding.SessionHeaderValue = New SessionHeader() binding.SessionHeaderValue.sessionId = loginResult.sessionId ' 結果表示 Dim userInfo As GetUserInfoResult = loginResult.userInfo Dim msg As String = "" msg += "UserID: " & userInfo.userId & vbCrLf msg += "User Full Name: " & userInfo.userFullName & vbCrLf msg += "User Email: " & userInfo.userEmail & vbCrLf msg += vbCrLf msg += "SessionID: " & loginResult.sessionId & vbCrLf msg += "Auth End Point: " & authEndPoint & vbCrLf msg += "Service End Point: " & loginResult.serverUrl & vbCrLf Console.WriteLine(msg) Return True End Function End Module |
パスワード + セキュリティトークンの文字列をAPI実行時に
SFが求める任意のIPからのアクセスの場合セキュリティトークン不要です。
取得(query)
今回はSFの標準オブジェクトである「キャンペーン」オブジェクトのレコードを取得するソースを例として書いております。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
' オブジェクトを取得するメソッド Private Sub getSfOjbect() ' SQL文を作る Dim conditions As String conditions = "'7015h000000IvaUAAS'" ' キャンペーンオブジェクトを取得する Dim soqlQuery As String = "SELECT Id, OwnerId, CampaignMemberRecordTypeId, CreatedById, LastModifiedById, Name FROM Campaign WHERE ID > " & conditions Try ' SQL文を実行する Dim qr As QueryResult = binding.query(soqlQuery) Dim msg As String = "" ' レコードの数分処理を繰り返す While True Dim records As sObject() = qr.records ' 始めのレコードから順に処理を繰り返していく For i As Integer = 0 To records.Length - 1 ' キャンペーンオブジェクトのレコード取得結果 Dim con As Campaign = CType(records(i), Campaign) ' キャンペーンオブジェクトのカラムをmsgに格納する msg += con.Id & " : " + con.OwnerId & " : " + con.CampaignMemberRecordTypeId & " : " + con.CreatedById & " : " + con.LastModifiedById & " : " + con.Name & vbCrLf Next ' レコード数分全て処理ができた場合、処理を終わらせる If qr.done Then Exit While ' レコード数分全処理が全てしきれていない場合、カーソルを繰り上げて処理を続行する Else qr = binding.queryMore(qr.queryLocator) End If End While ' コンソールに取得したレコード情報を表示する Console.WriteLine(msg) ' 例外が発生した場合コンソールに内容を表示する Catch ex As Exception Console.WriteLine(ex.Message) End Try End Sub |
◆取得したいオブジェクトに合わせて下記のソースをを静的に書きなおす必要があります。
①From句の対象オブジェクト名
②Dim con As Campaign = CType(records(i), Campaign)
◆取得する項目に合わせて下記の通りに、ソースを合わせる必要があります。
1 2 |
SELECT Id, OwnerId, CampaignMemberRecordTypeId, CreatedById, LastModifiedById, Name FROM Campaign con.Id & " : " + con.OwnerId & " : " + con.CampaignMemberRecordTypeId & " : " + con.CreatedById & " : " + con.LastModifiedById & " : " + con.Name |
実行結果
登録(create)
今回はSFの標準オブジェクトである「取引先」オブジェクトにレコードを登録するソースを例として書いております。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
Public Function createRecords() As String() Dim result As String() = New String(1) {} Dim account1 As Account = New Account() account1.Name = "松下テスト001" account1.BillingStreet = "403 McAdoo St" account1.BillingCity = "Truth or Consequences" account1.BillingState = "NM" account1.BillingCountry = "US" Dim account2 As Account = New Account() account2.Name = "松下テスト002" account2.BillingStreet = "25800 Arnold Dr" account2.BillingCity = "Sonoma" account2.BillingState = "CA" account2.BillingCountry = "US" Dim accounts As Account() = {account1, account2} Try Dim saveResults As SaveResult() = binding.create(accounts) For i As Integer = 0 To saveResults.Length - 1 If saveResults(i).success Then Console.WriteLine("Successfully created Account ID: " & saveResults(i).id) result(i) = saveResults(i).id Else Console.WriteLine("Error: could not create Account " & "for array element " & i & ".") Console.WriteLine(" The error reported was: " & saveResults(i).errors(0).message & vbLf) result(i) = saveResults(i).id End If Next Catch e As SoapException Console.WriteLine("An unexpected error has occurred: " & e.Message & vbLf + e.StackTrace) End Try Return result End Function |
createメソッドにはオブジェクトの配列を引数としてわせるので
複数のレコードを一度に登録することができます。
実行結果
更新(update)
今回はSFの標準オブジェクトである「取引先」オブジェクトにレコードを更新するソースを例として書いております。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
Public Sub updateRecords() Dim updates As Account() = New Account(1) {} Dim account1 As Account = New Account() account1.Id = "0015h000004Y7ftAAC" account1.ShippingPostalCode = "89044" updates(0) = account1 Dim account2 As Account = New Account() account2.Id = "0015h000004Y807AAC" account2.NumberOfEmployees = 1000 updates(1) = account2 Try Dim saveResults As SaveResult() = binding.update(updates) For Each saveResult As SaveResult In saveResults If saveResult.success Then Console.WriteLine("Successfully updated Account ID: " & saveResult.id) Else Dim errors As [Error]() = saveResult.errors If errors.Length > 0 Then Console.WriteLine("Error: could not update " & "Account ID " & saveResult.id & ".") Console.WriteLine(vbTab & "The error reported was: (" & errors(0).statusCode & ") " + errors(0).message & ".") End If End If Next Catch e As SoapException Console.WriteLine("An unexpected error has occurred: " & e.Message & vbLf + e.StackTrace) End Try End Sub |
updateメソッドにはオブジェクトの配列を引数としてわせるので
複数のレコードを一度に更新することができます。
実行結果
削除(delete)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
' SFのオブジェクトを削除するメソッド Public Sub deleteSfOjbect() ' 削除するレコードのID(主キー)を格納する文字列の配列を定義 Dim ids As String() ' 削除するIDを配列形式で定義する ids = New String() {"0015h000004Y7ftAAC"} Try ' 削除処理を実行する Dim deleteResults As DeleteResult() = binding.delete(ids) Dim msg As String = "" For Each result As DeleteResult In deleteResults If result.success Then msg += "Delete Successfull! Deleted Record ID: " & result.id & vbCrLf Else Console.WriteLine("Error!: " & result.errors(0).message) End If Next Console.WriteLine(msg) Catch e As SoapException Console.WriteLine(e.Message) End Try End Sub |
deleteメソッドにはIDの文字列の配列を引数としてわせるので
複数のレコードを一度に更新することができます。
実行結果
SalesForceのオブジェクトには全てIDという項目があり、このIDはSFによって自動採番されています。
※SFのオブジェクトマネージャーからは参照できません。
登録・更新(upsert)
SFには外部ID・ユニークキーで対象のレコードを識別して、
レコードがあれば更新、なければ登録というように処理をする便利なAPIがあります。
しかし、対象のオブジェクトが外部IDやユニークキーの項目を保持していないといけません。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
' オブジェクトを登録更新するメソッド Public Sub upsertSfOjbect() ' キャンペーンオブジェクトの配列を定義 Dim upserts As sObject() = New Campaign(0) {} ' キャンペーンオブジェクトを定義 Dim c0 As Campaign = New Campaign() c0.Description = "テスト001" c0.Name = "GC Product Webinar - Jan 7, 2002dm001" ' 配列の0番目にオブジェクトを代入する upserts(0) = c0 Try ' キャンペーンオブジェクトをキャンペーンオブジェクトの配列分登録/更新する(外部IDをNameとする) ' 外部IDが一致するレコードがある場合は更新。ない場合は登録。 Dim upsertResults As UpsertResult() = binding.upsert("Name", upserts) Dim msg As String = "" For Each result As UpsertResult In upsertResults If result.success Then msg += result.id & " : " & (If(result.created, "Insert", "Update")) & vbCrLf Else Console.WriteLine("Error!: " & result.errors(0).message) End If Next Console.WriteLine(msg) Catch e As SoapException Console.WriteLine(e.Message) End Try End Sub |
カスタムオブジェクトのみ付属できる項目。
※カスタムオブジェクトとは既存のSFが提供するオブジェクトではない、
自分で生成したオブジェクトです。
外部の機能からユニークにレコードを判別するための役割があります。
※外部の機能とは例えば、今回自分で作成しているsoapAPIです。
updateと違ってIDではなく、外部IDやユニークキーでレコードを識別して登録更新を行います。
つまり、外部IDもユニークキーも持たないオブジェクトでは使えません。
コメント