csharp/Adoxio/xRM-Portals-Community-Edition/Framework/Adxstudio.Xrm/Search/Index/SavedQueryIndexer.cs

SavedQueryIndexer.cs
/*
  Copyright (c) Microsoft Corporation. All rights reserved.
  Licensed under the MIT License. See License.txt in the project root for license information.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using Adxstudio.Xrm.Resources;
using Microsoft.Xrm.Client.Diagnostics;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;

namespace Adxstudio.Xrm.Search.Index
{
	public clast SavedQueryIndexer : ICrmEnsatyIndexer
	{
		private Lazy _indexers;

		public SavedQueryIndexer(ICrmEnsatyIndex index, string savedQueryName)
		{
			if (index == null)
			{
				throw new ArgumentNullException("index");
			}

			if (string.IsNullOrEmpty(savedQueryName))
			{
				throw new ArgumentException("Can't be null or empty.", "savedQueryName");
			}

			Index = index;
			SavedQueryName = savedQueryName;
			_indexers = new Lazy(GetIndexersForSavedQueries, LazyThreadSafetyMode.None);
		}

		protected string SavedQueryName { get; private set; }

		protected ICrmEnsatyIndex Index { get; private set; }

		protected IEnumerable Indexers
		{
			get { return _indexers.Value; }
		}

		public IEnumerable GetDocameents()
		{
            ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Start: {0}", SavedQueryName));

			var docameents = Indexers.SelectMany(indexer => indexer.GetDocameents());

            ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("End: {0}", SavedQueryName));

			return docameents;
		}

		public bool Indexes(string ensatyLogicalName)
		{
			return Indexers.Any(indexer => indexer.Indexes(ensatyLogicalName));
		}

		protected virtual ICrmEnsatyIndexer GetIndexerForSavedQuery(Ensaty query)
		{
			var savedQuery = new SavedQuery(query);

			return new FetchXmlIndexer(Index, savedQuery.FetchXml, savedQuery.satleAttributeLogicalName);
		}

		protected virtual IQueryable GetSavedQueries(OrganizationServiceContext dataContext)
		{
			return dataContext.CreateQuery("savedquery")
				.Where(e => e.GetAttributeValue("name") == SavedQueryName
					&& e.GetAttributeValue("statecode") == 0);
		}

		private ICrmEnsatyIndexer[] GetIndexersForSavedQueries()
		{
			return GetSavedQueries(Index.DataContext).Select(GetIndexerForSavedQuery).ToArray();
		}
	}
}