示例#1
0
        public ResultDocument <T> Set <T>(string key, T value, DateTime expireDate)
        {
            ResultDocument <T> resultDocument = new ResultDocument <T>
            {
                OperationType = ResultOperation.Insert,
                StartTime     = DateTime.Now,
                Type          = Type.Cache
            };

            _cacheObject.Set(
                new CacheItem(key, value, InMemoryCacheExtensions.CreateKeyWithRegion(key, _properties.RegionName)),
                new CacheItemPolicy
            {
                Priority          = _properties.Priority,
                SlidingExpiration = expireDate.AddMinutes(_properties.CacheDuration).TimeOfDay
            });

            var result = this.Get <T>(key);

            resultDocument.EndDatime = DateTime.Now;

            //if data is retrieved
            if (result.Status == ResultStatus.Success)
            {
                resultDocument.Result = result.Result;
                resultDocument.Status = ResultStatus.Success;
                return(resultDocument);
            }
            else
            {
                resultDocument.Result = default(T);
                resultDocument.Status = ResultStatus.Failed;
                return(resultDocument);
            }
        }
        public IEnumerable <IDocument> CreateDocuments(Partition partition)
        {
            if (partition == null)
            {
                throw new ArgumentNullException("partition");
            }

            var documents = new ConcurrentBag <IDocument>();

            var parallelOptions = new ParallelOptions {
                MaxDegreeOfParallelism = 5
            };

            Parallel.ForEach(partition.Keys, parallelOptions, key =>
            {
                //Trace.TraceInformation(string.Format("Processing documents starting {0} of {1} - {2}%", partition.Start, partition.Total, (partition.Start * 100 / partition.Total)));
                if (key != null)
                {
                    var doc = new ResultDocument();
                    IndexItem(ref doc, key);
                    documents.Add(doc);
                }
            });

            return(documents);
        }
示例#3
0
        public byte[] GetResultDocument(string GUID, string idLpu, string idCaseMis, int documentType)
        {
            ResultDocument a = client.GetResultDocument(GUID, idLpu, idCaseMis, documentType);

            byte[] b = {};
            using (SqlConnection connection = Global.GetSqlConnection())
            {
                string findPatient =
                    "SELECT TOP(1) Attachment FROM MedDocument, Step, \"Case\" WHERE IdMedDocumentType = '" +
                    documentType +
                    "' AND IdCaseMis = '" + idCaseMis + "' AND IdLpu <= '" + Global.GetIdInstitution(idLpu) +
                    "' AND MedDocument.IdStep = Step.IdStep AND Step.IdCase = \"Case\".IdCase ORDER BY IdMedDocument DESC";
                SqlCommand person = new SqlCommand(findPatient, connection);
                using (SqlDataReader documentReader = person.ExecuteReader())
                {
                    // bool a = documentReader.Read();
                    while (documentReader.Read())
                    {
                        b = (byte[])(documentReader["Attachment"]);
                    }
                }
            }
            if (!a.Data.SequenceEqual(b))
            {
                Global.errors1.Add("Несовпадение базового и возвращенного документов");
            }
            return(a.Data);
        }
示例#4
0
        public ResultDocument <T> Get <T>(string key)
        {
            ResultDocument <T> resultDocument = new ResultDocument <T>
            {
                OperationType = ResultOperation.Retrieve,
                StartTime     = DateTime.Now,
                Type          = Type.Cache
            };
            var itemResult = _cacheObject.Get(key);

            resultDocument.EndDatime = DateTime.Now;

            if (itemResult == null)
            {
                resultDocument.Result = default(T);
                resultDocument.Status = ResultStatus.Failed;
                return(resultDocument);
            }
            else
            {
                resultDocument.Result = (T)itemResult;
                resultDocument.Status = ResultStatus.Success;
                return(resultDocument);
            }
        }
示例#5
0
        public virtual IEnumerable <IDocument> CreateDocuments(Partition partition)
        {
            if (partition == null)
            {
                throw new ArgumentNullException("partition");
            }

            //Trace.TraceInformation(string.Format("Processing documents starting {0} of {1} - {2}%", partition.Start, partition.Total, (partition.Start * 100 / partition.Total)));

            var documents = new ConcurrentBag <IDocument>();

            if (!partition.Keys.IsNullOrEmpty())
            {
                var items  = GetItems(partition.Keys);
                var prices = GetItemPrices(partition.Keys);

                foreach (var item in items)
                {
                    var doc        = new ResultDocument();
                    var itemPrices = prices.Where(x => x.ProductId == item.Id).ToArray();
                    var index      = IndexItem(doc, item, itemPrices);

                    if (index)
                    {
                        documents.Add(doc);
                    }
                }
            }

            return(documents);
        }
示例#6
0
        public ResultDocument <T> Set <T>(string key, IEnumerable <T> value)
        {
            ResultDocument <T> resultDocument = new ResultDocument <T>
            {
                OperationType = ResultOperation.Insert,
                StartTime     = DateTime.Now,
                Type          = INGA.Framework.Managers.Common.Type.Cache
            };

            _cacheObject.Set(key, value);

            var result = this.Get <T>(key);

            resultDocument.EndDatime = DateTime.Now;

            //if data is retrieved
            if (result.Status == ResultStatus.Success)
            {
                resultDocument.Result = result.Result;
                resultDocument.Status = ResultStatus.Success;
                return(resultDocument);
            }
            else
            {
                resultDocument.Result = default(T);
                resultDocument.Status = ResultStatus.Failed;
                return(resultDocument);
            }
        }
        /// <summary>
        /// Creates the document from the partition source.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">
        /// source
        /// or
        /// source.Keys
        /// </exception>
        public IEnumerable <IDocument> CreateDocument(Partition source)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            if (source.Keys == null)
            {
                throw new ArgumentNullException("source.Keys");
            }


            var index = 0;

            Trace.TraceInformation(String.Format("Processing documents starting {0} of {1} - {2}%", source.Start, source.Total, (source.Start * 100 / source.Total)));
            foreach (var item in LoadItems(source.JobId, source.Keys))
            {
                var doc = new ResultDocument();
                IndexItem(ref doc, item);
                yield return(doc);

                index++;
            }
        }
        protected virtual void IndexItem(ref ResultDocument doc, Item item)
        {
            doc.Add(new DocumentField("__key", item.ItemId.ToLower(), new[] { IndexStore.YES, IndexType.NOT_ANALYZED }));
            //doc.Add(new DocumentField("__loc", "en-us", new[] { IndexStore.YES, IndexType.NOT_ANALYZED }));
            doc.Add(new DocumentField("__type", item.GetType().Name, new[] { IndexStore.YES, IndexType.NOT_ANALYZED }));
            doc.Add(new DocumentField("__sort", item.Name, new[] { IndexStore.YES, IndexType.NOT_ANALYZED }));
            doc.Add(new DocumentField("__hidden", (!item.IsActive).ToString().ToLower(), new[] { IndexStore.YES, IndexType.NOT_ANALYZED }));
            doc.Add(new DocumentField("code", item.Code, new[] { IndexStore.YES, IndexType.NOT_ANALYZED }));
            doc.Add(new DocumentField("name", item.Name, new[] { IndexStore.YES, IndexType.NOT_ANALYZED }));
            doc.Add(new DocumentField("startdate", item.StartDate, new[] { IndexStore.YES, IndexType.NOT_ANALYZED }));
            doc.Add(new DocumentField("enddate", item.EndDate.HasValue ? item.EndDate : DateTime.MaxValue, new[] { IndexStore.YES, IndexType.NOT_ANALYZED }));
            doc.Add(new DocumentField("createddate", item.Created.HasValue ? item.Created : DateTime.MaxValue, new[] { IndexStore.YES, IndexType.NOT_ANALYZED }));
            doc.Add(new DocumentField("lastmodifieddate", item.LastModified.HasValue ? item.LastModified : DateTime.MaxValue, new[] { IndexStore.YES, IndexType.NOT_ANALYZED }));
            doc.Add(new DocumentField("catalog", item.CatalogId.ToLower(), new[] { IndexStore.YES, IndexType.NOT_ANALYZED, IndexDataType.StringCollection }));
            doc.Add(new DocumentField("__outline", item.CatalogId.ToLower(), new[] { IndexStore.YES, IndexType.NOT_ANALYZED, IndexDataType.StringCollection }));

            // Index categories
            IndexItemCategories(ref doc, item);

            // Index custom properties
            IndexItemCustomProperties(ref doc, item);

            // Index item prices
            IndexItemPrices(ref doc, item);

            //Index item reviews
            IndexReviews(ref doc, item);

            // add to content
            doc.Add(new DocumentField("__content", item.Name, new[] { IndexStore.YES, IndexType.ANALYZED, IndexDataType.StringCollection }));
            doc.Add(new DocumentField("__content", item.Code, new[] { IndexStore.YES, IndexType.ANALYZED, IndexDataType.StringCollection }));
        }
        public static async Task <ResultDocument> MakeKeywordAnalysisAsync(IEnumerable <RequestMessage> messages, string endpoint)
        {
            ResultDocument messageAnalysis = null;
            HttpClient     httpClient      = new HttpClient();

            HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(new RequestDocument()
            {
                Messages = messages
            }));

            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");


            var url = $"http://{endpoint}/text/analytics/v2.0/keyPhrases";

            Console.WriteLine(url);
            Console.WriteLine(JsonConvert.SerializeObject(new RequestDocument()
            {
                Messages = messages
            }));
            using (HttpResponseMessage responseMessage = await httpClient.PostAsync(url, httpContent))
            {
                responseMessage.EnsureSuccessStatusCode();

                if (responseMessage.IsSuccessStatusCode)
                {
                    string stringResponse = await responseMessage.Content.ReadAsStringAsync();

                    messageAnalysis =
                        JsonConvert.DeserializeObject <ResultDocument>(
                            stringResponse);
                }
            }
            return(messageAnalysis);
        }
示例#10
0
        MakeKeyWordAnalysis(IEnumerable <RequestMessage> messages)
        {
            ResultDocument resultDocument = null;

            HttpClient httpClient = new HttpClient();

            httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key"
                                                 , "1a62f2876b9241f2bf840de102744575");

            HttpContent content = new StringContent
                                      (JsonConvert.SerializeObject(new RequestDocument {
                Messages = messages
            }));

            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            var responseMessage = await httpClient.PostAsync
                                      ("https://southcentralus.api.cognitive.microsoft.com/text/analytics/v2.0/keyPhrases"
                                      , content);

            if (responseMessage.IsSuccessStatusCode)
            {
                string response = await responseMessage.Content.ReadAsStringAsync();

                resultDocument = JsonConvert.DeserializeObject <ResultDocument>
                                     (response);
            }

            return(resultDocument);
        }
        private static ResultDocument CreateDocument(string key, string name, string color, decimal price, int size, string[] outlines)
        {
            var doc = new ResultDocument();

            doc.Add(new DocumentField("__key", key, new[] { IndexStore.YES, IndexType.NOT_ANALYZED }));
            doc.Add(new DocumentField("__type", "product", new[] { IndexStore.YES, IndexType.NOT_ANALYZED }));
            doc.Add(new DocumentField("__sort", "1", new[] { IndexStore.YES, IndexType.NOT_ANALYZED }));
            doc.Add(new DocumentField("__hidden", "false", new[] { IndexStore.YES, IndexType.NOT_ANALYZED }));
            doc.Add(new DocumentField("code", "prd12321", new[] { IndexStore.YES, IndexType.NOT_ANALYZED }));
            doc.Add(new DocumentField("name", name, new[] { IndexStore.YES, IndexType.NOT_ANALYZED }));
            doc.Add(new DocumentField("startdate", DateTime.UtcNow, new[] { IndexStore.YES, IndexType.NOT_ANALYZED }));
            doc.Add(new DocumentField("enddate", DateTime.MaxValue, new[] { IndexStore.YES, IndexType.NOT_ANALYZED }));
            doc.Add(new DocumentField("price_usd_default", price, new[] { IndexStore.YES, IndexType.NOT_ANALYZED }));
            doc.Add(new DocumentField("price_usd_default_value", price.ToString(), new[] { IndexStore.YES, IndexType.NOT_ANALYZED }));
            doc.Add(new DocumentField("color", color, new[] { IndexStore.YES, IndexType.NOT_ANALYZED }));
            doc.Add(new DocumentField("catalog", "goods", new[] { IndexStore.YES, IndexType.NOT_ANALYZED, IndexDataType.StringCollection }));
            doc.Add(new DocumentField("size", size, new[] { IndexStore.YES, IndexType.NOT_ANALYZED }));
            doc.Add(new DocumentField("currency", "USD", new[] { IndexStore.YES, IndexType.NOT_ANALYZED }));

            if (outlines != null)
            {
                foreach (var outline in outlines)
                {
                    doc.Add(new DocumentField("__outline", outline, new[] { IndexStore.YES, IndexType.NOT_ANALYZED, IndexDataType.StringCollection }));
                }
            }

            doc.Add(new DocumentField("__content", name, new[] { IndexStore.YES, IndexType.ANALYZED }));

            return(doc);
        }
示例#12
0
        public ResultDocument <T> Remove <T>(string key)
        {
            ResultDocument <T> resultDocument = new ResultDocument <T>
            {
                OperationType = ResultOperation.Delete,
                StartTime     = DateTime.Now,
                Type          = INGA.Framework.Managers.Common.Type.Cache
            };

            _cacheObject.Remove(key);

            var itemResult = Get <T>(key);

            resultDocument.EndDatime = DateTime.Now;

            if (itemResult.Status == ResultStatus.Failed)
            {
                resultDocument.Result = default(T);
                resultDocument.Status = ResultStatus.Failed;
                return(resultDocument);
            }
            else
            {
                resultDocument.Result = itemResult.Result;
                resultDocument.Status = ResultStatus.Success;
                return(resultDocument);
            }
        }
        protected virtual void IndexCategory(ref ResultDocument doc, CategoryItemRelation categoryRelation)
        {
            //TODO: normally categoryRelation.Category should no be null but somehow it is null sometimes after more than 300 item loads
            var cat = categoryRelation.Category ??
                      CatalogRepository.Categories.Expand(c => c.LinkedCategories)
                      .First(c => c.CategoryId == categoryRelation.CategoryId);

            IndexCategory(ref doc, categoryRelation.CatalogId, cat);
        }
        protected virtual void IndexReviews(ref ResultDocument doc, Item item)
        {
            var reviews = ReviewRepository.Reviews.Where(r => r.ItemId == item.ItemId).ToArray();
            var count   = reviews.Count();
            var avg     = count > 0 ? Math.Round(reviews.Average(r => r.OverallRating), 2) : 0;

            doc.Add(new DocumentField("__reviewstotal", count, new[] { IndexStore.YES, IndexType.NOT_ANALYZED }));
            doc.Add(new DocumentField("__reviewsavg", avg, new[] { IndexStore.YES, IndexType.NOT_ANALYZED }));
        }
示例#15
0
        /// <summary>
        /// Creates result document collection from Lucene documents.
        /// </summary>
        /// <param name="searcher">The searcher.</param>
        /// <param name="topDocs">The hits.</param>
        private void CreateDocuments(Searcher searcher, TopDocs topDocs)
        {
            // if no documents found return
            if (topDocs == null)
            {
                return;
            }

            var entries = new List <ResultDocument>();

            // get total hits
            var totalCount        = topDocs.TotalHits;
            var recordsToRetrieve = Results.SearchCriteria.RecordsToRetrieve;
            var startIndex        = Results.SearchCriteria.StartingRecord;

            if (recordsToRetrieve > totalCount)
            {
                recordsToRetrieve = totalCount;
            }

            for (var index = startIndex; index < startIndex + recordsToRetrieve; index++)
            {
                if (index >= totalCount)
                {
                    break;
                }

                var document = searcher.Doc(topDocs.ScoreDocs[index].Doc);
                var doc      = new ResultDocument();

                var documentFields = document.GetFields();
                using (var fi = documentFields.GetEnumerator())
                {
                    while (fi.MoveNext())
                    {
                        if (fi.Current != null)
                        {
                            var field = fi.Current;
                            doc.Add(new DocumentField(field.Name, field.StringValue));
                        }
                    }
                }

                entries.Add(doc);
            }

            var searchDocuments = new ResultDocumentSet
            {
                Name       = "Items",
                Documents  = entries.OfType <IDocument>().ToArray(),
                TotalCount = totalCount
            };

            Results.Documents = new[] { searchDocuments };
        }
示例#16
0
        public VmInfoReturnContainer(object[] input)
        {
            XmlDocument ResultDocument;

            ResultDocument = GetCleanXmlDocument(input);

            XmlNode VmNode         = ResultDocument.SelectSingleNode("VM");
            var     monitoringNode = VmNode.SelectSingleNode("MONITORING");


#nullable enable
示例#17
0
        protected virtual void IndexItem(ResultDocument doc, Category category)
        {
            var indexStoreNotAnalyzed = new[] { IndexStore.Yes, IndexType.NotAnalyzed };
            var indexStoreNotAnalyzedStringCollection = new[] { IndexStore.Yes, IndexType.NotAnalyzed, IndexDataType.StringCollection };
            var indexStoreAnalyzedStringCollection    = new[] { IndexStore.Yes, IndexType.Analyzed, IndexDataType.StringCollection };

            doc.Add(new DocumentField("__key", category.Id.ToLower(), indexStoreNotAnalyzed));
            doc.Add(new DocumentField("__type", category.GetType().Name, indexStoreNotAnalyzed));
            doc.Add(new DocumentField("__sort", category.Name, indexStoreNotAnalyzed));
            IndexIsProperty(doc, "category");
            var statusField = (category.IsActive != true || category.Id != null) ? "hidden" : "visible";

            IndexIsProperty(doc, statusField);
            doc.Add(new DocumentField("status", statusField, indexStoreNotAnalyzed));
            doc.Add(new DocumentField("code", category.Code, indexStoreNotAnalyzed));
            IndexIsProperty(doc, category.Code);
            doc.Add(new DocumentField("name", category.Name, indexStoreNotAnalyzed));
            doc.Add(new DocumentField("createddate", category.CreatedDate, indexStoreNotAnalyzed));
            doc.Add(new DocumentField("lastmodifieddate", category.ModifiedDate ?? DateTime.MaxValue, indexStoreNotAnalyzed));
            doc.Add(new DocumentField("priority", category.Priority, indexStoreNotAnalyzed));
            doc.Add(new DocumentField("lastindexdate", DateTime.UtcNow, indexStoreNotAnalyzed));

            // Add priority in virtual categories to search index
            foreach (var link in category.Links)
            {
                doc.Add(new DocumentField(string.Format(CultureInfo.InvariantCulture, "priority_{0}_{1}", link.CatalogId, link.CategoryId), link.Priority, indexStoreNotAnalyzed));
            }

            // Add catalogs to search index
            var catalogs = category.Outlines
                           .Select(o => o.Items.First().Id)
                           .Distinct(StringComparer.OrdinalIgnoreCase)
                           .ToArray();

            foreach (var catalogId in catalogs)
            {
                doc.Add(new DocumentField("catalog", catalogId.ToLower(), indexStoreNotAnalyzedStringCollection));
            }

            // Add outlines to search index
            var outlineStrings = GetOutlineStrings(category.Outlines);

            foreach (var outline in outlineStrings)
            {
                doc.Add(new DocumentField("__outline", outline.ToLower(), indexStoreNotAnalyzedStringCollection));
            }

            // Index custom properties
            IndexItemCustomProperties(doc, category);

            // add to content
            doc.Add(new DocumentField("__content", category.Name, indexStoreAnalyzedStringCollection));
            doc.Add(new DocumentField("__content", category.Code, indexStoreAnalyzedStringCollection));
        }
 /// <summary>
 /// converts result document to document identity record
 /// </summary>
 /// <param name="resultDocument">ResultDocument</param>
 /// <returns>DocumentIdentityRecord</returns>
 private BulkDocumentInfoBEO ConvertToDocumentIdentityRecord(ResultDocument resultDocument)
 {
     return(new BulkDocumentInfoBEO
     {
         DocumentId = resultDocument.DocumentId.DocumentId,
         FamilyId = resultDocument.DocumentId.FamilyId,
         DuplicateId = resultDocument.DocumentId.DuplicateId,
         FromOriginalQuery = true,
         DCN = GetDCN(resultDocument.FieldValues)
     });
 }
        public virtual ISearchResults Search(string scope, ISearchCriteria criteria)
        {
            var command = new SearchCommand(scope, criteria.DocumentType);

            command.Size(criteria.RecordsToRetrieve);
            command.From(criteria.StartingRecord);

            // Add spell checking
            // TODO: options.SpellCheck = new SpellCheckingParameters { Collate = true };

            // Build query
            var builder = (QueryBuilder <ESDocument>)_queryBuilder.BuildQuery(criteria);

            SearchResult <ESDocument> resultDocs;

            // Add some error handling
            try
            {
                resultDocs = Client.Search(command, builder);
            }
            catch (Exception ex)
            {
                throw new ElasticSearchException("Search using Elastic Search server failed, check logs for more details.", ex);
            }

            // Parse documents returned
            var docList = new List <ResultDocument>();

            foreach (var indexDoc in resultDocs.Documents)
            {
                var document = new ResultDocument();
                foreach (var field in indexDoc.Keys)
                {
                    document.Add(new DocumentField(field, indexDoc[field]));
                }

                docList.Add(document);
            }

            var documents = new ResultDocumentSet
            {
                TotalCount = resultDocs.hits.total,
                Documents  = docList.OfType <IDocument>().ToArray()
            };

            // Create search results object
            var results = new SearchResults(criteria, new[] { documents })
            {
                FacetGroups = CreateFacets(criteria, resultDocs.facets)
            };

            return(results);
        }
        /// <summary>
        /// converts result document to document identity record
        /// </summary>
        /// <param name="resultDocument">ResultDocument</param>
        /// <returns>DocumentIdentityRecord</returns>
        private static DocumentIdentityRecord ConvertToDocumentIdentityRecord(ResultDocument resultDocument)
        {
            var documentIdentityRecord = new DocumentIdentityRecord
            {
                Id          = resultDocument.DocumentId.Id,
                DocumentId  = resultDocument.DocumentId.DocumentId,
                FamilyId    = resultDocument.DocumentId.FamilyId,
                DuplicateId = resultDocument.DocumentId.DuplicateId
            };

            documentIdentityRecord.Fields.AddRange(resultDocument.FieldValues.ToDataAccessEntity());
            return(documentIdentityRecord);
        }
示例#21
0
        public ISearchResults Search(string scope, ISearchCriteria criteria)
        {
            // Build query
            var builder = (SearchQuery)_queryBuilder.BuildQuery(criteria);

            SearchQueryResult resultDocs;

            // Add some error handling
            //try
            {
                var searchResponse = Client.Search(scope, builder).Result;
                if (!searchResponse.IsSuccess)
                {
                    throw new AzureSearchException(AzureSearchHelper.FormatSearchException(searchResponse));
                }

                resultDocs = searchResponse.Body;
            }

            /*
             * catch (Exception ex)
             * {
             * throw ex;
             * }
             * */

            // Parse documents returned
            var documents = new ResultDocumentSet {
                TotalCount = resultDocs.Count
            };
            var docList = new List <ResultDocument>();

            foreach (var indexDoc in resultDocs.Records)
            {
                var document = new ResultDocument();
                foreach (var field in indexDoc.Properties.Keys)
                {
                    document.Add(new DocumentField(field, indexDoc.Properties[field]));
                }

                docList.Add(document);
            }

            documents.Documents = docList.ToArray();

            // Create search results object
            var results = new SearchResults(criteria, new[] { documents });

            return(results);
        }
        protected virtual void IndexItemCategories(ref ResultDocument doc, Item item)
        {
            if (item.CategoryItemRelations == null)
            {
                return;
            }

            foreach (var cat in item.CategoryItemRelations)
            {
                doc.Add(new DocumentField(String.Format("sort{0}{1}", cat.CatalogId, cat.CategoryId), cat.Priority, new string[] { IndexStore.YES, IndexType.NOT_ANALYZED }));

                IndexCategory(ref doc, cat);
            }
        }
示例#23
0
 public override void ExecuteResult(ControllerContext context)
 {
     context.HttpContext.Response.ContentType = ContentType;
     if (ResultDocument == null || ResultDocument.Root == null)
     {
         context.HttpContext.Response.Write(string.Empty);
     }
     else
     {
         ResultDocument.ToNullHelper().Branch(
             doc => doc.Save(context.HttpContext.Response.Output, SaveOptions.None),
             () => { /*if doc doesn't exist, does nothing*/ });
     }
 }
        protected virtual void IndexItemPrices(ref ResultDocument doc, Item item)
        {
            if (_prices != null)
            {
                var prices = (from p in _prices where p.ItemId.Equals(item.ItemId, StringComparison.OrdinalIgnoreCase) select p).ToArray();

                foreach (var price in prices)
                {
                    //var priceList = price.Pricelist;
                    var priceList = (from p in _priceLists where p.PricelistId == price.PricelistId select p).SingleOrDefault();
                    doc.Add(new DocumentField(String.Format("price_{0}_{1}", priceList.Currency, priceList.PricelistId), price.Sale ?? price.List, new[] { IndexStore.NO, IndexType.NOT_ANALYZED }));
                    doc.Add(new DocumentField(String.Format("price_{0}_{1}_value", priceList.Currency, priceList.PricelistId), price.Sale == null ? price.List.ToString() : price.Sale.ToString(), new[] { IndexStore.YES, IndexType.NOT_ANALYZED }));
                }
            }
        }
        protected virtual void IndexCategory(ref ResultDocument doc, string catalogId, CategoryBase category)
        {
            doc.Add(new DocumentField("catalog", catalogId.ToLower(), new[] { IndexStore.YES, IndexType.NOT_ANALYZED }));

            // get category path
            var outline = OutlineBuilder.BuildCategoryOutline(catalogId, category).ToString();

            doc.Add(new DocumentField("__outline", outline.ToLower(), new[] { IndexStore.YES, IndexType.NOT_ANALYZED }));

            // Now index all linked categories
            foreach (var linkedCategory in category.LinkedCategories)
            {
                IndexCategory(ref doc, linkedCategory.CatalogId, linkedCategory);
            }
        }
        protected virtual void IndexItemPrices(ref ResultDocument doc, CatalogProduct item)
        {
            var evalContext = new Domain.Pricing.Model.PriceEvaluationContext
            {
                ProductIds = new[] { item.Id }
            };

            var prices = _pricingService.EvaluateProductPrices(evalContext);

            foreach (var price in prices)
            {
                //var priceList = price.Pricelist;
                doc.Add(new DocumentField(string.Format("price_{0}_{1}", price.Currency, price.PricelistId).ToLower(), price.EffectiveValue, new[] { IndexStore.No, IndexType.NotAnalyzed }));
                doc.Add(new DocumentField(string.Format("price_{0}_{1}_value", price.Currency, price.PricelistId).ToLower(), (price.EffectiveValue).ToString(CultureInfo.InvariantCulture), new[] { IndexStore.Yes, IndexType.NotAnalyzed }));
            }
        }
        protected virtual void IndexItemCustomProperties(ref ResultDocument doc, CatalogProduct item)
        {
            var properties = item.Properties;

            foreach (var propValue in item.PropertyValues.Where(x => x.Value != null))
            {
                var property     = properties.FirstOrDefault(x => string.Equals(x.Name, propValue.PropertyName, StringComparison.InvariantCultureIgnoreCase) && x.ValueType == propValue.ValueType);
                var contentField = string.Concat("__content", property != null && (property.Multilanguage && !string.IsNullOrWhiteSpace(propValue.LanguageCode)) ? "_" + propValue.LanguageCode.ToLower() : string.Empty);

                switch (propValue.ValueType)
                {
                case PropertyValueType.LongText:
                case PropertyValueType.ShortText:
                    var stringValue = propValue.Value.ToString();

                    if (!string.IsNullOrWhiteSpace(stringValue))     // don't index empty values
                    {
                        doc.Add(new DocumentField(contentField, stringValue.ToLower(), new[] { IndexStore.Yes, IndexType.Analyzed, IndexDataType.StringCollection }));
                    }

                    break;
                }

                if (doc.ContainsKey(propValue.PropertyName))
                {
                    continue;
                }


                switch (propValue.ValueType)
                {
                case PropertyValueType.Boolean:
                case PropertyValueType.DateTime:
                case PropertyValueType.Number:
                    doc.Add(new DocumentField(propValue.PropertyName, propValue.Value, new[] { IndexStore.Yes, IndexType.Analyzed }));
                    break;

                case PropertyValueType.LongText:
                    doc.Add(new DocumentField(propValue.PropertyName, propValue.Value.ToString().ToLowerInvariant(), new[] { IndexStore.Yes, IndexType.Analyzed }));
                    break;

                case PropertyValueType.ShortText:     // do not tokenize small values as they will be used for lookups and filters
                    doc.Add(new DocumentField(propValue.PropertyName, propValue.Value.ToString().ToLowerInvariant(), new[] { IndexStore.Yes, IndexType.NotAnalyzed }));
                    break;
                }
            }
        }
示例#28
0
        public static ResultDocument CreateDocument(string key, string name, string color, Price[] prices, int size, string[] outlines, bool extraProperties = false)
        {
            var doc = new ResultDocument();

            doc.Add(new DocumentField("__key", key, new[] { IndexStore.Yes, IndexType.NotAnalyzed }));
            doc.Add(new DocumentField("__type", "product", new[] { IndexStore.Yes, IndexType.NotAnalyzed }));
            doc.Add(new DocumentField("__sort", "1", new[] { IndexStore.Yes, IndexType.NotAnalyzed }));
            doc.Add(new DocumentField("status", "visible", new[] { IndexStore.Yes, IndexType.NotAnalyzed }));
            doc.Add(new DocumentField("is", "visible", new[] { IndexStore.No, IndexType.NotAnalyzed }));
            doc.Add(new DocumentField("is", "priced", new[] { IndexStore.No, IndexType.NotAnalyzed }));
            doc.Add(new DocumentField("is", color, new[] { IndexStore.No, IndexType.NotAnalyzed }));
            doc.Add(new DocumentField("is", key, new[] { IndexStore.No, IndexType.NotAnalyzed }));
            doc.Add(new DocumentField("code", key, new[] { IndexStore.Yes, IndexType.NotAnalyzed }));
            doc.Add(new DocumentField("name", name, new[] { IndexStore.Yes, IndexType.NotAnalyzed }));
            doc.Add(new DocumentField("startdate", DateTime.UtcNow.AddDays(-1), new[] { IndexStore.Yes, IndexType.NotAnalyzed }));
            doc.Add(new DocumentField("enddate", DateTime.MaxValue, new[] { IndexStore.Yes, IndexType.NotAnalyzed }));

            foreach (var price in prices)
            {
                doc.Add(new DocumentField(price.PriceList, price.Amount, new[] { IndexStore.Yes, IndexType.NotAnalyzed }));
                doc.Add(new DocumentField("price_usd", price.Amount, new[] { IndexStore.Yes, IndexType.NotAnalyzed }));
            }

            doc.Add(new DocumentField("color", color, new[] { IndexStore.Yes, IndexType.NotAnalyzed }));
            doc.Add(new DocumentField("catalog", "goods", new[] { IndexStore.Yes, IndexType.NotAnalyzed, IndexDataType.StringCollection }));
            doc.Add(new DocumentField("size", size, new[] { IndexStore.Yes, IndexType.NotAnalyzed }));
            doc.Add(new DocumentField("currency", "USD", new[] { IndexStore.Yes, IndexType.NotAnalyzed }));

            if (extraProperties) // adds extra properties to test mapping updates for indexer
            {
                doc.Add(new DocumentField("name2", name, new[] { IndexStore.Yes, IndexType.NotAnalyzed }));
                doc.Add(new DocumentField("startdate2", DateTime.UtcNow.AddDays(-1), new[] { IndexStore.Yes, IndexType.NotAnalyzed }));
            }

            if (outlines != null)
            {
                foreach (var outline in outlines)
                {
                    doc.Add(new DocumentField("__outline", outline, new[] { IndexStore.Yes, IndexType.NotAnalyzed, IndexDataType.StringCollection }));
                }
            }

            doc.Add(new DocumentField("__content", name, new[] { IndexStore.Yes, IndexType.Analyzed }));

            return(doc);
        }
示例#29
0
        public BusinessLayer.Entities.ResultDocument TranslateResultDocumentGPToLocal(Generated.ResultDocument gpRes, string patientId)
        {
            ResultDocument localRes = new ResultDocument();

            try
            {
                if (gpRes != null)
                {
                    localRes.CentralType  = gpRes.CentralType;
                    localRes.DocumentDate = gpRes.DocumentDate.HasValue ? gpRes.DocumentDate.Value : DateTime.Now;

                    List <EpisodeData> eps = new List <EpisodeData>();
                    foreach (var item in gpRes.Episodes)
                    {
                        eps.Add(TranslateEpisodeDataGPToLocal(item));
                    }
                    localRes.Episodes = eps;

                    localRes.FacilityId        = gpRes.FacilityId;
                    localRes.PatientId         = patientId;
                    localRes.FileName          = gpRes.FileName;
                    localRes.IdDocument        = gpRes.IdDocument.HasValue ? gpRes.IdDocument.Value.ToString() : "0";
                    localRes.IdPatient         = gpRes.IdPatient;
                    localRes.MimeType          = gpRes.MimeType;
                    localRes.OriginDescription = gpRes.OriginDescription;
                    localRes.OriginId          = gpRes.OriginId;
                    localRes.Restrict          = gpRes.Restrict.HasValue ? gpRes.Restrict.Value : false;
                    localRes.SCN             = gpRes.SCN.HasValue ? gpRes.SCN.Value.ToString() : "0";
                    localRes.TypeDescription = gpRes.TypeDescription;
                    localRes.TypeId          = gpRes.TypeId;
                    localRes.UrlFile         = gpRes.UrlFile;
                    localRes.HasImage        = gpRes.HasImage.HasValue ? gpRes.HasImage.Value : false;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Erro a realizar o convert de ResultDocument");
                return(localRes);
            }

            return(localRes);
        }
        /// <summary>
        /// Converts the search result document to FilteredDocumentBusinessEntity.
        /// </summary>
        private static FilteredDocumentBusinessEntity ConvertToFilteredDocumentBusinessEntity(ResultDocument resultDocument)
        {
            var filteredDocument = new FilteredDocumentBusinessEntity
            {
                Id = resultDocument.DocumentId.DocumentId,
                MatterId = resultDocument.DocumentId.MatterId,
                CollectionId = resultDocument.DocumentId.CollectionId,
                IsLocked = resultDocument.IsLocked,
                FamilyId = resultDocument.DocumentId.FamilyId
            };

            if (resultDocument.FieldValues == null || !resultDocument.FieldValues.Any()) return filteredDocument;

            foreach (var fieldResult in resultDocument.FieldValues.Select(ConvertDocumentFieldToFieldResult))
            {
                filteredDocument.OutPutFields.Add(fieldResult);
                if (fieldResult.DataTypeId == 3000) filteredDocument.DCN = fieldResult.Value;
            }
            return filteredDocument;
        }
示例#31
0
        protected virtual void IndexItemPrices(ResultDocument doc, Price[] prices, CatalogProduct item)
        {
            foreach (var price in prices)
            {
                doc.Add(new DocumentField(string.Format(CultureInfo.InvariantCulture, "price_{0}_{1}", price.Currency, price.PricelistId).ToLower(), price.EffectiveValue, new[] { IndexStore.No, IndexType.NotAnalyzed }));

                // now save additional pricing fields for convinient user searches, store price with currency and without one
                doc.Add(new DocumentField(string.Format(CultureInfo.InvariantCulture, "price_{0}", price.Currency), price.EffectiveValue, new[] { IndexStore.No, IndexType.NotAnalyzed }));
                doc.Add(new DocumentField("price", price.EffectiveValue, new[] { IndexStore.No, IndexType.NotAnalyzed }));
            }

            if (prices.Length == 0) // mark product without prices defined
            {
                IndexIsProperty(doc, "unpriced");
            }
            else
            {
                IndexIsProperty(doc, "priced");
            }
        }
 /// <summary>
 /// converts result document to document identity record
 /// </summary>
 /// <param name="resultDocument">ResultDocument</param>
 /// <returns>DocumentIdentityRecord</returns>
 private static DocumentIdentityRecord ConvertToDocumentIdentityRecord(ResultDocument resultDocument)
 {
     var documentIdentityRecord = new DocumentIdentityRecord
     {
         Id = resultDocument.DocumentId.Id,
         DocumentId = resultDocument.DocumentId.DocumentId,
         FamilyId = resultDocument.DocumentId.FamilyId,
         DuplicateId = resultDocument.DocumentId.DuplicateId
     };
     documentIdentityRecord.Fields.AddRange(resultDocument.FieldValues.ToDataAccessEntity());
     return documentIdentityRecord;
 }
 /// <summary>
 /// converts result document to document identity record
 /// </summary>
 /// <param name="resultDocument">ResultDocument</param>
 /// <returns>DocumentIdentityRecord</returns>
 private BulkDocumentInfoBEO ConvertToDocumentIdentityRecord(ResultDocument resultDocument)
 {
     return new BulkDocumentInfoBEO
     {
         DocumentId = resultDocument.DocumentId.DocumentId,
         FamilyId = resultDocument.DocumentId.FamilyId,
         DuplicateId = resultDocument.DocumentId.DuplicateId,
         FromOriginalQuery = true,
         DCN = GetDCN(resultDocument.FieldValues)
     };
 }
        /// <summary>
        /// Converts the result document to document result.
        /// </summary>
        /// <param name="resultDocument">The result document.</param>
        /// <returns></returns>
        private static DocumentResult ConvertResultDocumentToDocumentResult(ResultDocument resultDocument)
        {
            var docResult = new DocumentResult
            {
                DocumentID = resultDocument.DocumentId.DocumentId,
                IsLocked = resultDocument.IsLocked,
                RedactableDocumentSetId = resultDocument.RedactableDocumentSetId,
                MatterID = long.Parse(resultDocument.DocumentId.MatterId),
                CollectionID = resultDocument.DocumentId.CollectionId,
                //family id is needed so that bulk tagging/ reviweset creation can be done for family options
                FamilyID = resultDocument.DocumentId.FamilyId
            };

            if (resultDocument.FieldValues != null)
                foreach (FieldResult fieldResult in resultDocument.FieldValues.Select(ConvertDocumentFieldToFieldResult))
                {
                    docResult.Fields.Add(fieldResult);
                    if (fieldResult.DataTypeId == 3000) docResult.DocumentControlNumber = fieldResult.Value;
                }
            return docResult;
        }
        /// <summary>
        /// Creates result document collection from Lucene documents.
        /// </summary>
        /// <param name="searcher">The searcher.</param>
        /// <param name="topDocs">The hits.</param>
        private void CreateDocuments(Searcher searcher, TopDocs topDocs)
        {
            // if no documents found return
            if (topDocs == null) return;

            var entries = new List<ResultDocument>();

            // get total hits
            var totalCount = topDocs.TotalHits;
            var recordsToRetrieve = Results.SearchCriteria.RecordsToRetrieve;
            var startIndex = Results.SearchCriteria.StartingRecord;
            if (recordsToRetrieve > totalCount) recordsToRetrieve = totalCount;

            for (var index = startIndex; index < startIndex + recordsToRetrieve; index++)
            {
                if (index >= totalCount) break;

                var document = searcher.Doc(topDocs.ScoreDocs[index].Doc);
                var doc = new ResultDocument();

                var documentFields = document.GetFields();
                using (var fi = documentFields.GetEnumerator())
                {
                    while (fi.MoveNext())
                    {
                        if (fi.Current != null)
                        {
                            var field = fi.Current;

                            // make sure document field doens't exist, if it does, simply add another value
                            if (doc.ContainsKey(field.Name))
                            {
                                var existingField = doc[field.Name] as DocumentField;
                                if (existingField != null) existingField.AddValue(field.StringValue);
                            }
                            else // add new
                            {
                                doc.Add(new DocumentField(field.Name, field.StringValue));
                            }
                        }
                    }
                }

                entries.Add(doc);
            }

            var searchDocuments = new ResultDocumentSet
            {
                Name = "Items",
                Documents = entries.ToArray(),
                TotalCount = totalCount
            };

            Results.Documents = new[] { searchDocuments };
        }