Example #1
0
        [STAThread] // Required to support the interactive login experience
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    // Create any entity records that the demonstration code requires
                    SetUpSample(service);

                    #region Demonstrate
                    // TODO Add demonstration code here
                    #region Search Knowledge base by Body

                    // Create the request
                    SearchByBodyKbArticleRequest searchByBodyRequest =
                        new SearchByBodyKbArticleRequest()
                    {
                        SubjectId     = _subjectId,
                        UseInflection = true,          // allows for a different tense or
                                                       // inflection to be substituted for the search text
                        SearchText      = "contained", // will also match on 'contains'
                        QueryExpression = new QueryExpression()
                        {
                            ColumnSet  = new ColumnSet("articlexml"),
                            EntityName = KbArticle.EntityLogicalName
                        }
                    };

                    // Execute the request
                    Console.WriteLine("  Searching for published article with 'contained' in the body");

                    SearchByBodyKbArticleResponse seachByBodyResponse =
                        (SearchByBodyKbArticleResponse)_context.Execute(searchByBodyRequest);

                    // Check success
                    var retrievedArticleBodies = seachByBodyResponse.EntityCollection.Entities
                                                 .Select((entity) => ((KbArticle)entity).ArticleXml);

                    if (retrievedArticleBodies.Count() == 0)
                    {
                        throw new Exception("No articles found");
                    }

                    Console.WriteLine("  Results of search (article bodies found):");
                    foreach (var body in retrievedArticleBodies)
                    {
                        Console.WriteLine(body);
                    }

                    #endregion

                    #region Search knowledge base by Keyword

                    // Create the request
                    SearchByKeywordsKbArticleRequest searchByKeywordRequest =
                        new SearchByKeywordsKbArticleRequest()
                    {
                        SubjectId       = _subjectId,
                        UseInflection   = true,
                        SearchText      = "Search",
                        QueryExpression = new QueryExpression()
                        {
                            ColumnSet  = new ColumnSet("keywords"),
                            EntityName = KbArticle.EntityLogicalName
                        }
                    };

                    // Execute the request
                    Console.WriteLine();
                    Console.WriteLine("  Searching for published article with 'search' as a keyword");
                    var searchByKeywordResponse =
                        (SearchByKeywordsKbArticleResponse)_context.Execute(searchByKeywordRequest);

                    // Check success
                    var retrievedArticleKeywords = searchByKeywordResponse.EntityCollection.Entities
                                                   .Select((entity) => (KbArticle)entity);

                    if (retrievedArticleKeywords.Count() == 0)
                    {
                        throw new Exception("No articles found");
                    }

                    Console.WriteLine("  Results of search (keywords found):");
                    foreach (var article in retrievedArticleKeywords)
                    {
                        Console.WriteLine(article.KeyWords);
                    }

                    #endregion

                    #region Search knowledge base by Title

                    // create the request
                    SearchByTitleKbArticleRequest searchByTitleRequest =
                        new SearchByTitleKbArticleRequest()
                    {
                        SubjectId       = _subjectId,
                        UseInflection   = false,
                        SearchText      = "code",
                        QueryExpression = new QueryExpression()
                        {
                            ColumnSet  = new ColumnSet("title"),
                            EntityName = KbArticle.EntityLogicalName
                        }
                    };

                    // execute the request
                    Console.WriteLine();
                    Console.WriteLine("  Searching for published articles with 'code' in the title");
                    var searchByTitleResponse = (SearchByTitleKbArticleResponse)
                                                _context.Execute(searchByTitleRequest);

                    // check success
                    var retrievedArticles = searchByTitleResponse.EntityCollection.Entities
                                            .Select((entity) => (KbArticle)entity);
                    Console.WriteLine("  Results of search (titles found):");
                    foreach (var article in retrievedArticles)
                    {
                        Console.WriteLine(article.Title);
                    }

                    #endregion

                    #region Retrieve by top incident subject

                    // create the request
                    var retrieveByTopIncidentSubjectRequest =
                        new RetrieveByTopIncidentSubjectKbArticleRequest()
                    {
                        SubjectId = _subjectId
                    };

                    // execute request
                    Console.WriteLine();
                    Console.WriteLine("  Searching for the top articles in subject 'Default Subject'");
                    var retrieveByTopIncidentSubjectResponse = (RetrieveByTopIncidentSubjectKbArticleResponse)
                                                               _context.Execute(retrieveByTopIncidentSubjectRequest);

                    // check success
                    var articles = retrieveByTopIncidentSubjectResponse.EntityCollection.Entities.Select(
                        (entity) => (KbArticle)entity);
                    Console.WriteLine("  Top articles in subject 'Default Subject':");
                    foreach (var article in articles)
                    {
                        Console.WriteLine(article.Title);
                    }

                    #endregion

                    #region Retrieve by top incident product

                    // create the request
                    var retrieveByTopIncidentProductRequest =
                        new RetrieveByTopIncidentProductKbArticleRequest()
                    {
                        ProductId = _product.Id
                    };

                    // execute request
                    Console.WriteLine();
                    Console.WriteLine("  Searching for the top articles for product 'Sample Product'");
                    var retrieveByTopIncidentProductResponse = (RetrieveByTopIncidentProductKbArticleResponse)
                                                               _context.Execute(retrieveByTopIncidentProductRequest);

                    // check success
                    articles = retrieveByTopIncidentProductResponse.EntityCollection.Entities.Select(
                        (entity) => (KbArticle)entity);
                    Console.WriteLine("  Top articles for product 'Sample Product':");
                    foreach (var article in articles)
                    {
                        Console.WriteLine(article.Title);
                    }

                    #endregion
                    #endregion Demonstrate
                }
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Common Data Service";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
        /// <summary>
        /// This method first creates sample articles and publishes them, then searches
        /// for the articles by body, keyword and title. Finally, it retrieves the
        /// articles by top incident subject and top incident product.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>

        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetSearchAndRetrieveArticles1>
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
                    // Using the ServiceContext class makes the queries easier
                    using (_context = new ServiceContext(_serviceProxy))
                    {
                        // This statement is required to enable early-bound type support.
                        _serviceProxy.EnableProxyTypes();

                        CreateRequiredRecords();

                        #region Search Knowledge base by Body
                        //<snippetSearchByBodyKbArticle>

                        // Create the request
                        SearchByBodyKbArticleRequest searchByBodyRequest =
                            new SearchByBodyKbArticleRequest()
                        {
                            SubjectId     = _subjectId,
                            UseInflection = true,          // allows for a different tense or
                            // inflection to be substituted for the search text
                            SearchText      = "contained", // will also match on 'contains'
                            QueryExpression = new QueryExpression()
                            {
                                ColumnSet  = new ColumnSet("articlexml"),
                                EntityName = KbArticle.EntityLogicalName
                            }
                        };

                        // Execute the request
                        Console.WriteLine("  Searching for published article with 'contained' in the body");

                        SearchByBodyKbArticleResponse seachByBodyResponse =
                            (SearchByBodyKbArticleResponse)_context.Execute(searchByBodyRequest);

                        // Check success
                        var retrievedArticleBodies = seachByBodyResponse.EntityCollection.Entities
                                                     .Select((entity) => ((KbArticle)entity).ArticleXml);

                        if (retrievedArticleBodies.Count() == 0)
                        {
                            throw new Exception("No articles found");
                        }

                        Console.WriteLine("  Results of search (article bodies found):");
                        foreach (var body in retrievedArticleBodies)
                        {
                            Console.WriteLine(body);
                        }
                        //</snippetSearchByBodyKbArticle>

                        #endregion

                        #region Search knowledge base by Keyword
                        //<snippetSearchByKeywordsKbArticle>

                        // Create the request
                        SearchByKeywordsKbArticleRequest searchByKeywordRequest =
                            new SearchByKeywordsKbArticleRequest()
                        {
                            SubjectId       = _subjectId,
                            UseInflection   = true,
                            SearchText      = "Search",
                            QueryExpression = new QueryExpression()
                            {
                                ColumnSet  = new ColumnSet("keywords"),
                                EntityName = KbArticle.EntityLogicalName
                            }
                        };

                        // Execute the request
                        Console.WriteLine();
                        Console.WriteLine("  Searching for published article with 'search' as a keyword");
                        var searchByKeywordResponse =
                            (SearchByKeywordsKbArticleResponse)_context.Execute(searchByKeywordRequest);

                        // Check success
                        var retrievedArticleKeywords = searchByKeywordResponse.EntityCollection.Entities
                                                       .Select((entity) => (KbArticle)entity);

                        if (retrievedArticleKeywords.Count() == 0)
                        {
                            throw new Exception("No articles found");
                        }

                        Console.WriteLine("  Results of search (keywords found):");
                        foreach (var article in retrievedArticleKeywords)
                        {
                            Console.WriteLine(article.KeyWords);
                        }
                        //</snippetSearchByKeywordsKbArticle>

                        #endregion

                        #region Search knowledge base by Title
                        //<snippetSearchByTitleKbArticle>

                        // create the request
                        SearchByTitleKbArticleRequest searchByTitleRequest =
                            new SearchByTitleKbArticleRequest()
                        {
                            SubjectId       = _subjectId,
                            UseInflection   = false,
                            SearchText      = "code",
                            QueryExpression = new QueryExpression()
                            {
                                ColumnSet  = new ColumnSet("title"),
                                EntityName = KbArticle.EntityLogicalName
                            }
                        };

                        // execute the request
                        Console.WriteLine();
                        Console.WriteLine("  Searching for published articles with 'code' in the title");
                        var searchByTitleResponse = (SearchByTitleKbArticleResponse)
                                                    _context.Execute(searchByTitleRequest);

                        // check success
                        var retrievedArticles = searchByTitleResponse.EntityCollection.Entities
                                                .Select((entity) => (KbArticle)entity);
                        Console.WriteLine("  Results of search (titles found):");
                        foreach (var article in retrievedArticles)
                        {
                            Console.WriteLine(article.Title);
                        }
                        //</snippetSearchByTitleKbArticle>

                        #endregion

                        #region Retrieve by top incident subject
                        //<snippetRetrieveByTopIncidentSubjectKbArticle>

                        // create the request
                        var retrieveByTopIncidentSubjectRequest =
                            new RetrieveByTopIncidentSubjectKbArticleRequest()
                        {
                            SubjectId = _subjectId
                        };

                        // execute request
                        Console.WriteLine();
                        Console.WriteLine("  Searching for the top articles in subject 'Default Subject'");
                        var retrieveByTopIncidentSubjectResponse = (RetrieveByTopIncidentSubjectKbArticleResponse)
                                                                   _context.Execute(retrieveByTopIncidentSubjectRequest);

                        // check success
                        var articles = retrieveByTopIncidentSubjectResponse.EntityCollection.Entities.Select(
                            (entity) => (KbArticle)entity);
                        Console.WriteLine("  Top articles in subject 'Default Subject':");
                        foreach (var article in articles)
                        {
                            Console.WriteLine(article.Title);
                        }
                        //</snippetRetrieveByTopIncidentSubjectKbArticle>

                        #endregion

                        #region Retrieve by top incident product
                        //<snippetRetrieveByTopIncidentProductKbArticle>

                        // create the request
                        var retrieveByTopIncidentProductRequest =
                            new RetrieveByTopIncidentProductKbArticleRequest()
                        {
                            ProductId = _product.Id
                        };

                        // execute request
                        Console.WriteLine();
                        Console.WriteLine("  Searching for the top articles for product 'Sample Product'");
                        var retrieveByTopIncidentProductResponse = (RetrieveByTopIncidentProductKbArticleResponse)
                                                                   _context.Execute(retrieveByTopIncidentProductRequest);

                        // check success
                        articles = retrieveByTopIncidentProductResponse.EntityCollection.Entities.Select(
                            (entity) => (KbArticle)entity);
                        Console.WriteLine("  Top articles for product 'Sample Product':");
                        foreach (var article in articles)
                        {
                            Console.WriteLine(article.Title);
                        }
                        //</snippetRetrieveByTopIncidentProductKbArticle>

                        #endregion

                        DeleteRequiredRecords(promptforDelete);
                    }
                //</snippetSearchAndRetrieveArticles1>
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
        /// <summary>
        /// This method first creates sample articles and publishes them, then searches
        /// for the articles by body, keyword and title. Finally, it retrieves the 
        /// articles by top incident subject and top incident product.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>

        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetSearchAndRetrieveArticles1>
                // Connect to the Organization service. 
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
                // Using the ServiceContext class makes the queries easier
                using (_context = new ServiceContext(_serviceProxy))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    #region Search Knowledge base by Body
                    //<snippetSearchByBodyKbArticle>

                    // Create the request
                    SearchByBodyKbArticleRequest searchByBodyRequest = 
                        new SearchByBodyKbArticleRequest()
                    {
                        SubjectId = _subjectId,
                        UseInflection = true, // allows for a different tense or 
                        // inflection to be substituted for the search text
                        SearchText = "contained", // will also match on 'contains'
                        QueryExpression = new QueryExpression()
                        {
                            ColumnSet = new ColumnSet("articlexml"),
                            EntityName = KbArticle.EntityLogicalName
                        }
                    };

                    // Execute the request
                    Console.WriteLine("  Searching for published article with 'contained' in the body");

                    SearchByBodyKbArticleResponse seachByBodyResponse =
                        (SearchByBodyKbArticleResponse)_context.Execute(searchByBodyRequest);

                    // Check success
                    var retrievedArticleBodies = seachByBodyResponse.EntityCollection.Entities
                        .Select((entity) => ((KbArticle)entity).ArticleXml);

                    if (retrievedArticleBodies.Count() == 0)
                        throw new Exception("No articles found");

                    Console.WriteLine("  Results of search (article bodies found):");
                    foreach (var body in retrievedArticleBodies)
                        Console.WriteLine(body);
                    //</snippetSearchByBodyKbArticle>

                    #endregion

                    #region Search knowledge base by Keyword
                    //<snippetSearchByKeywordsKbArticle>

                    // Create the request
                    SearchByKeywordsKbArticleRequest searchByKeywordRequest = 
                        new SearchByKeywordsKbArticleRequest()
                    {
                        SubjectId = _subjectId,
                        UseInflection = true,
                        SearchText = "Search",
                        QueryExpression = new QueryExpression()
                        {
                            ColumnSet = new ColumnSet("keywords"),
                            EntityName = KbArticle.EntityLogicalName
                        }
                    };

                    // Execute the request
                    Console.WriteLine();
                    Console.WriteLine("  Searching for published article with 'search' as a keyword");
                    var searchByKeywordResponse =
                        (SearchByKeywordsKbArticleResponse)_context.Execute(searchByKeywordRequest);

                    // Check success
                    var retrievedArticleKeywords = searchByKeywordResponse.EntityCollection.Entities
                        .Select((entity) => (KbArticle)entity);

                    if (retrievedArticleKeywords.Count() == 0)
                        throw new Exception("No articles found");

                    Console.WriteLine("  Results of search (keywords found):");
                    foreach (var article in retrievedArticleKeywords)
                        Console.WriteLine(article.KeyWords);
                    //</snippetSearchByKeywordsKbArticle>

                    #endregion

                    #region Search knowledge base by Title
                    //<snippetSearchByTitleKbArticle>

                    // create the request
                    SearchByTitleKbArticleRequest searchByTitleRequest = 
                        new SearchByTitleKbArticleRequest()
                    {
                        SubjectId = _subjectId,
                        UseInflection = false,
                        SearchText = "code",
                        QueryExpression = new QueryExpression()
                        {
                            ColumnSet = new ColumnSet("title"),
                            EntityName = KbArticle.EntityLogicalName
                        }
                    };

                    // execute the request
                    Console.WriteLine();
                    Console.WriteLine("  Searching for published articles with 'code' in the title");
                    var searchByTitleResponse = (SearchByTitleKbArticleResponse)
                        _context.Execute(searchByTitleRequest);

                    // check success
                    var retrievedArticles = searchByTitleResponse.EntityCollection.Entities
                        .Select((entity) => (KbArticle)entity);
                    Console.WriteLine("  Results of search (titles found):");
                    foreach (var article in retrievedArticles)
                        Console.WriteLine(article.Title);
                    //</snippetSearchByTitleKbArticle>

                    #endregion

                    #region Retrieve by top incident subject
                    //<snippetRetrieveByTopIncidentSubjectKbArticle>

                    // create the request
                    var retrieveByTopIncidentSubjectRequest = 
                        new RetrieveByTopIncidentSubjectKbArticleRequest()
                    {
                        SubjectId = _subjectId
                    };

                    // execute request
                    Console.WriteLine();
                    Console.WriteLine("  Searching for the top articles in subject 'Default Subject'");
                    var retrieveByTopIncidentSubjectResponse = (RetrieveByTopIncidentSubjectKbArticleResponse)
                        _context.Execute(retrieveByTopIncidentSubjectRequest);

                    // check success
                    var articles = retrieveByTopIncidentSubjectResponse.EntityCollection.Entities.Select(
                        (entity) => (KbArticle)entity);
                    Console.WriteLine("  Top articles in subject 'Default Subject':");
                    foreach (var article in articles)
                        Console.WriteLine(article.Title);
                    //</snippetRetrieveByTopIncidentSubjectKbArticle>

                    #endregion

                    #region Retrieve by top incident product
                    //<snippetRetrieveByTopIncidentProductKbArticle>

                    // create the request
                    var retrieveByTopIncidentProductRequest = 
                        new RetrieveByTopIncidentProductKbArticleRequest()
                    {
                        ProductId = _product.Id
                    };

                    // execute request
                    Console.WriteLine();
                    Console.WriteLine("  Searching for the top articles for product 'Sample Product'");
                    var retrieveByTopIncidentProductResponse = (RetrieveByTopIncidentProductKbArticleResponse)
                        _context.Execute(retrieveByTopIncidentProductRequest);

                    // check success
                    articles = retrieveByTopIncidentProductResponse.EntityCollection.Entities.Select(
                        (entity) => (KbArticle)entity);
                    Console.WriteLine("  Top articles for product 'Sample Product':");
                    foreach (var article in articles)
                        Console.WriteLine(article.Title);
                    //</snippetRetrieveByTopIncidentProductKbArticle>

                    #endregion

                    DeleteRequiredRecords(promptforDelete);
                }
                //</snippetSearchAndRetrieveArticles1>
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
        /// <summary>
        /// Search for <c>Knowledge Base Articles</c>.
        /// <para>
        /// For more information look at
        /// <c>By Body</c> : https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.searchbybodykbarticlerequest(v=crm.7).aspx
        /// <c>By Keyword</c> : https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.searchbykeywordskbarticlerequest(v=crm.7).aspx
        /// <c>By Title</c> : https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.searchbytitlekbarticlerequest(v=crm.7).aspx
        /// </para>
        /// </summary>
        /// <param name="searchType"><see cref="SearchTypeCode"/></param>
        /// <param name="query">
        /// Query criteria to find knowledge base articles with specified keyword.
        /// This parameter supports <c>QueryExpression</c> and <c>FetchXml</c>.
        /// </param>
        /// <param name="subjectId">Knowledge base article subject Id</param>
        /// <param name="searchText">Text contained in the body of the article</param>
        /// <param name="useInflection">Indicates whether to use inflectional stem matching when searching for knowledge base articles with a specified body text</param>
        /// <returns>
        /// <see cref="EntityCollection"/> for <c>Article</c> data
        /// </returns>
        public EntityCollection Search(SearchTypeCode searchType, QueryBase query, Guid subjectId, string searchText, bool useInflection)
        {
            ExceptionThrow.IfNull(query, "query");
            ExceptionThrow.IfGuidEmpty(subjectId, "subjectId");
            ExceptionThrow.IfNullOrEmpty(searchText, "searchText");

            EntityCollection result = new EntityCollection();

            if (query is QueryExpression)
            {
                ExceptionThrow.IfNullOrEmpty(((QueryExpression)query).EntityName, "QueryExpression.EntityName");
            }

            OrganizationRequest  request;
            OrganizationResponse serviceResponse;

            switch (searchType)
            {
            case SearchTypeCode.ByBody:
                //INFO : SDK Url --> https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.searchbybodykbarticlerequest(v=crm.7).aspx

                request = new SearchByBodyKbArticleRequest()
                {
                    QueryExpression = query,
                    SearchText      = searchText,
                    SubjectId       = subjectId,
                    UseInflection   = useInflection
                };

                serviceResponse = this.OrganizationService.Execute(request);
                result          = ((SearchByBodyKbArticleResponse)serviceResponse).EntityCollection;

                break;

            case SearchTypeCode.ByKeyword:
                //INFO : SDK Url --> https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.searchbykeywordskbarticlerequest(v=crm.7).aspx

                request = new SearchByKeywordsKbArticleRequest()
                {
                    QueryExpression = query,
                    SearchText      = searchText,
                    SubjectId       = subjectId,
                    UseInflection   = useInflection
                };

                serviceResponse = this.OrganizationService.Execute(request);
                result          = ((SearchByKeywordsKbArticleResponse)serviceResponse).EntityCollection;

                break;

            case SearchTypeCode.ByTitle:
                //INFO : SDK Url --> https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.searchbytitlekbarticlerequest(v=crm.7).aspx

                request = new SearchByTitleKbArticleRequest()
                {
                    QueryExpression = query,
                    SearchText      = searchText,
                    SubjectId       = subjectId,
                    UseInflection   = useInflection
                };

                serviceResponse = this.OrganizationService.Execute(request);
                result          = ((SearchByTitleKbArticleResponse)serviceResponse).EntityCollection;

                break;
            }

            return(result);
        }