2017-03-27 16 views
1

그래서 나는 documentdb에 대해 microsoft에서 제공 한 샘플 코드에있는이 메서드를 호출하지만 새로운 저장 프로 시저를 만들려고 할 때 null 응답을 얻습니다.CreateStoredProcedureAsync에서 빈 응답 documentdb

private static async Task RunBulkImport(string collectionLink) 
    { 


     string Datafilepath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Data"); 
     string inputDirectory = Datafilepath; 
     string inputFileMask = "*.json"; 
     int maxFiles = 2000; 
     int maxScriptSize = 50000; 

     // 1. Get the files. 
     string[] fileNames = Directory.GetFiles(inputDirectory, inputFileMask); 
     DirectoryInfo di = new DirectoryInfo(inputDirectory); 
     FileInfo[] fileInfos = di.GetFiles(inputFileMask); 

     // 2. Prepare for import. 
     int currentCount = 0; 
     int fileCount = maxFiles != 0 ? Math.Min(maxFiles, fileNames.Length) : fileNames.Length; 

     // 3. Create stored procedure for this script. 
     string procedurepath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"SP\BulkImport.js"); 
     string body = File.ReadAllText(procedurepath); 
     StoredProcedure sproc = new StoredProcedure 
     { 
      Id = "BulkImport", 
      Body = body 
     }; 

     await TryDeleteStoredProcedure(collectionLink, sproc.Id); 
     sproc = await client.CreateStoredProcedureAsync(collectionLink, sproc); 

     while (currentCount < fileCount) 
     { 
      // 5. Create args for current batch. 
      // Note that we could send a string with serialized JSON and JSON.parse it on the script side, 
      // but that would cause script to run longer. Since script has timeout, unload the script as much 
      // as we can and do the parsing by client and framework. The script will get JavaScript objects. 
      string argsJson = CreateBulkInsertScriptArguments(fileNames, currentCount, fileCount, maxScriptSize); 
      var args = new dynamic[] { JsonConvert.DeserializeObject<dynamic>(argsJson) }; 

      // 6. execute the batch. 
      StoredProcedureResponse<int> scriptResult = await client.ExecuteStoredProcedureAsync<int>(
       sproc.SelfLink, 
       new RequestOptions { PartitionKey = new PartitionKey("Andersen") }, 
       args); 

      // 7. Prepare for next batch. 
      int currentlyInserted = scriptResult.Response; 
      currentCount += currentlyInserted; 
     } 

     // 8. Validate 
     int numDocs = 0; 
     string continuation = string.Empty; 
     do 
     { 
      // Read document feed and count the number of documents. 
      FeedResponse<dynamic> response = await client.ReadDocumentFeedAsync(collectionLink, new FeedOptions { RequestContinuation = continuation }); 
      numDocs += response.Count; 

      // Get the continuation so that we know when to stop. 
      continuation = response.ResponseContinuation; 
     } 
     while (!string.IsNullOrEmpty(continuation)); 

     Console.WriteLine("Found {0} documents in the collection. There were originally {1} files in the Data directory\r\n", numDocs, fileCount); 
    } 


    private static async Task TryDeleteStoredProcedure(string collectionLink, string sprocId) 
    { 
     StoredProcedure sproc = client.CreateStoredProcedureQuery(collectionLink).Where(s => s.Id == sprocId).AsEnumerable().FirstOrDefault(); 
     if (sproc != null) 
     { 
      await client.DeleteStoredProcedureAsync(sproc.SelfLink); 
     } 
    } 

    private static string CreateBulkInsertScriptArguments(string[] docFileNames, int currentIndex, int maxCount, int maxScriptSize) 
    { 
     var jsonDocumentArray = new StringBuilder(); 
     jsonDocumentArray.Append("["); 

     if (currentIndex >= maxCount) return string.Empty; 
     jsonDocumentArray.Append(File.ReadAllText(docFileNames[currentIndex])); 

     int scriptCapacityRemaining = maxScriptSize; 
     string separator = string.Empty; 

     int i = 1; 
     while (jsonDocumentArray.Length < scriptCapacityRemaining && (currentIndex + i) < maxCount) 
     { 
      jsonDocumentArray.Append(", " + File.ReadAllText(docFileNames[currentIndex + i])); 
      i++; 
     } 

     jsonDocumentArray.Append("]"); 
     return jsonDocumentArray.ToString(); 
    } 

그리고 여기가 itself.Kindly 새로운 프로 시저를 만들 수 내게 도움이 BulkImport.js이

function bulkImport(docs) { 
var collection = getContext().getCollection(); 
var collectionLink = collection.getSelfLink(); 

    //count used as doc index 
var count = 0; 

// Validate input 
if (!docs) throw new Error("The array is undefined or null."); 

var docsLength = docs.length; 
if (docsLength == 0) { 
    getContext().getResponse().setBody(0); 
} 

// CRUD API to create a document. 
tryCreate(docs[count], callback); 

function tryCreate(doc, callback) { 
    var options = { 
     disableAutomaticIdGeneration: true 
    }; 

    var isAccepted = collection.createDocument(collectionLink, doc, options, callback); 

    if (!isAccepted) getContext().getResponse().setBody(count); 
} 

function callback(err, doc, options) { 
    if (err) throw err; 
    count++; 

    if (count >= docsLength) { 
      getContext().getResponse().setBody(count); 
    } else { 

     tryCreate(docs[count], callback); 
    } 
} 
} 

파일 및 데이터 폴더에 내가 샘플에 제공된 100 개 JSON 파일이입니다 난 documentdb 에뮬레이터를 사용하고 있습니다.

답변

0

documentdb 에뮬레이터를 사용하여 새 절차를 만들 수 있습니다. 아시다시피 현재 documentDB Emulator exploer로 저장 프로 시저를 실행하는 것은 지원되지 않습니다.

1.Download documentdb-emulator 로컬 시스템

2.Download GitHub의에서 문서 demo code에 설치 : 내 세부 단계입니다 다음.

3. 우리

document에서 지역 documentdb 계정 마스터 키를 얻을, 프로젝트

DocumentDB 에뮬레이터는 하나의 고정 된 계정과 잘 알려진 마스터 키를 지원에 추가 할 수 있습니다. 키 재생은 DB 및 수집

enter image description here

enter image description here

5.Execute을 만들 수 DocumentDB 에뮬레이터

// Connect to the DocumentDB Emulator running locally 

    DocumentClient client = new DocumentClient(new Uri("https://localhost:8081"),"C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="); 

enter image description here

4.Open documentdb 에뮬레이터 수 없습니다 데모 코드 및 확인 푸른 에뮬레이터 착취 자로부터의 결과.

enter image description here

enter image description here

참고 : 스크린 샷에 따르면, 우리가 찾을 수있을 푸른 documentdb 에뮬레이터를 사용하여 선택한 프로 시저 탭에 아무런 입력 또는 결과 필드.

우리가 푸른 documentdb를 사용하는 경우는 우리는 하늘빛 documentdb와 푸른 포털에서 절차를 실행 할 수 있습니다.

enter image description here

우리가 documentdb 에뮬레이터에 대한 문제가 있다면 우리는 documentdb 에뮬레이터 exploer에 클릭 피드백에 의해 우리의 피드백에게 푸른 documentdb 팀을 제공 할 수 있습니다. 그것에 대해

enter image description here

+0

감사하지만이 가능 같은 사용하여 C# 코드를 실행하는 경우, 내가 createstoredprocedure를 사용하는 동안 내가 널 반응을 얻고있는 이유는 말해 줄 수 수?또한 나는 그것을 사용하는 정확한 시간을 알 수 있습니다 파티션을 사용하여 U를 참조하십시오? – Melvin

+0

mothod를 호출하는 방법에 대한 자세한 정보를 제공해 주시겠습니까? RunDemoAsync (DatabaseName, CollectionName) .Wait(); ? –

+0

[github] (https://github.com/Azure/azure-documentdb-dotnet)에서 최신 데모 코드를 받았습니다. 콜렉션을 생성하고 파티션 키를 스크린 샷으로 추가 할 때. **/성 **은 데모 코드의 값입니다. –