protected ManagedProperty GetCurrentObject(object modelHost, ManagedPropertyDefinition definition,
            out ManagedPropertyCollection properties,
            out List<CrawledPropertyInfo> crawledProps)
        {
            if (modelHost is FarmModelHost)
            {
                var context = SPServiceContext.GetContext(SPServiceApplicationProxyGroup.Default,
                    SPSiteSubscriptionIdentifier.Default);
                var searchProxy =
                    context.GetDefaultProxy(typeof(SearchServiceApplicationProxy)) as SearchServiceApplicationProxy;

                var ssai = searchProxy.GetSearchServiceApplicationInfo();
                var application = SearchService.Service.SearchApplications.GetValue<SearchServiceApplication>(ssai.SearchServiceApplicationId);

                SearchObjectOwner searchOwner = new SearchObjectOwner(SearchObjectLevel.Ssa);

                if (cachedCrawledProps == null)
                    cachedCrawledProps = application.GetAllCrawledProperties(string.Empty, string.Empty, 0, searchOwner);

                crawledProps = cachedCrawledProps;

                var schema = new Schema(application);

                properties = schema.AllManagedProperties;
                return properties.FirstOrDefault(p => p.Name.ToUpper() == definition.Name.ToUpper());
            }

            throw new NotImplementedException();
        }
        private void DeploySearchConfiguration(object modelHost, Site site, SearchConfigurationDefinition definition)
        {
            var context = site.Context;

            var conf = new SearchConfigurationPortability(context);
            var owner = new SearchObjectOwner(context, SearchObjectLevel.SPSite);

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioning,
                Object = conf,
                ObjectType = typeof(SearchConfigurationPortability),
                ObjectDefinition = definition,
                ModelHost = modelHost
            });

            conf.ImportSearchConfiguration(owner, definition.SearchConfiguration);

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioned,
                Object = conf,
                ObjectType = typeof(SearchConfigurationPortability),
                ObjectDefinition = definition,
                ModelHost = modelHost
            });

            context.ExecuteQueryWithTrace();
        }
        protected override void ExecuteCmdlet()
        {
            switch (Scope)
            {
                case SearchConfigurationScope.Web:
                    {
                        WriteObject(this.SelectedWeb.GetSearchConfiguration());
                        break;
                    }
                case SearchConfigurationScope.Site:
                    {
                        WriteObject(ClientContext.Site.GetSearchConfiguration());
                        break;
                    }
                case SearchConfigurationScope.Subscription:
                {
                    if (!ClientContext.Url.ToLower().Contains("-admin"))
                    {
                        throw new InvalidOperationException(Resources.CurrentSiteIsNoTenantAdminSite);
                    }

                    SearchObjectOwner owningScope = new SearchObjectOwner(ClientContext, SearchObjectLevel.SPSiteSubscription);
                    var config = new SearchConfigurationPortability(ClientContext);
                    ClientResult<string> configuration = config.ExportSearchConfiguration(owningScope);
                    ClientContext.ExecuteQueryRetry(10, 60*5*1000);
                    WriteObject(configuration.Value);
                    break;
                }
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Creates a query rule object for the search level.
        /// If the rule already exists, if may be overwritten, depending on
        /// the QueryRuleInfo upgrade behavior definition (the OverwriteIfAlreadyExists
        /// flag is false by default).
        /// </summary>
        /// <param name="site">The current site collection.</param>
        /// <param name="queryRuleMetadata">The query rule definition.</param>
        /// <param name="level">The search level object.</param>
        /// <returns>The new query rule object.</returns>
        public QueryRule EnsureQueryRule(SPSite site, QueryRuleInfo queryRuleMetadata, SearchObjectLevel level)
        {
            var searchApp = this.searchHelper.GetDefaultSearchServiceApplication(site);
            var queryRuleManager = new QueryRuleManager(searchApp);
            var searchOwner = new SearchObjectOwner(level, site.RootWeb);

            // Build the SearchObjectFilter
            var searchObjectFilter = new SearchObjectFilter(searchOwner);

            QueryRuleCollection rules = queryRuleManager.GetQueryRules(searchObjectFilter);

            QueryRule returnedRule = null;
            var existingRule = rules.FirstOrDefault(r => r.DisplayName == queryRuleMetadata.DisplayName);

            if (existingRule != null)
            {
                // Deal with upgrade behavior (delete and re-create or return existing)
                if (queryRuleMetadata.OverwriteIfAlreadyExists)
                {
                    rules.RemoveQueryRule(existingRule);
                    returnedRule = rules.CreateQueryRule(queryRuleMetadata.DisplayName, queryRuleMetadata.StartDate, queryRuleMetadata.EndDate, queryRuleMetadata.IsActive);
                }
                else
                {
                    returnedRule = existingRule;
                }
            }
            else
            {
                // None exist already with that display name, create it
                returnedRule = rules.CreateQueryRule(queryRuleMetadata.DisplayName, queryRuleMetadata.StartDate, queryRuleMetadata.EndDate, queryRuleMetadata.IsActive);
            }

            return returnedRule;
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Returns the current search configuration for the specified object level
        /// </summary>
        /// <param name="context"></param>
        /// <param name="searchSettingsObjectLevel"></param>
        /// <returns></returns>
        private static string GetSearchConfigurationImplementation(ClientRuntimeContext context, SearchObjectLevel searchSettingsObjectLevel)
        {
            SearchConfigurationPortability sconfig = new SearchConfigurationPortability(context);
            SearchObjectOwner owner = new SearchObjectOwner(context, searchSettingsObjectLevel);

            ClientResult<string> configresults = sconfig.ExportSearchConfiguration(owner);
            context.ExecuteQueryRetry();

            return configresults.Value;
        }
Ejemplo n.º 6
0
        public void ImportSearchConfiguration(ClientContext context, string pathToSearchXml)
        {
            var searchConfigurationPortability = new SearchConfigurationPortability(context);
            var owningScope = new SearchObjectOwner(context, SearchObjectLevel.SPSite);

            var configurationXml = new XmlDocument();
            configurationXml.Load(pathToSearchXml);

            searchConfigurationPortability.ImportSearchConfiguration(owningScope, configurationXml.OuterXml);
            context.ExecuteQuery();
        }
        /// <summary>
        /// Returns the current search configuration for the specified object level
        /// </summary>
        /// <param name="context"></param>
        /// <param name="searchSettingsObjectLevel"></param>
        /// <returns></returns>
        private static string GetSearchConfigurationImplementation(ClientRuntimeContext context, SearchObjectLevel searchSettingsObjectLevel)
        {
            SearchConfigurationPortability sconfig = new SearchConfigurationPortability(context);
            SearchObjectOwner owner = new SearchObjectOwner(context, searchSettingsObjectLevel);

            ClientResult <string> configresults = sconfig.ExportSearchConfiguration(owner);

            context.ExecuteQueryRetry();

            return(configresults.Value);
        }
Ejemplo n.º 8
0
        private void SetCrawledPropertyMappings(
            SPSite site,
            SPManagedPropertyInfo managedPropertyDefinition,
            ManagedPropertyInfo managedPropertyInfo,
            SearchServiceApplication ssa,
            SearchObjectOwner owner,
            List <MappingInfo> mappings)
        {
            // Ensure crawl properties mappings
            foreach (var crawledPropertyKeyAndOrder in managedPropertyInfo.CrawledProperties)
            {
                // Get the crawled property (there may be more than one matching that name)
                var matchingCrawledProperties = this.GetCrawledPropertyByName(site, crawledPropertyKeyAndOrder.Key);
                if (matchingCrawledProperties != null && matchingCrawledProperties.Count > 0)
                {
                    foreach (var crawledProperty in matchingCrawledProperties)
                    {
                        // Create mapping information
                        var mapping = new MappingInfo
                        {
                            CrawledPropertyName = crawledProperty.Name,
                            CrawledPropset      = crawledProperty.Propset,
                            ManagedPid          = managedPropertyDefinition.Pid,
                            MappingOrder        = crawledPropertyKeyAndOrder.Value
                        };

                        // If managed property doesn't already contain a mapping for the crawled property, add it
                        if (
                            ssa.GetManagedPropertyMappings(managedPropertyDefinition, owner)
                            .All(m => m.CrawledPropertyName != mapping.CrawledPropertyName))
                        {
                            mappings.Add(mapping);
                        }
                        else
                        {
                            this.logger.Info(
                                "Mapping for managed property {0} and crawled property with name {1} is already exists",
                                managedPropertyDefinition.Name,
                                crawledPropertyKeyAndOrder);
                        }
                    }
                }
                else
                {
                    this.logger.Warn("Crawled property with name {0} not found!", crawledPropertyKeyAndOrder);
                }
            }

            // Apply mappings to the managed property
            if (mappings.Count > 0)
            {
                ssa.SetManagedPropertyMappings(managedPropertyDefinition, mappings, owner);
            }
        }
Ejemplo n.º 9
0
        private void DeploySearchResult(object modelHost, Microsoft.SharePoint.SPSite site, SearchResultDefinition definition)
        {
            FederationManager federationManager = null;
            SearchObjectOwner searchOwner       = null;

            var currentSource = GetCurrentSource(site, definition, out federationManager, out searchOwner);

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model            = null,
                EventType        = ModelEventType.OnProvisioning,
                Object           = currentSource,
                ObjectType       = typeof(Source),
                ObjectDefinition = definition,
                ModelHost        = modelHost
            });

            if (currentSource == null)
            {
                currentSource      = federationManager.CreateSource(searchOwner);
                currentSource.Name = definition.Name;

                if (definition.ProviderId.HasValue)
                {
                    currentSource.ProviderId = definition.ProviderId.Value;
                }
                else
                {
                    currentSource.ProviderId = GetProviderByName(federationManager, definition.ProviderName).Id;
                }
            }

            currentSource.Description = definition.Description ?? string.Empty;
            currentSource.CreateQueryTransform(new QueryTransformProperties(), definition.Query);

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model            = null,
                EventType        = ModelEventType.OnProvisioned,
                Object           = currentSource,
                ObjectType       = typeof(Source),
                ObjectDefinition = definition,
                ModelHost        = modelHost
            });

            currentSource.Commit();

            if (definition.IsDefault)
            {
                federationManager.UpdateDefaultSource(currentSource.Id, searchOwner);
            }
        }
Ejemplo n.º 10
0
        public void ImportSearchConfiguration(ClientContext context, string pathToSearchXml)
        {
            var searchConfigurationPortability = new SearchConfigurationPortability(context);
            var owningScope = new SearchObjectOwner(context, SearchObjectLevel.SPSite);

            var configurationXml = new XmlDocument();

            configurationXml.Load(pathToSearchXml);

            searchConfigurationPortability.ImportSearchConfiguration(owningScope, configurationXml.OuterXml);
            context.ExecuteQuery();
        }
Ejemplo n.º 11
0
        protected Source GetCurrentSource(Microsoft.SharePoint.SPSite site, SearchResultDefinition definition,
            out FederationManager federationManager,
            out SearchObjectOwner searchOwner)
        {
            var context = SPServiceContext.GetContext(site);
            var searchAppProxy = context.GetDefaultProxy(typeof(SearchServiceApplicationProxy)) as SearchServiceApplicationProxy;

            federationManager = new FederationManager(searchAppProxy);
            searchOwner = new SearchObjectOwner(SearchObjectLevel.SPSite, site.RootWeb);

            return federationManager.GetSourceByName(definition.Name, searchOwner);
        }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();
            var ctx = base.Context;

            SearchObjectLevel configScope = ConfigScope;
            var searchConfigurationPortability = new SearchConfigurationPortability(ctx);
            var owner = new SearchObjectOwner(ctx, configScope);
            var result = searchConfigurationPortability.ExportSearchConfiguration(owner);
            ctx.ExecuteQuery();
            System.IO.File.WriteAllText(Path, result.Value);
        }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();
            var ctx = base.Context;

            SearchObjectLevel configScope = ConfigScope;
            var searchConfigurationPortability = new SearchConfigurationPortability(ctx);
            var owner = new SearchObjectOwner(ctx, configScope);
            var searchConfigXml = InputObject.Read();
            searchConfigurationPortability.ImportSearchConfiguration(owner, searchConfigXml.OuterXml);
            ctx.ExecuteQuery();
        }
Ejemplo n.º 14
0
        protected Source GetCurrentSource(Microsoft.SharePoint.SPSite site, SearchResultDefinition definition,
                                          out FederationManager federationManager,
                                          out SearchObjectOwner searchOwner)
        {
            var context        = SPServiceContext.GetContext(site);
            var searchAppProxy = context.GetDefaultProxy(typeof(SearchServiceApplicationProxy)) as SearchServiceApplicationProxy;

            federationManager = new FederationManager(searchAppProxy);
            searchOwner       = new SearchObjectOwner(SearchObjectLevel.SPSite, site.RootWeb);

            return(federationManager.GetSourceByName(definition.Name, searchOwner));
        }
Ejemplo n.º 15
0
        public void EnsureManagedProperty_WhenOverwriteIfAlreadyExists_ShouldCreateTheManagedProperty()
        {
            const string ManagedPropertyName = "TestManagedProperty";

            using (var testScope = SiteTestScope.BlankSite())
            {
                // Arrange
                var owner = new SearchObjectOwner(SearchObjectLevel.Ssa, testScope.SiteCollection.RootWeb);
                var managedPropertyInfo = new ManagedPropertyInfo(ManagedPropertyName, ManagedDataType.Text)
                {
                    Sortable          = true,
                    Refinable         = true,
                    Queryable         = true,
                    CrawledProperties = new Dictionary <string, int>()
                    {
                        { "ows_Title", 1 }
                    },
                    UpdateBehavior = ManagedPropertyUpdateBehavior.OverwriteIfAlreadyExists
                };

                using (var injectionScope = IntegrationTestServiceLocator.BeginLifetimeScope())
                {
                    var searchHelper = injectionScope.Resolve <ISearchHelper>();
                    var ssa          = searchHelper.GetDefaultSearchServiceApplication(testScope.SiteCollection);

                    try
                    {
                        // Act
                        var actualManagedProperty          = searchHelper.EnsureManagedProperty(testScope.SiteCollection, managedPropertyInfo);
                        var refetchedActualManagedProperty = ssa.GetManagedProperty(ManagedPropertyName, owner);

                        // Assert
                        Assert.IsNotNull(actualManagedProperty);
                        Assert.AreEqual(true, actualManagedProperty.Sortable);
                        Assert.AreEqual(true, actualManagedProperty.Refinable);
                        Assert.AreEqual(true, actualManagedProperty.Queryable);
                        Assert.IsTrue(actualManagedProperty.GetMappedCrawledProperties(1)[0].Name == "ows_Title");

                        Assert.IsNotNull(refetchedActualManagedProperty);
                        Assert.AreEqual(true, refetchedActualManagedProperty.Sortable);
                        Assert.AreEqual(true, refetchedActualManagedProperty.Refinable);
                        Assert.AreEqual(true, refetchedActualManagedProperty.Queryable);
                        Assert.IsTrue(ssa.GetManagedPropertyMappings(refetchedActualManagedProperty, owner)[0].CrawledPropertyName == "ows_Title");
                    }
                    finally
                    {
                        // Clean up
                        searchHelper.DeleteManagedProperty(testScope.SiteCollection, managedPropertyInfo);
                    }
                }
            }
        }
        protected string GetCurrentSearchConfiguration(Site site)
        {
            var context = site.Context;

            var conf = new SearchConfigurationPortability(context);
            var owner = new SearchObjectOwner(context, SearchObjectLevel.SPSite);

            var result = conf.ExportSearchConfiguration(owner);

            context.ExecuteQueryWithTrace();

            return result.Value;
        }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();
            var ctx = base.Context;

            SearchObjectLevel configScope      = ConfigScope;
            var searchConfigurationPortability = new SearchConfigurationPortability(ctx);
            var owner  = new SearchObjectOwner(ctx, configScope);
            var result = searchConfigurationPortability.ExportSearchConfiguration(owner);

            ctx.ExecuteQuery();
            System.IO.File.WriteAllText(Path, result.Value);
        }
Ejemplo n.º 18
0
        protected override void ProcessRecord()
        {
            base.ProcessRecord();
            var ctx = base.Context;

            SearchObjectLevel configScope      = ConfigScope;
            var searchConfigurationPortability = new SearchConfigurationPortability(ctx);
            var owner           = new SearchObjectOwner(ctx, configScope);
            var searchConfigXml = InputObject.Read();

            searchConfigurationPortability.ImportSearchConfiguration(owner, searchConfigXml.OuterXml);
            ctx.ExecuteQuery();
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Deletes the result source.
        /// </summary>
        /// <param name="contextSite">Current site collection</param>
        /// <param name="resultSourceName">Name of the result source.</param>
        /// <param name="level">The level.</param>
        public void DeleteResultSource(SPSite contextSite, string resultSourceName, SearchObjectLevel level)
        {
            var searchApp         = this.GetDefaultSearchServiceApplication(contextSite);
            var federationManager = new FederationManager(searchApp);
            var searchOwner       = new SearchObjectOwner(level, contextSite.RootWeb);

            var resultSource = federationManager.GetSourceByName(resultSourceName, searchOwner);

            if (resultSource != null)
            {
                federationManager.RemoveSource(resultSource);
            }
        }
        protected string GetCurrentSearchConfiguration(Site site)
        {
            var context = site.Context;

            var conf  = new SearchConfigurationPortability(context);
            var owner = new SearchObjectOwner(context, SearchObjectLevel.SPSite);

            var result = conf.ExportSearchConfiguration(owner);

            context.ExecuteQueryWithTrace();

            return(result.Value);
        }
Ejemplo n.º 21
0
        private SearchSettingsUtility(SPSite site)
        {
            _searchOwner = new SearchObjectOwner(SearchObjectLevel.SPSite, site.RootWeb);

            SPServiceContext context = SPServiceContext.GetContext(site);

            _searchProxy = context.GetDefaultProxy(typeof(SearchServiceApplicationProxy)) as SearchServiceApplicationProxy;

            if (_searchProxy == null)
            {
                throw new ArgumentException("SearchServiceApplicationProxy not found for site collection {0}", site.Url);
            }
        }
        protected override void ExecuteCmdlet()
        {
            string configoutput = string.Empty;

            switch (Scope)
            {
            case SearchConfigurationScope.Web:
            {
                configoutput = SelectedWeb.GetSearchConfiguration();
                break;
            }

            case SearchConfigurationScope.Site:
            {
                configoutput = ClientContext.Site.GetSearchConfiguration();
                break;
            }

            case SearchConfigurationScope.Subscription:
            {
                if (!ClientContext.Url.ToLower().Contains("-admin"))
                {
                    throw new InvalidOperationException(Resources.CurrentSiteIsNoTenantAdminSite);
                }

                SearchObjectOwner owningScope = new SearchObjectOwner(ClientContext, SearchObjectLevel.SPSiteSubscription);
                var config = new SearchConfigurationPortability(ClientContext);
                ClientResult <string> configuration = config.ExportSearchConfiguration(owningScope);
                ClientContext.ExecuteQueryRetry(10, 60 * 5 * 1000);

                configoutput = configuration.Value;
            }
            break;
            }

            if (Path != null)
            {
                if (!System.IO.Path.IsPathRooted(Path))
                {
                    Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path);
                }
                System.IO.File.WriteAllText(Path, configoutput);
            }
            else
            {
                WriteObject(configoutput);
            }
        }
Ejemplo n.º 23
0
        public void EnsureResultSource_WhenAppendingQuery_ShouldAppendToEndOfExistingQuery()
        {
            const string ResultSourceName = "Test Result Source";
            const string Query            = "{?{searchTerms} -ContentClass=urn:content-class:SPSPeople}";
            const string AppendedQuery    = "{?{|owstaxidmetadataalltagsinfo:{User.SPSResponsibility}}}";

            using (var testScope = SiteTestScope.BlankSite())
            {
                // Arrange
                var resultSourceInfo = new ResultSourceInfo()
                {
                    Name       = ResultSourceName,
                    Level      = SearchObjectLevel.SPSite,
                    Query      = Query,
                    UpdateMode = ResultSourceUpdateBehavior.OverwriteResultSource
                };

                var appendedResultSourceInfo = new ResultSourceInfo()
                {
                    Name       = ResultSourceName,
                    Level      = SearchObjectLevel.SPSite,
                    Query      = AppendedQuery,
                    UpdateMode = ResultSourceUpdateBehavior.AppendToQuery
                };

                var expectedQuery = string.Format(CultureInfo.InvariantCulture, "{0} {1}", Query, AppendedQuery);

                using (var injectionScope = IntegrationTestServiceLocator.BeginLifetimeScope())
                {
                    var searchHelper      = injectionScope.Resolve <ISearchHelper>();
                    var ssa               = searchHelper.GetDefaultSearchServiceApplication(testScope.SiteCollection);
                    var federationManager = new FederationManager(ssa);
                    var searchOwner       = new SearchObjectOwner(SearchObjectLevel.SPSite, testScope.SiteCollection.RootWeb);

                    // Act
                    searchHelper.EnsureResultSource(testScope.SiteCollection, resultSourceInfo);
                    searchHelper.EnsureResultSource(testScope.SiteCollection, appendedResultSourceInfo);

                    // Assert
                    var source = federationManager.GetSourceByName(ResultSourceName, searchOwner);

                    Assert.IsNotNull(source);
                    Assert.IsNotNull(source.QueryTransform);
                    Assert.AreEqual(ResultSourceName, source.Name);
                    Assert.AreEqual(expectedQuery, source.QueryTransform.QueryTemplate);
                }
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Delete a result type in the site collection
        /// </summary>
        /// <param name="site">The site</param>
        /// <param name="resultType">The result type object</param>
        public void DeleteResultType(SPSite site, ResultTypeInfo resultType)
        {
            ResultItemType resType = null;

            var searchOwner         = new SearchObjectOwner(SearchObjectLevel.SPSite, site.RootWeb);
            var resultTypeManager   = new ResultItemTypeManager(this.GetDefaultSearchServiceApplication(site));
            var existingResultTypes = resultTypeManager.GetResultItemTypes(searchOwner, true);

            // Get the existing result type
            resType = existingResultTypes.FirstOrDefault(r => r.Name.Equals(resultType.Name));

            if (resType != null)
            {
                resultTypeManager.DeleteResultItemType(resType);
            }
        }
        public override void Export()
        {
            var ctx = base.AcquireContext();
            //var site = base.GetSite();
            SearchConfigurationPortability conf = new SearchConfigurationPortability(ctx);
            SearchObjectOwner owner             = new SearchObjectOwner(ctx, SearchObjectLevel.SPSiteSubscription);
            var buff = conf.ExportSearchConfiguration(owner);

            ctx.ExecuteQuery();
            var dir  = Path.Combine(Provider.Connector.Parameters["ConnectionString"].ToString(), $"{ExportFolderName}");
            var path = Path.Combine($"{dir}\\SearchSettings.xml");

            System.IO.Directory.CreateDirectory(dir);

            System.IO.File.WriteAllText(path, buff.Value);
        }
        protected override void ExecuteCmdlet()
        {
            string configoutput = string.Empty;

            switch (Scope)
            {
                case SearchConfigurationScope.Web:
                    {
                        configoutput = SelectedWeb.GetSearchConfiguration();
                        break;
                    }
                case SearchConfigurationScope.Site:
                    {
                        configoutput = ClientContext.Site.GetSearchConfiguration();
                        break;
                    }
                case SearchConfigurationScope.Subscription:
                    {
                        if (!ClientContext.Url.ToLower().Contains("-admin"))
                        {
                            throw new InvalidOperationException(Resources.CurrentSiteIsNoTenantAdminSite);
                        }

                        SearchObjectOwner owningScope = new SearchObjectOwner(ClientContext, SearchObjectLevel.SPSiteSubscription);
                        var config = new SearchConfigurationPortability(ClientContext);
                        ClientResult<string> configuration = config.ExportSearchConfiguration(owningScope);
                        ClientContext.ExecuteQueryRetry(10, 60 * 5 * 1000);

                        configoutput = configuration.Value;
                    }
                    break;
            }

            if (Path != null)
            {
                if (!System.IO.Path.IsPathRooted(Path))
                {
                    Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path);
                }
                System.IO.File.WriteAllText(Path, configoutput);
            }
            else
            {
                WriteObject(configoutput);
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Delete the search configuration at the specified object level - does not apply to managed properties.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="searchObjectLevel"></param>
        /// <param name="searchConfiguration"></param>
        private static void DeleteSearchConfigurationImplementation(ClientRuntimeContext context, SearchObjectLevel searchObjectLevel, string searchConfiguration)
        {
#if ONPREMISES
            if (searchObjectLevel == SearchObjectLevel.Ssa)
            {
                // Reference: https://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.search.portability.searchconfigurationportability_members.aspx
                throw new Exception("You cannot import customized search configuration settings to a Search service application (SSA).");
            }
#endif
            SearchConfigurationPortability searchConfig = new SearchConfigurationPortability(context);
            SearchObjectOwner owner = new SearchObjectOwner(context, searchObjectLevel);

            // Delete search configuration
            searchConfig.DeleteSearchConfiguration(owner, searchConfiguration);
            context.Load(searchConfig);
            context.ExecuteQueryRetry();
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Ensure a managed property in the search service application schema
        /// </summary>
        /// <param name="site">The context site</param>
        /// <param name="managedPropertyInfo">The managed property info</param>
        /// <returns>The managed property</returns>
        public ManagedProperty EnsureManagedProperty(SPSite site, ManagedPropertyInfo managedPropertyInfo)
        {
            var ssa          = this.GetDefaultSearchServiceApplication(site);
            var propertyName = managedPropertyInfo.Name;

            // this forces managed prop definition to SSA-scope
            // (i.e. all managed props will be farm-wide)
            var owner = new SearchObjectOwner(SearchObjectLevel.Ssa, site.RootWeb);

            // Get the managed property and if null, create it
            var managedPropertyDefinition = this.GetManagedProperty(managedPropertyInfo, ssa, owner);

            if (managedPropertyDefinition == null)
            {
                // If managed property was created, make sure it sets the crawled property mappings and configuration
                managedPropertyInfo.UpdateBehavior = ManagedPropertyUpdateBehavior.OverwriteIfAlreadyExists;
                managedPropertyDefinition          = this.CreateManagedProperty(managedPropertyInfo, ssa, owner);
            }

            if (managedPropertyDefinition != null)
            {
                // If crawled property mappings need to be overwritten or appended
                if (ShouldUpdateCrawledPropertyMappings(managedPropertyInfo))
                {
                    var mappings = GetInitialCrawledPropertyMappings(managedPropertyDefinition, managedPropertyInfo, ssa, owner);
                    this.SetCrawledPropertyMappings(site, managedPropertyDefinition, managedPropertyInfo, ssa, owner, mappings);
                }

                if (ShouldUpdateConfiguration(managedPropertyInfo))
                {
                    this.ConfigureManagerProperty(managedPropertyDefinition, managedPropertyInfo);
                }

                // Save through the schema manager (don't call .Update on the managed property object itself, its config won't get saved properly)
                ssa.UpdateManagedProperty(managedPropertyDefinition, owner);
            }

            // Re-fetch schema, it might be stale at this point
            var sspSchema = new Schema(ssa);

            return(sspSchema.AllManagedProperties[propertyName]);
        }
Ejemplo n.º 29
0
        private static void ExportSearchSettings(ClientContext context, string settingsFile)
        {
            ConsoleColor defaultForeground = Console.ForegroundColor;

            /*
             * SearchConfigurationPortability Class
             * http://msdn.microsoft.com/en-us/library/office/microsoft.sharepoint.client.search.portability.searchconfigurationportability(v=office.15).aspx
             *
             * SearchObjectOwner Class
             * http://msdn.microsoft.com/en-us/library/office/microsoft.office.server.search.administration.searchobjectowner(v=office.15).aspx
             */
            SearchConfigurationPortability sconfig = new SearchConfigurationPortability(context);
            SearchObjectOwner owner = new SearchObjectOwner(context, SearchObjectLevel.SPWeb);

            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("Writing out search configuration settings from: " + context.Web.Title);
            Console.ForegroundColor = defaultForeground;

            ClientResult <string> configresults = sconfig.ExportSearchConfiguration(owner);

            context.ExecuteQuery();

            if (configresults.Value != null)
            {
                string results = configresults.Value;
                System.IO.File.WriteAllText(settingsFile, results, Encoding.ASCII);

                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("Search settings have been exported. Press any key to continue");
                Console.ForegroundColor = defaultForeground;
                Console.Read();
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("No search settings configuration results were returned. Press any key to continue");
                Console.ForegroundColor = defaultForeground;
                Console.Read();
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Imports search settings from file.
        /// </summary>
        /// <param name="context">Context for SharePoint objects and operations</param>
        /// <param name="searchSchemaImportFilePath">Search schema xml file path</param>
        /// <param name="searchSettingsImportLevel">Search settings import level
        /// Reference: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.search.administration.searchobjectlevel(v=office.15).aspx
        /// </param>
        public static void ImportSearchSettings(this ClientContext context, string searchSchemaImportFilePath, SearchObjectLevel searchSettingsImportLevel)
        {
            if (string.IsNullOrEmpty(searchSchemaImportFilePath))
            {
                throw new ArgumentNullException("searchSchemaImportFilePath");
            }

            #if CLIENTSDKV15
            if (searchSettingsImportLevel == SearchObjectLevel.Ssa)
            {
                // Reference: https://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.search.portability.searchconfigurationportability_members.aspx
                throw new Exception("You cannot import customized search configuration settings to a Search service application (SSA).");
            }
            #endif
            SearchConfigurationPortability searchConfig = new SearchConfigurationPortability(context);
            SearchObjectOwner owner = new SearchObjectOwner(context, searchSettingsImportLevel);

            // Import search configuration
            searchConfig.ImportSearchConfiguration(owner, System.IO.File.ReadAllText(searchSchemaImportFilePath));
            context.Load(searchConfig);
            context.ExecuteQuery();
        }
Ejemplo n.º 31
0
        public void ApplySearchSchema(string templatePath, string SPUrl, string tenantAdminUser, string tenantAdminPassword, SearchObjectLevel level)
        {
            try
            {
                using (ClientContext ctx = new ClientContext(SPUrl))
                {
                    ctx.Credentials =
                        new SharePointOnlineCredentials(
                            tenantAdminUser,
                            tenantAdminPassword.GetSecureString());

                    SearchConfigurationPortability conf = new SearchConfigurationPortability(ctx);
                    SearchObjectOwner owner             = new SearchObjectOwner(ctx, level);
                    conf.ImportSearchConfiguration(owner, System.IO.File.ReadAllText(templatePath));
                    ctx.ExecuteQuery();
                }
            }
            catch (System.Exception e)
            {
                Console.Error.WriteLine($"##vso[task.logissue type=error] Failed to apply search settings with error {e.Message}");
            }
        }
Ejemplo n.º 32
0
        public void EnsureResultSource_WhenSortingByRank_ShouldApplySpecifiedRankingModel()
        {
            const string ResultSourceName = "Test Result Source";

            // Arrange
            using (var testScope = SiteTestScope.BlankSite())
            {
                var resultSourceInfo = new ResultSourceInfo()
                {
                    Name = ResultSourceName,
                    Level = SearchObjectLevel.SPSite,
                    Query = "{?{searchTerms} -ContentClass=urn:content-class:SPSPeople}",
                    SortSettings = new Dictionary<string, SortDirection>()
                    {
                        { BuiltInManagedProperties.Rank.Name, SortDirection.Descending }
                    },
                    RankingModelId = BuiltInRankingModels.DefaultSearchModelId,
                    UpdateMode = ResultSourceUpdateBehavior.OverwriteResultSource
                };

                using (var injectionScope = IntegrationTestServiceLocator.BeginLifetimeScope())
                {
                    var searchHelper = injectionScope.Resolve<ISearchHelper>();
                    var ssa = searchHelper.GetDefaultSearchServiceApplication(testScope.SiteCollection);
                    var federationManager = new FederationManager(ssa);
                    var searchOwner = new SearchObjectOwner(SearchObjectLevel.SPSite, testScope.SiteCollection.RootWeb);

                    // Act
                    searchHelper.EnsureResultSource(testScope.SiteCollection, resultSourceInfo);

                    // Assert
                    var source = federationManager.GetSourceByName(ResultSourceName, searchOwner);

                    Assert.IsNotNull(source);
                    Assert.AreEqual(ResultSourceName, source.Name);
                    Assert.AreEqual(BuiltInRankingModels.DefaultSearchModelId.ToString(), source.QueryTransform.OverrideProperties["RankingModelId"]);
                }
            }
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Imports search settings from file.
        /// </summary>
        /// <param name="context">Context for SharePoint objects and operations</param>
        /// <param name="searchSchemaImportFilePath">Search schema xml file path</param>
        /// <param name="searchSettingsImportLevel">Search settings import level
        /// Reference: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.search.administration.searchobjectlevel(v=office.15).aspx
        /// </param>
        public static void ImportSearchSettings(this ClientContext context, string searchSchemaImportFilePath, SearchObjectLevel searchSettingsImportLevel)
        {
            if (string.IsNullOrEmpty(searchSchemaImportFilePath))
            {
                throw new ArgumentNullException("searchSchemaImportFilePath");
            }

#if CLIENTSDKV15
            if (searchSettingsImportLevel == SearchObjectLevel.Ssa)
            {
                // Reference: https://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.search.portability.searchconfigurationportability_members.aspx
                throw new Exception("You cannot import customized search configuration settings to a Search service application (SSA).");
            }
#endif
            SearchConfigurationPortability searchConfig = new SearchConfigurationPortability(context);
            SearchObjectOwner owner = new SearchObjectOwner(context, searchSettingsImportLevel);

            // Import search configuration
            searchConfig.ImportSearchConfiguration(owner, System.IO.File.ReadAllText(searchSchemaImportFilePath));
            context.Load(searchConfig);
            context.ExecuteQueryRetry();
        }
Ejemplo n.º 34
0
        public void EnsureResultSource_WhenSortingByRank_ShouldApplySpecifiedRankingModel()
        {
            const string ResultSourceName = "Test Result Source";

            // Arrange
            using (var testScope = SiteTestScope.BlankSite())
            {
                var resultSourceInfo = new ResultSourceInfo()
                {
                    Name         = ResultSourceName,
                    Level        = SearchObjectLevel.SPSite,
                    Query        = "{?{searchTerms} -ContentClass=urn:content-class:SPSPeople}",
                    SortSettings = new Dictionary <string, SortDirection>()
                    {
                        { BuiltInManagedProperties.Rank.Name, SortDirection.Descending }
                    },
                    RankingModelId = BuiltInRankingModels.DefaultSearchModelId,
                    UpdateMode     = ResultSourceUpdateBehavior.OverwriteResultSource
                };

                using (var injectionScope = IntegrationTestServiceLocator.BeginLifetimeScope())
                {
                    var searchHelper      = injectionScope.Resolve <ISearchHelper>();
                    var ssa               = searchHelper.GetDefaultSearchServiceApplication(testScope.SiteCollection);
                    var federationManager = new FederationManager(ssa);
                    var searchOwner       = new SearchObjectOwner(SearchObjectLevel.SPSite, testScope.SiteCollection.RootWeb);

                    // Act
                    searchHelper.EnsureResultSource(testScope.SiteCollection, resultSourceInfo);

                    // Assert
                    var source = federationManager.GetSourceByName(ResultSourceName, searchOwner);

                    Assert.IsNotNull(source);
                    Assert.AreEqual(ResultSourceName, source.Name);
                    Assert.AreEqual(BuiltInRankingModels.DefaultSearchModelId.ToString(), source.QueryTransform.OverrideProperties["RankingModelId"]);
                }
            }
        }
Ejemplo n.º 35
0
        /// <summary>
        /// Ensure a Result Type in a site collection
        /// </summary>
        /// <param name="site">The site collection</param>
        /// <param name="resultType">The result type info object</param>
        /// <returns>The result type item</returns>
        public ResultItemType EnsureResultType(SPSite site, ResultTypeInfo resultType)
        {
            var searchOwner  = new SearchObjectOwner(SearchObjectLevel.SPSite, site.RootWeb);
            var resultSource = this.GetResultSourceByName(site, resultType.ResultSource.Name, resultType.ResultSource.Level);

            var resultTypeManager   = new ResultItemTypeManager(this.GetDefaultSearchServiceApplication(site));
            var existingResultTypes = resultTypeManager.GetResultItemTypes(searchOwner, true);

            // Get the existing result type
            var resType = existingResultTypes.FirstOrDefault(r => r.Name.Equals(resultType.Name));

            if (resType == null)
            {
                resType          = new ResultItemType(searchOwner);
                resType.Name     = resultType.Name;
                resType.SourceID = resultSource.Id;

                resType.DisplayTemplateUrl = resultType.DisplayTemplate.ItemTemplateTokenizedPath;
                var properties = resultType.DisplayProperties.Select(t => t.Name).ToArray();
                resType.DisplayProperties = string.Join(",", properties);
                resType.RulePriority      = resultType.Priority;

                // Create rules
                var rules =
                    resultType.Rules.Select(
                        this.CreateCustomPropertyRule)
                    .ToList();
                resType.Rules = new PropertyRuleCollection(rules);

                typeof(ResultItemType).GetProperty("OptimizeForFrequentUse")
                .SetValue(resType, resultType.OptimizeForFrequenUse);

                // Add the result type
                resultTypeManager.AddResultItemType(resType);
            }

            return(resType);
        }
Ejemplo n.º 36
0
        static void Main(string[] args)
        {
            using (SPSite site = new SPSite("http://portal.spdev16.com/one-stop-shop"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPServiceContext serviceContext = SPServiceContext.GetContext(site);

                    var searchApplicationProxy = (SearchServiceApplicationProxy)serviceContext.GetDefaultProxy(typeof(SearchServiceApplicationProxy));
                    //var owner = new SearchObjectOwner(SearchObjectLevel.SPSite, web);
                    var owner = new SearchObjectOwner(SearchObjectLevel.SPWeb, web);

                    ICollection <ResultItemType> itemTypes = searchApplicationProxy.GetResultItemTypes(null, null, owner, true);

                    ResultItemType item = CreateResultType(web, "Internal Resource - Deployed", "/_catalogs/masterpage/Display Templates/Search/Item_InternalResource.js",
                                                           new PropertyRule[] {
                        CustomPropertyRule("ContentTypeId", PropertyRuleOperator.DefaultOperator.Contains, new string[] { "41E5CAB13DEA48B8A69A7A47EA4F4EE4" })
                    }, false);

                    searchApplicationProxy.AddResultItemType(item);
                }
            }
        }
Ejemplo n.º 37
0
        /// <summary>
        /// Exports the search settings to file.
        /// </summary>
        /// <param name="context">Context for SharePoint objects and operations</param>
        /// <param name="exportFilePath">Path where to export the search settings</param>
        /// <param name="searchSettingsExportLevel">Search settings export level
        /// Reference: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.search.administration.searchobjectlevel(v=office.15).aspx
        /// </param>
        public static void ExportSearchSettings(this ClientContext context, string exportFilePath, SearchObjectLevel searchSettingsExportLevel)
        {
            if (string.IsNullOrEmpty(exportFilePath))
            {
                throw new ArgumentNullException("exportFilePath");
            }

            SearchConfigurationPortability sconfig = new SearchConfigurationPortability(context);
            SearchObjectOwner owner = new SearchObjectOwner(context, searchSettingsExportLevel);

            ClientResult<string> configresults = sconfig.ExportSearchConfiguration(owner);
            context.ExecuteQuery();

            if (configresults.Value != null)
            {
                string results = configresults.Value;
                System.IO.File.WriteAllText(exportFilePath, results, Encoding.ASCII);
            }
            else
            {
                throw new Exception("No search settings to export.");
            }
        }
Ejemplo n.º 38
0
        private SPManagedPropertyInfo CreateManagedProperty(
            ManagedPropertyInfo managedPropertyInfo,
            SearchServiceApplication ssa,
            SearchObjectOwner owner)
        {
            SPManagedPropertyInfo managedPropertyDefinition = null;
            var propertyName = managedPropertyInfo.Name;
            var propertyType = managedPropertyInfo.DataType;

            // Get the search schema
            var sspSchema         = new Schema(ssa);
            var managedProperties = sspSchema.AllManagedProperties;

            // If the managed property already exists
            // Else create it.
            if (managedProperties.Contains(propertyName))
            {
                var prop = managedProperties[propertyName];
                if (prop.DeleteDisallowed)
                {
                    this.logger.Warn("Delete is disallowed on the Managed Property {0}", propertyName);
                }
                else
                {
                    prop.DeleteAllMappings();
                    prop.Delete();
                    managedPropertyDefinition = ssa.CreateManagedProperty(propertyName, propertyType, owner);
                }
            }
            else
            {
                managedPropertyDefinition = ssa.CreateManagedProperty(propertyName, propertyType, owner);
            }

            return(managedPropertyDefinition);
        }
Ejemplo n.º 39
0
        /// <summary>
        /// Exports the search settings to file.
        /// </summary>
        /// <param name="context">Context for SharePoint objects and operations</param>
        /// <param name="exportFilePath">Path where to export the search settings</param>
        /// <param name="searchSettingsExportLevel">Search settings export level
        /// Reference: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.search.administration.searchobjectlevel(v=office.15).aspx
        /// </param>
        public static void ExportSearchSettings(this ClientContext context, string exportFilePath, SearchObjectLevel searchSettingsExportLevel)
        {
            if (string.IsNullOrEmpty(exportFilePath))
            {
                throw new ArgumentNullException("exportFilePath");
            }

            SearchConfigurationPortability sconfig = new SearchConfigurationPortability(context);
            SearchObjectOwner owner = new SearchObjectOwner(context, searchSettingsExportLevel);

            ClientResult <string> configresults = sconfig.ExportSearchConfiguration(owner);

            context.ExecuteQuery();

            if (configresults.Value != null)
            {
                string results = configresults.Value;
                System.IO.File.WriteAllText(exportFilePath, results, Encoding.ASCII);
            }
            else
            {
                throw new Exception("No search settings to export.");
            }
        }
Ejemplo n.º 40
0
        /// <summary>
        /// Deletes the result source.
        /// </summary>
        /// <param name="contextSite">Current site collection</param>
        /// <param name="resultSourceName">Name of the result source.</param>
        /// <param name="level">The level.</param>
        public void DeleteResultSource(SPSite contextSite, string resultSourceName, SearchObjectLevel level)
        {
            var searchApp = this.GetDefaultSearchServiceApplication(contextSite);
            var federationManager = new FederationManager(searchApp);
            var searchOwner = new SearchObjectOwner(level, contextSite.RootWeb);

            var resultSource = federationManager.GetSourceByName(resultSourceName, searchOwner);
            if (resultSource != null)
            {
                federationManager.RemoveSource(resultSource);
            }
        }
Ejemplo n.º 41
0
        protected override void ExecuteCmdlet()
        {
            string configOutput = string.Empty;

            switch (Scope)
            {
            case SearchConfigurationScope.Web:
            {
                configOutput = SelectedWeb.GetSearchConfiguration();
                break;
            }

            case SearchConfigurationScope.Site:
            {
                configOutput = ClientContext.Site.GetSearchConfiguration();
                break;
            }

            case SearchConfigurationScope.Subscription:
            {
                if (!ClientContext.Url.ToLower().Contains("-admin"))
                {
                    throw new InvalidOperationException(Resources.CurrentSiteIsNoTenantAdminSite);
                }

                SearchObjectOwner owningScope = new SearchObjectOwner(ClientContext, SearchObjectLevel.SPSiteSubscription);
                var config = new SearchConfigurationPortability(ClientContext);
                ClientResult <string> configuration = config.ExportSearchConfiguration(owningScope);
                ClientContext.ExecuteQueryRetry(10, 60 * 5 * 1000);

                configOutput = configuration.Value;
            }
            break;
            }

            if (Path != null)
            {
                if (!System.IO.Path.IsPathRooted(Path))
                {
                    Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path);
                }
                System.IO.File.WriteAllText(Path, configOutput);
            }
            else
            {
                if (OutputFormat == OutputFormat.CompleteXml)
                {
                    WriteObject(configOutput);
                }
                else if (OutputFormat == OutputFormat.ManagedPropertyMappings)
                {
                    StringReader sr  = new StringReader(configOutput);
                    var          doc = XDocument.Load(sr);
                    var          mps = GetCustomManagedProperties(doc);

                    foreach (var mp in mps)
                    {
                        mp.Aliases  = new List <string>();
                        mp.Mappings = new List <string>();

                        var mappings = GetCpMappingsFromPid(doc, mp.Pid);
                        mp.Mappings = mappings;
                        var aliases = GetAliasesFromPid(doc, mp.Pid);
                        mp.Aliases = aliases;
                    }
                    WriteObject(mps);
                }
            }
        }
        protected string GetCurrentSearchConfiguration(SPSite site)
        {
            var owner = new SearchObjectOwner(SearchObjectLevel.SPSite, site.RootWeb);

            return(new SearchConfigurationPortability(site).ExportSearchConfiguration(owner));
        }
Ejemplo n.º 43
0
 protected Source GetDefaultSource(FederationManager federationManager, SearchObjectOwner owner)
 {
     return(federationManager.GetDefaultSource(owner));
 }
Ejemplo n.º 44
0
        /// <summary>
        /// Sets the search configuration at the specified object level
        /// </summary>
        /// <param name="context"></param>
        /// <param name="searchObjectLevel"></param>
        /// <param name="searchConfiguration"></param>
        private static void SetSearchConfigurationImplementation(ClientRuntimeContext context, SearchObjectLevel searchObjectLevel, string searchConfiguration)
        {
#if CLIENTSDKV15
            if (searchObjectLevel == SearchObjectLevel.Ssa)
            {
                // Reference: https://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.search.portability.searchconfigurationportability_members.aspx
                throw new Exception("You cannot import customized search configuration settings to a Search service application (SSA).");
            }
#endif
            SearchConfigurationPortability searchConfig = new SearchConfigurationPortability(context);
            SearchObjectOwner owner = new SearchObjectOwner(context, searchObjectLevel);

            // Import search configuration
            searchConfig.ImportSearchConfiguration(owner, searchConfiguration);
            context.Load(searchConfig);
            context.ExecuteQueryRetry();
        }
Ejemplo n.º 45
0
        private static List<MappingInfo> GetInitialCrawledPropertyMappings(
            SPManagedPropertyInfo managedPropertyDefinition,
            ManagedPropertyInfo managedPropertyInfo,
            SearchServiceApplication ssa,
            SearchObjectOwner owner)
        {
            var mappingCollection = new List<MappingInfo>();

            // If specified to overwrite all crawled property mappings
            // set an empty mapping info list before recreating the mappings.
            // Else if, if specified to append the crawled properties, initialize the
            // mapping collection to the existing mappings on the managed property.
            switch (managedPropertyInfo.UpdateBehavior)
            {
                case ManagedPropertyUpdateBehavior.OverwriteCrawledProperties:
                case ManagedPropertyUpdateBehavior.OverwriteIfAlreadyExists:
                    ssa.SetManagedPropertyMappings(managedPropertyDefinition, mappingCollection, owner);
                    break;
                case ManagedPropertyUpdateBehavior.AppendCrawledProperties:
                    mappingCollection = ssa.GetManagedPropertyMappings(managedPropertyDefinition, owner);
                    break;
            }

            return mappingCollection;
        }
Ejemplo n.º 46
0
        /// <summary>
        /// Returns result source id for Matter Center result source
        /// </summary>
        /// <param name="login">Login detail</param>
        /// <param name="password">Password</param>
        /// <returns>Result source id</returns>
        private static string GetResultSourceId(string login, string password)
        {
            string filePath = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + ConstantStrings.BACKSLASH + ConfigurationManager.AppSettings["filename"];
            string configSheet = ConfigurationManager.AppSettings["manifestSheetname"];
            Dictionary<string, string> ConfigDetails = ExcelOperations.ReadFromExcel(filePath, configSheet);
            string url = ConfigDetails[ConfigurationManager.AppSettings["TenantSiteUrlKey"]].TrimEnd(ConstantStrings.FRONTSLASH);
            string resultSourceID = null;

            try
            {
                using (ClientContext clientContext = ConfigureSharePointContext.ConfigureClientContext(url, login, password))
                {
                    ClientRuntimeContext context = clientContext;
                    SearchConfigurationPortability searchConfigPortability = new SearchConfigurationPortability(context);
                    SearchObjectOwner owner = new SearchObjectOwner(context, SearchObjectLevel.SPSite);
                    ClientResult<string> searchConfigXML = searchConfigPortability.ExportSearchConfiguration(owner);
                    context.ExecuteQuery();

                    using (Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(searchConfigXML.Value)))
                    {
                        string id = ConfigurationManager.AppSettings["XMLNodeId"], resultSourceName = ConfigurationManager.AppSettings["ResultSourceName"];

                        if (0 < stream.Length)
                        {
                            XDocument xmlDoc = XDocument.Load(stream);
                            XElement element = null;
                            GetResultSource(resultSourceName, xmlDoc, ref element);
                            if (null != element)
                            {
                                resultSourceID = element.Descendants().Where(x => x.Name.LocalName.Equals(id)).FirstOrDefault().Value;
                            }
                            else
                            {
                                string errorMessage = "Result Source ID not found.";
                                ErrorLogger.DisplayErrorMessage(errorMessage);
                                throw new Exception(errorMessage);
                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                ErrorLogger.LogErrorToTextFile(errorPath, ConstantStrings.MESSAGE + exception.Message + ConstantStrings.STACKTRACE + exception.StackTrace);
            }
            return resultSourceID;
        }
Ejemplo n.º 47
0
        private SPManagedPropertyInfo CreateManagedProperty(
            ManagedPropertyInfo managedPropertyInfo,
            SearchServiceApplication ssa,
            SearchObjectOwner owner)
        {
            SPManagedPropertyInfo managedPropertyDefinition = null;
            var propertyName = managedPropertyInfo.Name;
            var propertyType = managedPropertyInfo.DataType;

            // Get the search schema
            var sspSchema = new Schema(ssa);
            var managedProperties = sspSchema.AllManagedProperties;

            // If the managed property already exists
            // Else create it.
            if (managedProperties.Contains(propertyName))
            {
                var prop = managedProperties[propertyName];
                if (prop.DeleteDisallowed)
                {
                    this.logger.Warn("Delete is disallowed on the Managed Property {0}", propertyName);
                }
                else
                {
                    prop.DeleteAllMappings();
                    prop.Delete();
                    managedPropertyDefinition = ssa.CreateManagedProperty(propertyName, propertyType, owner);
                }
            }
            else
            {
                managedPropertyDefinition = ssa.CreateManagedProperty(propertyName, propertyType, owner);
            }

            return managedPropertyDefinition;
        }
Ejemplo n.º 48
0
        private void SetCrawledPropertyMappings(
            SPSite site,
            SPManagedPropertyInfo managedPropertyDefinition,
            ManagedPropertyInfo managedPropertyInfo,
            SearchServiceApplication ssa,
            SearchObjectOwner owner,
            List<MappingInfo> mappings)
        {
            // Ensure crawl properties mappings
            foreach (var crawledPropertyKeyAndOrder in managedPropertyInfo.CrawledProperties)
            {
                // Get the crawled property (there may be more than one matching that name)
                var matchingCrawledProperties = this.GetCrawledPropertyByName(site, crawledPropertyKeyAndOrder.Key);
                if (matchingCrawledProperties != null && matchingCrawledProperties.Count > 0)
                {
                    foreach (var crawledProperty in matchingCrawledProperties)
                    {
                        // Create mapping information
                        var mapping = new MappingInfo
                        {
                            CrawledPropertyName = crawledProperty.Name,
                            CrawledPropset = crawledProperty.Propset,
                            ManagedPid = managedPropertyDefinition.Pid,
                            MappingOrder = crawledPropertyKeyAndOrder.Value
                        };

                        // If managed property doesn't already contain a mapping for the crawled property, add it
                        if (
                            ssa.GetManagedPropertyMappings(managedPropertyDefinition, owner)
                                .All(m => m.CrawledPropertyName != mapping.CrawledPropertyName))
                        {
                            mappings.Add(mapping);
                        }
                        else
                        {
                            this.logger.Info(
                                "Mapping for managed property {0} and crawled property with name {1} is already exists",
                                managedPropertyDefinition.Name,
                                crawledPropertyKeyAndOrder);
                        }
                    }
                }
                else
                {
                    this.logger.Warn("Crawled property with name {0} not found!", crawledPropertyKeyAndOrder);
                }
            }

            // Apply mappings to the managed property
            if (mappings.Count > 0)
            {
                ssa.SetManagedPropertyMappings(managedPropertyDefinition, mappings, owner);
            }
        }
Ejemplo n.º 49
0
        /// <summary>
        /// Ensure a search result source
        /// </summary>
        /// <param name="ssa">The search service application.</param>
        /// <param name="resultSourceName">The result source name</param>
        /// <param name="level">The search object level.</param>
        /// <param name="searchProvider">The search provider for the result source.</param>
        /// <param name="contextWeb">The SPWeb to retrieve the search context.</param>
        /// <param name="query">The search query in KQL format.</param>
        /// <param name="properties">Query properties.</param>
        /// <param name="overwrite">if set to <c>true</c> [overwrite].</param>
        /// <param name="isDefaultResultSourceForOwner">Whether this result source will be flagged as the default for the current search owner</param>
        /// <returns>
        /// The result source.
        /// </returns>
        private static Source InnerEnsureResultSource(SearchServiceApplication ssa, string resultSourceName, SearchObjectLevel level, string searchProvider, SPWeb contextWeb, string query, QueryTransformProperties properties, bool overwrite, bool isDefaultResultSourceForOwner)
        {
            var federationManager = new FederationManager(ssa);
            var searchOwner = new SearchObjectOwner(level, contextWeb);

            var resultSource = federationManager.GetSourceByName(resultSourceName, searchOwner);

            if (resultSource != null && overwrite)
            {
                federationManager.RemoveSource(resultSource);
            }

            if (resultSource == null || overwrite)
            {
                resultSource = federationManager.CreateSource(searchOwner);
                resultSource.Name = resultSourceName;
                resultSource.ProviderId = federationManager.ListProviders()[searchProvider].Id;
                resultSource.CreateQueryTransform(properties, query);
                resultSource.Commit();

                if (isDefaultResultSourceForOwner)
                {
                    federationManager.UpdateDefaultSource(resultSource.Id, searchOwner);
                }
            }

            return resultSource;
        }
Ejemplo n.º 50
0
        private SPManagedPropertyInfo GetManagedProperty(
            ManagedPropertyInfo managedPropertyInfo,
            SearchServiceApplication ssa,
            SearchObjectOwner owner)
        {
            SPManagedPropertyInfo managedPropertyDefinition = null;
            var propertyName = managedPropertyInfo.Name;

            // Get the search schema
            var sspSchema = new Schema(ssa);
            var managedProperties = sspSchema.AllManagedProperties;

            // If the managed property already exists
            // Else create it.
            if (managedProperties.Contains(propertyName))
            {
                managedPropertyDefinition = ssa.GetManagedProperty(propertyName, owner);
            }
            else
            {
                this.logger.Warn("Managed Property '{0}' not found.", propertyName);
            }

            return managedPropertyDefinition;
        }
Ejemplo n.º 51
0
        /// <summary>
        /// Ensure a managed property in the search service application schema
        /// </summary>
        /// <param name="site">The context site</param>
        /// <param name="managedPropertyInfo">The managed property info</param>
        /// <returns>The managed property</returns>
        public ManagedProperty EnsureManagedProperty(SPSite site, ManagedPropertyInfo managedPropertyInfo)
        {
            SPManagedPropertyInfo managedPropertyDefinition = null;

            var ssa = this.GetDefaultSearchServiceApplication(site);
            var propertyName = managedPropertyInfo.Name;
            var propertyType = managedPropertyInfo.DataType;
            var owner = new SearchObjectOwner(SearchObjectLevel.Ssa, site.RootWeb);     // this forces managed prop definition to SSA-scope
                                                                                        // (i.e. all managed props will be farm-wide)

            // Get the search schema
            var sspSchema = new Schema(ssa);
            var managedProperties = sspSchema.AllManagedProperties;

            if (managedProperties.Contains(propertyName))
            {
                var prop = managedProperties[propertyName];
                if (managedPropertyInfo.OverwriteIfAlreadyExists)
                {
                    if (prop.DeleteDisallowed)
                    {
                        this.logger.Warn("Delete is disallowed on the Managed Property {0}", propertyName);
                    }
                    else
                    {
                        prop.DeleteAllMappings();
                        prop.Delete();
                        managedPropertyDefinition = ssa.CreateManagedProperty(propertyName, propertyType, owner);
                    }
                }
            }
            else
            {
                managedPropertyDefinition = ssa.CreateManagedProperty(propertyName, propertyType, owner);
            }

            if (managedPropertyDefinition != null)
            {
                var mappingCollection = new List<MappingInfo>(); // new MappingCollection();

                // Ensure crawl properties mappings
                foreach (KeyValuePair<string, int> crawledPropertyKeyAndOrder in managedPropertyInfo.CrawledProperties)
                {
                    // Get the crawled property (there may be more than one matching that name)
                    var matchingCrawledProperties = this.GetCrawledPropertyByName(site, crawledPropertyKeyAndOrder.Key);

                    if (matchingCrawledProperties != null && matchingCrawledProperties.Count > 0)
                    {
                        foreach (var cp in matchingCrawledProperties)
                        {
                            // Create mapping information
                            var mapping = new MappingInfo
                            {
                                CrawledPropertyName = cp.Name,
                                CrawledPropset = cp.Propset,
                                ManagedPid = managedPropertyDefinition.Pid,
                                MappingOrder = crawledPropertyKeyAndOrder.Value
                            };

                            if (!ssa.GetManagedPropertyMappings(managedPropertyDefinition, owner).Any(m => m.CrawledPropertyName == mapping.CrawledPropertyName))
                            {
                                mappingCollection.Add(mapping);
                            }
                            else
                            {
                                this.logger.Info("Mapping for managed property {0} and crawled property with name {1} is already exists", managedPropertyDefinition.Name, crawledPropertyKeyAndOrder);
                            }
                        }
                    }
                    else
                    {
                        this.logger.Warn("Crawled property with name {0} not found!", crawledPropertyKeyAndOrder);
                    }
                }

                // Apply mappings to the managed property
                if (mappingCollection.Count > 0)
                {
                    ssa.SetManagedPropertyMappings(managedPropertyDefinition, mappingCollection, owner);
                }

                // Configure the managed property
                managedPropertyDefinition.Sortable = managedPropertyInfo.Sortable;
                if (managedPropertyDefinition.Sortable)
                {
                    managedPropertyDefinition.SortableType = managedPropertyInfo.SortableType;
                }

                managedPropertyDefinition.Refinable = managedPropertyInfo.Refinable;
                if (managedPropertyDefinition.Refinable)
                {
                    // use "active" refine mode whenever refinable=TRUE
                    managedPropertyDefinition.RefinerConfiguration.Type = Microsoft.Office.Server.Search.Administration.RefinerType.Deep;
                }

                managedPropertyDefinition.Retrievable = managedPropertyInfo.Retrievable;
                managedPropertyDefinition.RespectPriority = managedPropertyInfo.RespectPriority;
                managedPropertyDefinition.Queryable = managedPropertyInfo.Queryable;
                managedPropertyDefinition.Searchable = managedPropertyInfo.Searchable;

                if (managedPropertyDefinition.Searchable)
                {
                    managedPropertyDefinition.FullTextIndex = managedPropertyInfo.FullTextIndex;
                    managedPropertyDefinition.Context = managedPropertyInfo.Context;
                }
                else
                {
                    managedPropertyDefinition.FullTextIndex = string.Empty;
                    managedPropertyDefinition.Context = (short)0;
                }

                managedPropertyDefinition.HasMultipleValues = managedPropertyInfo.HasMultipleValues;
                managedPropertyDefinition.SafeForAnonymous = managedPropertyInfo.SafeForAnonymous;

                // Save through the schema manager (don't call .Update on the managed property object itself, its config won't get saved properly)
                ssa.UpdateManagedProperty(managedPropertyDefinition, owner);
            }

            // Re-fetch schema, it might be stale at this point
            sspSchema = new Schema(ssa);

            return sspSchema.AllManagedProperties[propertyName];
        }
Ejemplo n.º 52
0
        public void EnsureResultSource_WhenRevertingAppendedQuery_ShouldRevertToPreviousQuery()
        {
            const string ResultSourceName = "Test Result Source";
            const string Query = "{?{searchTerms} -ContentClass=urn:content-class:SPSPeople}";
            const string AppendedQuery = "{?{|owstaxidmetadataalltagsinfo:{User.SPSResponsibility}}}";

            using (var testScope = SiteTestScope.BlankSite())
            {
                // Arrange
                var resultSourceInfo = new ResultSourceInfo()
                {
                    Name = ResultSourceName,
                    Level = SearchObjectLevel.SPSite,
                    Query = Query,
                    UpdateMode = ResultSourceUpdateBehavior.OverwriteResultSource
                };

                var appendedResultSourceInfo = new ResultSourceInfo()
                {
                    Name = ResultSourceName,
                    Level = SearchObjectLevel.SPSite,
                    Query = AppendedQuery,
                    UpdateMode = ResultSourceUpdateBehavior.AppendToQuery
                };

                var revertedResultSourceInfo = new ResultSourceInfo()
                {
                    Name = ResultSourceName,
                    Level = SearchObjectLevel.SPSite,
                    Query = AppendedQuery,
                    UpdateMode = ResultSourceUpdateBehavior.RevertQuery
                };

                using (var injectionScope = IntegrationTestServiceLocator.BeginLifetimeScope())
                {
                    var searchHelper = injectionScope.Resolve<ISearchHelper>();
                    var ssa = searchHelper.GetDefaultSearchServiceApplication(testScope.SiteCollection);
                    var federationManager = new FederationManager(ssa);
                    var searchOwner = new SearchObjectOwner(SearchObjectLevel.SPSite, testScope.SiteCollection.RootWeb);

                    // Act
                    searchHelper.EnsureResultSource(testScope.SiteCollection, resultSourceInfo);
                    searchHelper.EnsureResultSource(testScope.SiteCollection, appendedResultSourceInfo);
                    searchHelper.EnsureResultSource(testScope.SiteCollection, revertedResultSourceInfo);

                    // Assert
                    var source = federationManager.GetSourceByName(ResultSourceName, searchOwner);

                    Assert.IsNotNull(source);
                    Assert.IsNotNull(source.QueryTransform);
                    Assert.AreEqual(ResultSourceName, source.Name);
                    Assert.AreEqual(Query, source.QueryTransform.QueryTemplate);
                }
            }
        }
Ejemplo n.º 53
0
        /// <summary>
        /// Update Search Configuration file and set new Search Term for restricting search scope
        /// </summary>
        /// <param name="filePath">path of the configuration Excel</param>
        /// <param name="login">Login detail</param>
        /// <param name="password">Password</param>
        public static void UpdateSearchConfig(string filePath, string login, string password)
        {
            // 1. Read Configuration Excel and form Search Term            
            string clientSheetName = ConfigurationManager.AppSettings["manifestSheetname"], xmlQueryTemplate = ConfigurationManager.AppSettings["XMLNodeQueryTemplate"];
            Dictionary<string, string> constantsList = ExcelOperations.ReadFromExcel(filePath, clientSheetName);

            string updatedSearchTerm;
            using (ClientContext context = ConfigureSharePointContext.ConfigureClientContext(constantsList[ConstantStrings.TENANT_ADMIN_URL], login, password))
            {
                string groupName = ConfigurationManager.AppSettings["PracticeGroupName"];
                string termSetName = ConfigurationManager.AppSettings["TermSetName"];
                string clientIdProperty = ConfigurationManager.AppSettings["ClientIDProperty"];
                string clientUrlProperty = ConfigurationManager.AppSettings["ClientUrlProperty"];
                ClientTermSets clientTermSets = TermStoreOperations.GetClientDetails(context, groupName, termSetName, clientIdProperty, clientUrlProperty);
                updatedSearchTerm = GetSearchTerm(clientTermSets);
            }

            // 2. Read Search Configuration XML file
            string resultSourceSearchConfigFilename = ConfigurationManager.AppSettings["ResultSourceXML"], resultSourceName = ConfigurationManager.AppSettings["ResultSourceName"],
            mangedPropertySearchConfigFileName = ConfigurationManager.AppSettings["SearchConfigXML"];
            string xmlFolderPath = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.GetDirectories(ConfigurationManager.AppSettings["StaticContentFolder"]).FirstOrDefault().GetDirectories(ConfigurationManager.AppSettings["XMLFolderName"]).FirstOrDefault().FullName;
            string resultSourceSearchConfigPath = string.Concat(xmlFolderPath, ConstantStrings.BACKSLASH, resultSourceSearchConfigFilename);
            string managedPropertySearchConfigPath = string.Concat(xmlFolderPath, ConstantStrings.BACKSLASH, mangedPropertySearchConfigFileName);
            XDocument resultSourceXml = XDocument.Load(resultSourceSearchConfigPath);
            XDocument managedPropertyXml = XDocument.Load(managedPropertySearchConfigPath);
            XElement resultSource = null;

            GetResultSource(resultSourceName, resultSourceXml, ref resultSource); // Existing result source

            if (null != resultSource)
            {
                XElement queryTemplate = resultSource.Descendants().Where(item => item.Name.LocalName.Equals(xmlQueryTemplate)).FirstOrDefault();
                // 3. Update XML file and set updated search term
                if (null != queryTemplate)
                {
                    queryTemplate.Value = updatedSearchTerm;
                    resultSourceXml.Save(resultSourceSearchConfigPath);
                }
                else
                {
                    string errorMessage = "Query Template not found in Search Configuration";
                    ErrorLogger.DisplayErrorMessage(errorMessage);
                    ErrorLogger.LogErrorToTextFile(errorPath, errorMessage);
                }
            }

            try
            {
                // 4. Upload Search Configuration to SharePoint, Import search configuration For creating Result Source at Catalog Level
                string configSheet = ConfigurationManager.AppSettings["manifestSheetname"];
                Dictionary<string, string> configDetails = ExcelOperations.ReadFromExcel(filePath, configSheet);
                string url = configDetails[ConfigurationManager.AppSettings["TenantSiteUrlKey"]].TrimEnd();
                using (ClientContext clientContext = ConfigureSharePointContext.ConfigureClientContext(url, login, password))
                {
                    ClientRuntimeContext context = clientContext;
                    SearchConfigurationPortability searchConfigPortability = new SearchConfigurationPortability(context);
                    SearchObjectOwner owner = new SearchObjectOwner(context, SearchObjectLevel.SPSite);
                    searchConfigPortability.ImportSearchConfiguration(owner, resultSourceXml.ToString());
                    context.ExecuteQuery();
                    Console.WriteLine("Imported search configuration and created result source.");
                }

                // 5. Upload Search Configuration tenant level and create managed properties
                url = configDetails[ConstantStrings.TENANT_ADMIN_URL].Trim();
                using (ClientContext clientContext = ConfigureSharePointContext.ConfigureClientContext(url, login, password))
                {
                    ClientRuntimeContext context = clientContext;
                    SearchConfigurationPortability searchConfigPortability = new SearchConfigurationPortability(context);
                    SearchObjectOwner owner = new SearchObjectOwner(context, SearchObjectLevel.SPSiteSubscription);
                    searchConfigPortability.ImportSearchConfiguration(owner, managedPropertyXml.ToString());
                    context.ExecuteQuery();
                    Console.WriteLine("Imported search configuration and created search schema.");
                }
            }
            catch (Exception exception)
            {
                ErrorLogger.LogErrorToTextFile(errorPath, ConstantStrings.MESSAGE + exception.Message + ConstantStrings.STACKTRACE + exception.StackTrace);
            }
        }
Ejemplo n.º 54
0
        /// <summary>
        /// Gets the result source by name using the default search service application
        /// </summary>
        /// <param name="site">The site collection.</param>
        /// <param name="resultSourceName">Name of the result source.</param>
        /// <param name="scopeOwnerLevel">The level of the scope's owner.</param>
        /// <returns>
        /// The corresponding result source.
        /// </returns>
        public ISource GetResultSourceByName(SPSite site, string resultSourceName, SearchObjectLevel scopeOwnerLevel)
        {
            var serviceApplicationOwner = new SearchObjectOwner(scopeOwnerLevel, site.RootWeb);

            var context = SPServiceContext.GetContext(site);
            var searchProxy = context.GetDefaultProxy(typeof(SearchServiceApplicationProxy)) as SearchServiceApplicationProxy;

            return searchProxy.GetResultSourceByName(resultSourceName, serviceApplicationOwner);
        }
Ejemplo n.º 55
0
        /// <summary>
        /// Ensure a managed property in the search service application schema
        /// </summary>
        /// <param name="site">The context site</param>
        /// <param name="managedPropertyInfo">The managed property info</param>
        /// <returns>The managed property</returns>
        public ManagedProperty EnsureManagedProperty(SPSite site, ManagedPropertyInfo managedPropertyInfo)
        {
            var ssa = this.GetDefaultSearchServiceApplication(site);
            var propertyName = managedPropertyInfo.Name;

            // this forces managed prop definition to SSA-scope 
            // (i.e. all managed props will be farm-wide)
            var owner = new SearchObjectOwner(SearchObjectLevel.Ssa, site.RootWeb);

            // Get the managed property and if null, create it
            var managedPropertyDefinition = this.GetManagedProperty(managedPropertyInfo, ssa, owner);
            if ((managedPropertyDefinition == null) || ShouldRecreateManagedProperty(managedPropertyDefinition, managedPropertyInfo))
            {
                // If managed property was created, make sure it sets the crawled property mappings and configuration
                managedPropertyInfo.UpdateBehavior = ManagedPropertyUpdateBehavior.OverwriteIfAlreadyExists;
                managedPropertyDefinition = this.CreateManagedProperty(managedPropertyInfo, ssa, owner);
            }

            if (managedPropertyDefinition != null)
            {
                // If crawled property mappings need to be overwritten or appended
                if (ShouldUpdateCrawledPropertyMappings(managedPropertyInfo))
                {
                    var mappings = GetInitialCrawledPropertyMappings(managedPropertyDefinition, managedPropertyInfo, ssa, owner);
                    this.SetCrawledPropertyMappings(site, managedPropertyDefinition, managedPropertyInfo, ssa, owner, mappings);
                }

                if (ShouldUpdateConfiguration(managedPropertyInfo))
                {
                    this.ConfigureManagerProperty(managedPropertyDefinition, managedPropertyInfo);
                }

                // Save through the schema manager (don't call .Update on the managed property object itself, its config won't get saved properly)
                ssa.UpdateManagedProperty(managedPropertyDefinition, owner);
            }

            // Re-fetch schema, it might be stale at this point
            var sspSchema = new Schema(ssa);
            return sspSchema.AllManagedProperties[propertyName];
        }
Ejemplo n.º 56
0
        public void EnsureManagedProperty_WhenUpdatingConfiguration_ShouldChangeConfigurationAndKeepCrawledPropertyMappings()
        {
            const string ManagedPropertyName = "TestManagedProperty";

            using (var testScope = SiteTestScope.BlankSite())
            {
                // Arrange
                var owner = new SearchObjectOwner(SearchObjectLevel.Ssa, testScope.SiteCollection.RootWeb);
                var managedPropertyInfo = new ManagedPropertyInfo(ManagedPropertyName, ManagedDataType.Text)
                {
                    Sortable = true,
                    Refinable = true,
                    Queryable = true,
                    CrawledProperties = new Dictionary<string, int>()
                    {
                        { "ows_Title", 1 }
                    },
                    UpdateBehavior = ManagedPropertyUpdateBehavior.OverwriteIfAlreadyExists
                };

                var updatedManagedPropertyInfo = new ManagedPropertyInfo(ManagedPropertyName, ManagedDataType.Text)
                {
                    Sortable = false,
                    Refinable = false,
                    Queryable = false,
                    CrawledProperties = new Dictionary<string, int>()
                    {
                        { "ows_Description", 2 }
                    },
                    UpdateBehavior = ManagedPropertyUpdateBehavior.UpdateConfiguration
                };

                using (var injectionScope = IntegrationTestServiceLocator.BeginLifetimeScope())
                {
                    var searchHelper = injectionScope.Resolve<ISearchHelper>();
                    var ssa = searchHelper.GetDefaultSearchServiceApplication(testScope.SiteCollection);

                    try
                    {
                        // Act
                        searchHelper.EnsureManagedProperty(testScope.SiteCollection, managedPropertyInfo);
                        var actualManagedProperty = searchHelper.EnsureManagedProperty(testScope.SiteCollection, updatedManagedPropertyInfo);
                        var refetchedActualManagedProperty = ssa.GetManagedProperty(ManagedPropertyName, owner);

                        // Assert
                        Assert.IsNotNull(actualManagedProperty);
                        Assert.AreEqual(false, actualManagedProperty.Sortable);
                        Assert.AreEqual(false, actualManagedProperty.Refinable);
                        Assert.AreEqual(false, actualManagedProperty.Queryable);
                        Assert.IsTrue(actualManagedProperty.GetMappedCrawledProperties(2).Count == 1);
                        Assert.IsTrue(actualManagedProperty.GetMappedCrawledProperties(2)[0].Name == "ows_Title");

                        Assert.IsNotNull(refetchedActualManagedProperty);
                        Assert.AreEqual(false, refetchedActualManagedProperty.Sortable);
                        Assert.AreEqual(false, refetchedActualManagedProperty.Refinable);
                        Assert.AreEqual(false, refetchedActualManagedProperty.Queryable);
                        Assert.IsTrue(ssa.GetManagedPropertyMappings(refetchedActualManagedProperty, owner).Count == 1);
                        Assert.IsTrue(ssa.GetManagedPropertyMappings(refetchedActualManagedProperty, owner)[0].CrawledPropertyName == "ows_Title");
                    }
                    finally
                    {
                        // Clean up
                        searchHelper.DeleteManagedProperty(testScope.SiteCollection, managedPropertyInfo);
                    }
                }
            }
        }
Ejemplo n.º 57
0
        /// <summary>
        /// Ensure a Result Type in a site collection
        /// </summary>
        /// <param name="site">The site collection</param>
        /// <param name="resultType">The result type info object</param>
        /// <returns>The result type item</returns>
        public ResultItemType EnsureResultType(SPSite site, ResultTypeInfo resultType)
        {
            var searchOwner = new SearchObjectOwner(SearchObjectLevel.SPSite, site.RootWeb);
            var resultSource = this.GetResultSourceByName(site, resultType.ResultSource.Name, resultType.ResultSource.Level);

            var resultTypeManager = new ResultItemTypeManager(this.GetDefaultSearchServiceApplication(site));
            var existingResultTypes = resultTypeManager.GetResultItemTypes(searchOwner, true);

            // Get the existing result type
            var resType = existingResultTypes.FirstOrDefault(r => r.Name.Equals(resultType.Name));

            if (resType == null)
            {
                resType = new ResultItemType(searchOwner);
                resType.Name = resultType.Name;
                resType.SourceID = resultSource.Id;

                resType.DisplayTemplateUrl = resultType.DisplayTemplate.ItemTemplateTokenizedPath;
                var properties = resultType.DisplayProperties.Select(t => t.Name).ToArray();
                resType.DisplayProperties = string.Join(",", properties);
                resType.RulePriority = resultType.Priority;

                // Create rules
                var rules = 
                    resultType.Rules.Select(
                        this.CreateCustomPropertyRule)
                        .ToList();
                resType.Rules = new PropertyRuleCollection(rules);

                typeof(ResultItemType).GetProperty("OptimizeForFrequentUse")
                    .SetValue(resType, resultType.OptimizeForFrequenUse);

                // Add the result type
                resultTypeManager.AddResultItemType(resType);
            }
 
            return resType;
        }
Ejemplo n.º 58
0
        /// <summary>
        /// Delete a result type in the site collection
        /// </summary>
        /// <param name="site">The site</param>
        /// <param name="resultType">The result type object</param>
        public void DeleteResultType(SPSite site, ResultTypeInfo resultType)
        {
            ResultItemType resType = null;
    
            var searchOwner = new SearchObjectOwner(SearchObjectLevel.SPSite, site.RootWeb);
            var resultTypeManager = new ResultItemTypeManager(this.GetDefaultSearchServiceApplication(site));
            var existingResultTypes = resultTypeManager.GetResultItemTypes(searchOwner, true);

            // Get the existing result type
            resType = existingResultTypes.FirstOrDefault(r => r.Name.Equals(resultType.Name));

            if (resType != null)
            {
                resultTypeManager.DeleteResultItemType(resType);
            }  
        }
Ejemplo n.º 59
0
        /// <summary>
        /// Ensure a managed property in the search service application schema
        /// </summary>
        /// <param name="site">The context site</param>
        /// <param name="managedPropertyInfo">The managed property info</param>
        /// <returns>The managed property</returns>
        public ManagedProperty EnsureManagedProperty(SPSite site, ManagedPropertyInfo managedPropertyInfo)
        {
            SPManagedPropertyInfo managedPropertyDefinition = null;

            var ssa          = this.GetDefaultSearchServiceApplication(site);
            var propertyName = managedPropertyInfo.Name;
            var propertyType = managedPropertyInfo.DataType;
            var owner        = new SearchObjectOwner(SearchObjectLevel.Ssa, site.RootWeb); // this forces managed prop definition to SSA-scope
                                                                                           // (i.e. all managed props will be farm-wide)

            // Get the search schema
            var sspSchema         = new Schema(ssa);
            var managedProperties = sspSchema.AllManagedProperties;

            if (managedProperties.Contains(propertyName))
            {
                var prop = managedProperties[propertyName];
                if (managedPropertyInfo.OverwriteIfAlreadyExists)
                {
                    if (prop.DeleteDisallowed)
                    {
                        this.logger.Warn("Delete is disallowed on the Managed Property {0}", propertyName);
                    }
                    else
                    {
                        prop.DeleteAllMappings();
                        prop.Delete();
                        managedPropertyDefinition = ssa.CreateManagedProperty(propertyName, propertyType, owner);
                    }
                }
            }
            else
            {
                managedPropertyDefinition = ssa.CreateManagedProperty(propertyName, propertyType, owner);
            }

            if (managedPropertyDefinition != null)
            {
                var mappingCollection = new List <MappingInfo>(); // new MappingCollection();

                // Ensure crawl properties mappings
                foreach (KeyValuePair <string, int> crawledPropertyKeyAndOrder in managedPropertyInfo.CrawledProperties)
                {
                    // Get the crawled property (there may be more than one matching that name)
                    var matchingCrawledProperties = this.GetCrawledPropertyByName(site, crawledPropertyKeyAndOrder.Key);

                    if (matchingCrawledProperties != null && matchingCrawledProperties.Count > 0)
                    {
                        foreach (var cp in matchingCrawledProperties)
                        {
                            // Create mapping information
                            var mapping = new MappingInfo
                            {
                                CrawledPropertyName = cp.Name,
                                CrawledPropset      = cp.Propset,
                                ManagedPid          = managedPropertyDefinition.Pid,
                                MappingOrder        = crawledPropertyKeyAndOrder.Value
                            };

                            if (!ssa.GetManagedPropertyMappings(managedPropertyDefinition, owner).Any(m => m.CrawledPropertyName == mapping.CrawledPropertyName))
                            {
                                mappingCollection.Add(mapping);
                            }
                            else
                            {
                                this.logger.Info("Mapping for managed property {0} and crawled property with name {1} is already exists", managedPropertyDefinition.Name, crawledPropertyKeyAndOrder);
                            }
                        }
                    }
                    else
                    {
                        this.logger.Warn("Crawled property with name {0} not found!", crawledPropertyKeyAndOrder);
                    }
                }

                // Apply mappings to the managed property
                if (mappingCollection.Count > 0)
                {
                    ssa.SetManagedPropertyMappings(managedPropertyDefinition, mappingCollection, owner);
                }

                // Configure the managed property
                managedPropertyDefinition.Sortable = managedPropertyInfo.Sortable;
                if (managedPropertyDefinition.Sortable)
                {
                    managedPropertyDefinition.SortableType = managedPropertyInfo.SortableType;
                }

                managedPropertyDefinition.Refinable = managedPropertyInfo.Refinable;
                if (managedPropertyDefinition.Refinable)
                {
                    // use "active" refine mode whenever refinable=TRUE
                    managedPropertyDefinition.RefinerConfiguration.Type = Microsoft.Office.Server.Search.Administration.RefinerType.Deep;
                }

                managedPropertyDefinition.Retrievable     = managedPropertyInfo.Retrievable;
                managedPropertyDefinition.RespectPriority = managedPropertyInfo.RespectPriority;
                managedPropertyDefinition.Queryable       = managedPropertyInfo.Queryable;
                managedPropertyDefinition.Searchable      = managedPropertyInfo.Searchable;

                if (managedPropertyDefinition.Searchable)
                {
                    managedPropertyDefinition.FullTextIndex = managedPropertyInfo.FullTextIndex;
                    managedPropertyDefinition.Context       = managedPropertyInfo.Context;
                }
                else
                {
                    managedPropertyDefinition.FullTextIndex = string.Empty;
                    managedPropertyDefinition.Context       = (short)0;
                }

                managedPropertyDefinition.HasMultipleValues = managedPropertyInfo.HasMultipleValues;
                managedPropertyDefinition.SafeForAnonymous  = managedPropertyInfo.SafeForAnonymous;

                // Save through the schema manager (don't call .Update on the managed property object itself, its config won't get saved properly)
                ssa.UpdateManagedProperty(managedPropertyDefinition, owner);
            }

            // Re-fetch schema, it might be stale at this point
            sspSchema = new Schema(ssa);

            return(sspSchema.AllManagedProperties[propertyName]);
        }