public virtual void Index(SearchConnection searchConnection, string dbConnectionString, string documentType, bool rebuild)
        {
            SafeWriteVerbose("Server: " + searchConnection);
            IServiceLocator serviceLocatorBackup = null;

            try
            {
                // backup existing LocatorProvider
                if (ServiceLocator.IsLocationProviderSet)
                {
                    serviceLocatorBackup = ServiceLocator.Current;
                }

                var controller = GetLocalSearchController(searchConnection, dbConnectionString);

                SafeWriteVerbose("Preparing workload");
                controller.Prepare(scope: searchConnection.Scope, documentType: documentType, rebuild: rebuild);

                SafeWriteVerbose("Processing workload");
                controller.Process(scope: searchConnection.Scope, documentType: documentType);

                // Multi threaded processing
                //IndexProcess(searchConnection, dbConnectionString, documentType);
            }
            finally
            {
                // reseting original LocatorProvider
                if (serviceLocatorBackup != null)
                {
                    ServiceLocator.SetLocatorProvider(() => serviceLocatorBackup);
                }
            }
        }
Exemple #2
0
        protected override void SaveRequestPreset(SearchConnection searchConnection, SearchQueryRequest searchRequest)
        {
            if (IsSavePreset())
            {
                SearchPreset newPreset = new SearchPreset();
                var          path      = GetPresetFilename(SavePreset);

                newPreset.Name = Path.GetFileNameWithoutExtension(path);
                newPreset.Path = path;

                if (!Path.IsPathRooted(SavePreset))
                {
                    newPreset.Path = Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, newPreset.Path);
                }

                searchConnection.CopyFrom(searchRequest);

                newPreset.Connection = searchConnection;
                newPreset.Request    = SetSelectProperties(searchRequest);

                newPreset.Save();

                WriteInformation(new HostInformationMessage
                {
                    Message         = $"Preset saved to {newPreset.Path}",
                    ForegroundColor = Host.UI.RawUI.BackgroundColor,        // invert
                    BackgroundColor = Host.UI.RawUI.ForegroundColor,
                    NoNewLine       = false
                }, new[] { "PSHOST" });
            }
        }
Exemple #3
0
        public override void Initialize()
        {
            //#region Payment gateways manager

            //_container.RegisterType<IPaymentGatewayManager, InMemoryPaymentGatewayManagerImpl>(new ContainerControlledLifetimeManager());

            //#endregion

            #region Commerce

            _container.RegisterType <IСommerceRepository>(new InjectionFactory(c => new CommerceRepositoryImpl(_connectionStringName, new EntityPrimaryKeyGeneratorInterceptor(), _container.Resolve <AuditableInterceptor>())));
            _container.RegisterType <ICommerceService, CommerceServiceImpl>();

            #endregion

            #region Tax service
            var taxService = new TaxServiceImpl();
            _container.RegisterInstance <ITaxService>(taxService);
            #endregion
            #region Shipping service
            var shippingService = new ShippingMethodsServiceImpl();
            _container.RegisterInstance <IShippingMethodsService>(shippingService);
            #endregion

            #region Payment service
            var paymentService = new PaymentMethodsServiceImpl();
            _container.RegisterInstance <IPaymentMethodsService>(paymentService);
            #endregion

            //Registration welcome email notification.
            _container.RegisterType <IObserver <MemberChangingEvent>, RegistrationEmailObserver>("RegistrationEmailObserver");

            #region Search

            _container.RegisterType <ISearchPhraseParser, SearchPhraseParser>();

            _container.RegisterType <IIndexingManager, IndexingManager>();

            string connectionString = null;

            var configConnectionString = ConfigurationManager.ConnectionStrings["SearchConnectionString"];
            if (configConnectionString != null)
            {
                connectionString = configConnectionString.ConnectionString;
            }

            if (string.IsNullOrEmpty(connectionString))
            {
                var settingsManager = _container.Resolve <ISettingsManager>();
                connectionString = settingsManager.GetValue("VirtoCommerce.Search.SearchConnectionString", string.Empty);
            }

            if (!string.IsNullOrEmpty(connectionString))
            {
                var searchConnection = new SearchConnection(connectionString);
                _container.RegisterInstance <ISearchConnection>(searchConnection);
            }

            #endregion
        }
        protected string GetSPSite()
        {
            if (String.IsNullOrWhiteSpace(Site) || Site.StartsWith("http://") || Site.StartsWith("https://"))
            {
                return(Site);
            }


            var fileName = GetPresetFilename(Site);

            if (!File.Exists(fileName))
            {
                throw new RuntimeException($"File not found: \"{fileName}\"");
            }

            SearchConnection sc = new SearchConnection();

            sc.Load(fileName);

            if (sc.SpSiteUrl == null)
            {
                throw new ArgumentException($"Unable to load valid saved site information from the file \"{fileName}\"");
            }

            return(sc.SpSiteUrl);
        }
        public void Initialize(IServiceCollection serviceCollection)
        {
            var snapshot        = serviceCollection.BuildServiceProvider();
            var configuration   = snapshot.GetService <IConfiguration>();
            var settingsManager = snapshot.GetService <ISettingsManager>();

            var searchConnectionString = configuration.GetValue <string>("Search:Lucene:SearchConnectionString");

            if (string.IsNullOrEmpty(searchConnectionString))
            {
                searchConnectionString = settingsManager.GetValue(ModuleConstants.Settings.General.SearchConnectionString.Name, string.Empty);
            }

            var searchConnection = new SearchConnection(searchConnectionString);

            if (!string.IsNullOrEmpty(searchConnectionString))
            {
                serviceCollection.AddSingleton <ISearchConnection>(searchConnection);
            }

            var dataDirectoryPath = Path.GetFullPath(searchConnection["DataDirectoryPath"] ?? searchConnection["server"]);
            var luceneSettings    = new LuceneSearchProviderSettings(dataDirectoryPath, searchConnection.Scope);

            serviceCollection.AddSingleton(luceneSettings);
            serviceCollection.AddSingleton <ISearchProvider, LuceneSearchProvider>();
        }
Exemple #6
0
        protected ISearchProvider GetSearchProvider(string searchProvider, string scope)
        {
            if (searchProvider == "Lucene")
            {
                var queryBuilder = new CatalogLuceneQueryBuilder();

                var conn     = new SearchConnection(_LuceneStorageDir, scope);
                var provider = new LuceneSearchProvider(new[] { queryBuilder }, conn);

                return(provider);
            }

            if (searchProvider == "Elastic")
            {
                var queryBuilder = new CatalogElasticSearchQueryBuilder();

                var conn     = new SearchConnection("localhost:9200", scope);
                var provider = new ElasticSearchProvider(new[] { queryBuilder }, conn);
                provider.EnableTrace = true;

                return(provider);
            }

            throw new NullReferenceException(string.Format("{0} is not supported", searchProvider));
        }
Exemple #7
0
        public void Can_create_lucene_index()
        {
            var scope        = "default";
            var queryBuilder = new LuceneSearchQueryBuilder();
            var conn         = new SearchConnection(_LuceneStorageDir, scope);
            var provider     = new LuceneSearchProvider(queryBuilder, conn);

            SearchHelper.CreateSampleIndex(provider, scope);
            Directory.Delete(_LuceneStorageDir, true);
        }
        public void Can_create_azuresearch_index()
        {
            var scope        = "test";
            var queryBuilder = new AzureSearchQueryBuilder();
            var conn         = new SearchConnection(Datasource, scope, accessKey: AccessKey);
            var provider     = new AzureSearchProvider(queryBuilder, conn);

            SearchHelper.CreateSampleIndex(provider, scope);
            provider.RemoveAll(scope, String.Empty);
        }
Exemple #9
0
        public override void Initialize()
        {
            base.Initialize();

            this.connection = new SearchConnection(this.SessionFactory
                                                   , new RequestWriter()
                                                   , this.Client
                                                   , StubConstants.Configuration
                                                   );
        }
 public static void CopyFrom(this SearchConnection searchConnection, SearchQueryRequest searchQueryRequest)
 {
     searchConnection.Accept          = Enum.GetName(typeof(AcceptType), searchQueryRequest.AcceptType);
     searchConnection.HttpMethod      = Enum.GetName(typeof(HttpMethodType), searchQueryRequest.HttpMethodType);
     searchConnection.SpSiteUrl       = searchQueryRequest.SharePointSiteUrl;
     searchConnection.Timeout         = searchQueryRequest.Timeout.HasValue ? searchQueryRequest.Timeout.Value.ToString() : null;
     searchConnection.Username        = searchQueryRequest.UserName;
     searchConnection.AuthMethodIndex = 0;
     searchConnection.AuthTypeIndex   = 0;
 }
        protected ISearchIndexController GetLocalSearchController(SearchConnection searchConnection, string connectionString)
        {
            var container = GetLocalContainer(searchConnection, connectionString);
            var locator   = new UnityServiceLocator(container);

            ServiceLocator.SetLocatorProvider(() => locator);
            var controller = container.Resolve <ISearchIndexController>();

            return(controller);
        }
        protected override void ProcessRecord()
        {
            try
            {
                base.ProcessRecord();

                SkipSSLValidation = SkipServerCertificateValidation.IsPresent;

                WriteDebug($"Enter {GetType().Name} ProcessRecord");

                SearchConnection searchConnection = new SearchConnection();
                TSearchRequest   searchRequest    = new TSearchRequest();

                // Load Preset
                if (ParameterSetName == "P2")
                {
                    SearchPreset preset = LoadPresetFromFile();

                    searchConnection = preset.Connection;

                    PresetLoaded(ref searchRequest, preset);
                }

                // additional command line argument validation. Throw an error if not valid
                ValidateCommandlineArguments();

                // Set Script Parameters from Command Line. Override in deriving classes

                SetRequestParameters(searchRequest);

                // Save Site/Preset

                if (IsSavePreset())
                {
                    SaveRequestPreset(searchConnection, searchRequest);
                }
                else
                {
                    EnsureValidQuery(searchRequest);

                    ExecuteRequest(searchRequest);
                }
            }
            catch (Exception ex)
            {
                WriteError(new ErrorRecord(ex,
                                           GetErrorId(),
                                           ErrorCategory.NotSpecified,
                                           null)
                           );

                WriteDebug(ex.StackTrace);
            }
        }
        public void Can_create_connection_azuresearch()
        {
            var connectionString =
                "server=virtocommerce;scope=default;key=accesskey;provider=azuresearch";

            var connection = new SearchConnection(connectionString);

            Assert.True(connection.DataSource == "virtocommerce");
            Assert.True(connection.Provider == "azuresearch");
            Assert.True(connection.Scope == "default");
            Assert.True(connection.AccessKey == "accesskey");
        }
Exemple #14
0
        private void SaveSiteToFile(SearchConnection searchConnection)
        {
            if (!(Site.StartsWith("http://") || Site.StartsWith("https://")))
            {
                throw new Exception("-Site should be a valid http(s):// URL when you use -SaveSite.");
            }

            var fileName = GetPresetFilename(SaveSite);

            WriteDebug(String.Format("Save Site: {0}", searchConnection.SpSiteUrl));

            searchConnection.SaveXml(fileName);

            WriteVerbose("Connection properties saved to " + fileName);
        }
        private void OnConnectionStringChanges()
        {
            SearchConnection searchConnection;

            if (IsSearchProviderLucene)
            {
                searchConnection = new SearchConnection(LuceneFolderLocation, IndexScope, "lucene");
            }
            else
            {
                searchConnection = new SearchConnection(IndexesLocation, IndexScope);
            }

            _confirmationViewModel.SearchConnection = searchConnection;
        }
        private void UpdateIndex(InstallModel model)
        {
            var searchConnection = new SearchConnection(ConnectionHelper.GetConnectionString("SearchConnectionString"));

            if (searchConnection.Provider.Equals(
                    SearchProviders.Lucene.ToString(), StringComparison.OrdinalIgnoreCase) && searchConnection.DataSource.StartsWith("~/"))
            {
                var dataSource = searchConnection.DataSource.Replace(
                    "~/", HttpRuntime.AppDomainAppPath + "\\");

                searchConnection = new SearchConnection(dataSource, searchConnection.Scope, searchConnection.Provider);
            }

            SendFriendlyMessage("Updating search index...");
            new UpdateSearchIndex().Index(searchConnection, model.ConnectionStringBuilder.ConnectionString, null, true);
        }
Exemple #17
0
        private string GetSPSite()
        {
            if (String.IsNullOrWhiteSpace(Site) || Site.StartsWith("http://") || Site.StartsWith("https://"))
            {
                return(Site);
            }


            var fileName = GetPresetFilename(Site);

            SearchConnection sc = new SearchConnection();

            sc.Load(fileName);

            return(sc.SpSiteUrl);
        }
        private SearchIndexController GetSearchIndexController()
        {
            var cacheSettings = new[]
            {
                new CacheSettings("CatalogItemIndexBuilder.IndexItemCategories", TimeSpan.FromMinutes(30))
            };

            var settingManager      = new Moq.Mock <ISettingsManager>();
            var cacheManager        = new CacheManager(new InMemoryCachingProvider(), cacheSettings);
            var searchConnection    = new SearchConnection(ConnectionHelper.GetConnectionString("SearchConnectionString"));
            var searchProvider      = new LuceneSearchProvider(new LuceneSearchQueryBuilder(), searchConnection);
            var catalogIndexBuilder = new CatalogItemIndexBuilder(searchProvider, GetSearchService(), GetItemService(), GetPricingService(), GetPropertyService(), GetChangeLogService(), new CatalogOutlineBuilder(GetCategoryService(), cacheManager));
            var searchController    = new SearchIndexController(settingManager.Object, catalogIndexBuilder);

            return(searchController);
        }
        public override void Initialize()
        {
            base.Initialize();

            _container.RegisterType <ISearchIndexBuilder, CatalogItemIndexBuilder>(CatalogIndexedSearchCriteria.DocType);
            _container.RegisterType <ISearchIndexController, SearchIndexController>();

            var searchConnection = new SearchConnection(ConnectionHelper.GetConnectionString("SearchConnectionString"));

            _container.RegisterInstance <ISearchConnection>(searchConnection);

            var searchProviderManager = new SearchProviderManager(searchConnection);

            _container.RegisterInstance <ISearchProviderManager>(searchProviderManager);
            _container.RegisterInstance <ISearchProvider>(searchProviderManager);
        }
Exemple #20
0
        public void Can_find_item_lucene()
        {
            var scope        = "default";
            var queryBuilder = new LuceneSearchQueryBuilder();
            var conn         = new SearchConnection(_LuceneStorageDir, scope);
            var provider     = new LuceneSearchProvider(queryBuilder, conn);


            if (Directory.Exists(_LuceneStorageDir))
            {
                Directory.Delete(_LuceneStorageDir, true);
            }

            SearchHelper.CreateSampleIndex(provider, scope);

            var criteria = new CatalogItemSearchCriteria
            {
                SearchPhrase      = "product",
                IsFuzzySearch     = true,
                Catalog           = "goods",
                RecordsToRetrieve = 10,
                StartingRecord    = 0,
                Pricelists        = new string[] { }
            };


            var results = provider.Search(scope, criteria);

            Assert.True(results.DocCount == 1, String.Format("Returns {0} instead of 1", results.DocCount));

            criteria = new CatalogItemSearchCriteria
            {
                SearchPhrase      = "sample product ",
                IsFuzzySearch     = true,
                Catalog           = "goods",
                RecordsToRetrieve = 10,
                StartingRecord    = 0,
                Pricelists        = new string[] { }
            };


            results = provider.Search(scope, criteria);

            Assert.True(results.DocCount == 1, String.Format("\"Sample Product\" search returns {0} instead of 1", results.DocCount));

            Directory.Delete(_LuceneStorageDir, true);
        }
        protected ISearchProvider GetSearchProvider(string searchProvider, string scope, string dataSource = null)
        {
            ISearchProvider provider = null;

            var phraseSearchCriteriaPreprocessor  = new PhraseSearchCriteriaPreprocessor(new SearchPhraseParser()) as ISearchCriteriaPreprocessor;
            var catalogSearchCriteriaPreprocessor = new CatalogSearchCriteriaPreprocessor();
            var searchCriteriaPreprocessors       = new[] { phraseSearchCriteriaPreprocessor, catalogSearchCriteriaPreprocessor };

            if (searchProvider == "Lucene")
            {
                var connection   = new SearchConnection(_luceneStorageDir, scope);
                var queryBuilder = new LuceneSearchQueryBuilder() as ISearchQueryBuilder;
                provider = new LuceneSearchProvider(new[] { queryBuilder }, connection, searchCriteriaPreprocessors);
            }

            if (searchProvider == "Elastic")
            {
                var elasticsearchHost = dataSource ?? Environment.GetEnvironmentVariable("TestElasticsearchHost") ?? "localhost:9200";

                var connection            = new SearchConnection(elasticsearchHost, scope);
                var queryBuilder          = new ElasticSearchQueryBuilder() as ISearchQueryBuilder;
                var elasticSearchProvider = new ElasticSearchProvider(connection, searchCriteriaPreprocessors, new[] { queryBuilder }, GetSettingsManager())
                {
                    EnableTrace = true
                };
                provider = elasticSearchProvider;
            }

            if (searchProvider == "Azure")
            {
                var azureSearchServiceName = Environment.GetEnvironmentVariable("TestAzureSearchServiceName");
                var azureSearchAccessKey   = Environment.GetEnvironmentVariable("TestAzureSearchAccessKey");

                var connection   = new SearchConnection(azureSearchServiceName, scope, accessKey: azureSearchAccessKey);
                var queryBuilder = new AzureSearchQueryBuilder() as ISearchQueryBuilder;
                provider = new AzureSearchProvider(connection, searchCriteriaPreprocessors, new[] { queryBuilder });
            }

            if (provider == null)
            {
                throw new ArgumentException($"Search provider '{searchProvider}' is not supported", nameof(searchProvider));
            }

            return(provider);
        }
        public void Can_find_item_azuresearch()
        {
            var scope        = "test";
            var queryBuilder = new AzureSearchQueryBuilder();
            var conn         = new SearchConnection(Datasource, scope, accessKey: AccessKey);
            var provider     = new AzureSearchProvider(queryBuilder, conn);

            provider.RemoveAll(scope, String.Empty);
            SearchHelper.CreateSampleIndex(provider, scope);

            var criteria = new CatalogItemSearchCriteria
            {
                SearchPhrase      = "product",
                IsFuzzySearch     = true,
                Catalog           = "goods",
                RecordsToRetrieve = 10,
                StartingRecord    = 0,
                Pricelists        = new string[] { }
            };


            // force delay, otherwise records are not available
            Thread.Sleep(1000);

            var results = provider.Search(scope, criteria);

            Assert.True(results.DocCount == 1, String.Format("Returns {0} instead of 1", results.DocCount));

            criteria = new CatalogItemSearchCriteria
            {
                SearchPhrase      = "sample product ",
                IsFuzzySearch     = true,
                Catalog           = "goods",
                RecordsToRetrieve = 10,
                StartingRecord    = 0,
                Pricelists        = new string[] { }
            };


            results = provider.Search(scope, criteria);

            Assert.True(results.DocCount == 1, String.Format("\"Sample Product\" search returns {0} instead of 1", results.DocCount));

            provider.RemoveAll(scope, String.Empty);
        }
        public void Configure(CancellationToken ct)
        {
            ct.ThrowIfCancellationRequested();

            Result = null; // sets result to InProgress
            try
            {
                var searchConnection = _confirmationViewModel.SearchConnection;
                // Update Search index

                // handle special case for lucene, resolve relative path to the actual folder
                if (searchConnection.Provider.Equals(
                        "lucene", StringComparison.OrdinalIgnoreCase) && searchConnection.DataSource.StartsWith("~/"))
                {
                    var dataSource = searchConnection.DataSource.Replace(
                        "~/", _confirmationViewModel.ProjectLocation + "\\");

                    searchConnection = new SearchConnection(dataSource, searchConnection.Scope, searchConnection.Provider);
                }

                new UpdateSearchIndex().Index(searchConnection, _confirmationViewModel.DatabaseConnectionString, null, true);
                ct.ThrowIfCancellationRequested();

                Result = OperationResult.Successful;
            }
            catch (OperationCanceledException)
            {
                throw;
            }
            catch (Exception e)
            {
#if (DEBUG)
                MessageBox.Show(e.StackTrace);
#endif

                Message = string.Format("{0} {1}: {2}", Resources.SearchSettingsAction, Resources.Failed, e.ExpandExceptionMessage());
                Result  = OperationResult.Failed;
                throw;
            }
        }
Exemple #24
0
        public void Throws_exceptions_elastic()
        {
            var providerType    = "Elastic";
            var scope           = _DefaultScope;
            var badscope        = "doesntexist";
            var baddocumenttype = "badtype";
            var provider        = GetSearchProvider(providerType, scope);

            // try removing non-existing index
            // no exception should be generated, since 404 will be just eaten when index doesn't exist
            provider.RemoveAll(badscope, "");
            provider.RemoveAll(badscope, baddocumenttype);

            // now create an index and try removing non-existent document type
            SearchHelper.CreateSampleIndex(provider, scope);
            provider.RemoveAll(scope, "sometype");

            // create bad connection
            var queryBuilder = new ElasticSearchQueryBuilder();

            var conn         = new SearchConnection("localhost:9201", scope);
            var bad_provider = new ElasticSearchProvider(new[] { queryBuilder }, conn);

            bad_provider.EnableTrace = true;

            Assert.Throws <ElasticSearchException>(() => bad_provider.RemoveAll(badscope, ""));

            var criteria = new CatalogItemSearchCriteria
            {
                SearchPhrase      = "product",
                IsFuzzySearch     = true,
                Catalog           = "goods",
                RecordsToRetrieve = 10,
                StartingRecord    = 0,
                Pricelists        = new string[] { }
            };

            Assert.Throws <ElasticSearchException>(() => bad_provider.Search <DocumentDictionary>(scope, criteria));
        }
Exemple #25
0
        private void SavePresetToFile(SearchConnection searchConnection, SearchQueryRequest searchQueryRequest)
        {
            if (!String.IsNullOrWhiteSpace(SavePreset))
            {
                SearchPreset newPreset = new SearchPreset();
                var          path      = GetPresetFilename(SavePreset);

                newPreset.Name = Path.GetFileNameWithoutExtension(path);
                newPreset.Path = path;

                if (!Path.IsPathRooted(SavePreset))
                {
                    newPreset.Path = Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, newPreset.Path);
                }

                newPreset.Connection = searchConnection;
                newPreset.Request    = SetSelectProperties(searchQueryRequest);

                newPreset.Save();

                WriteVerbose("Configuration saved to " + newPreset.Path);
            }
        }
        public void Can_find_items_azuresearch()
        {
            var scope        = "default";
            var queryBuilder = new AzureSearchQueryBuilder();
            var conn         = new SearchConnection(Datasource, scope, accessKey: AccessKey);
            var provider     = new AzureSearchProvider(queryBuilder, conn);

            var criteria = new CatalogItemSearchCriteria
            {
                SearchPhrase      = "sony",
                IsFuzzySearch     = true,
                Catalog           = "vendorvirtual",
                RecordsToRetrieve = 10,
                StartingRecord    = 0,
                Pricelists        = new string[] { },
                StartDate         = DateTime.UtcNow,
                Sort = new SearchSort("price_usd_saleusd")
            };

            criteria.Outlines.Add("vendorvirtual*");

            //"(startdate lt 2014-09-26T22:05:11Z) and sys__hidden eq 'false' and sys__outline/any(t:t eq 'VendorVirtual/e1b56012-d877-4bdd-92d8-3fc186899d0f*') and catalog/any(t: t eq 'VendorVirtual')"
            var results = provider.Search(scope, criteria);
        }
        /// <summary>Registers the type mappings with the Unity container.</summary>
        /// <param name="container">The unity container to configure.</param>
        /// <remarks>There is no need to register concrete types such as controllers or API controllers (unless you want to
        /// change the defaults), as Unity allows resolving a concrete type even if it was not previously registered.</remarks>
        public static void RegisterTypes(IUnityContainer container)
        {
            // NOTE: To load from web.config uncomment the line below. Make sure to add a Microsoft.Practices.Unity.Configuration to the using statements.
            // container.LoadConfiguration();

            #region Common Settings for Web and Services

            // this section is common for both web application and services application and should be kept identical
            var isAzure = AzureCommonHelper.IsAzureEnvironment();

            container.RegisterType <IKnownSerializationTypes, CatalogEntityFactory>("catalog",
                                                                                    new ContainerControlledLifetimeManager
                                                                                        ());

            //container.RegisterType<IKnowSerializationTypes, OrderEntityFactory>("order", new ContainerControlledLifetimeManager(), null);
            container.RegisterInstance <IConsumerFactory>(new DomainAssemblyScannerConsumerFactory(container));
            container.RegisterType <IKnownSerializationTypes, DomainAssemblyScannerConsumerFactory>("scaned",
                                                                                                    new ContainerControlledLifetimeManager
                                                                                                        (),
                                                                                                    new InjectionConstructor
                                                                                                        (container));



            container.RegisterType <IConsumerFactory, DomainAssemblyScannerConsumerFactory>();
            container.RegisterType <ISystemObserver, NullSystemObserver>();
            container.RegisterType <IEngineProcess, SingleThreadConsumingProcess>();
            container.RegisterType <IMessageSerializer, DataContractMessageSerializer>();
            if (isAzure)
            {
                container.RegisterType <IQueueWriter, AzureQueueWriter>();
                container.RegisterType <IQueueReader, AzureQueueReader>();
            }
            else
            {
                container.RegisterType <IQueueWriter, InMemoryQueueWriter>();
                container.RegisterType <IQueueReader, InMemoryQueueReader>();
            }
            container.RegisterType <IMessageSender, DefaultMessageSender>(new ContainerControlledLifetimeManager());
            container.RegisterType <ICurrencyService, CurrencyService>(new ContainerControlledLifetimeManager());

            //container.RegisterType<ICacheProvider, InMemCachingProvider>();
            container.RegisterType <ICacheRepository, HttpCacheRepository>();
            container.RegisterType <IOperationLogRepository, OperationLogContext>(new PerRequestLifetimeManager());
            container.RegisterType <ILogOperationFactory, LogOperationFactory>();

            //Register Sequences
            container.RegisterType <ISequenceService, SequenceService>();

            //Register Template and Email service
            container.RegisterType <ITemplateService, TemplateService>();

            if (isAzure)
            {
                container.RegisterType <IEmailService, AzureEmailService>();
            }
            else
            {
                container.RegisterType <IEmailService, NetEmailService>();
            }

            container.RegisterType <ICatalogOutlineBuilder, CatalogOutlineBuilder>();

            #region Interceptors

            // register interceptors
            container.RegisterType <IInterceptor, AuditChangeInterceptor>("audit");
            container.RegisterType <IInterceptor, LogInterceptor>("log");
            container.RegisterType <IInterceptor, EntityEventInterceptor>("events");

            #endregion

            #region Marketing

            container.RegisterType <IMarketingRepository, EFMarketingRepository>(new PerRequestLifetimeManager());
            container.RegisterType <IMarketingEntityFactory, MarketingEntityFactory>();
            container.RegisterType <IPromotionUsageProvider, PromotionUsageProvider>();
            container.RegisterType <IPromotionEntryPopulate, PromotionEntryPopulate>();

            //Register prmotion evaluation policies
            container.RegisterType <IEvaluationPolicy, GlobalExclusivityPolicy>("global");
            container.RegisterType <IEvaluationPolicy, GroupExclusivityPolicy>("group");
            container.RegisterType <IEvaluationPolicy, CartSubtotalRewardCombinePolicy>("cart");
            container.RegisterType <IEvaluationPolicy, ShipmentRewardCombinePolicy>("shipment");


            container.RegisterType <IPromotionEvaluator, DefaultPromotionEvaluator>();

            #endregion

            #region Search

            var searchConnection = new SearchConnection(ConnectionHelper.GetConnectionString("SearchConnectionString"));
            container.RegisterInstance <ISearchConnection>(searchConnection);
            container.RegisterType <ISearchService, SearchService>(new HierarchicalLifetimeManager());
            container.RegisterType <ISearchIndexController, SearchIndexController>();
            container.RegisterType <IBuildSettingsRepository, EFSearchRepository>(new PerRequestLifetimeManager());
            container.RegisterType <ISearchEntityFactory, SearchEntityFactory>(new ContainerControlledLifetimeManager());
            container.RegisterType <ISearchIndexBuilder, CatalogItemIndexBuilder>("catalogitem");

            // If provider specified as lucene, use lucene libraries, otherwise use default, which is elastic search
            if (string.Equals(searchConnection.Provider, SearchProviders.Lucene.ToString(), StringComparison.OrdinalIgnoreCase))
            {
                // Lucene Search implementation
                container.RegisterType <ISearchProvider, LuceneSearchProvider>();
                container.RegisterType <ISearchQueryBuilder, LuceneSearchQueryBuilder>();
            }
            else if (string.Equals(searchConnection.Provider, SearchProviders.AzureSearch.ToString(), StringComparison.OrdinalIgnoreCase))
            {
                // Azure Search implementation
                container.RegisterType <ISearchProvider, AzureSearchProvider>();
                container.RegisterType <ISearchQueryBuilder, AzureSearchQueryBuilder>();
            }
            else
            {
                container.RegisterType <ISearchProvider, ElasticSearchProvider>();
                container.RegisterType <ISearchQueryBuilder, ElasticSearchQueryBuilder>();
            }
            #endregion

            #region Assets

            container.RegisterType <IAssetEntityFactory, AssetEntityFactory>();

            // using azure assets
            if (isAzure)
            {
                container.RegisterType <IAssetRepository, AzureBlobAssetRepository>();
                container.RegisterType <IBlobStorageProvider, AzureBlobAssetRepository>();
                container.RegisterType <IAssetUrl, AzureBlobAssetRepository>();
            }
            else
            {
                // using local storage assets
                container.RegisterType <IAssetRepository, FileSystemBlobAssetRepository>();
                container.RegisterType <IBlobStorageProvider, FileSystemBlobAssetRepository>();
                container.RegisterType <IAssetUrl, FileSystemAssetUrl>();
            }

            container.RegisterType <IAssetService, AssetService>();
            #endregion

            #region Catalog
            container.RegisterType <ICatalogEntityFactory, CatalogEntityFactory>(new ContainerControlledLifetimeManager());

            container.RegisterType <ICatalogRepository, EFCatalogRepository>(new PerRequestLifetimeManager());
            container.RegisterType <IPricelistRepository, EFCatalogRepository>(new PerRequestLifetimeManager());
            container.RegisterType <ICatalogService, CatalogService>();
            container.RegisterType <IPriceListAssignmentEvaluator, PriceListAssignmentEvaluator>();
            container.RegisterType <IPriceListAssignmentEvaluationContext, PriceListAssignmentEvaluationContext>();

            container.RegisterType <IImportJobEntityFactory, ImportJobEntityFactory>(
                new ContainerControlledLifetimeManager());
            container.RegisterType <IImportRepository, EFImportingRepository>(new PerRequestLifetimeManager());
            container.RegisterType <IImportService, ImportService>();
            #endregion

            #region Customer

            container.RegisterType <ICustomerEntityFactory, CustomerEntityFactory>(
                new ContainerControlledLifetimeManager());

            container.RegisterType <ICustomerRepository, EFCustomerRepository>(new PerRequestLifetimeManager());
            container.RegisterType <ICustomerSessionService, CustomerSessionService>();

            #endregion

            #region Inventory

            container.RegisterType <IInventoryEntityFactory, InventoryEntityFactory>(
                new ContainerControlledLifetimeManager());
            container.RegisterType <IInventoryRepository, EFInventoryRepository>(new PerRequestLifetimeManager());

            #endregion

            #region Order

            container.RegisterType <IOrderEntityFactory, OrderEntityFactory>(new ContainerControlledLifetimeManager());

            var activityProvider = WorkflowConfiguration.Instance.DefaultActivityProvider;
            var workflowService  = new WFWorkflowService(activityProvider);
            container.RegisterInstance <IWorkflowService>(workflowService);
            container.RegisterType <IOrderStateController, OrderStateController>();

            container.RegisterType <IOrderRepository, EFOrderRepository>(new PerRequestLifetimeManager());
            container.RegisterType <IShippingRepository, EFOrderRepository>(new PerRequestLifetimeManager());
            container.RegisterType <IPaymentMethodRepository, EFOrderRepository>(new PerRequestLifetimeManager());
            container.RegisterType <ITaxRepository, EFOrderRepository>(new PerRequestLifetimeManager());

            container.RegisterType <ICountryRepository, EFOrderRepository>(new PerRequestLifetimeManager());
            container.RegisterType <IOrderService, OrderService>();

            #endregion

            #region Review

            container.RegisterType <IReviewEntityFactory, ReviewEntityFactory>(new ContainerControlledLifetimeManager());
            container.RegisterType <IReviewRepository, EFReviewRepository>(new PerRequestLifetimeManager());

            #endregion

            #region Security

            container.RegisterType <ISecurityEntityFactory, SecurityEntityFactory>(
                new ContainerControlledLifetimeManager());
            container.RegisterType <ISecurityRepository, EFSecurityRepository>(new PerRequestLifetimeManager());
            container.RegisterType <IUserSecurity, WebUserSecurity>();
            container.RegisterType <IAuthenticationService, AuthenticationService>();
            container.RegisterType <ISecurityService, SecurityService>();
            container.RegisterType <IOAuthWebSecurity, OAuthWebSecurityWrapper>();

            #endregion

            #region Store

            container.RegisterType <IStoreEntityFactory, StoreEntityFactory>(new ContainerControlledLifetimeManager());

            container.RegisterType <IStoreService, StoreService>();
            container.RegisterType <IStoreRepository, EFStoreRepository>(new PerRequestLifetimeManager());

            #endregion

            #region Reporting

            container.RegisterType <IReportingService, ReportingService>();
            #endregion

            #endregion

            #region MVC Helpers

            container.RegisterType <MarketingHelper>();
            container.RegisterType <PriceListClient>();
            container.RegisterType <StoreClient>();
            container.RegisterType <CatalogClient>();
            container.RegisterType <UserClient>();
            container.RegisterType <ShippingClient>();
            container.RegisterType <PromotionClient>();
            container.RegisterType <DynamicContentClient>();
            container.RegisterType <CountryClient>();
            container.RegisterType <OrderClient>();
            container.RegisterType <DisplayTemplateClient>();
            container.RegisterType <SettingsClient>();
            container.RegisterType <SequencesClient>();
            container.RegisterType <SeoKeywordClient>(new PerRequestLifetimeManager());
            container.RegisterType <ReviewClient>();
            container.RegisterType <IPaymentOption, CreditCardOption>("creditcard");
            container.RegisterType <ISearchFilterService, StoreSearchFilterService>(new PerRequestLifetimeManager());

            #endregion

            #region DynamicContent

            container.RegisterType <IDynamicContentService, DynamicContentService>();
            container.RegisterType <IDynamicContentRepository, EFDynamicContentRepository>(new PerRequestLifetimeManager());
            container.RegisterType <IDynamicContentEvaluator, DynamicContentEvaluator>();

            #endregion

            #region AppConfig

            container.RegisterType <IAppConfigRepository, EFAppConfigRepository>(new PerRequestLifetimeManager());
            container.RegisterType <IAppConfigEntityFactory, AppConfigEntityFactory>(new ContainerControlledLifetimeManager());

            #endregion

            #region DisplayTemplates

            container.RegisterType <IDisplayTemplatesService, DisplayTemplatesService>();
            container.RegisterType <IDisplayTemplateEvaluator, DisplayTemplateEvaluator>();

            #endregion

            #region Events

            // Register event listeners
            container.RegisterType <IEntityEventListener, OrderChangeEventListener>("order");
            container.RegisterType <IEntityEventListener, PublicReplyEventListener>("customer");
            container.RegisterType <IEntityEventListener, CaseChangeEventListener>("customer");
            container.RegisterType <IEntityEventListener, ReviewApprovedEventListener>("review");
            container.RegisterType <IEntityEventContext, EntityEventContext>(new PerRequestLifetimeManager());

            #endregion

            #region Jobs

            container.RegisterType <GenerateSearchIndexWork>();
            container.RegisterType <ProcessOrderStatusWork>();
            container.RegisterType <ProcessSearchIndexWork>();

            #endregion

            #region Globalization

            //For using database resources
            container.RegisterType <IElementRepository, DatabaseElementRepository>(new PerRequestLifetimeManager());
            //For using Local Resources
            //container.RegisterInstance<IElementRepository>(new CacheElementRepository(new XmlElementRepository()));

            #endregion

            #region OutputCache

            container.RegisterType <IKeyBuilder, KeyBuilder>(new PerRequestLifetimeManager());
            container.RegisterType <IKeyGenerator, KeyGenerator>(new PerRequestLifetimeManager());
            container.RegisterType <IDonutHoleFiller, DonutHoleFiller>(new PerRequestLifetimeManager());
            container.RegisterType <ICacheHeadersHelper, CacheHeadersHelper>(new PerRequestLifetimeManager());
            container.RegisterType <ICacheSettingsManager, CacheSettingsManager>(new PerRequestLifetimeManager());
            container.RegisterType <IReadWriteOutputCacheManager, OutputCacheManager>(new PerRequestLifetimeManager());
            container.RegisterInstance <IActionSettingsSerialiser>(new EncryptingActionSettingsSerialiser(new ActionSettingsSerialiser(), new Encryptor()));
            container.RegisterType <ICacheService, CacheService>();

            #endregion

            container.RegisterInstance(container);
        }
Exemple #28
0
        public void Can_get_item_facets_lucene()
        {
            var scope        = "default";
            var queryBuilder = new LuceneSearchQueryBuilder();
            var conn         = new SearchConnection(_LuceneStorageDir, scope);
            var provider     = new LuceneSearchProvider(queryBuilder, conn);

            Debug.WriteLine("Lucene connection: {0}", conn.ToString());

            if (Directory.Exists(_LuceneStorageDir))
            {
                Directory.Delete(_LuceneStorageDir, true);
            }

            SearchHelper.CreateSampleIndex(provider, scope);

            var criteria = new CatalogIndexedSearchCriteria
            {
                SearchPhrase      = "",
                IsFuzzySearch     = true,
                Catalog           = "goods",
                RecordsToRetrieve = 10,
                StartingRecord    = 0,
                Currency          = "USD",
                Pricelists        = new[] { "default" }
            };

            var filter = new AttributeFilter {
                Key = "Color"
            };

            filter.Values = new[]
            {
                new AttributeFilterValue {
                    Id = "red", Value = "red"
                },
                new AttributeFilterValue {
                    Id = "blue", Value = "blue"
                },
                new AttributeFilterValue {
                    Id = "black", Value = "black"
                }
            };

            var rangefilter = new RangeFilter {
                Key = "size"
            };

            rangefilter.Values = new[]
            {
                new RangeFilterValue {
                    Id = "0_to_5", Lower = "0", Upper = "5"
                },
                new RangeFilterValue {
                    Id = "5_to_10", Lower = "5", Upper = "10"
                }
            };

            var priceRangefilter = new PriceRangeFilter {
                Currency = "usd"
            };

            priceRangefilter.Values = new[]
            {
                new RangeFilterValue {
                    Id = "0_to_100", Lower = "0", Upper = "100"
                },
                new RangeFilterValue {
                    Id = "100_to_700", Lower = "100", Upper = "700"
                }
            };

            criteria.Add(filter);
            criteria.Add(rangefilter);
            criteria.Add(priceRangefilter);

            var results = provider.Search(scope, criteria);

            Assert.True(results.DocCount == 4, String.Format("Returns {0} instead of 4", results.DocCount));

            var redCount = GetFacetCount(results, "Color", "red");

            Assert.True(redCount == 2, String.Format("Returns {0} facets of red instead of 2", redCount));

            var priceCount = GetFacetCount(results, "Price", "0_to_100");

            Assert.True(priceCount == 2, String.Format("Returns {0} facets of 0_to_100 prices instead of 2", priceCount));

            var priceCount2 = GetFacetCount(results, "Price", "100_to_700");

            Assert.True(priceCount2 == 2, String.Format("Returns {0} facets of 100_to_700 prices instead of 2", priceCount2));

            var sizeCount = GetFacetCount(results, "size", "0_to_5");

            Assert.True(sizeCount == 2, String.Format("Returns {0} facets of 0_to_5 size instead of 2", sizeCount));

            var sizeCount2 = GetFacetCount(results, "size", "5_to_10");

            Assert.True(sizeCount2 == 1, String.Format("Returns {0} facets of 5_to_10 size instead of 1", sizeCount2)); // only 1 result because upper bound is not included

            var outlineCount = results.Documents[0].Documents[0]["__outline"].Values.Count();

            Assert.True(outlineCount == 2, String.Format("Returns {0} outlines instead of 2", outlineCount));

            Directory.Delete(_LuceneStorageDir, true);
        }
Exemple #29
0
        public void Can_get_item_multiple_filters_lucene()
        {
            var scope        = "default";
            var queryBuilder = new LuceneSearchQueryBuilder();
            var conn         = new SearchConnection(_LuceneStorageDir, scope);
            var provider     = new LuceneSearchProvider(queryBuilder, conn);

            Debug.WriteLine("Lucene connection: {0}", conn.ToString());

            if (Directory.Exists(_LuceneStorageDir))
            {
                Directory.Delete(_LuceneStorageDir, true);
            }

            SearchHelper.CreateSampleIndex(provider, scope);

            var criteria = new CatalogIndexedSearchCriteria
            {
                SearchPhrase      = "",
                IsFuzzySearch     = true,
                Catalog           = "goods",
                RecordsToRetrieve = 10,
                StartingRecord    = 0,
                Currency          = "USD",
                Pricelists        = new[] { "default" }
            };

            var colorFilter = new AttributeFilter {
                Key = "Color"
            };

            colorFilter.Values = new[]
            {
                new AttributeFilterValue {
                    Id = "red", Value = "red"
                },
                new AttributeFilterValue {
                    Id = "blue", Value = "blue"
                },
                new AttributeFilterValue {
                    Id = "black", Value = "black"
                }
            };

            var filter = new AttributeFilter {
                Key = "Color"
            };

            filter.Values = new[]
            {
                new AttributeFilterValue {
                    Id = "black", Value = "black"
                }
            };

            var rangefilter = new RangeFilter {
                Key = "size"
            };

            rangefilter.Values = new[]
            {
                new RangeFilterValue {
                    Id = "0_to_5", Lower = "0", Upper = "5"
                },
                new RangeFilterValue {
                    Id = "5_to_10", Lower = "5", Upper = "11"
                }
            };

            var priceRangefilter = new PriceRangeFilter {
                Currency = "usd"
            };

            priceRangefilter.Values = new[]
            {
                new RangeFilterValue {
                    Id = "100_to_700", Lower = "100", Upper = "700"
                }
            };

            criteria.Add(colorFilter);
            criteria.Add(priceRangefilter);

            // add applied filters
            criteria.Apply(filter);
            //criteria.Apply(rangefilter);
            //criteria.Apply(priceRangefilter);

            var results = provider.Search(scope, criteria);

            var blackCount = GetFacetCount(results, "Color", "black");

            Assert.True(blackCount == 1, String.Format("Returns {0} facets of black instead of 2", blackCount));

            //Assert.True(results.DocCount == 1, String.Format("Returns {0} instead of 1", results.DocCount));

            Directory.Delete(_LuceneStorageDir, true);
        }
 protected abstract void SaveRequestPreset(SearchConnection searchConnection, TSearchRequest searchRequest);