private static string CreateMessage(DocumentIndexResponse indexResponse)
        {
            if (indexResponse == null)
            {
                throw new ArgumentNullException("indexResponse");
            }

            return String.Format(
                MessageFormat, 
                indexResponse.Results.Count(r => !r.Succeeded),
                indexResponse.Results.Count);
        }
        private static string CreateMessage(DocumentIndexResponse indexResponse)
        {
            if (indexResponse == null)
            {
                throw new ArgumentNullException("indexResponse");
            }

            return(String.Format(
                       MessageFormat,
                       indexResponse.Results.Count(r => !r.Succeeded),
                       indexResponse.Results.Count));
        }
Ejemplo n.º 3
0
        public void IndexDoesNotThrowWhenAllActionsSucceed()
        {
            Run(() =>
            {
                SearchIndexClient client = Data.GetSearchIndexClient();

                var batch = IndexBatch.Create(new[] { IndexAction.Create(new Hotel()
                    {
                        HotelId = "1"
                    }) });

                DocumentIndexResponse indexResponse = client.Documents.Index(batch);
                Assert.Equal(HttpStatusCode.OK, indexResponse.StatusCode);

                Assert.Equal(1, indexResponse.Results.Count);
                AssertIndexActionSucceeded("1", indexResponse.Results[0]);
            });
        }
Ejemplo n.º 4
0
        public void CanIndexWithPascalCaseFields()
        {
            Run(() =>
            {
                SearchServiceClient serviceClient = Data.GetSearchServiceClient();

                Index index =
                    new Index()
                {
                    Name   = TestUtilities.GenerateName(),
                    Fields = new[]
                    {
                        new Field("ISBN", DataType.String)
                        {
                            IsKey = true
                        },
                        new Field("Title", DataType.String),
                        new Field("Author", DataType.String)
                    }
                };

                IndexDefinitionResponse createIndexResponse = serviceClient.Indexes.Create(index);
                Assert.Equal(HttpStatusCode.Created, createIndexResponse.StatusCode);

                SearchIndexClient indexClient = Data.GetSearchIndexClient(createIndexResponse.Index.Name);

                var batch =
                    IndexBatch.Create(
                        new[]
                {
                    IndexAction.Create(
                        new Book()
                    {
                        ISBN = "123", Title = "Lord of the Rings", Author = "J.R.R. Tolkien"
                    })
                });

                DocumentIndexResponse indexResponse = indexClient.Documents.Index(batch);
                Assert.Equal(HttpStatusCode.OK, indexResponse.StatusCode);

                Assert.Equal(1, indexResponse.Results.Count);
                AssertIndexActionSucceeded("123", indexResponse.Results[0]);
            });
        }
        /// <summary>
        /// Initializes a new instance of the IndexBatchException class.
        /// </summary>
        /// <param name="httpRequest">The original HTTP index request.</param>
        /// <param name="httpResponse">The original HTTP index response.</param>
        /// <param name="indexResponse">The deserialized response from the index request.</param>
        public IndexBatchException(
            HttpRequestMessage httpRequest, 
            HttpResponseMessage httpResponse, 
            DocumentIndexResponse indexResponse) : base(CreateMessage(indexResponse))
        {
            // Null check in CreateMessage().
            _indexResponse = indexResponse;

            Error =
                new CloudError()
                {
                    Code = String.Empty,
                    Message = this.Message,
                    OriginalMessage = this.Message,
                    ResponseBody = String.Empty
                };

            Request = CloudHttpRequestErrorInfo.Create(httpRequest);
            Response = CloudHttpResponseErrorInfo.Create(httpResponse);
        }
        /// <summary>
        /// Initializes a new instance of the IndexBatchException class.
        /// </summary>
        /// <param name="httpRequest">The original HTTP index request.</param>
        /// <param name="httpResponse">The original HTTP index response.</param>
        /// <param name="indexResponse">The deserialized response from the index request.</param>
        public IndexBatchException(
            HttpRequestMessage httpRequest,
            HttpResponseMessage httpResponse,
            DocumentIndexResponse indexResponse) : base(CreateMessage(indexResponse))
        {
            // Null check in CreateMessage().
            _indexResponse = indexResponse;

            Error =
                new CloudError()
            {
                Code            = String.Empty,
                Message         = this.Message,
                OriginalMessage = this.Message,
                ResponseBody    = String.Empty
            };

            Request  = CloudHttpRequestErrorInfo.Create(httpRequest);
            Response = CloudHttpResponseErrorInfo.Create(httpResponse);
        }
Ejemplo n.º 7
0
        static void Main(string[] args)
        {
            string searchServiceName = args[0];
            var    credentials       = new SearchCredentials(args[1]);
            var    searchClient      = new SearchServiceClient(searchServiceName, credentials);

            try
            {
                IndexDefinitionResponse getResponse = searchClient.Indexes.Get(IndexName);
                if (getResponse?.Index != null)
                {
                    Console.WriteLine("Deleting and recreating index " + IndexName);
                    searchClient.Indexes.Delete(IndexName);
                }
            }
            catch (CloudException)
            {
                // We expect this if the index does not yet exist.
            }

            IndexDefinitionResponse createIndexResponse = searchClient.Indexes.Create(new Index(
                                                                                          IndexName,
                                                                                          new[]
            {
                new Field("ItemId", DataType.String)
                {
                    IsKey = true
                },
                new Field("Title", DataType.String)
                {
                    IsSearchable = true
                },
                new Field("Content", DataType.String)
                {
                    IsSearchable = true
                },
                new Field("CommentThreadId", DataType.Int32),
                new Field("TimelineEntryId", DataType.Int32),
                new Field("MediaAlbumId", DataType.Int32),
                new Field("UserMediaId", DataType.Int32)
            }));

            Index index       = createIndexResponse.Index;
            var   indexClient = new SearchIndexClient(searchServiceName, IndexName, credentials);

            using (var dbContext = new ApplicationDbContext(args[2]))
            {
                IEnumerable <TimelineEntry> timelineEntries = dbContext.TimelineEntries
                                                              .Include(te => te.Message)
                                                              .Include(te => te.CommentThread.Comments.Select(c => c.Text));

                foreach (TimelineEntry entry in timelineEntries)
                {
                    var batchActions = new List <IndexAction <MessageIndexEntry> >();

                    batchActions.Add(new IndexAction <MessageIndexEntry>(
                                         IndexActionType.Upload,
                                         new MessageIndexEntry
                    {
                        ItemId          = "timeline-" + entry.TimelineEntryId,
                        Content         = entry.Message.Content,
                        TimelineEntryId = entry.TimelineEntryId
                    }));

                    if (entry.CommentThread != null)
                    {
                        foreach (Comment comment in entry.CommentThread.Comments)
                        {
                            batchActions.Add(new IndexAction <MessageIndexEntry>(
                                                 IndexActionType.Upload,
                                                 new MessageIndexEntry
                            {
                                ItemId          = "comment-" + comment.CommentId,
                                Content         = comment.Text.Content,
                                TimelineEntryId = entry.TimelineEntryId,
                                CommentThreadId = comment.CommentThreadId
                            }));
                        }
                    }
                    var batch = new IndexBatch <MessageIndexEntry>(batchActions);
                    DocumentIndexResponse indexDocumentsResponse = indexClient.Documents.Index(batch);
                }

                IEnumerable <MediaAlbum> albums = dbContext.MediaAlbums
                                                  .Include(a => a.CommentThread.Comments.Select(c => c.Text));

                foreach (MediaAlbum album in albums)
                {
                    var batchActions = new List <IndexAction <MessageIndexEntry> >();

                    batchActions.Add(new IndexAction <MessageIndexEntry>(
                                         IndexActionType.Upload,
                                         new MessageIndexEntry
                    {
                        ItemId       = "album-" + album.MediaAlbumId,
                        Title        = album.Title,
                        Content      = album.Description,
                        MediaAlbumId = album.MediaAlbumId
                    }));

                    if (album.CommentThread != null)
                    {
                        foreach (Comment comment in album.CommentThread.Comments)
                        {
                            batchActions.Add(new IndexAction <MessageIndexEntry>(
                                                 IndexActionType.Upload,
                                                 new MessageIndexEntry
                            {
                                ItemId          = "comment-" + comment.CommentId,
                                Content         = comment.Text.Content,
                                MediaAlbumId    = album.MediaAlbumId,
                                CommentThreadId = comment.CommentThreadId
                            }));
                        }
                    }
                    var batch = new IndexBatch <MessageIndexEntry>(batchActions);
                    DocumentIndexResponse indexDocumentsResponse = indexClient.Documents.Index(batch);
                }


                IEnumerable <UserMedia> medias = dbContext.UserMedias
                                                 .Include(m => m.Description)
                                                 .Include(m => m.CommentThread.Comments.Select(c => c.Text));

                foreach (UserMedia media in medias)
                {
                    var batchActions = new List <IndexAction <MessageIndexEntry> >();

                    batchActions.Add(new IndexAction <MessageIndexEntry>(
                                         IndexActionType.Upload,
                                         new MessageIndexEntry
                    {
                        ItemId       = "media-" + media.UserMediaId,
                        Title        = media.Title,
                        Content      = media.Description?.Content,
                        UserMediaId  = media.UserMediaId,
                        MediaAlbumId = media.MediaAlbumId
                    }));

                    if (media.CommentThread != null)
                    {
                        foreach (Comment comment in media.CommentThread.Comments)
                        {
                            batchActions.Add(new IndexAction <MessageIndexEntry>(
                                                 IndexActionType.Upload,
                                                 new MessageIndexEntry
                            {
                                ItemId          = "comment-" + comment.CommentId,
                                Content         = comment.Text.Content,
                                UserMediaId     = media.UserMediaId,
                                MediaAlbumId    = media.MediaAlbumId,
                                CommentThreadId = comment.CommentThreadId
                            }));
                        }
                    }
                    var batch = new IndexBatch <MessageIndexEntry>(batchActions);
                    DocumentIndexResponse indexDocumentsResponse = indexClient.Documents.Index(batch);
                }
            }
        }
        private async Task <DocumentIndexResponse> DoIndexAsync(string payload, CancellationToken cancellationToken)
        {
            // Validate
            if (payload == null)
            {
                throw new ArgumentNullException("payload");
            }

            // Tracing
            bool   shouldTrace  = TracingAdapter.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("payload", payload);
                TracingAdapter.Enter(invocationId, this, "IndexAsync", tracingParameters);
            }

            // Construct URL
            string url     = "docs/index?api-version=2015-02-28";
            string baseUrl = this.Client.BaseUri.AbsoluteUri;

            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }

            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

            try
            {
                httpRequest            = new HttpRequestMessage();
                httpRequest.Method     = HttpMethod.Post;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers
                httpRequest.Headers.Add("Accept", "application/json;odata.metadata=none");

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Serialize Request
                string requestContent = payload;
                httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
                httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK && statusCode != (HttpStatusCode)207)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    DocumentIndexResponse result = null;

                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    result = new DocumentIndexResponse();
                    if (string.IsNullOrEmpty(responseContent) == false)
                    {
                        var deserializedResult =
                            JsonConvert.DeserializeObject <DocumentIndexResponseFormat>(responseContent);
                        result.Results = new LazyList <IndexResult>(deserializedResult.Value);
                    }

                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }

                    if (result.StatusCode == (HttpStatusCode)207)
                    {
                        CloudException ex = new IndexBatchException(httpRequest, httpResponse, result);
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }