// POST api/<controller>
        public SearchResult[] Post()
        {
            var httpPostedFile = HttpContext.Current.Request.Files["file"];

            if (httpPostedFile == null)
            {
                ThowError("No file uploaded.");
                return(null);
            }

            string baseFileName = System.IO.Path.GetFileName(httpPostedFile.FileName);

            byte[] fileBytes = PdfHelper.ReadFully(httpPostedFile.InputStream);
            string content   = PdfHelper.GetTextFromPdfBytes(fileBytes);

            if (string.IsNullOrEmpty(content))
            {
                ThowError("No content found for file: " + baseFileName);
                return(null);
            }

            // Save original file
            string fileUrl = AzureStorageHelper.UploadBlob(fileBytes, baseFileName);

            if (string.IsNullOrEmpty(fileUrl))
            {
                ThowError("Could not upload file to azure.");
                return(null);
            }

            // Add to index
            SearchDocument document = new SearchDocument
            {
                DocId       = Guid.NewGuid().ToString(),
                Content     = content,
                DocFileName = baseFileName,
                DocUrl      = fileUrl,
                InsertDate  = DateTime.UtcNow
            };

            if (!AzureSearchHelper.InsertDocument(document))
            {
                ThowError("Could not add document to the index. If this is the first time you are using the index you need to click on the 'Delete all documents and rebuild index button' first.");
            }

            return(AzureSearchHelper.CategorizeDocument(document.DocId));
        }
Example #2
0
    protected void bt_Click(object sender, EventArgs e)
    {
        try
        {
            StringBuilder sb  = new StringBuilder();
            Button        btn = sender as Button;
            switch (btn.ID)
            {
            case "btnCreateIndex":     //Create the index in Azure Saerch
                Uri uri = new Uri(_serviceUri, "/indexes/" + this.AzureSearchServiceIndexName);
                HttpResponseMessage response = AzureSearchHelper.SendSearchRequest(_httpClient, HttpMethod.Get, uri);
                if (response.StatusCode == HttpStatusCode.NotFound)
                {
                    CreateCatalogIndex();
                    sb.Append("Index created!");
                }
                else
                {
                    sb.Append("Index exists!");
                }
                break;

            case "btnLoadIndex":     //Populate the Azure Search Index
                LoadIndex();
                sb.Append("Index data loaded!");
                break;

            case "btnSearch":     //Search against the Azure Search
                sb.Append(SearchIndex(ValidationHelper.GetString(txtSearch.Text, "")));
                break;

            case "btnReset":     //Do a whole lot of nothing, but make things look nice.
                txtSearch.Text = "";
                sb.Clear();
                break;
            }
            lblResults.Text = sb.ToString();
        }
        catch (Exception ex)
        {
            lblResults.Text = ex.Message;
        }
    }
Example #3
0
    /// <summary>
    /// This function will return a formatted string of the documents mathcing the specified search value
    /// </summary>
    /// <param name="strValue">string - Search value</param>
    /// <returns>string - Some totally awesome search results</returns>
    private string SearchIndex(string strValue)
    {
        StringBuilder sb = new StringBuilder();

        try
        {
            //Build up the search parameter
            string search = "&search=" + Uri.EscapeDataString(strValue);

            //Get the Azure Search records for the specified value
            if (strValue.Length > 2)
            {
                Uri uri = new Uri(_serviceUri, "/indexes/" + this.AzureSearchServiceIndexName + "/docs/suggest?" + search);
                HttpResponseMessage response = AzureSearchHelper.SendSearchRequest(_httpClient, HttpMethod.Get, uri);
                AzureSearchHelper.EnsureSuccessfulSearchResponse(response);

                dynamic results = AzureSearchHelper.DeserializeJson <dynamic>(response.Content.ReadAsStringAsync().Result);

                //Create a list of the results so we can loop over them and find the assoicated document
                IEnumerable <AzureResultItem> items = ((JArray)results["value"]).Select(x => new AzureResultItem
                {
                    documentid   = (string)x["DocumentID"],
                    documentname = (string)x["@search.text"]
                }).ToList();

                foreach (AzureResultItem item in items)
                {
                    sb.Append(item.documentname + "<br />");
                    var doc = DocumentHelper.GetDocument(ValidationHelper.GetInteger(item.documentid, 0), null);
                    sb.Append("<a href=\"~" + doc.NodeAliasPath + "\">" + doc.NodeAliasPath + "</a><br /><br />");
                }
            }
            else
            {
                sb.Append("You must enter atleast 3 characters.");
            }
        }
        catch (Exception ex)
        {
            sb.Append(ex.Message);
        }
        return(sb.ToString());
    }
Example #4
0
        public override async Task <EkKioskAutocompleteOptionsGetResponse> ExecuteAsync(EkKioskAutocompleteOptionsGetRequest request)
        {
            if (string.IsNullOrEmpty(request.Term) ||
                request.SearchType != EkSearchTypeEnum.Name)
            {
                return(new EkKioskAutocompleteOptionsGetResponse()
                {
                    AutocompleteOptions = new string[0],
                });
            }

            // cancellation token
            var cancellationToken = _httpContextAccessor.HttpContext?.RequestAborted ?? CancellationToken.None;

            using (var searchIndexClient = AzureSearchHelper.CreateSearchIndexClient(_ekSearchSettings.ServiceName, _ekSearchSettings.QueryKey))
            {
                searchIndexClient.IndexName = _ekSearchSettings.ProductsIndexName;

                var autocompleteParameters = new AutocompleteParameters()
                {
                    // todo: request by OneTermWithContext first, only then by OneTerm (if not enough results)
                    AutocompleteMode = AutocompleteMode.OneTerm,
                    UseFuzzyMatching = true,
                    Top          = 10,
                    SearchFields = EkKioskProductSearchByNameGet.GetLanguageSpecificTextFields(request.LanguageCode),
                };

                var autocompleteResult = await searchIndexClient.Documents.AutocompleteAsync(
                    request.Term,
                    SearchConstants.SuggesterName,
                    autocompleteParameters,
                    cancellationToken : cancellationToken);

                var autocompleteOptions = autocompleteResult.Results
                                          .Select(x => x.Text)
                                          .ToArray();

                return(new EkKioskAutocompleteOptionsGetResponse()
                {
                    AutocompleteOptions = autocompleteOptions,
                });
            }
        }
Example #5
0
    /// <summary>
    /// This function will load the index with documents for the current site
    /// </summary>
    /// <returns>string - Results response.</returns>
    private string LoadIndex()
    {
        try
        {
            // Get documents
            var documents = DocumentHelper.GetDocuments()
                            .Types("CMS.MenuItem", "CMS.Folder")
                            .OnSite(CurrentSiteName);

            StringBuilder sb = new StringBuilder();

            sb.Append("{");
            sb.Append("\"value\": [");
            int i = 1;
            foreach (var document in documents)
            {
                sb.Append("{");
                sb.Append("\"@search.action\":\"mergeOrUpload\",");
                sb.Append("\"DocumentID\":\"" + document.DocumentID + "\",");
                sb.Append("\"DocumentName\":\"" + document.DocumentName + "\"");
                sb.Append("}");
                if (i < documents.Count)
                {
                    sb.Append(",");
                }
                i += 1;
            }
            sb.Append("]");
            sb.Append("}");

            Uri    uri  = new Uri(_serviceUri, "/indexes/" + this.AzureSearchServiceIndexName + "/docs/index");
            string json = sb.ToString();
            HttpResponseMessage response = AzureSearchHelper.SendSearchRequest(_httpClient, HttpMethod.Post, uri, json);
            response.EnsureSuccessStatusCode();

            return("Index data loaded");
        }
        catch (Exception ex)
        {
            return("Index data not created.<br />" + ex.Message);
        }
    }
Example #6
0
        public ActionResult HandleSearchForm(AzureSearchViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(CurrentUmbracoPage());
            }

            string searchPhrase = model.SearchPhrase;

            // If blank search, assume they want to search everything
            if (string.IsNullOrWhiteSpace(searchPhrase))
            {
                searchPhrase = "*";
            }
            model.SearchResult = AzureSearchHelper.Search(searchPhrase);

            //Set the data that will be used in the view
            TempData["AzureSearchViewModel"] = model;

            //All done - redirect to the current page
            return(RedirectToCurrentUmbracoPage());
        }
        public override async Task <EkKioskProductAndReplacementsByPartNumberGetResponse> ExecuteAsync(EkKioskProductAndReplacementsByPartNumberGetRequest request)
        {
            Assure.ArgumentNotNull(request.PartNumberBrand, nameof(request.PartNumberBrand));
            Assure.ArgumentNotNull(request.PartNumberBrand.ProductKey, nameof(request.PartNumberBrand.ProductKey));
            Assure.ArgumentNotNull(request.PartNumberBrand.PartNumber, nameof(request.PartNumberBrand.PartNumber));

            var response = new EkKioskProductAndReplacementsByPartNumberGetResponse();

            // cancellation token
            var cancellationToken = _httpContextAccessor.HttpContext?.RequestAborted ?? CancellationToken.None;

            using (var searchIndexClient = AzureSearchHelper.CreateSearchIndexClient(_ekSearchSettings.ServiceName, _ekSearchSettings.QueryKey))
            {
                searchIndexClient.IndexName = _ekSearchSettings.ProductsIndexName;

                // FIND PRODUCT
                try
                {
                    var indexProduct = await searchIndexClient.Documents.GetAsync <IndexProduct>(
                        request.PartNumberBrand.ProductKey,
                        cancellationToken : cancellationToken);

                    response.Product = EkConvertHelper.EkNewIndexProductToProduct(indexProduct);

                    // todo: add search by Brand/PartNumber to find all direct matches since many products sources are supported
                    // it's not done since new product search model is planned anyway
                }
                catch (CloudException)
                {
                    response.Product = EkConvertHelper.EkOmegaPartNumberBrandToProduct(request.PartNumberBrand);
                }

                // FIND REPLACEMENTS
                var cleanedPartNumber = PartNumberCleaner.GetCleanedPartNumber(request.PartNumberBrand.PartNumber);

                // TecDoc replacements
                // todo: add cancellationToken support to proxy based clients
                var tecDocReplacements = await _tecDocWsClient.SearchByArticleNumberAsync(cleanedPartNumber);

                tecDocReplacements = tecDocReplacements
                                     // except direct match
                                     .Where(x => x.NumberType != ArticleNumberTypeEnum.ArticleNumber)
                                     .ToArray();

                var replacementCleanedBrandPartNumbers = tecDocReplacements
                                                         .Select(x => PartNumberCleaner.GetCleanedBrandPartNumber(x.BrandName, x.ArticleNo))
                                                         .Take(100)
                                                         .ToArray();

                if (replacementCleanedBrandPartNumbers.Length > 0)
                {
                    var replacementsIndexSearchParameters = new SearchParameters()
                    {
                        Top          = 100,
                        SearchFields = new[] { "cleanedBrandPartNumber" },
                    };
                    var searchTerm   = string.Join("|", replacementCleanedBrandPartNumbers);
                    var searchResult = await searchIndexClient.Documents.SearchAsync <IndexProduct>(
                        searchTerm,
                        replacementsIndexSearchParameters,
                        cancellationToken : cancellationToken);

                    response.Replacements = searchResult.Results
                                            .Select(x => EkConvertHelper.EkNewIndexProductToProduct(x.Document))
                                            .ToArray();
                }
                else
                {
                    response.Replacements = new EkProduct[0];
                }

                return(response);
            }
        }
 // DELETE api/<controller>
 public void Delete(string id)
 {
     AzureSearchHelper.DeleteDocById(id);
 }
        // POST api/<controller>
        public SearchResult[] Post(SearchRequest request)
        {
            var result = AzureSearchHelper.DoSearch(request);

            return(result);
        }
Example #10
0
 public void AddCategory(string docId, [FromBody] string categoryName)
 {
     AzureSearchHelper.AddDocumentCategory(docId, categoryName);
 }
Example #11
0
 public void RemoveCategory(string docId, [FromBody] string categoryName)
 {
     AzureSearchHelper.RemoveDocumentCategory(docId, categoryName);
 }
Example #12
0
 public SearchResult[] Recategorize(string docId)
 {
     // Recategorize doc
     return(AzureSearchHelper.CategorizeDocument(docId));
 }
Example #13
0
 // DELETE api/<controller>
 public void Delete()
 {
     AzureSearchHelper.ResetIndexes();
 }
Example #14
0
        public dynamic Search(string searchText, string sort, string category, string department, string portfolio, string brandName)
        {
            string search = "&search=" + Uri.EscapeDataString(searchText);
            string facets = "&facet=L3_NAME&facet=L1_NAME&facet=L2_NAME&facet=BRAND_NAME";

            string paging = "&$top=100";

            string filter  = String.Empty;
            string orderby = String.Empty;

            string[] depList = department.Split(',');

            if (!string.IsNullOrWhiteSpace(department))
            {
                foreach (String d in depList)
                {
                    if (!String.IsNullOrEmpty(d))
                    {
                        if (string.IsNullOrEmpty(filter))
                        {
                            filter += "&$filter=(L1_NAME eq '" + EscapeODataString(d) + "'";
                        }
                        else
                        {
                            filter += " or L1_NAME eq '" + EscapeODataString(d) + "'";
                        }
                    }
                }

                if (!string.IsNullOrEmpty(filter))
                {
                    filter += ")";
                }
            }


            if (!string.IsNullOrWhiteSpace(category))
            {
                filter += "&$filter=L3_NAME eq '" + EscapeODataString(category) + "'";
            }


            string[] brandList = brandName.Split(',');

            if (!string.IsNullOrWhiteSpace(brandName.Replace(',', ' ').Trim()))
            {
                foreach (String b in brandList)
                {
                    if (!String.IsNullOrEmpty(b))
                    {
                        if (string.IsNullOrEmpty(filter))
                        {
                            filter += "&$filter=(BRAND_NAME eq '" + EscapeODataString(b) + "'";
                        }
                        else
                        {
                            if (b == brandList[0])
                            {
                                filter += " and (BRAND_NAME eq '" + EscapeODataString(b) + "'";
                            }
                            else
                            {
                                filter += " or BRAND_NAME eq '" + EscapeODataString(b) + "'";
                            }
                        }
                    }
                }

                if (!string.IsNullOrEmpty(filter))
                {
                    filter += ")";
                }
            }

            Uri uri = new Uri(_serviceUri, "/indexes/dpg/docs?$count=true" + search + facets + paging + filter + orderby);

            HttpResponseMessage response = AzureSearchHelper.SendSearchRequest(_httpClient, HttpMethod.Get, uri);

            AzureSearchHelper.EnsureSuccessfulSearchResponse(response);

            var result = AzureSearchHelper.DeserializeJson <dynamic>(response.Content.ReadAsStringAsync().Result);

            return(result);
        }
 public string CreateIndex()
 {
     return(AzureSearchHelper.CreateIndex());
 }
Example #16
0
        public override async Task <EkKioskProductSearchByCategoryGetResponse> ExecuteAsync(EkKioskProductSearchByCategoryGetRequest request)
        {
            var response = new EkKioskProductSearchByCategoryGetResponse();

            // cancellation token
            var cancellationToken = _httpContextAccessor.HttpContext?.RequestAborted ?? CancellationToken.None;

            // todo: add cancellationToken support to proxy based clients

            // determine TecDoc car type of modification first
            CarTypeEnum carType;
            // request categories for cars first
            var categories = await _tecDocWsClient.GetCategoriesAsync(CarTypeEnum.Car, request.ModificationId, null, childNodes : false);

            if (categories?.Length > 0)
            {
                carType = CarTypeEnum.Car;
            }
            else
            {
                // then request for trucks
                categories = await _tecDocWsClient.GetCategoriesAsync(CarTypeEnum.Truck, request.ModificationId, null, childNodes : false);

                if (categories?.Length > 0)
                {
                    carType = CarTypeEnum.Truck;
                }
                else
                {
                    return(response);
                }
            }

            const int MaxProductCount = 200;

            // TecDoc articles
            var tecDocProducts = await _tecDocWsClient.GetArticlesCompactInfoAsync(carType, request.ModificationId, request.CategoryId);

            var productCleanedBrandPartNumbers = tecDocProducts
                                                 .Select(x => PartNumberCleaner.GetCleanedBrandPartNumber(x.BrandName, x.ArticleNo))
                                                 .Take(MaxProductCount)
                                                 .ToArray();

            if (productCleanedBrandPartNumbers.Length == 0)
            {
                return(response);
            }

            // FIND PRODUCTS IN STOCK
            using (var searchIndexClient = AzureSearchHelper.CreateSearchIndexClient(_ekSearchSettings.ServiceName, _ekSearchSettings.QueryKey))
            {
                searchIndexClient.IndexName = _ekSearchSettings.ProductsIndexName;

                var replacementsIndexSearchParameters = new SearchParameters()
                {
                    Top          = MaxProductCount,
                    SearchFields = new[] { "cleanedBrandPartNumber" },
                };
                var searchTerm   = string.Join("|", productCleanedBrandPartNumbers);
                var searchResult = await searchIndexClient.Documents.SearchAsync <IndexProduct>(
                    searchTerm,
                    replacementsIndexSearchParameters,
                    cancellationToken : cancellationToken);

                response.Products = searchResult.Results
                                    .Select(x => EkConvertHelper.EkNewIndexProductToProduct(x.Document))
                                    .ToArray();

                return(response);
            }
        }
        public override async Task <EkKioskProductSearchByNameGetResponse> ExecuteAsync(EkKioskProductSearchByNameGetRequest request)
        {
            if (string.IsNullOrEmpty(request.Term) ||
                request.Term.Length < 3)
            {
                return(new EkKioskProductSearchByNameGetResponse()
                {
                    Products = new EkProduct[0],
                });
            }

            // cancellation token
            var cancellationToken = _httpContextAccessor.HttpContext?.RequestAborted ?? CancellationToken.None;

            using (var searchIndexClient = AzureSearchHelper.CreateSearchIndexClient(_ekSearchSettings.ServiceName, _ekSearchSettings.QueryKey))
            {
                searchIndexClient.IndexName = _ekSearchSettings.ProductsIndexName;

                // paging
                var indexSearchParameters = new SearchParameters()
                {
                    Skip = request.From,
                    Top  = request.Count,
                    IncludeTotalResultCount = request.IncludeTotal,
                    SearchFields            = GetLanguageSpecificTextFields(request.LanguageCode),
                    ScoringProfile          = SearchConstants.BoostNameScoringProfileName,
                };

                // sorting
                switch (request.Sorting)
                {
                case EkProductSearchSortingEnum.PriceAscending:
                    indexSearchParameters.OrderBy = new[] { "price asc" };
                    break;

                case EkProductSearchSortingEnum.PriceDescending:
                    indexSearchParameters.OrderBy = new[] { "price desc" };
                    break;

                case EkProductSearchSortingEnum.Default:
                default:
                    // no sorting
                    break;
                }

                // term
                var term = request.Term;

                var searchResult = await searchIndexClient.Documents.SearchAsync <IndexProduct>(
                    term,
                    indexSearchParameters,
                    cancellationToken : cancellationToken);

                var products = searchResult.Results
                               .Select(x => EkConvertHelper.EkNewIndexProductToProduct(x.Document))
                               .ToArray();
                var total = searchResult.Count ?? 0;

                return(new EkKioskProductSearchByNameGetResponse()
                {
                    Products = products,
                    Total = total,
                });
            }
        }
 public SearchResult[] MoreLikeThis(string docId)
 {
     return(AzureSearchHelper.MoreLikeThis(docId));
 }