示例#1
0
        public IEnumerable <SearchResult> Search(string query)
        {
            ISearchCriteria criteria = null;
            var             searcher = ExamineManager.Instance.SearchProviderCollection[IndexName];

            if (searchQueryCache.ContainsKey(query))
            {
                criteria = searchQueryCache[query];
            }
            else
            {
                criteria = searcher.CreateSearchCriteria();
                criteria = criteria.RawQuery(query);
                searchQueryCache.Add(query, criteria);
            }

            return(searcher.Search(criteria));
        }
        /// <summary>
        /// Gets the search results.
        /// </summary>
        /// <param name="searchTerm">The search text. Search string separated whitespace.</param>
        /// <param name="searchFields">The search fields.</param>
        /// <param name="searchProviderName">Name of the search provider.</param>
        /// <param name="useAndOperation">Search with wildcard.</param>
        /// <returns>Collection of <see cref="Examine.SearchResult"/>.</returns>
        public static IEnumerable <SearchResult> GetSearchResults(string searchTerm, string[] searchFields, string searchProviderName, bool useAndOperation)
        {
            if (searchTerm == null)
            {
                throw new ArgumentNullException(nameof(searchTerm));
            }
            if (searchFields == null)
            {
                throw new ArgumentNullException(nameof(searchFields));
            }
            if (searchProviderName == null)
            {
                throw new ArgumentNullException(nameof(searchProviderName));
            }

            BaseSearchProvider searchProvider = ExamineManager.Instance.SearchProviderCollection[searchProviderName];
            ISearchCriteria    criteria       = searchProvider.CreateSearchCriteria(BooleanOperation.Or);

            string[]             terms      = searchTerm.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            IEnumerable <string> rawQueries = GetRawQueries(searchFields, useAndOperation, searchFields.Length, terms);
            ISearchCriteria      filter     = criteria.RawQuery(rawQueries.ToStringWithBrackets());

            return(searchProvider.Search(filter).DistinctBy(sr => sr.Id));
        }
示例#3
0
        public ActionResult LinkGitHub(string state, string code = null)
        {
            // Get the member of the current ID
            int memberId = Members.GetCurrentMemberId();

            if (memberId <= 0)
            {
                return(GetErrorResult("Oh noes! An error happened."));
            }

            try
            {
                IPublishedContent profilePage = Umbraco.TypedContent(1057);
                if (profilePage == null)
                {
                    return(GetErrorResult("Oh noes! This really shouldn't happen."));
                }

                // Initialize the OAuth client
                GitHubOAuthClient client = new GitHubOAuthClient
                {
                    ClientId     = WebConfigurationManager.AppSettings["GitHubClientId"],
                    ClientSecret = WebConfigurationManager.AppSettings["GitHubClientSecret"]
                };

                // Validate state - Step 1
                if (String.IsNullOrWhiteSpace(state))
                {
                    LogHelper.Info <ProfileController>("No OAuth state specified in the query string.");
                    return(GetErrorResult("No state specified in the query string."));
                }

                // Validate state - Step 2
                string session = Session["GitHub_" + state] as string;
                if (String.IsNullOrWhiteSpace(session))
                {
                    LogHelper.Info <ProfileController>("Failed finding OAuth session item. Most likely the session expired.");
                    return(GetErrorResult("Session expired? Please click the link below and try to link with your GitHub account again ;)"));
                }

                // Remove the state from the session
                Session.Remove("GitHub_" + state);

                // Exchange the auth code for an access token
                GitHubTokenResponse accessTokenResponse;
                try
                {
                    accessTokenResponse = client.GetAccessTokenFromAuthorizationCode(code);
                }
                catch (Exception ex)
                {
                    LogHelper.Error <ProfileController>("Unable to retrieve access token from GitHub API", ex);
                    return(GetErrorResult("Oh noes! An error happened."));
                }

                // Initialize a new service instance from the retrieved access token
                var service = Skybrud.Social.GitHub.GitHubService.CreateFromAccessToken(accessTokenResponse.Body.AccessToken);

                // Get some information about the authenticated GitHub user
                GitHubGetUserResponse userResponse;
                try
                {
                    userResponse = service.User.GetUser();
                }
                catch (Exception ex)
                {
                    LogHelper.Error <ProfileController>("Unable to get user information from the GitHub API", ex);
                    return(GetErrorResult("Oh noes! An error happened."));
                }

                // Get the GitHub username from the API response
                string githubUsername = userResponse.Body.Login;

                // Get a reference to the member searcher
                BaseSearchProvider searcher = ExamineManager.Instance.SearchProviderCollection["InternalMemberSearcher"];

                // Initialize new search criteria for the GitHub username
                ISearchCriteria criteria = searcher.CreateSearchCriteria();
                criteria = criteria.RawQuery($"github:{githubUsername}");

                // Check if there are other members with the same GitHub username
                foreach (var result in searcher.Search(criteria))
                {
                    if (result.Id != memberId)
                    {
                        LogHelper.Info <ProfileController>("Failed setting GitHub username for user with ID " + memberId + ". Username is already used by member with ID " + result.Id + ".");
                        return(GetErrorResult("Another member already exists with the same GitHub username."));
                    }
                }

                // Get the member from the member service
                var ms  = ApplicationContext.Services.MemberService;
                var mem = ms.GetById(memberId);

                // Update the "github" property and save the value
                mem.SetValue("github", githubUsername);
                mem.SetValue("githubId", userResponse.Body.Id);
                mem.SetValue("githubData", userResponse.Body.JObject.ToString());
                ms.Save(mem);

                // Clear the runtime cache for the member
                ApplicationContext.ApplicationCache.RuntimeCache.ClearCacheItem("MemberData" + mem.Username);

                // Redirect the member back to the profile page
                return(RedirectToUmbracoPage(1057));
            }
            catch (Exception ex)
            {
                LogHelper.Error <ProfileController>("Unable to link with GitHub user for member with ID " + memberId, ex);
                return(GetErrorResult("Oh noes! An error happened."));
            }
        }
示例#4
0
        public ActionResult LinkTwitter(string oauth_token, string oauth_verifier)
        {
            // Get the member of the current ID
            int memberId = Members.GetCurrentMemberId();

            if (memberId <= 0)
            {
                return(GetErrorResult("Oh noes! An error happened."));
            }

            try
            {
                IPublishedContent profilePage = Umbraco.TypedContent(1057);
                if (profilePage == null)
                {
                    return(GetErrorResult("Oh noes! This really shouldn't happen."));
                }

                // Initialize the OAuth client
                TwitterOAuthClient client = new TwitterOAuthClient();
                client.ConsumerKey    = WebConfigurationManager.AppSettings["twitterConsumerKey"];
                client.ConsumerSecret = WebConfigurationManager.AppSettings["twitterConsumerSecret"];

                // Grab the request token from the session
                SocialOAuthRequestToken requestToken = Session[oauth_token] as SocialOAuthRequestToken;
                if (requestToken == null)
                {
                    return(GetErrorResult("Session expired? Please click the link below and try to link with your Twitter account again ;)"));
                }

                // Update the OAuth client with information from the request token
                client.Token       = requestToken.Token;
                client.TokenSecret = requestToken.TokenSecret;

                // Make the request to the Twitter API to get the access token
                SocialOAuthAccessTokenResponse response = client.GetAccessToken(oauth_verifier);

                // Get the access token from the response body
                TwitterOAuthAccessToken accessToken = (TwitterOAuthAccessToken)response.Body;

                // Update the OAuth client properties
                client.Token       = accessToken.Token;
                client.TokenSecret = accessToken.TokenSecret;

                // Initialize a new service instance from the OAUth client
                var service = Skybrud.Social.Twitter.TwitterService.CreateFromOAuthClient(client);

                // Get some information about the authenticated Twitter user
                TwitterAccount user;
                try
                {
                    // Initialize the options for the request (we don't need the status)
                    var options = new TwitterVerifyCrendetialsOptions
                    {
                        SkipStatus = true
                    };

                    // Make the request to the Twitter API
                    var userResponse = service.Account.VerifyCredentials(options);

                    // Update the "user" variable
                    user = userResponse.Body;
                }
                catch (Exception ex)
                {
                    LogHelper.Error <ProfileController>("Unable to get user information from the Twitter API", ex);
                    return(GetErrorResult("Oh noes! An error happened."));
                }

                // Get a reference to the member searcher
                BaseSearchProvider searcher = ExamineManager.Instance.SearchProviderCollection["InternalMemberSearcher"];

                // Initialize new search criteria for the Twitter screen name
                ISearchCriteria criteria = searcher.CreateSearchCriteria();
                criteria = criteria.RawQuery($"twitter:{user.ScreenName}");

                // Check if there are other members with the same Twitter screen name
                foreach (var result in searcher.Search(criteria))
                {
                    if (result.Id != memberId)
                    {
                        LogHelper.Info <ProfileController>("Failed setting Twitter screen name for user with ID " + memberId + ". Username is already used by member with ID " + result.Id + ".");
                        return(GetErrorResult("Another member already exists with the same Twitter screen name."));
                    }
                }

                // Get the member from the member service
                var ms  = ApplicationContext.Services.MemberService;
                var mem = ms.GetById(memberId);

                // Update the "twitter" property and save the value
                mem.SetValue("twitter", user.ScreenName);
                mem.SetValue("twitterId", user.IdStr);
                mem.SetValue("twitterData", user.JObject.ToString());
                ms.Save(mem);

                // Clear the runtime cache for the member
                ApplicationContext.ApplicationCache.RuntimeCache.ClearCacheItem("MemberData" + mem.Username);

                // Redirect the member back to the profile page
                return(RedirectToUmbracoPage(1057));
            }
            catch (Exception ex)
            {
                LogHelper.Error <ProfileController>("Unable to link with Twitter user for member with ID " + memberId, ex);
                return(GetErrorResult("Oh noes! An error happened."));
            }
        }
        public static IEnumerable <SearchResult> PerformMemberSearch(string filter, IDictionary <string, string> filters, out int totalRecordCount,
                                                                     string memberType        = "",
                                                                     int pageNumber           = 0,
                                                                     int pageSize             = 0,
                                                                     string orderBy           = "",
                                                                     Direction orderDirection = Direction.Ascending)
        {
            var             internalSearcher = ExamineManager.Instance.SearchProviderCollection[CoreConstants.Examine.InternalMemberSearcher];
            ISearchCriteria criteria         = internalSearcher.CreateSearchCriteria().RawQuery(" +__IndexType:member");

            var basicFields = new List <string>()
            {
                "id", "_searchEmail", "email", "loginName"
            };

            var filterParameters = filters.Where(q => !string.IsNullOrWhiteSpace(q.Value));

            //build a lucene query
            if (string.IsNullOrWhiteSpace(filter) && !filterParameters.Any())
            {
                // Generic get everything...
                criteria.RawQuery("a* b* c* d* e* f* g* h* i* j* k* l* m* n* o* p* q* r* s* t* u* v* w* x* y* z*");
            }
            else
            {
                // the __nodeName will be boosted 10x without wildcards
                // then __nodeName will be matched normally with wildcards
                // the rest will be normal without wildcards
                if (!string.IsNullOrWhiteSpace(filter))
                {
                    var sb = new StringBuilder();
                    sb.Append("+(");
                    //node name exactly boost x 10
                    sb.AppendFormat("__nodeName:{0}^10.0 ", filter.ToLower());

                    //node name normally with wildcards
                    sb.AppendFormat(" __nodeName:{0}* ", filter.ToLower());

                    foreach (var field in basicFields)
                    {
                        //additional fields normally
                        sb.AppendFormat("{0}:{1} ", field, filter);
                    }
                    sb.Append(")");
                    criteria.RawQuery(sb.ToString());
                }

                // Now specific field searching. - these should be ANDed and grouped.
                foreach (var qs in filterParameters)
                {
                    string alias = qs.Key;
                    if (alias == Constants.Members.Groups)
                    {
                        // search on list with no commas.
                        alias = $"_{alias}";
                    }
                    else if (alias.StartsWith("f_"))
                    {
                        alias = qs.Key.Substring(2);
                    }

                    var values = filters[qs.Key].Split(',');
                    if (values.Length > 0)
                    {
                        criteria.GroupedOr(new[] { alias }, values);
                    }
                }
            }

            //must match index type
            if (!string.IsNullOrWhiteSpace(memberType))
            {
                criteria.NodeTypeAlias(memberType);
            }

            //// Order the results
            //// Examine Sorting seems too unreliable, particularly on nodeName
            //if (orderDirection == Direction.Ascending) {
            //    criteria.OrderBy(orderBy.ToLower() == "name" ? "nodeName" : "email");
            //} else {
            //    criteria.OrderByDescending(orderBy.ToLower() == "name" ? "nodeName" : "email");
            //}

            var result = internalSearcher.Search(criteria);

            totalRecordCount = result.TotalItemCount;

            string orderFieldName;

            switch (orderBy.ToLower())
            {
            case "isapproved":
                orderFieldName = CoreConstants.Conventions.Member.IsApproved;
                break;

            case "islockedout":
                orderFieldName = CoreConstants.Conventions.Member.IsLockedOut;
                break;

            case "name":
                orderFieldName = "nodeName";
                break;

            default:
                orderFieldName = orderBy;
                break;
            }
            // Order the results
            var orderedResults = orderDirection == Direction.Ascending
                ? result.OrderBy(o => o.Fields[orderFieldName])
                : result.OrderByDescending(o => o.Fields[orderFieldName]);

            if (pageSize > 0)
            {
                int skipCount = (pageNumber > 0 && pageSize > 0) ? Convert.ToInt32((pageNumber - 1) * pageSize) : 0;
                if (result.TotalItemCount < skipCount)
                {
                    skipCount = result.TotalItemCount / pageSize;
                }

                return(orderedResults.Skip(skipCount).Take(pageSize));
            }
            return(orderedResults);
        }
示例#6
0
 public ISearchCriteria RawQuery(ISearchCriteria criteria, string query)
 {
     return(criteria.RawQuery(query));
 }