メインコンテンツへスキップ
この例では、手動による追加のデータ処理ステージを作成する方法を示します。たとえば、このステージは自社のセキュリティ部門で利用できます。セキュリティ部門では、特定の条件を満たす文書について、後続の処理に送ってよいかを確認して承認し、これらの条件を満たさない文書は差し戻すことができます。 承認されたすべての文書には、デジタル署名を模したバイト列が付加されます。 こちらからプロジェクトと関連資料をダウンロードできます: UserStage.zip

サンプルコードでは、次の手順を実行します。

  • 接続を設定します
  • プロジェクトの作業を開始します
  • タスクの一覧を取得して処理します
  • サービスステージで各タスクを処理します
  • ファイルをサーバーにアップロードします
  • セッションを終了します

この例を実行するには:

Visual Studio 2013 以降で UserStageExample.sln を開きます。
  1. Application Server の URL を入力します。
  2. 認証の種類を選択します。
  3. Login をクリックします。

接続の設定

private const string FlexiHandlerPath = "/FlexiCapture12/Server/{0}API/v1/Soap"; // FlexiCapture APIへのパス
private const string FlexiCaptureAuthPart = "FCAuth/"; // FlexiCapture認証用のパス
private const string UserStageProjectName = "UserStageExample"; // この例で使用するプロジェクト名
private const string UserStageName = "Service"; // サービスステージ名
// 新しいバインディングを作成
var binding = new BasicHttpBinding();
// メッセージサイズがFlexiCaptureには小さすぎるため、拡大する必要がある
binding.MaxReceivedMessageSize = MessageSize;
// プロトコルに応じて接続セキュリティモードを選択
binding.Security.Mode = serverUri.Scheme == Uri.UriSchemeHttps
   ? BasicHttpSecurityMode.Transport
   : BasicHttpSecurityMode.TransportCredentialOnly;
// 認証方式を選択
binding.Security.Transport.ClientCredentialType = windowsAuth
   ? HttpClientCredentialType.Windows
   : HttpClientCredentialType.Basic;
// 認証方式に応じてAPIへのパスを選択
var externalSuffix = windowsAuth ? string.Empty : FlexiCaptureAuthPart;
var remoteAddress = new EndpointAddress(new Uri(serverUri, string.Format(FlexiHandlerPath, externalSuffix)));
// SOAPクライアントを作成
_client = new FlexiCapture.FlexiCaptureWebServiceSoapClient(binding, remoteAddress);
// FlexiCaptureの認証にはログインとパスワードを指定する
if (_client.ClientCredentials != null && !windowsAuth)
{
   _client.ClientCredentials.UserName.UserName = login;
   _client.ClientCredentials.UserName.Password = password;
}
Starting working with the project
// セッションを開く
_sessionId = _client.OpenSession(RoleType, WorkstationType);
var projectGuid = string.Empty;
// 対象プロジェクトを検索する
foreach (var project in _client.GetProjects())
{
   if (project.Name == UserStageProjectName)
   {
      projectGuid = project.Guid;
   }
}
if (string.IsNullOrEmpty(projectGuid))
{
   MessageBox.Show("The server does not contain the UserStageExample project which is needed for this example");
}
// プロジェクトを開く
_projectId = _client.OpenProject(_sessionId, projectGuid);
// サービスステージの識別子を検索して保存する
var stages = _client.GetProcessingStages(_projectId, 0, 0, UserStageName);
if (stages.Count != 1) throw new Exception("Invalid project");
   _serviceStageId = stages[0].Id;
// 例外ステージの外部IDを検索して保存する
stages = _client.GetProcessingStages(_projectId, 0, ExceptionStageType, string.Empty);
if (stages.Count != 1) throw new Exception("Invalid project");
   _exceptionsStageId = stages[0].ExternalId;

サービスステージで保留中のタスク一覧の取得と処理

// タスクのリストを取得する
var tasks = _client.GetAvailableTasksByStageId(_sessionId, _projectId,
new FlexiCapture.stageIds() { _serviceStageId }, false);
var result = new Dictionary<int, Task>();
if (tasks == null || tasks.Count == 0) return result;
foreach (var task in tasks)
{
   // 各タスクに対してTask型のオブジェクトを作成する
   var item = new Task
   {
      Id = task.Id,
      BatchId = task.BatchId
   };
   // タスクのドキュメントリストを取得する
   var documents = _client.GetTaskDocuments(task.Id);
   if (documents == null || documents.Count == 0) continue;
   foreach (var document in documents)
   {
      // タスクのXMLをロードする
      var file = _client.LoadDocumentResult(_sessionId, document.BatchId, document.Id, "DocumentBody"); // "DocumentBody" - 認識済みデータを含むファイルの名前
      if (file == null || file.Bytes == null) continue;
      // XMLを解析する
      var doc = new Document(document.Id, XDocument.Load(new MemoryStream(file.Bytes)));
      // 解析済みドキュメントリストを保存する
      item.Documents.Add(document.Id, doc);
   }
   result.Add(item.Id, item);
}

タスクを後続処理に送信する

var ids = new FlexiCapture.docIds();
foreach (var rejectedDocument in rejectedDocuments)
{
   ids.Add(rejectedDocument.Id);
}
if (ids.Count > 0)
{
   _client.CreateTask(_sessionId, batchId, _exceptionsStageId, 0, "Rejection reason", 0, ids, false);
}
_client.OpenBatch(_sessionId, batchId);
var hasDocuments = false;
try
{
   var uri = _client.Endpoint.Address.Uri.OriginalString.Replace("/API/v1/Soap", "/FileService/v1");
   foreach (var document in acceptedDocuments)
   {
      hasDocuments = true;
      var buffer = new byte[SignatureSize]; // ドキュメントに追加されるデジタル署名のサイズ: 1024
      _rng.GetBytes(buffer);
      //DocumentAttachment: 添付ファイルの型 (9 - ドキュメント添付ファイル)
      _client.SaveAttachment(_sessionId, DocumentAttachment, document.Id, batchId, _projectId, new FlexiCapture.File
      {
         Bytes = buffer,
         Name = "Signature.dat"
      });
      document.CreateStamp();
      UploadTextFileToServer(new Uri(uri),
         _client.ClientCredentials.UserName.UserName,
         _client.ClientCredentials.UserName.Password,
         document.GetXml(), 0, _sessionId, _projectId,
         batchId, 0, document.Id, 0, "DocumentBody"
      ).Wait();
   }
};
private static async Task<string> UploadTextFileToServer(Uri server, string login, string password,
        string stream, int objectType, int sessionId, int projectId, int batchId, int parentId,
        int objectId, int version, string streamName)
{
        var creds = CredentialCache.DefaultNetworkCredentials;
        if (!string.IsNullOrEmpty(login)) creds = new NetworkCredential(login, password);
        using (var handler = new HttpClientHandler { Credentials = creds })
        using (var client = new HttpClient(handler))
        {
                var encodedStreamName = Convert.ToBase64String(Encoding.Unicode.GetBytes(streamName));
                var content = new MultipartFormDataContent
                {
                        {new StringContent("Save"), "Action"},
                        {new StringContent(objectType.ToString()), "objectType"},
                        {new StringContent(sessionId.ToString()), "sessionId"},
                        {new StringContent(projectId.ToString()), "projectId"},
                        {new StringContent(batchId.ToString()), "batchId"},
                        {new StringContent(parentId.ToString()), "parentId"},
                        {new StringContent(objectId.ToString()), "objectId"},
                        {new StringContent(version.ToString()), "version"},
                        {new StringContent(encodedStreamName), "streamName"},
                        {new ByteArrayContent(Encoding.Unicode.GetBytes(stream)), "blob", "data.txt"}
                };
                var msg = client.PostAsync(server, content).Result;
                return await msg.Content.ReadAsStringAsync();
        }
}

セッションを終了する

_client.CloseProject(_sessionId, _projectId);
   _client.CloseSession(_sessionId);