Exemple #1
0
 public Search(SearchParameters p, Player searchingPlayer, SearchResults searchResults, Game game)
 {
     _p = p;
       _searchResults = searchResults;
       _game = game;
       _root = new InnerResult(_game.CalculateHash(), searchingPlayer.IsMax, 0);
 }
Exemple #2
0
 /// <summary>
 /// Creates a clear map with a start and end point and sets up the search parameters
 /// </summary>
 private void InitializeMap(int[,] iMap, Point S, Point F)
 {
     this.map = IntToBool(iMap);
     //var tmp = BoolToString(map);
     //var tmp1 = ParseIntArrayToString(iMap);
     this.sp = new SearchParameters(S, F, map);
 }
Exemple #3
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            _appTask = AppTask.GetTaskInOnCreate(bundle, Intent);
            SetContentView(Resource.Layout.search);
            SearchParameters sp = new SearchParameters();
            PopulateCheckBox(Resource.Id.cbSearchInTitle, sp.SearchInTitles);
            PopulateCheckBox(Resource.Id.cbSearchInUsername, sp.SearchInUserNames);
            PopulateCheckBox(Resource.Id.cbSearchInNotes, sp.SearchInNotes);
            PopulateCheckBox(Resource.Id.cbSearchInPassword, sp.SearchInPasswords);
            PopulateCheckBox(Resource.Id.cbSearchInTags, sp.SearchInTags);
            PopulateCheckBox(Resource.Id.cbSearchInGroupName, sp.SearchInGroupNames);
            PopulateCheckBox(Resource.Id.cbSearchInUrl, sp.SearchInUrls);
            PopulateCheckBox(Resource.Id.cbSearchInOtherStrings, sp.SearchInOther);
            PopulateCheckBox(Resource.Id.cbRegEx, sp.RegularExpression);

            StringComparison sc = sp.ComparisonMode;
            bool caseSensitive = ((sc != StringComparison.CurrentCultureIgnoreCase) &&
                                         (sc != StringComparison.InvariantCultureIgnoreCase) &&
                                         (sc != StringComparison.OrdinalIgnoreCase));
            PopulateCheckBox(Resource.Id.cbCaseSensitive, caseSensitive);
            PopulateCheckBox(Resource.Id.cbExcludeExpiredEntries, sp.ExcludeExpired);

            ImageButton btnSearch = (ImageButton)FindViewById(Resource.Id.search_button);

            btnSearch.Click += (sender, e) => PerformSearch();

            FindViewById<EditText>(Resource.Id.searchEditText).EditorAction += (sender, e) =>
            {
                if (e.ActionId == Android.Views.InputMethods.ImeAction.Search) {
                    PerformSearch();
                }
            };
        }
 // Loads UI elements and an initial webmap
 private async void LoadWebMap_Loaded(object sender, RoutedEventArgs e)
 {
     _portal = await ArcGISPortal.CreateAsync();
     var searchParams = new SearchParameters("type: \"web map\" NOT \"web mapping application\"");
     var result = await _portal.ArcGISPortalInfo.SearchHomePageFeaturedContentAsync(searchParams);
     comboWebMap.ItemsSource = result.Results;
 }
 public void Constructor_Full_NullDocumentTypeTags()
 {
     SearchParameters par = new SearchParameters("query", null, SearchOptions.AllWords);
     Assert.AreEqual("query", par.Query, "Wrong query");
     Assert.IsNull(par.DocumentTypeTags, "DocumentTypeTags should be null");
     Assert.AreEqual(SearchOptions.AllWords, par.Options);
 }
Exemple #6
0
        internal static string GetTransformation(SearchParameters spIn)
        {
            if(spIn == null) { Debug.Assert(false); return string.Empty; }

            if(spIn.DataTransformationFn == null) return string.Empty;
            return StrTrfDeref;
        }
		/// <summary>
		/// Binds the model to a value by using the specified controller context and binding context.
		/// </summary>
		/// <param name="controllerContext">The controller context.</param>
		/// <param name="bindingContext">The binding context.</param>
		/// <returns>The bound value.</returns>
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
		  
		    var parameters = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            var sp = parameters != null ? parameters.RawValue as SearchParameters : null;
		    if (sp == null)
		    {
            var qs = GetParams(controllerContext);
            var qsDict = NvToDict(qs);
            var facets = qsDict.Where(k => FacetRegex.IsMatch(k.Key)).Select(k => k.WithKey(FacetRegex.Replace(k.Key, ""))).ToDictionary(x=>x.Key, y=>y.Value.Split(','));

		    sp = new SearchParameters
            {
                FreeSearch = qs["q"].EmptyToNull(),
                PageIndex = qs["p"].TryParse(1),
                PageSize = qs["pageSize"].TryParse(0),
                Sort = qs["sort"].EmptyToNull(),
		        SortOrder = qs["sortorder"].EmptyToNull(),
                Facets = facets
            };
		        if (!string.IsNullOrEmpty(sp.FreeSearch))
		        {
		            sp.FreeSearch = sp.FreeSearch.EscapeSearchTerm();
		        }
		    }
            return sp;
        }
    public SearchRunner(SearchParameters searchParameters, Game game)
    {
      _game = game;
      _searchParameters = searchParameters;

      CurrentDepth = _searchParameters.SearchDepth;
      CurrentTargetCount = _searchParameters.TargetCount;
    }
Exemple #9
0
 /// <summary>
 /// Create a new instance of PathFinder
 /// </summary>
 /// <param name="searchParameters"></param>
 public PathFinder(SearchParameters searchParameters)
 {
     this.searchParameters = searchParameters;
     InitializeNodes(searchParameters.Map);
     this.startNode = this.nodes[searchParameters.StartLocation.X, searchParameters.StartLocation.Y];
     this.startNode.State = NodeState.Open;
     this.endNode = this.nodes[searchParameters.EndLocation.X, searchParameters.EndLocation.Y];
 }
 public void RegisterSearchChannel(SearchContext searchContext)
 {
     this._searchService.GetSearchParameters(CLAIMS_SEARCH_SP_NAME, parameters =>
     {
         this._searchParameters = parameters;
         searchContext.RegisterSearchChannel(this.GetChannel(this._searchTypeName));
     });
 }
Exemple #11
0
 public void Test_Selected_Filters_To_Search_Parameter()
 {
     var query = Conditions.From("MAYY380WWPGYY1", urlOfuscator);
     var selectedFiltersContext = new QueryUrlParser(facetConfiguration.FacetHierarchy, urlOfuscator).Parse(query).GetSelectedFilters();
     var searchParameter = new SearchParameters<Publication>(string.Empty, selectedFiltersContext,
                                                             facetConfiguration.FacetHierarchy.ByName(selectedFiltersContext.SelectedFilters.Last().Name),
                                                             facetConfiguration.FacetHierarchy.FacetsNotInBranchOf((selectedFiltersContext.SelectedFilters.Last().Name)));
     var result = indexServiceImpl.Query(searchParameter);
 }
 public void Constructor_Full()
 {
     SearchParameters par = new SearchParameters("query", new string[] { "blah", "doc" }, SearchOptions.AllWords);
     Assert.AreEqual("query", par.Query, "Wrong query");
     Assert.AreEqual(2, par.DocumentTypeTags.Length, "Wrong DocumentTypeTag count");
     Assert.AreEqual("blah", par.DocumentTypeTags[0], "Wrong type tag");
     Assert.AreEqual("doc", par.DocumentTypeTags[1], "Wrong type tag");
     Assert.AreEqual(SearchOptions.AllWords, par.Options);
 }
 public void Constructor_QueryDocumentTypeTags()
 {
     SearchParameters par = new SearchParameters("query", "blah", "doc");
     Assert.AreEqual("query", par.Query, "Wrong query");
     Assert.AreEqual(2, par.DocumentTypeTags.Length, "Wrong DocumentTypeTag count");
     Assert.AreEqual("blah", par.DocumentTypeTags[0], "Wrong type tag");
     Assert.AreEqual("doc", par.DocumentTypeTags[1], "Wrong type tag");
     Assert.AreEqual(SearchOptions.AtLeastOneWord, par.Options);
 }
        public SearchResults Search(SearchParameters parameters)
        {
            if (string.IsNullOrEmpty(parameters.Query) && string.IsNullOrEmpty(parameters.Title) && string.IsNullOrEmpty(parameters.Skills))
            {
                throw new ArgumentException("At least one of the Query, Title, or Skills parameters must be specified.");
            }

            return restTemplate.GetForObject<SearchResults>(searchBaseUri + parameters.ToString());
        }
Exemple #15
0
        internal static void SetTransformation(SearchParameters spOut,
			string strTrf)
        {
            if(spOut == null) { Debug.Assert(false); return; }
            if(strTrf == null) { Debug.Assert(false); return; }

            if(strTrf == StrTrfDeref)
                spOut.DataTransformationFn = SprEngine.DerefFn;
            else spOut.DataTransformationFn = null;
        }
 public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
     var qs = controllerContext.HttpContext.Request.QueryString;
     var qsDict = NVToDict(qs);
     var sp = new SearchParameters {
         FreeSearch = StringHelper.EmptyToNull(qs["q"]),
         PageIndex = StringHelper.TryParse(qs["page"], 1),
         PageSize = StringHelper.TryParse(qs["pageSize"], DefaultPageSize),
         Sort = StringHelper.EmptyToNull(qs["sort"]),
         Facets = qsDict.Where(k => FacetRegex.IsMatch(k.Key))
             .Select(k => k.WithKey(FacetRegex.Replace(k.Key, "")))
             .ToDictionary()
     };
     return sp;
 }
        // Loads UI elements and an initial webmap
        private async void LoadWebMap_Loaded(object sender, RoutedEventArgs e)
        {
            _portal = await ArcGISPortal.CreateAsync();

            var searchParams = new SearchParameters("type: \"web map\" NOT \"web mapping application\"");
            var result = await _portal.ArcGISPortalInfo.SearchHomePageFeaturedContentAsync(searchParams);
            comboWebMap.ItemsSource = result.Results;

            var webmap = result.Results.FirstOrDefault();
            if (webmap != null)
            {
                comboWebMap.SelectedIndex = 0;
                await LoadWebMapAsync(webmap.Id);
            }
        }
Exemple #18
0
 private SearchParameters MakeSearchParameters()
 {
     var p = new SearchParameters();
     p.SearchInTitles = true;
     p.RegularExpression = true;
     p.SearchInGroupNames = false;
     p.SearchInNotes = false;
     p.SearchInOther = false;
     p.SearchInPasswords = false;
     p.SearchInTags = false;
     p.SearchInUrls = true;
     p.SearchInUserNames = false;
     p.SearchInUuids = false;
     return p;
 }
   public static GameParameters Load(PlayerType player1Controller, PlayerType player2Controller,
 SavedGame savedGame, int? looser = null, int rollback = 0, SearchParameters searchParameters = null)
   {
       return new GameParameters
       {
         Player1 = savedGame.Player1,
         Player2 = savedGame.Player2,
         Player1Controller = player1Controller,
         Player2Controller = player2Controller,
         SearchParameters = searchParameters ?? SearchParameters.Default,
         SavedGame = savedGame,
         RollBack = rollback,
         Looser = looser
       };
   }
        public static Game LoadReport(string filename, int rollback = 0, SearchParameters searchParameters = null)
        {
            using (var stream = new FileStream(filename, FileMode.Open))
              {
            var saveGameFile = SavedGames.ReadFromStream(stream);

            var gameParameters = GameParameters.Load(
              player1Controller: PlayerType.Machine,
              player2Controller: PlayerType.Machine,
              savedGame: (SavedGame) saveGameFile.Data,
              rollback: rollback,
              searchParameters: searchParameters);

            return new Game(gameParameters);
              }
        }
Exemple #21
0
        public PwGroup Search(Database database, SearchParameters sp, IDictionary<PwUuid, KeyValuePair<string, string>> resultContexts)
        {
            if(sp.RegularExpression) // Validate regular expression
            {
                new Regex(sp.SearchString);
            }

            string strGroupName = _app.GetResourceString(UiStringKey.search_results) + " (\"" + sp.SearchString + "\")";
            PwGroup pgResults = new PwGroup(true, true, strGroupName, PwIcon.EMailSearch) {IsVirtual = true};

            PwObjectList<PwEntry> listResults = pgResults.Entries;

            database.Root.SearchEntries(sp, listResults, resultContexts, new NullStatusLogger());

            return pgResults;
        }
        public static SearchParameters CreateSearchParameters(string searchText, PortalQuery portalQuery, int startIndex = 1, int limit = 20, IList<string> favoriteItemIDs = null)
        {
            string queryString = string.Format("{0} ({1})", searchText, "type:\"web map\" NOT type:\"web mapping application\"");
            string sortField = "";
            QuerySortOrder sortOrder = QuerySortOrder.Descending;

            switch (portalQuery)
            {
                case PortalQuery.Default:
                    //searchParamters.QueryString = "sdfgsdfhh type:\"web map\" NOT \"web mapping application\"";
                    break;
                case PortalQuery.Recent:
                    sortField = "uploaded";
                    break;
                case PortalQuery.HighestRated:
                    sortField = "avgrating";
                    break;
                case PortalQuery.MostComments:
                    sortField = "numcomments";
                    break;
                case PortalQuery.MostPopular:
                    sortField = "numviews";
                    break;
                case PortalQuery.Favorites:
                    queryString = GenerateFavoriteQueryFromIDs(favoriteItemIDs);
                    break;
                case PortalQuery.MyGroups:
                    break;
                case PortalQuery.MyMaps:
                    break;
                case PortalQuery.Title:
                    sortField = "title";
                    sortOrder = QuerySortOrder.Ascending;
                    break;
                case PortalQuery.Owner:
                    sortField = "owner";
                    sortOrder = QuerySortOrder.Ascending;
                    break;
            }

            SearchParameters searchParamters = new SearchParameters(queryString);
            searchParamters.StartIndex = startIndex;
            searchParamters.Limit = limit;
            searchParamters.SortField = sortField;
            searchParamters.SortOrder = sortOrder;
            return searchParamters;
        }
Exemple #23
0
   protected AiScenario(SearchParameters searchParameters = null)
       : base(player1ControlledByScript: false,
 player2ControlledByScript: false,
 searchParameters: searchParameters)
   {
       Game.Ai.SearchFinished += delegate
       {
         _measurements.Add(new Measurement
       {
         TreeSize = Game.Ai.LastSearchStatistics.SearchTreeSize,
         NodeCount = Game.Ai.LastSearchStatistics.NodeCount,
         WorkerCount = Game.Ai.LastSearchStatistics.NumOfWorkersCreated,
         SubtreesPrunned = Game.Ai.LastSearchStatistics.SubtreesPrunned,
         ElapsedTime = Game.Ai.LastSearchStatistics.Elapsed.TotalMilliseconds
       });
       };
   }
Exemple #24
0
        public void Initialize()
        {
            //  □ □ □ □ □ □ □
            //  □ □ □ □ □ □ □
            //  □ S □ □ □ F □
            //  □ □ □ □ □ □ □
            //  □ □ □ □ □ □ □

            this.map = new bool[7, 5];
            for (int y = 0; y < 5; y++)
                for (int x = 0; x < 7; x++)
                    map[x, y] = true;

            var startLocation = new Point(1, 2);
            var endLocation = new Point(5, 2);
            this.searchParameters = new SearchParameters(startLocation, endLocation, map);
        }
 public List<DpiNotesDto> GetDpiNotes(SearchParameters searchParam)
 {
     var dpiNotes = new List<DpiNotesDto>();
     try
     {
         var request = CreateRequest(searchParam);
         var response = _customerInformationInquiry.retrieveCustomerAccountMemos(request);
         dpiNotes = MapResponse(response);
     }
     catch (System.Exception ex)
     {
         var isServiceException = _enterpriseException.HandleGeneralServiceExceptions(ex);
         if (!isServiceException)
         {
             if (_errorLoggingService != null)
             {
                 _errorLoggingService.LogErrorNoContext(ex);
             }
         }
         throw ex;
     }
     return dpiNotes;
 }
        public DocumentSearchResult <T> SearchContent <T>(string searchTerm = "*", List <string> facets = null) where T : class, new()
        {
            SearchParameters searchParams = SetSearchParams(string.Empty, facets);

            return(_indexClient.Documents.Search <T>(searchTerm, searchParams));
        }
    /// <summary>
    /// Perform search.
    /// </summary>
    protected void Search()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            // Check if the search was triggered
            bool searchAllowed = SearchOnEachPageLoad || QueryHelper.Contains("searchtext");

            // Get query strings
            string searchText = QueryHelper.GetString("searchtext", "");
            // Check whether string passes text requirements settings
            bool searchTextIsNotEmptyOrNotRequired = (!SearchTextRequired || !String.IsNullOrEmpty(searchText));

            // Proceed when search was triggered and search text is passing requirements settings.
            // Requirements setting could be overridden on this level by obsolete web.config key. The reason is backward compatibility.
            // Search text required web part setting was introduced after this web.config key. Key default value was at the time set to true.
            // This default value had the same effect as this new web part setting. When someone changed the web.config key to false and then upgraded the solution,
            // required web part setting with default value true would override previous behavior. That's the reason why this obsolete key can override this setting.
            if (searchAllowed && (searchTextIsNotEmptyOrNotRequired || !SearchHelper.SearchOnlyWhenContentPresent))
            {
                string         searchMode     = QueryHelper.GetString("searchMode", "");
                SearchModeEnum searchModeEnum = searchMode.ToEnum <SearchModeEnum>();

                // Get current culture
                string culture = CultureCode;
                if (string.IsNullOrEmpty(culture))
                {
                    culture = ValidationHelper.GetString(ViewState["CultureCode"], LocalizationContext.PreferredCultureCode);
                }

                var siteName = SiteContext.CurrentSiteName;

                // Get default culture
                string defaultCulture = CultureHelper.GetDefaultCultureCode(siteName);

                // Resolve path
                string path = Path;
                if (!string.IsNullOrEmpty(path))
                {
                    path = MacroResolver.ResolveCurrentPath(Path);
                }

                // Check if search action was fired really on the live site
                if (PortalContext.ViewMode.IsLiveSite() && (DocumentContext.CurrentPageInfo != null))
                {
                    if (AnalyticsHelper.AnalyticsEnabled(siteName) && !string.IsNullOrEmpty(searchText))
                    {
                        if (AnalyticsHelper.JavascriptLoggingEnabled(siteName))
                        {
                            WebAnalyticsServiceScriptsRenderer.RegisterLogSearchCall(Page, DocumentContext.CurrentPageInfo, searchText);
                        }
                        else
                        {
                            // Log on site keywords
                            AnalyticsHelper.LogOnSiteSearchKeywords(siteName, DocumentContext.CurrentAliasPath, culture, searchText, 0, 1);
                        }
                    }
                }

                // Prepare search text
                var docCondition = new DocumentSearchCondition(DocumentTypes, culture, defaultCulture, CombineWithDefaultCulture);

                var searchCond = SearchCondition;
                if (!string.IsNullOrEmpty(FilterSearchCondition) && (searchModeEnum == SearchModeEnum.AnyWordOrSynonyms))
                {
                    // Make sure the synonyms are expanded before the filter condition is applied (filter condition is Lucene syntax, cannot be expanded)
                    searchCond = SearchSyntaxHelper.ExpandWithSynonyms(searchCond, docCondition.Culture);
                }

                var condition = new SearchCondition(searchCond + FilterSearchCondition, searchModeEnum, SearchOptions, docCondition, DoFuzzySearch);

                searchText = SearchSyntaxHelper.CombineSearchCondition(searchText, condition);

                // Get positions and ranges for search method
                int startPosition     = 0;
                int numberOfProceeded = 100;
                int displayResults    = 100;
                if (pgr.PageSize != 0 && pgr.GroupSize != 0)
                {
                    // Reset pager if needed
                    if (mResetPager)
                    {
                        pgr.CurrentPage = 1;
                    }

                    startPosition = (pgr.CurrentPage - 1) * pgr.PageSize;
                    // Only results covered by current page group are proccessed (filtered) for performance reasons. This may cause decrease of the number of results while paging.
                    numberOfProceeded = (((pgr.CurrentPage / pgr.GroupSize) + 1) * pgr.PageSize * pgr.GroupSize) + pgr.PageSize;
                    displayResults    = pgr.PageSize;
                }

                if ((MaxResults > 0) && (numberOfProceeded > MaxResults))
                {
                    numberOfProceeded = MaxResults;
                }

                // Combine regular search sort with filter sort
                string srt       = ValidationHelper.GetString(SearchSort, String.Empty).Trim();
                string filterSrt = ValidationHelper.GetString(FilterSearchSort, String.Empty).Trim();

                if (!String.IsNullOrEmpty(filterSrt))
                {
                    if (!String.IsNullOrEmpty(srt))
                    {
                        srt += ", ";
                    }

                    srt += filterSrt;
                }

                // Prepare parameters
                SearchParameters parameters = new SearchParameters
                {
                    SearchFor                 = searchText,
                    SearchSort                = srt,
                    Path                      = path,
                    ClassNames                = DocumentTypes,
                    CurrentCulture            = culture,
                    DefaultCulture            = defaultCulture,
                    CombineWithDefaultCulture = CombineWithDefaultCulture,
                    CheckPermissions          = CheckPermissions,
                    SearchInAttachments       = SearchInAttachments,
                    User                      = MembershipContext.AuthenticatedUser,
                    SearchIndexes             = Indexes,
                    StartingPosition          = startPosition,
                    DisplayResults            = displayResults,
                    NumberOfProcessedResults  = numberOfProceeded,
                    NumberOfResults           = 0,
                    AttachmentWhere           = AttachmentsWhere,
                    AttachmentOrderBy         = AttachmentsOrderBy,
                    BlockFieldOnlySearch      = BlockFieldOnlySearch,
                };

                // Search
                var results = SearchHelper.Search(parameters);

                int numberOfResults = parameters.NumberOfResults;
                if ((MaxResults > 0) && (numberOfResults > MaxResults))
                {
                    numberOfResults = MaxResults;
                }

                // Limit displayed results according to MaxPages property
                var maxDisplayedResultsOnMaxPages = MaxPages * PageSize;
                // Apply only if MaxPages and PageSize properties are set
                if ((maxDisplayedResultsOnMaxPages > 0) && (numberOfResults > maxDisplayedResultsOnMaxPages))
                {
                    numberOfResults = maxDisplayedResultsOnMaxPages;
                }

                // Fill repeater with results
                repSearchResults.DataSource = results.Items;
                repSearchResults.PagerForceNumberOfResults = numberOfResults;
                PagerForceNumberOfResults = numberOfResults;
                repSearchResults.DataBind();

                // Call page binding event
                if (OnPageBinding != null)
                {
                    OnPageBinding(this, null);
                }

                // Show no results found ?
                if (numberOfResults == 0)
                {
                    if (ShowParsingErrors)
                    {
                        Exception searchError = results.LastError;
                        if (searchError != null)
                        {
                            ShowError(GetString("smartsearch.searcherror") + " " + HTMLHelper.HTMLEncode(searchError.Message));
                        }
                    }
                    lblNoResults.Text    = NoResultsText;
                    lblNoResults.Visible = true;
                }
            }
            else
            {
                if (!String.IsNullOrEmpty(SearchTextValidationFailedText) && searchAllowed)
                {
                    pnlSearchResults.AddCssClass(SearchTextValidationFailedCssClass);
                    lblNoResults.Text    = SearchTextValidationFailedText;
                    lblNoResults.Visible = true;
                }
                else
                {
                    Visible = false;
                }
            }

            // Invoke search completed event
            if (OnSearchCompleted != null)
            {
                OnSearchCompleted(Visible);
            }
        }
    }
Exemple #28
0
        /// <summary>
        /// Main XSLT Helper Search function, the laundry list of parameters are documented more fully in FullTextSearch.xslt
        /// Basically this constructs a search object and a highlighter object from the parameters, then calls another
        /// function to return search results as XML.
        /// </summary>
        /// <param name="searchType">MultiRelevance, MultiAnd, etc.</param>
        /// <param name="searchTerm">The search terms as entered by user</param>
        /// <param name="titleProperties">A list of umbraco properties, comma separated, to be searched as the page title</param>
        /// <param name="bodyProperties">A list of umbraco properties, comma separated, to be searched as the page body</param>
        /// <param name="rootNodes">Return only results under these nodes, set to blank or -1 to search all nodes</param>
        /// <param name="titleLinkProperties">Umbraco properties, comma separated, to use in forming the (optionally highlighted) title</param>
        /// <param name="summaryProperties">Umbraco properties, comma separated, to use in forming the (optionally highlighted) summary text</param>
        /// <param name="useHighlighting">Enable context highlighting(note this can slow things down)</param>
        /// <param name="summaryLength">Number of characters in the summary text</param>
        /// <param name="pageNumber">Page number of results to return</param>
        /// <param name="pageLength">Number of results on each page, zero disables paging and returns all results</param>
        /// <param name="fuzzieness">Amount 0-1 to "fuzz" the search, return non exact matches</param>
        /// <param name="wildcard">Add wildcard to the end of search term. Doesn't work together with fuzzyness</param>
        /// <returns></returns>
        public static XPathNodeIterator Search(string searchType, string searchTerm, string titleProperties, string bodyProperties, string rootNodes, string titleLinkProperties, string summaryProperties, int useHighlighting, int summaryLength, int pageNumber = 0, int pageLength = 0, string fuzzieness = "1.0", int wildcard = 0)
        {
            // Measure time taken. This could be done more neatly, but this is more accurate
            var stopwatch = new Stopwatch();

            stopwatch.Start();
            // Check search terms were actually entered
            if (String.IsNullOrEmpty(searchTerm))
            {
                return(ReturnError("NoTerms", "You must enter a search term"));
            }
            // Setup search parameters
            double fuzzy;

            if (String.IsNullOrEmpty(fuzzieness) || !Double.TryParse(fuzzieness, out fuzzy))
            {
                fuzzy = 1.0;
            }
            var wildcardBool     = wildcard > 0;
            var searchParameters = new SearchParameters();
            var searchProperties = GetSearchProperties(titleProperties, bodyProperties, fuzzy, wildcardBool);

            if (searchProperties != null)
            {
                searchParameters.SearchProperties = searchProperties;
            }
            searchParameters.RootNodes  = GetRootNotes(rootNodes);
            searchParameters.SearchTerm = searchTerm;

            //Setup summarizer parameters
            var summaryParameters = new SummarizerParameters {
                SearchTerm = searchTerm
            };

            if (summaryLength > 0)
            {
                summaryParameters.SummaryLength = summaryLength;
            }
            AddSummaryProperties(summaryParameters, titleLinkProperties, summaryProperties, fuzzy, wildcardBool);
            // Create summarizer according to highlighting option
            Summarizer summarizer;

            if (useHighlighting > 0)
            {
                summarizer = new Highlight(summaryParameters);
            }
            else
            {
                summarizer = new Plain(summaryParameters);
            }
            //Finally create search object and pass ISearchResults to XML renderer
            var search = new Search(searchParameters);

            switch (searchType)
            {
            case "MultiAnd":
                return(ResultsAsXml(search.ResultsMultiAnd(), summarizer, pageNumber, pageLength, stopwatch));

            case "SimpleOr":
                return(ResultsAsXml(search.ResultsSimpleOr(), summarizer, pageNumber, pageLength, stopwatch));

            case "AsEntered":
                return(ResultsAsXml(search.ResultsAsEntered(), summarizer, pageNumber, pageLength, stopwatch));

            default:
                return(ResultsAsXml(search.ResultsMultiRelevance(), summarizer, pageNumber, pageLength, stopwatch));
            }
        }
        protected void TestCanSearchWithValueFacets()
        {
            SearchIndexClient client = GetClientForQuery();

            var searchParameters =
                new SearchParameters()
            {
                Facets = new[]
                {
                    "rating,count:2,sort:-value",
                    "smokingAllowed,sort:count",
                    "category",
                    "lastRenovationDate,interval:year",
                    "rooms/baseRate,sort:value",
                    "tags,sort:value"
                }
            };

            DocumentSearchResult <Hotel> response = client.Documents.Search <Hotel>("*", searchParameters);

            AssertContainsKeys(response, Data.TestDocuments.Select(d => d.HotelId).ToArray());

            Assert.NotNull(response.Facets);

            AssertValueFacetsEqual(
                GetValueFacetsForField <long>(response.Facets, "rating", 2),
                new ValueFacetResult <long>(1, 5),
                new ValueFacetResult <long>(4, 4));

            AssertValueFacetsEqual(
                GetValueFacetsForField <bool>(response.Facets, "smokingAllowed", 2),
                new ValueFacetResult <bool>(4, false),
                new ValueFacetResult <bool>(3, true));

            AssertValueFacetsEqual(
                GetValueFacetsForField <string>(response.Facets, "category", 3),
                new ValueFacetResult <string>(5, "Budget"),
                new ValueFacetResult <string>(1, "Boutique"),
                new ValueFacetResult <string>(1, "Luxury"));

            AssertValueFacetsEqual(
                GetValueFacetsForField <DateTimeOffset>(response.Facets, "lastRenovationDate", 6),
                new ValueFacetResult <DateTimeOffset>(1, new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero)),
                new ValueFacetResult <DateTimeOffset>(1, new DateTimeOffset(1982, 1, 1, 0, 0, 0, TimeSpan.Zero)),
                new ValueFacetResult <DateTimeOffset>(2, new DateTimeOffset(1995, 1, 1, 0, 0, 0, TimeSpan.Zero)),
                new ValueFacetResult <DateTimeOffset>(1, new DateTimeOffset(1999, 1, 1, 0, 0, 0, TimeSpan.Zero)),
                new ValueFacetResult <DateTimeOffset>(1, new DateTimeOffset(2010, 1, 1, 0, 0, 0, TimeSpan.Zero)),
                new ValueFacetResult <DateTimeOffset>(1, new DateTimeOffset(2012, 1, 1, 0, 0, 0, TimeSpan.Zero)));

            AssertValueFacetsEqual(
                GetValueFacetsForField <double>(response.Facets, "rooms/baseRate", 4),
                new ValueFacetResult <double>(1, 2.44),
                new ValueFacetResult <double>(1, 7.69),
                new ValueFacetResult <double>(1, 8.09),
                new ValueFacetResult <double>(1, 9.69));

            AssertValueFacetsEqual(
                GetValueFacetsForField <string>(response.Facets, "tags", 10),
                new ValueFacetResult <string>(1, "24-hour front desk service"),
                new ValueFacetResult <string>(1, "air conditioning"),
                new ValueFacetResult <string>(4, "budget"),
                new ValueFacetResult <string>(1, "coffee in lobby"),
                new ValueFacetResult <string>(2, "concierge"),
                new ValueFacetResult <string>(1, "motel"),
                new ValueFacetResult <string>(2, "pool"),
                new ValueFacetResult <string>(1, "restaurant"),
                new ValueFacetResult <string>(1, "view"),
                new ValueFacetResult <string>(4, "wifi"));
        }
Exemple #30
0
        internal static List <ProductSearchFacet> BuildProductFacets(string accountNameKey, bool includeHidden = true)
        {
            bool includeTags = true;                 //<--- Move to turn off in settings

            int facetMaximumResultCount        = 80; //<--- 8 times the default of 10
            int facetMaximumResultCountNumbers = 40; //<--- 4 times the default of 10
            int facetMaximumResultCountSwatch  = 80; //<--- 8 times the default of 10

            var productSearchFacets = new List <ProductSearchFacet>();

            //Get the account
            var account = AccountManager.GetAccount(accountNameKey, true, AccountManager.AccountIdentificationType.AccountName);

            //Get a list of all Properties
            var properties = PropertiesManager.GetProperties(account, PropertyListType.All);


            //Get client/index for this accounts search index
            //var searchServiceClient = Settings.Azure.Search.AccountsSearchServiceClient;
            //var accountSearchIndex = searchServiceClient.Indexes.GetClient(account.ProductSearchIndex);

            //Get from cache first
            var accountSearchIndex = Common.MemoryCacheManager.SearchIndexCache[account.ProductSearchIndex] as ISearchIndexClient;

            if (accountSearchIndex == null)
            {
                //Not in cache, create: ----------------------------

                //Switched to accounts partitioned search client:
                var searchServiceClient = Settings.Azure.Search.GetSearchPartitionClient(account.SearchPartition);
                accountSearchIndex = searchServiceClient.Indexes.GetClient(account.ProductSearchIndex);

                //Store in cache: ---------------------
                Common.MemoryCacheManager.SearchIndexCache.Set(account.ProductSearchIndex, accountSearchIndex, new CacheItemPolicy {
                    AbsoluteExpiration = DateTimeOffset.UtcNow.AddMinutes(Common.MemoryCacheManager.SearchIndexClientCacheTimeInMinutes)
                });
            }



            //Loop through and create facet request from Azure search for each property.searchFieldName
            var facets = new List <string>();

            foreach (PropertyModel property in properties)
            {
                if (property.Facetable)
                {
                    if (property.PropertyTypeNameKey == "number") // || property.PropertyTypeNameKey == "money" || property.PropertyTypeNameKey == "double")
                    {
                        if (property.FacetInterval > 0)           //<-- We can override using ranges by setting this to 0
                        {
                            facets.Add(property.SearchFieldName + ",interval:" + property.FacetInterval);
                        }
                        else
                        {
                            facets.Add(property.SearchFieldName + ",count:" + facetMaximumResultCountNumbers);
                        }
                    }
                    else if (property.PropertyTypeNameKey == "location")
                    {
                        //Handle location data or ignore it
                    }
                    else if (property.PropertyTypeNameKey == "swatch")
                    {
                        facets.Add(property.SearchFieldName + ",count:" + facetMaximumResultCountSwatch);
                    }
                    else
                    {
                        facets.Add(property.SearchFieldName + ",count:" + facetMaximumResultCount);
                    }
                }
            }

            if (includeTags)
            {
                facets.Add("tags,count: " + facetMaximumResultCount);
                properties.Add(new PropertyModel {
                    PropertyName = "Tags", SearchFieldName = "tags", Facetable = true, AlwaysFacetable = true, PropertyTypeNameKey = "tags"
                });
            }

            //Prepare the query
            var searchParameters = new SearchParameters();

            searchParameters.Facets = facets;
            searchParameters.Top    = 0; //<-- We just want the facets


            if (!includeHidden)
            {
                //Filter out all products that should not be publicly visble from their equivelant facet counts:
                searchParameters.Filter = "visible eq true";
            }

            //Get facet results from Azure Search (Perform the search)

            DocumentSearchResult searchresult = null;

            try
            {
                searchresult = accountSearchIndex.Documents.Search("", searchParameters);
            }
            catch (Exception e)
            {
                var str = e.Message;
            }

            //Loop through results and build out customized facet list FOR uiS TO USE
            //foreach(var facetResult in searchresult.Facets.AsEnumerable())
            //{
            //facetResult
            //}

            foreach (PropertyModel property in properties)
            {
                if (property.Facetable) // <-- Ensure we only handle the facetable properties first (ig
                {
                    //find the corresponding facet result if the type is not "location" or "swatch"
                    dynamic facetResult = null;
                    if (property.PropertyTypeNameKey != "location") // && property.PropertyTypeNameKey != "swatch")
                    {
                        facetResult = searchresult.Facets[property.SearchFieldName];
                    }

                    //foreach (var facet in facetResult)
                    //{
                    var productSearchFacet = new ProductSearchFacet();
                    productSearchFacet.PropertyName    = property.PropertyName;
                    productSearchFacet.SearchFieldName = property.SearchFieldName;
                    productSearchFacet.Values          = new List <FacetValue>();
                    productSearchFacet.ShowAdvanced    = false; //<-- Show or hide advanced options in the UI
                    productSearchFacet.BooleanOperator = "and"; //<-- "and" is default can also use "or"


                    if (property.PropertyTypeNameKey == "predefined")  // <-- Anything predefined we use as a facet automtically
                    {
                        #region build predefined facet

                        productSearchFacet.PropertyType = property.PropertyTypeNameKey;
                        //productSearchFacet.FilterStyle = "checklist";

                        if (facetResult.Count >= 2) //<-- We only use this in search if there are 2 or more values
                        {
                            foreach (var facet in facetResult)
                            {
                                var name = facet.Value.ToString();

                                if (property.Symbol != null)
                                {
                                    #region Add symbol to value name

                                    string symbol = Common.Methods.Strings.ReplaceLeadingAndTrailingUnderscoresWithSpaces(property.Symbol);

                                    switch (property.SymbolPlacement)
                                    {
                                    case "leading":
                                        name = symbol + name;
                                        break;

                                    case "trailing":
                                        name = name + symbol;
                                        break;
                                    }

                                    #endregion
                                }

                                productSearchFacet.Values.Add(new FacetValue
                                {
                                    Name   = name,
                                    Value  = facet.Value.ToString(),
                                    Filter = property.SearchFieldName + "/any(s: s eq '" + facet.Value.ToString() + "')",
                                    Count  = facet.Count.ToString()
                                });
                            }

                            productSearchFacets.Add(productSearchFacet);
                        }

                        #endregion
                    }
                    else if (property.PropertyTypeNameKey == "location")
                    {
                        //We add this in order to flag desire to search against this location property
                        productSearchFacet.PropertyType    = property.PropertyTypeNameKey;
                        productSearchFacet.Values          = null;
                        productSearchFacet.BooleanOperator = null;
                        productSearchFacets.Add(productSearchFacet);
                    }
                    else if (property.PropertyTypeNameKey == "swatch")
                    {
                        #region build swatch facet

                        productSearchFacet.PropertyType = property.PropertyTypeNameKey;
                        //productSearchFacet.FilterStyle = "checklist";

                        if (facetResult.Count >= 2) //<-- We only use this in search if there are 2 or more values
                        {
                            foreach (var facet in facetResult)
                            {
                                #region Get the corresponding swatch image from the properties object

                                var swatchItem = property.Swatches.Find(i => i.PropertySwatchLabel == facet.Value);
                                var swatchUrl  = swatchItem.PropertySwatchImage;

                                #endregion

                                var name = facet.Value.ToString();

                                productSearchFacet.Values.Add(new FacetValue
                                {
                                    Name   = name,
                                    Value  = facet.Value.ToString(),
                                    Filter = property.SearchFieldName + "/any(s: s eq '" + facet.Value.ToString() + "')",
                                    Count  = facet.Count.ToString(),
                                    Image  = swatchUrl
                                });
                            }

                            productSearchFacets.Add(productSearchFacet);
                        }

                        #endregion
                    }
                    else if (property.PropertyTypeNameKey == "tags")
                    {
                        #region build tags facet

                        productSearchFacet.PropertyType = property.PropertyTypeNameKey;
                        //productSearchFacet.FilterStyle = "checklist";

                        if (facetResult.Count >= 2) //<-- We only use this in search if there are 2 or more values
                        {
                            foreach (var facet in facetResult)
                            {
                                var name = facet.Value.ToString();

                                productSearchFacet.Values.Add(new FacetValue
                                {
                                    Name   = name,
                                    Value  = facet.Value.ToString(),
                                    Filter = property.SearchFieldName + "/any(t: t eq '" + facet.Value.ToString() + "')",
                                    Count  = facet.Count.ToString()
                                });
                            }

                            productSearchFacets.Add(productSearchFacet);
                        }

                        #endregion
                    }
                    else if (property.PropertyTypeNameKey == "number") // || property.PropertyTypeNameKey == "money" || property.PropertyTypeNameKey == "double")
                    {
                        if (property.FacetInterval > 0)                //<-- Create ranged facets
                        {
                            #region build numberic range facet with intervals

                            productSearchFacet.PropertyType = property.PropertyTypeNameKey;
                            //productSearchFacet.FilterStyle = "checklist";

                            if (facetResult.Count >= 2) //<-- We only use this in search if there are 2 or more values
                            {
                                foreach (var facet in facetResult)
                                {
                                    var     valueFrom = facet.Value; //facet.From.ToString();
                                    dynamic valueTo;

                                    #region Attempt to get nameTo value

                                    try
                                    {
                                        valueTo = (Int32.Parse(facet.Value.ToString())) + property.FacetInterval; //facet.To.ToString();
                                    }
                                    catch
                                    {
                                        try
                                        {
                                            valueTo = Decimal.Parse(facet.Value.ToString()) + property.FacetInterval; //facet.To.ToString();
                                        }
                                        catch
                                        {
                                            try
                                            {
                                                valueTo = Double.Parse(facet.Value.ToString()) + property.FacetInterval; //facet.To.ToString();
                                            }
                                            catch
                                            {
                                                valueTo = float.Parse(facet.Value.ToString()) + property.FacetInterval; //facet.To.ToString();
                                            }
                                        }
                                    }

                                    #endregion

                                    string nameFrom = valueFrom.ToString();
                                    string nameTo   = valueTo.ToString();

                                    #region Add commas

                                    if (nameFrom.Contains("."))
                                    {
                                        //Maintain Decimals (Not implemented)
                                    }
                                    else
                                    {
                                        try
                                        {
                                            nameFrom = (int.Parse(nameFrom).ToString("N0"));
                                        }
                                        catch
                                        {
                                        }
                                    }


                                    if (nameTo.Contains("."))
                                    {
                                        //Maintain Decimals (Not implemented)
                                    }
                                    else
                                    {
                                        try
                                        {
                                            nameTo = (int.Parse(nameTo).ToString("N0"));
                                        }
                                        catch
                                        {
                                        }
                                    }

                                    #endregion

                                    if (property.Symbol != null)
                                    {
                                        #region Add symbol to value names

                                        string symbol = Common.Methods.Strings.ReplaceLeadingAndTrailingUnderscoresWithSpaces(property.Symbol);

                                        switch (property.SymbolPlacement)
                                        {
                                        case "leading":
                                            nameFrom = symbol + nameFrom;
                                            nameTo   = symbol + nameTo;
                                            break;

                                        case "trailing":
                                            nameFrom = nameFrom + symbol;
                                            nameTo   = nameTo + symbol;
                                            break;
                                        }

                                        #endregion
                                    }
                                    productSearchFacet.Values.Add(new FacetValue
                                    {
                                        Name   = nameFrom + " - " + nameTo,
                                        Value  = valueFrom + " - " + valueTo,
                                        Filter = property.SearchFieldName + " ge " + valueFrom + " and " + property.SearchFieldName + " lt " + valueTo,
                                        Count  = facet.Count.ToString()
                                    });
                                }

                                productSearchFacets.Add(productSearchFacet);
                            }


                            #endregion
                        }
                        else //<-- Create a full listing (NOT DEFAULT BEHAVIOUR!)
                        {
                            #region build full listing for numerical facet

                            productSearchFacet.PropertyType = property.PropertyTypeNameKey;
                            //productSearchFacet.FilterStyle = "checklist";

                            if (facetResult.Count >= 2) //<-- We only use this in search if there are 2 or more values
                            {
                                foreach (var facet in facetResult)
                                {
                                    productSearchFacet.Values.Add(new FacetValue
                                    {
                                        Name   = facet.Value.ToString(),
                                        Value  = facet.Value.ToString(),
                                        Filter = property.SearchFieldName + " eq " + facet.Value.ToString(),
                                        Count  = facet.Count.ToString()
                                    });
                                }

                                productSearchFacets.Add(productSearchFacet);
                            }

                            #endregion
                        }
                    }
                }
            }


            return(productSearchFacets);
        }
Exemple #31
0
        public async Task <IActionResult> GetArticles(int page, [FromQuery] SearchParameters parameters)
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(Unauthorized());
            }

            if (parameters == null)
            {
                parameters = new SearchParameters();
            }

            if (page == 0)
            {
                page = 1;
            }

            ArticleSearchType searchType = 0;

            if (parameters.SearchTitle)
            {
                searchType = searchType | ArticleSearchType.Name;
            }
            if (parameters.SearchLead)
            {
                searchType = searchType | ArticleSearchType.Lead;
            }
            if (parameters.SearchContent)
            {
                searchType = searchType | ArticleSearchType.Content;
            }


            ArticleApiOptions options = new ArticleApiOptions
            {
                Offset        = (page - 1) * LIST_LIMIT,
                Limit         = LIST_LIMIT,
                ArticleType   = ArticleType.All,
                IncludeAuthor = true,
                SearchType    = searchType,
                SearchString  = parameters.Search,
                DateStart     = parameters.DateStart,
                DateEnd       = parameters.DateEnd
            };

            if (options.DateEnd.HasValue)
            {
                options.DateEnd = options.DateEnd.Value.AddDays(1).Date; //Add one day to include DateEnd in search
            }
            if (options.DateStart.HasValue)
            {
                options.DateStart = options.DateStart.Value.Date; //Set DateTime to midnight;
            }


            //_newsService.GetArticles(options);

            IQueryable <Article> query = _context.Articles;

            query = RestrictArticleType(query, options.ArticleType.Value);
            query = RestrictDate(query, options);
            query = RestrictSearch(query, options);

            if (options.IncludeAuthor.HasValue && options.IncludeAuthor.Value)
            {
                query = query.Include(a => a.Author);
            }

            query = query.Where(a => a.Author == user);


            int count = query.Count();

            query = query.OrderByDescending(a => a.CreatedAt);

            if (options.Offset.HasValue && options.Offset.Value > 0)
            {
                query = query.Skip(options.Offset.Value);
            }

            if (options.Limit.HasValue && options.Limit.Value > 0)
            {
                query = query.Take(options.Limit.Value);
            }

            int pageCount = options.Limit.Value > 0 ? ((count - 1) / options.Limit.Value) + 1 : 1;

            List <ArticleListElemDTO> list = query.Select <Article, ArticleListElemDTO>(x => new ArticleListElemDTO
            {
                Id            = x.Id,
                Name          = x.Name,
                Lead          = x.Lead,
                ImageCount    = x.Images.Count(),
                Author        = x.Author.Name,
                PublishedAt   = x.PublishedAt,
                IsPublished   = x.IsPublished,
                IsHighlighted = x.IsHighlighted,
                HighlightedAt = x.HighlightedAt,
                CreatedAt     = x.CreatedAt
            }
                                                                                        ).ToList();

            ArticleListDTO result = new ArticleListDTO {
                Limit     = options.Limit.Value,
                Page      = page,
                Count     = count,
                PageCount = pageCount,
                Articles  = list
            };

            return(Ok(result));
        }
        // Method responsible for getting Flights according to the search parameters (note: still in early stages not functional)
        public static List <ResultFlightsTable> SearchFlights(SearchParameters sp)
        {
            List <ResultFlightsTable> flightLists = new List <ResultFlightsTable>();
            ResultFlightsTable        flights;

            SqlConnection connection      = UnversalDBControls.GetConnection();
            string        selectStatement = "SELECT FlightId, FltPlaneNo, FltDepart, FltReturn, FltLocation, FltDestination, RegionId, FltTicketPrice " +
                                            "FROM FlightsTable ";
            List <string> whereStt = new List <string>();

            if (sp.Location != null)
            {
                whereStt.Add("FltLocation = @FltLocation ");
            }
            if (sp.Destination != null)
            {
                whereStt.Add("FltDestination = @FltDestination ");
            }
            if (sp.departDt != null)
            {
                whereStt.Add("FltDepart = @FltDepart ");
            }

            /*
             * if (sp.returnDt != null)
             * {
             *  whereStt.Add("FltReturn = @FltReturn");
             * }
             */
            selectStatement += "WHERE ";
            for (int i = 1; i <= whereStt.Count; i++)
            {
                selectStatement += whereStt[i - 1];
                if (i != whereStt.Count)
                {
                    selectStatement += "AND ";
                }
            }
            SqlCommand selectCommand = new SqlCommand(selectStatement, connection);

            if (sp.Location != null)
            {
                selectCommand.Parameters.AddWithValue("@FltLocation", sp.Location);
            }
            if (sp.Destination != null)
            {
                selectCommand.Parameters.AddWithValue("@FltDestination", sp.Destination);
            }
            if (sp.departDt != null)
            {
                selectCommand.Parameters.AddWithValue("@FltDepart", sp.departDt);
            }

            /*
             * if (sp.returnDt != null)
             * {
             *  selectCommand.Parameters.AddWithValue("@FltReturn", sp.returnDt);
             * }
             */

            try
            {
                connection.Open();
                SqlDataReader dr = selectCommand.ExecuteReader();
                while (dr.Read())
                {
                    flights                = new ResultFlightsTable();
                    flights.DepartPlId     = (int)dr["FlightId"];
                    flights.DepartPlaneNo  = (int)dr["FltPlaneNo"];
                    flights.ReturnPlId     = (int)dr["FlightId"];
                    flights.RetuPlaneNo    = (int)dr["FltPlaneNo"];
                    flights.FltDepart      = (DateTime)dr["FltDepart"];
                    flights.FltReturn      = (DateTime)dr["FltReturn"];
                    flights.FltLocation    = dr["FltLocation"].ToString();
                    flights.FltDestination = dr["FltDestination"].ToString();
                    flights.RegionId       = dr["RegionId"].ToString();
                    flights.FltTicketPrice = Convert.ToDouble(dr["FltTicketPrice"]);
                    flightLists.Add(flights);
                }
            }
            catch (SqlException ex)
            {
                throw ex;
            }
            finally
            {
                connection.Close();
            }
            return(flightLists);
        }
        // Executes the search
        protected override void doSearch(object parameter)
        {
            base.doSearch(parameter);

            IsSearching = true; // Update busy state so new searches can't be initiated until the current one completes or fails

            string input = parameter as string != null ? parameter as string : Input as string;
            string searchString = input.ToString().Trim();

            if (searchString == "*")
                searchString = _serviceTypeQualifier;
            else
                searchString += " AND " + _serviceTypeQualifier;

            if (!_pageChangeSearch)
            {
                // Search was not the result of a page change, but rather was user-initiated.  Reset search data.
                _lastSearch = searchString; // Store the initial search string so it can be used when the page changes.
                _searchStartIndex = 1;
                _pagesRetrieved.Clear();
                _pagesRetrieved.Add(0);
                _results.Clear(); // Clear results from previous searches
            }

            // Reset flag for whether operation was cancelled
            _cancelled = false;

            // Initialize search parameters and execute
            SearchParameters searchParams = new SearchParameters()
            {
                Limit = _pageSize,
                StartIndex = _searchStartIndex,
                QueryString = !_pageChangeSearch ? searchString : _lastSearch,
                SortField = "NumViews",
                SortOrder = QuerySortOrder.Descending
            };

            Portal.SearchItemsAsync(searchParams, SearchItemsCompleted);
        }
Exemple #34
0
 public async Task <IList <ArcGISPortalItem> > GetFeaturedItems(SearchParameters searchParameters)
 {
     return(await GetPortalItemsInternal(ItemsRequestedType.Featured, searchParameters));
 }
 public void Constructor_Full_EmptyDocumentTypeTags()
 {
     SearchParameters par = new SearchParameters("query", new string[0], SearchOptions.AllWords);
 }
 private static void ApplyPaging(SearchParameters searchParameters, SearchRequest request)
 {
     searchParameters.Skip = request.Skip < 0 ? 0 : request.Skip;
     searchParameters.Top  = request.Take <0 || request.Take> MaximumTake ? DefaultTake : request.Take;
 }
        public DocumentSearchResult <T> FilterContent <T>(string filter, List <string> facets = null) where T : class, new()
        {
            SearchParameters parameters = SetSearchParams(filter, facets);

            return(_indexClient.Documents.Search <T>("*", parameters));
        }
Exemple #38
0
        static void Main(string[] args)
        {
            // Useful tool for working with search service: https://azsearch.azurewebsites.net/

            string searchServiceName = "ebornorth";
            string indexname         = "hotels";
            string adminApiKey       = "AF04406350DA2FA54BD24674A1F8B411";
            string queryApiKey       = "CEA041884F40DAC1F9B0D457067C9C7D";

            #region Create Schema
            Console.WriteLine("Defining the schema.....");

            SearchServiceClient serviceClient = new SearchServiceClient(searchServiceName, new SearchCredentials(adminApiKey));

            var definition = new Index()
            {
                Name   = indexname,
                Fields = new[]
                {   // Every entry need a unique ID, just like an primary key. The IsKey=true denotes this.
                    new Field("hotelId", DataType.String)
                    {
                        IsKey = true, IsFilterable = true
                    },
                    new Field("baseRate", DataType.Double)
                    {
                        IsFilterable = true, IsSortable = true, IsFacetable = true
                    },
                    new Field("description", DataType.String)
                    {
                        IsSearchable = true
                    },
                    //new Field("description_fr", AnalyzerName.FrLucene), // needed for multi-language support
                    new Field("hotelName", DataType.String)
                    {
                        IsSearchable = true, IsFilterable = true, IsSortable = true
                    },
                    new Field("category", DataType.String)
                    {
                        IsSearchable = true, IsFilterable = true, IsSortable = true, IsFacetable = true
                    },
                    new Field("tags", DataType.Collection(DataType.String))
                    {
                        IsSearchable = true, IsFilterable = true, IsFacetable = true
                    },
                    new Field("parkingIncluded", DataType.Boolean)
                    {
                        IsFilterable = true, IsFacetable = true
                    },
                    new Field("smokingAllowed", DataType.Boolean)
                    {
                        IsFilterable = true, IsFacetable = true
                    },
                    new Field("lastRenovationDate", DataType.DateTimeOffset)
                    {
                        IsFilterable = true, IsSortable = true, IsFacetable = true
                    },
                    new Field("rating", DataType.Int32)
                    {
                        IsFilterable = true, IsSortable = true, IsFacetable = true
                    },
                    new Field("location", DataType.GeographyPoint)
                    {
                        IsFilterable = true, IsSortable = true
                    }
                }
            };

            // Now create the index.
            //serviceClient.Indexes.Create(definition);

            #endregion

            #region Upload data
            Console.WriteLine("Populating the index....");

            SearchIndexClient indexClient = serviceClient.Indexes.GetClient("hotels");

            var actions = new IndexAction <Hotel>[]
            {
                IndexAction.Upload(
                    new Hotel {
                    HotelId     = "1",
                    BaseRate    = 199.0,
                    Description = "Best hotel in town",
                    //DescriptionFr = "Meilleur hôtel en ville",
                    HotelName          = "Fancy Stay",
                    Category           = "Luxury",
                    Tags               = new[] { "pool", "view", "wifi", "concierge" },
                    ParkingIncluded    = false,
                    SmokingAllowed     = false,
                    LastRenovationDate = new DateTimeOffset(2010, 6, 27, 0, 0, 0, TimeSpan.Zero),
                    Rating             = 5,
                    Location           = GeographyPoint.Create(47.678581, -122.131577)
                }),
                IndexAction.Upload(
                    new Hotel()
                {
                    HotelId     = "2",
                    BaseRate    = 79.99,
                    Description = "Cheapest hotel in town",
                    //DescriptionFr = "Hôtel le moins cher en ville",
                    HotelName          = "Roach Motel",
                    Category           = "Budget",
                    Tags               = new[] { "motel", "budget" },
                    ParkingIncluded    = true,
                    SmokingAllowed     = true,
                    LastRenovationDate = new DateTimeOffset(1982, 4, 28, 0, 0, 0, TimeSpan.Zero),
                    Rating             = 1,
                    Location           = GeographyPoint.Create(49.678581, -122.131577)
                }),
                IndexAction.MergeOrUpload(
                    new Hotel()
                {
                    HotelId     = "3",
                    BaseRate    = 129.99,
                    Description = "Close to town hall and the river"
                }),
                IndexAction.Delete(new Hotel()
                {
                    HotelId = "6"
                })
            };

            var batch = IndexBatch.New(actions);

            try
            {
                indexClient.Documents.Index(batch);
            }
            catch (IndexBatchException e)
            {
                // Sometimes when your Search service is under load, indexing will fail for some of the documents in
                // the batch. Depending on your application, you can take compensating actions like delaying and
                // retrying. For this simple demo, we just log the failed document keys and continue.
                Console.WriteLine(
                    "Failed to index some of the documents: {0}",
                    String.Join(", ", e.IndexingResults.Where(r => !r.Succeeded).Select(r => r.Key)));
            }

            Console.WriteLine("Waiting for documents to be indexed...\n");
            Thread.Sleep(2000);

            #endregion

            #region Perform a query

            SearchIndexClient indexqueryClient = new SearchIndexClient(searchServiceName, indexname, new SearchCredentials(queryApiKey));

            //Perform a query.
            // See https://azure.microsoft.com/en-gb/documentation/articles/search-query-dotnet/ for more examples


            Console.Write("Search the entire index, order by a specific field (lastRenovationDate) ");
            Console.Write("in descending order, take the top two results, and show only hotelName and ");
            Console.WriteLine("lastRenovationDate:\n");

            SearchParameters             parameters;
            DocumentSearchResult <Hotel> results;

            parameters =
                new SearchParameters()
            {
                OrderBy = new[] { "lastRenovationDate desc" },
                Select  = new[] { "hotelName", "lastRenovationDate" },
                Top     = 2
            };

            results = indexClient.Documents.Search <Hotel>("*", parameters);

            WriteDocuments(results);


            #endregion

            Console.ReadKey();
        }
Exemple #39
0
 public async Task <IList <ArcGISPortalItem> > GetMyMapsAsync(SearchParameters searchParameters)
 {
     return(await GetPortalItemsInternal(ItemsRequestedType.Default, searchParameters));
 }
Exemple #40
0
 public async Task <IList <ArcGISPortalItem> > GetBasemaps(SearchParameters searchParameters)
 {
     return(await GetPortalItemsInternal(ItemsRequestedType.Basemaps, searchParameters));
 }
    public void Method1()
    {
        var serviceProvider = ((IServiceProvider)Startup.Container);

        if (serviceProvider == null)
        {
            return;
        }

        var solrOperation = serviceProvider.GetService(typeof(ISolrReadOnlyOperations <MySampleItem>));

        if (solrOperation == null)
        {
            return;
        }

        ISolrReadOnlyOperations <MySampleItem> solr = (ISolrReadOnlyOperations <MySampleItem>)solrOperation;
        SearchParameters parameters = new SearchParameters();

        parameters.FreeSearch = txtSearch.Text;
        DateTime currentdate     = DateTime.Now;
        var      facetweek       = new SolrQueryByRange <DateTime?>("date", new DateTime(currentdate.Year, currentdate.Month, currentdate.Day).AddDays(-7), new DateTime(currentdate.Year, currentdate.Month, currentdate.Day));
        var      facetyear       = new SolrQueryByRange <DateTime?>("date", new DateTime(currentdate.Year, currentdate.Month, currentdate.Day).AddYears(-1), new DateTime(currentdate.Year, currentdate.Month, currentdate.Day));
        var      facetmonth      = new SolrQueryByRange <DateTime?>("date", new DateTime(currentdate.Year, currentdate.Month, currentdate.Day).AddMonths(-1), new DateTime(currentdate.Year, currentdate.Month, currentdate.Day));
        var      start           = (parameters.PageIndex - 1) * parameters.PageSize;
        var      matchingRecords = solr.Query(BuildQuery(parameters), new QueryOptions
        {
            ExtraParams = new Dictionary <string, string>
            {
                { "fq", "-type file)  roles 1)" },
                { "group.truncate", "true" },
            },
            Highlight = new HighlightingParameters {
            },
            Grouping  = new GroupingParameters()
            {
                Fields  = new[] { "collapse" },
                Ngroups = true,
            },
            FilterQueries = BuildFilterQueries(parameters),
            Rows          = parameters.PageSize,
            Facet         = new FacetParameters
            {
                Queries = new ISolrFacetQuery[]
                {
                    new SolrFacetFieldQuery("category")
                    {
                        MinCount = 0, Limit = 12, Offset = 0, Sort = true
                    },
                    new SolrFacetFieldQuery("user")
                    {
                        MinCount = 1, Limit = 12, Offset = 0, Sort = true
                    },
                    new SolrFacetFieldQuery("group")
                    {
                        MinCount = 1, Limit = 12, Offset = 0, Sort = true
                    },
                    new SolrFacetFieldQuery("tag")
                    {
                        MinCount = 1, Limit = 12, Offset = 0, Sort = true
                    },
                    new SolrFacetQuery(facetweek),
                    new SolrFacetQuery(facetyear),
                    new SolrFacetQuery(facetmonth),
                }
            },
        });
    }
		internal static void AutoAdjustMemProtSettings(PwDatabase pd,
			SearchParameters sp)
		{
			if(pd == null) { Debug.Assert(false); return; }

			// if(sp != null)
			// {
			//	if(sp.SearchInTitles) pd.MemoryProtection.ProtectTitle = false;
			//	if(sp.SearchInUserNames) pd.MemoryProtection.ProtectUserName = false;
			//	// if(sp.SearchInPasswords) pd.MemoryProtection.ProtectPassword = false;
			//	if(sp.SearchInUrls) pd.MemoryProtection.ProtectUrl = false;
			//	if(sp.SearchInNotes) pd.MemoryProtection.ProtectNotes = false;
			// }
		}
 public Task <IList <ArcGISPortalItem> > GetPortalItems(SearchParameters searchParamaters)
 {
     return(Task.FromResult <IList <ArcGISPortalItem> >(new List <ArcGISPortalItem>()));
 }
 public ElasticQuery()
 {
     SearchParameters = new SearchParameters();
 }
        public ActionResult Buscar(SearchParameters parameters)
        {
            var queriable = _pedidosService.Buscar();

            queriable = queriable.Where(a => a.EstadoId != (int)EstadosEnum.Cancelado && a.EmpresaId == parameters.IdEmpresa);

            if (parameters.IdPedido.HasValue)
            {
                queriable = queriable.Where(a => a.Id == parameters.IdPedido.Value);
            }

            if (parameters.Finalizados.HasValue)
            {
                queriable = parameters.Finalizados.Value
                    ? queriable.Where(a => a.EstadoId == (int)EstadosEnum.Finalizado)
                    : queriable.Where(a => a.EstadoId != (int)EstadosEnum.Finalizado);
            }
            else
            {
                queriable = queriable.Where(a => a.EstadoId != (int)EstadosEnum.Finalizado);
            }

            if (!string.IsNullOrEmpty(parameters.Nombre))
            {
                queriable = queriable.Where(a => (a.Cliente.Nombres + " " + a.Cliente.Apellidos).Contains(parameters.Nombre));
            }
            if (!string.IsNullOrEmpty(parameters.Carnet))
            {
                queriable = queriable.Where(a => a.Cliente.Carnet.Contains(parameters.Carnet));
            }
            if (!string.IsNullOrEmpty(parameters.Contenedor))
            {
                queriable = queriable.Where(a => a.Contenedores.Contains(parameters.Contenedor));
            }

            if (parameters.FechaDesde.HasValue && parameters.FechaHasta.HasValue)
            {
                queriable = queriable.Where(a => a.Fecha >= parameters.FechaDesde.Value && a.Fecha <= parameters.FechaHasta.Value);
            }
            else if (parameters.FechaDesde.HasValue)
            {
                queriable = queriable.Where(a => a.Fecha >= parameters.FechaDesde.Value);
            }
            else if (parameters.FechaHasta.HasValue)
            {
                queriable = queriable.Where(a => a.Fecha <= parameters.FechaHasta.Value);
            }
            var querySelect = queriable.Select(a => new
            {
                Pedido = new
                {
                    a.Id,
                    a.Descripcion,
                    Contenedores = a.Contenedores,
                    a.Fecha,
                    a.Precio,
                    Cliente = new
                    {
                        a.Cliente.Id,
                        a.Cliente.Carnet,
                        a.Cliente.Nombres,
                        a.Cliente.Apellidos,
                        NombreCompleto = (a.Cliente.Nombres + " " + a.Cliente.Apellidos).Trim()
                    },
                    Estado = new
                    {
                        a.Estado.Id,
                        a.Estado.Nombre
                    }
                }
            });

            var order = parameters.GetEnum(SearchParameters.PedidoOrderColumn.Fecha);

            switch (order)
            {
            case SearchParameters.PedidoOrderColumn.Id:
                querySelect = parameters.Ascendente
                        ? querySelect.OrderBy(a => a.Pedido.Id)
                        : querySelect.OrderByDescending(a => a.Pedido.Id);
                break;

            case SearchParameters.PedidoOrderColumn.Nombre:
                querySelect = parameters.Ascendente
                        ? querySelect.OrderBy(a => a.Pedido.Cliente.Nombres).ThenBy(a => a.Pedido.Cliente.Apellidos)
                        : querySelect.OrderByDescending(a => a.Pedido.Cliente.Nombres).ThenByDescending(a => a.Pedido.Cliente.Apellidos);
                break;

            case SearchParameters.PedidoOrderColumn.Fecha:
                querySelect = parameters.Ascendente
                        ? querySelect.OrderByDescending(a => a.Pedido.Fecha)
                        : querySelect.OrderByDescending(a => a.Pedido.Fecha);
                break;
            }

            var listado = querySelect.Skip((parameters.PageIndex - 1) * parameters.ItemsPerPage)
                          .Take(parameters.ItemsPerPage).ToList();

            var returnList = listado.Select(a =>
            {
                var tieneObservaciones = _observacionesService.TieneObservaciones(a.Pedido.Id);
                var returnData         = new
                {
                    a.Pedido,
                    FechaPedido        = a.Pedido.Fecha.ToString("dd/MM/yyyy"),
                    Contenedor         = string.Join(", ", a.Pedido.Contenedores),
                    TieneObservaciones = tieneObservaciones
                };
                return(returnData);
            });
            var transfer      = new ClientTransfer();
            var totalElements = querySelect.Count();
            var totalPages    = totalElements / parameters.ItemsPerPage;

            transfer.Data = returnList;
            transfer.Pagination.TotalPages          = totalPages + ((totalElements % parameters.ItemsPerPage) > 0 ? 1 : 0);
            transfer.Pagination.TotalRecords        = totalElements; //Total de elementos segun filtro
            transfer.Pagination.TotalDisplayRecords = listado.Count; //Total de elementos segun pagina
            return(Json(transfer));
        }
Exemple #46
0
        private async void searchButton_Click(object sender, EventArgs e)
        {
            if (_searchCancelToken != null)
            {
                _searchCancelToken.Cancel();
                _searchCancelToken = null;
                return;
            }

            if (!Utils.LevDirectoryExists())
            {
                Utils.ShowError(Constants.LevDirNotFound);
                return;
            }
            var res = GetRegexes();

            if (!res.HasValue)
            {
                Utils.ShowError("Some of the search parameters have invalid syntax (regex).");
                return;
            }

            var allFiles = Directory.GetFiles(Global.AppSettings.General.LevelDirectory, "*.lev",
                                              Global.AppSettings.LevelManager.LevDirSearchOption);
            var recFiles = Directory.GetFiles(Global.AppSettings.General.ReplayDirectory, "*.rec",
                                              Global.AppSettings.LevelManager.RecDirSearchOption);
            var levFiles = Utils.FilterByRegex(allFiles, SearchPattern).ToList();

            searchProgressBar.Maximum = recFiles.Length;
            var progressHandler = new Progress <(int progress, string statusText)>(value =>
            {
                var(progressValue, status) = value;
                searchProgressBar.Value    = progressValue;
                statusLabel.Text           = status;
            });
            var progress = (IProgress <(int progress, string statusText)>)progressHandler;

            var errorFiles = new List <string>();

            _recsByLevel       = new Dictionary <string, List <Replay> >();
            _searchCancelToken = new CancellationTokenSource();
            var token         = _searchCancelToken.Token;
            var foundLevs     = new List <Level>();
            var clickedButton = (Button)sender;
            var oldButtonText = clickedButton.Text;

            clickedButton.Text = "Stop";
            try
            {
                await Task.Run(() =>
                {
                    var iter = 0;
                    foreach (var f in recFiles)
                    {
                        iter++;
                        Replay r;
                        try
                        {
                            r = new Replay(f);
                        }
                        catch (BadFileException)
                        {
                            continue;
                        }
                        var key = r.LevelFilename.ToLower() + r.LevId;
                        _recsByLevel.TryGetValue(key, out var list);
                        if (list == null)
                        {
                            list = new List <Replay>();
                            _recsByLevel[key] = list;
                        }

                        list.Add(r);
                        if (iter % 10 == 0)
                        {
                            progress.Report((iter, $"Processing replay files first: {iter} of {recFiles.Length}"));
                        }
                        token.ThrowIfCancellationRequested();
                    }
                }, token);
            }
            catch (OperationCanceledException)
            {
                Finalize();
                return;
            }

            searchProgressBar.Maximum = levFiles.Count;
            var(titleRe, lgrRe, gtRe, stRe, spnRe, mpnRe) = res.Value;
            var searchParams = new LevelSearchParameters
            {
                AcrossLev            = SearchParameters.GetBoolOptionFromTriSelect(elmaAcrossSelect),
                Date                 = new Range <DateTime>(minDateTime.Value, maxDateTime.Value),
                Size                 = new Range <int>((int)minFileSizeBox.Value * 1024, (int)maxFileSizeBox.Value * 1024),
                Title                = titleRe,
                Lgr                  = lgrRe,
                GroundTexture        = gtRe,
                SkyTexture           = stRe,
                SinglePlayerNick     = spnRe,
                MultiPlayerNick      = mpnRe,
                SinglePlayerBestTime = Utils.GetTimeRange(minSingleBestTimeBox.Text, maxSingleBestTimeBox.Text),
                MultiPlayerBestTime  = Utils.GetTimeRange(minMultiBestTimeBox.Text, maxMultiBestTimeBox.Text),
                GroundPolygons       = Range <int> .FromNumericBoxes(minGroundPolygonsBox, maxGroundPolygonsBox),
                GroundVertices       = Range <int> .FromNumericBoxes(minGroundVerticesBox, maxGroundVerticesBox),
                GrassPolygons        = Range <int> .FromNumericBoxes(minGrassPolygonsBox, maxGrassPolygonsBox),
                GrassVertices        = Range <int> .FromNumericBoxes(minGrassVerticesBox, maxGrassVerticesBox),
                SingleTop10Times     = Range <int> .FromNumericBoxes(minSingleplayerTimesBox, maxSingleplayerTimesBox),
                MultiTop10Times      = Range <int> .FromNumericBoxes(minMultiplayerTimesBox, maxMultiplayerTimesBox),
                Killers              = Range <int> .FromNumericBoxes(minKillersBox, maxKillersBox),
                Flowers              = Range <int> .FromNumericBoxes(minFlowersBox, maxFlowersBox),
                Pictures             = Range <int> .FromNumericBoxes(minPicturesBox, maxPicturesBox),
                Textures             = Range <int> .FromNumericBoxes(minTexturesBox, maxTexturesBox),
                Apples               = Range <int> .FromNumericBoxes(minApplesBox, maxApplesBox),
                GravApples           = new Dictionary <AppleType, Range <int> >
                {
                    { AppleType.Normal, Range <int> .FromNumericBoxes(minNormApplesBox, maxNormApplesBox) },
                    { AppleType.GravityUp, Range <int> .FromNumericBoxes(minGravUpApplesBox, maxGravUpApplesBox) },
                    { AppleType.GravityDown, Range <int> .FromNumericBoxes(minGravDownApplesBox, maxGravDownApplesBox) },
                    { AppleType.GravityLeft, Range <int> .FromNumericBoxes(minGravLeftApplesBox, maxGravLeftApplesBox) },
                    { AppleType.GravityRight, Range <int> .FromNumericBoxes(minGravRightApplesBox, maxGravRightApplesBox) }
                }
            };

            try
            {
                await Task.Run(() =>
                {
                    var iter = 0;
                    foreach (var levFile in levFiles)
                    {
                        iter++;
                        Level srp;
                        try
                        {
                            srp = Level.FromPath(levFile);
                        }
                        catch (BadFileException)
                        {
                            errorFiles.Add(levFile);
                            continue;
                        }

                        if (searchParams.Matches(srp))
                        {
                            foundLevs.Add(srp);
                        }

                        if (iter % 10 == 0)
                        {
                            progress.Report((iter, $"Found {foundLevs.Count} levels so far"));
                        }
                        token.ThrowIfCancellationRequested();
                    }
                }, token);
            }
            catch (OperationCanceledException)
            {
            }

            Finalize();

            void Finalize()
            {
                foreach (var lev in foundLevs)
                {
                    var key = lev.FileName.ToLower() + lev.Identifier;
                    _recsByLevel.TryGetValue(key, out var recs);
                    if (recs != null)
                    {
                        lev.Replays = recs.Count;
                    }
                }

                ObjectList.SetObjects(foundLevs);
                statusLabel.Text        = "Ready";
                searchProgressBar.Value = 0;
                _searchCancelToken      = null;
                configButton.Enabled    = true;
                clickedButton.Text      = oldButtonText;
                DisplaySelectionInfo();
                if (errorFiles.Count > 0)
                {
                    using (var ef = new ErrorForm(errorFiles))
                    {
                        ef.ShowDialog();
                    }
                }
            }
        }
Exemple #47
0
 public override List <RulePersonType> Search(SearchParameters criteria)
 {
     return(SearchInternal(criteria));
 }
Exemple #48
0
        public override ImportContactsData GetContacts(string fileName, IEnumerable <FieldViewModel> customFields, int jobId, IEnumerable <DropdownValueViewModel> DropdownFields)
        {
            var persons = new List <RawContact>();
            var personCustomFieldData = new List <ImportCustomData>();
            var personPhoneData       = new List <ImportPhoneData>();
            ImportContactsData data   = new ImportContactsData();
            var oldNewValues          = new Dictionary <string, dynamic> {
            };

            Func <RawContact, bool> ValidateEmail = (c) =>
            {
                /*
                 * If email is not empty or null then validate email
                 * If email is empty/or null then check for legth of first name and lastname
                 */
                if ((!string.IsNullOrEmpty(c.PrimaryEmail) && c.IsValidEmail(c.PrimaryEmail)) ||
                    (string.IsNullOrEmpty(c.PrimaryEmail) && !string.IsNullOrEmpty(c.FirstName) && !string.IsNullOrEmpty(c.LastName)))
                {
                    return(true);
                }
                return(false);
            };

            try
            {
                Logger.Current.Verbose("Getting the data for BDX Lead adapter provider");

                var xDocument = XDocument.Load(fileName);
                customFields = customFields.Where(i => i.IsLeadAdapterField && i.LeadAdapterType == (byte)LeadAdapterTypes.PROPLeads && i.StatusId == FieldStatus.Active);
                IList <string> hashes = new List <string>();
                //Process for each person
                var leads     = xDocument.Descendants("Lead");
                int AccountID = leadAdapterAndAccountMap.AccountID;
                foreach (var lead in leads)
                {
                    var guid            = Guid.NewGuid();
                    var propertyIntrest = lead.Descendants("PropertyInterest").FirstOrDefault();
                    var leadcontact     = lead.Descendants("Contact").FirstOrDefault();

                    string BuilderNumber = propertyIntrest.Attribute("BuilderNumber") != null?propertyIntrest.Attribute("BuilderNumber").Value : "";

                    bool   builderNumberPass   = leadAdapterAndAccountMap.BuilderNumber.ToLower().Split(',').Contains(BuilderNumber.ToLower());
                    bool   communityNumberPass = true;
                    string CommunityNumber     = propertyIntrest.Attribute("CommunityNumber") != null?propertyIntrest.Attribute("CommunityNumber").Value : "";

                    //bool communityNumberPass = String.IsNullOrEmpty(leadAdapterAndAccountMap.CommunityNumber) ? true :
                    //    leadAdapterAndAccountMap.CommunityNumber.ToLower().Split(',').Contains(CommunityNumber.ToLower()) && !string.IsNullOrEmpty(CommunityNumber);
                    Logger.Current.Informational("Processing leads for account : " + leadAdapterAndAccountMap.AccountName + " IsCommunityPass : "******"FirstName") != null?leadcontact.Attribute("FirstName").Value : null;

                    string LastName = leadcontact.Attribute("LastName") != null?leadcontact.Attribute("LastName").Value : null;

                    string PrimaryEmail = leadcontact.Attribute("Email") != null?leadcontact.Attribute("Email").Value : null;

                    string CompanyName = string.Empty;

                    StringBuilder hash   = new StringBuilder();
                    IList <Email> emails = new List <Email>();

                    if (!string.IsNullOrEmpty(PrimaryEmail))
                    {
                        Email primaryemail = new Email()
                        {
                            EmailId   = PrimaryEmail,
                            AccountID = leadAdapterAndAccountMap.AccountID,
                            IsPrimary = true
                        };
                        emails.Add(primaryemail);
                        hash.Append("-").Append(PrimaryEmail);
                    }
                    else
                    {
                        hash.Append("-").Append("*****@*****.**");
                    }

                    Person person = new Person()
                    {
                        FirstName   = FirstName,
                        LastName    = LastName,
                        CompanyName = CompanyName,
                        Emails      = emails,
                        AccountID   = AccountID
                    };

                    if (string.IsNullOrEmpty(FirstName))
                    {
                        hash.Append("-").Append(string.Empty);
                    }
                    else
                    {
                        hash.Append("-").Append(FirstName);
                    }

                    if (string.IsNullOrEmpty(LastName))
                    {
                        hash.Append("-").Append(string.Empty);
                    }
                    else
                    {
                        hash.Append("-").Append(LastName);
                    }

                    if (string.IsNullOrEmpty(CompanyName))
                    {
                        hash.Append("-").Append(string.Empty);
                    }
                    else
                    {
                        hash.Append("-").Append(CompanyName);
                    }


                    bool IsNotValidContact = false;

                    bool isDuplicateFromFile = false;

                    if (!IsNotValidContact && builderNumberPass && communityNumberPass)
                    {
                        bool duplicateemailcount = hashes.Where(h => h.Contains(PrimaryEmail)).Any();
                        if (!string.IsNullOrEmpty(PrimaryEmail) && duplicateemailcount)
                        {
                            isDuplicateFromFile = true;
                        }
                        else if (!string.IsNullOrEmpty(PrimaryEmail) && !duplicateemailcount)
                        {
                            isDuplicateFromFile = false;
                        }
                        else if (string.IsNullOrEmpty(PrimaryEmail) && hashes.Where(h => h.Contains(hash.ToString())).Any())
                        {
                            isDuplicateFromFile = true;
                        }
                        else
                        {
                            isDuplicateFromFile = false;
                        }
                    }

                    SearchResult <Contact> duplicateResult = new SearchResult <Contact>();
                    if (!IsNotValidContact && builderNumberPass && isDuplicateFromFile == false && communityNumberPass)
                    {
                        SearchParameters parameters = new SearchParameters()
                        {
                            AccountId = AccountID
                        };
                        IEnumerable <Contact> duplicateContacts = contactService.CheckIfDuplicate(new CheckContactDuplicateRequest()
                        {
                            Person = person
                        }).Contacts;
                        duplicateResult = new SearchResult <Contact>()
                        {
                            Results = duplicateContacts, TotalHits = duplicateContacts != null?duplicateContacts.Count() : 0
                        };
                    }


                    if (!builderNumberPass)
                    {
                        status = LeadAdapterRecordStatus.BuilderNumberFailed;
                    }
                    else if (!communityNumberPass)
                    {
                        status = LeadAdapterRecordStatus.CommunityNumberFailed;
                    }
                    else if (IsNotValidContact)
                    {
                        status = LeadAdapterRecordStatus.ValidationFailed;
                    }
                    else if (isDuplicateFromFile)
                    {
                        status = LeadAdapterRecordStatus.DuplicateFromFile;
                    }
                    else if (duplicateResult.TotalHits > 0)
                    {
                        status = LeadAdapterRecordStatus.Updated;
                        guid   = duplicateResult.Results.FirstOrDefault().ReferenceId;
                    }
                    else
                    {
                        status = LeadAdapterRecordStatus.Added;
                    }


                    Contact duplicateperson = default(Person);
                    //contact.LeadAdapterRecordStatusId = (byte)status;
                    if (status == LeadAdapterRecordStatus.Updated)
                    {
                        duplicateperson = duplicateResult.Results.FirstOrDefault();
                    }
                    else
                    {
                        duplicateperson = new Person();
                    }

                    ////////////////////////////////////////////////////////////////

                    try
                    {
                        XDocument            doc           = XDocument.Parse(lead.ToString());
                        List <XMLTypeHolder> allattributes = new List <XMLTypeHolder>();
                        foreach (XElement node in doc.Nodes())
                        {
                            allattributes.AddRange(node.Attributes().Select(x => new XMLTypeHolder {
                                NodeName = node.Name.LocalName, LocalName = x.Name.LocalName, Value = x.Value
                            }).ToList());
                            if (node.HasElements)
                            {
                                foreach (XElement ele in node.Elements())
                                {
                                    allattributes.AddRange(ele.Attributes().Select(x => new XMLTypeHolder {
                                        NodeName = ele.Name.LocalName, LocalName = x.Name.LocalName, Value = x.Value
                                    }).ToList());
                                }
                            }
                        }

                        foreach (var attribute in allattributes)
                        {
                            ImportCustomData customData = new ImportCustomData();
                            try
                            {
                                var elementvalue = string.Empty;
                                if (attribute.LocalName.ToLower() == "firstname" && attribute.NodeName == "Contact")
                                {
                                    elementvalue      = ((Person)person).FirstName == null ? "" : ((Person)person).FirstName;
                                    contact.FirstName = attribute.Value;
                                }
                                else if (attribute.LocalName.ToLower() == "lastname" && attribute.NodeName == "Contact")
                                {
                                    elementvalue     = ((Person)person).LastName;
                                    contact.LastName = attribute.Value;
                                }
                                else if (attribute.LocalName.ToLower() == "email" && attribute.NodeName == "Contact")
                                {
                                    Email primaryemail = person.Emails == null ? null : person.Emails.Where(i => i.IsPrimary == true).FirstOrDefault();
                                    if (primaryemail != null)
                                    {
                                        elementvalue = primaryemail.EmailId;
                                    }
                                    contact.PrimaryEmail = attribute.Value;
                                }
                                else if (attribute.LocalName.ToLower() == "company" && attribute.NodeName == "Contact")
                                {
                                    elementvalue        = person.CompanyName;
                                    contact.CompanyName = attribute.Value;
                                }
                                else if (attribute.LocalName.ToLower() == "phone" && attribute.NodeName == "Contact")
                                {
                                    DropdownValueViewModel drpvalue = DropdownFields.Where(i => i.DropdownValueTypeID == (short)DropdownValueTypes.MobilePhone).FirstOrDefault();
                                    var             mobilephone     = default(Phone);
                                    ImportPhoneData phoneData       = new ImportPhoneData();
                                    phoneData.ReferenceID = guid;
                                    if (drpvalue != null)
                                    {
                                        if (!string.IsNullOrEmpty(attribute.Value))
                                        {
                                            string nonnumericstring = GetNonNumericData(attribute.Value);
                                            if (IsValidPhoneNumberLength(nonnumericstring))
                                            {
                                                contact.PhoneData     = drpvalue.DropdownValueID.ToString() + "|" + nonnumericstring;
                                                phoneData.PhoneType   = (int?)drpvalue.DropdownValueID;
                                                phoneData.PhoneNumber = nonnumericstring;
                                                contactPhoneData.Add(phoneData);
                                            }
                                        }
                                        mobilephone = person.Phones == null ? null : person.Phones.Where(i => i.PhoneType == drpvalue.DropdownValueID).FirstOrDefault();
                                    }

                                    if (mobilephone != null)
                                    {
                                        elementvalue = mobilephone.Number;
                                    }
                                }
                                else if (attribute.LocalName.ToLower() == "workphone" && attribute.NodeName == "Contact")
                                {
                                    DropdownValueViewModel drpvalue = DropdownFields.Where(i => i.DropdownValueTypeID == (short)DropdownValueTypes.WorkPhone).FirstOrDefault();
                                    var workphone = default(Phone);
                                    if (drpvalue != null)
                                    {
                                        if (!string.IsNullOrEmpty(attribute.Value))
                                        {
                                            string nonnumericstring = GetNonNumericData(attribute.Value);
                                            if (IsValidPhoneNumberLength(nonnumericstring))
                                            {
                                                contact.PhoneData = drpvalue.DropdownValueID.ToString() + "|" + nonnumericstring;
                                            }
                                        }
                                        workphone = person.Phones == null ? null : person.Phones.Where(i => i.PhoneType == drpvalue.DropdownValueID).FirstOrDefault();
                                    }

                                    if (workphone != null)
                                    {
                                        elementvalue = workphone.Number;
                                    }
                                }
                                else if (attribute.LocalName.ToLower() == "city" && attribute.NodeName == "Contact")
                                {
                                    contact.City = attribute.Value;
                                }
                                else if (attribute.LocalName.ToLower() == "state" && attribute.NodeName == "Contact")
                                {
                                    contact.State = attribute.Value;
                                }
                                else if (attribute.LocalName.ToLower() == "postalcode" && attribute.NodeName == "Contact")
                                {
                                    contact.ZipCode = attribute.Value;
                                }
                                else if (attribute.LocalName.ToLower() == "address" && attribute.NodeName == "Contact")
                                {
                                    contact.AddressLine1 = attribute.Value;
                                }
                                else if (attribute.LocalName.ToLower() == "streetname" && attribute.NodeName == "Contact")
                                {
                                    contact.AddressLine2 = attribute.Value;
                                }
                                else
                                {
                                    var customField = customFields.Where(i => i.Title.Replace(" ", string.Empty).ToLower() == (attribute.LocalName.ToLower() + "(" + LeadAdapterTypes.PROPLeads.ToString().ToLower() + ")")).FirstOrDefault();
                                    if (customField != null)
                                    {
                                        var customfielddata = person.CustomFields == null ? null : person.CustomFields.Where(i => i.CustomFieldId == customField.FieldId).FirstOrDefault();
                                        if (customfielddata != null)
                                        {
                                            elementvalue = customfielddata.Value;
                                        }

                                        customData.FieldID     = customField.FieldId;
                                        customData.FieldTypeID = (int?)customField.FieldInputTypeId;
                                        customData.ReferenceID = guid;
                                        if (customField.FieldInputTypeId == FieldType.date || customField.FieldInputTypeId == FieldType.datetime || customField.FieldInputTypeId == FieldType.time)
                                        {
                                            DateTime converteddate;
                                            if (DateTime.TryParse(attribute.Value, out converteddate))
                                            {
                                                CustomFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + converteddate.ToString("MM/dd/yyyy hh:mm tt"));
                                                customData.FieldValue = converteddate.ToString("MM/dd/yyyy hh:mm tt");
                                            }
                                        }
                                        else if (customField.FieldInputTypeId == FieldType.number)
                                        {
                                            double number;
                                            if (double.TryParse(attribute.Value, out number))
                                            {
                                                CustomFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + number.ToString());
                                                customData.FieldValue = number.ToString();
                                            }
                                        }
                                        else if (customField.FieldInputTypeId == FieldType.url)
                                        {
                                            if (IsValidURL(attribute.Value.Trim()))
                                            {
                                                CustomFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + attribute.Value.Trim());
                                                customData.FieldValue = attribute.Value.Trim();
                                            }
                                        }
                                        else
                                        {
                                            CustomFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + attribute.Value.Trim());
                                            customData.FieldValue = attribute.Value.Trim();
                                        }
                                        contactCustomData.Add(customData);
                                    }
                                }
                                if (oldNewValues == null)
                                {
                                    oldNewValues = new Dictionary <string, dynamic> {
                                    }
                                }
                                ;
                                if (!oldNewValues.ContainsKey(attribute.LocalName))
                                {
                                    oldNewValues.Add(attribute.LocalName, new { OldValue = string.IsNullOrEmpty(elementvalue) ? string.Empty : elementvalue, NewValue = attribute.Value });
                                }
                            }
                            catch (Exception ex)
                            {
                                Logger.Current.Error("An exception occured in Genereating old new values attribute in Prop Leads : " + attribute.LocalName, ex);
                                continue;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Current.Error("An exception occured in Genereating old new values attribute in Prop Leads : ", ex);
                    }
                    if (CustomFieldData.Length > 0)
                    {
                        CustomFieldData.Remove(0, 1);
                    }
                    contact.CustomFieldsData          = CustomFieldData.ToString();
                    contact.ReferenceId               = guid;
                    contact.AccountID                 = AccountID;
                    contact.IsBuilderNumberPass       = builderNumberPass;
                    contact.IsCommunityNumberPass     = communityNumberPass;
                    contact.LeadAdapterRecordStatusId = (byte)status;
                    contact.JobID           = jobId;
                    contact.ContactStatusID = 1;
                    contact.ContactTypeID   = 1;
                    JavaScriptSerializer js = new JavaScriptSerializer();
                    contact.LeadAdapterSubmittedData = js.Serialize(oldNewValues);
                    contact.LeadAdapterRowData       = lead.ToString();
                    personCustomFieldData.AddRange(contactCustomData);
                    personPhoneData.AddRange(contactPhoneData);

                    contact.ValidEmail = ValidateEmail(contact);

                    RawContact duplicate_data = null;
                    if (!String.IsNullOrEmpty(Convert.ToString(contact.PrimaryEmail)))
                    {
                        duplicate_data = persons.Where(p => string.Compare(p.PrimaryEmail, Convert.ToString(contact.PrimaryEmail), true) == 0).FirstOrDefault();
                    }
                    else
                    {
                        duplicate_data = persons.Where(p => string.Compare(p.FirstName, Convert.ToString(contact.FirstName), true) == 0 && string.Compare(p.LastName, Convert.ToString(contact.LastName), true) == 0).FirstOrDefault();
                    }

                    if (duplicate_data != null)
                    {
                        contact.IsDuplicate = true;
                        //RawContact updatedperson = MergeDuplicateData(duplicate_data, contact, guid);
                        //duplicate_data = updatedperson;
                    }

                    persons.Add(contact);
                }
            }
            catch (Exception ex)
            {
                Logger.Current.Error("Exception occured while getting bdx files :" + ex);
            }
            data.ContactPhoneData  = personPhoneData;
            data.ContactCustomData = personCustomFieldData;
            data.ContactData       = persons;
            return(data);
        }
Exemple #49
0
 private static extern void FindFiles(CriteriaInfo[] criteria, SearchParameters searchParameters, out SearchResults outResults);
 public override List <PersonSimple> Search(SearchParameters criteria)
 {
     return(SearchInternal(criteria));
 }
Exemple #51
0
        static async Task Search(string index, string query, double threatIntent, bool identityhate, bool search_links, int top)
        {
            var client = new SearchIndexClient("socialnews", index, new SearchCredentials("0FD303356E9F04596A433B00CCE37F1E"));

            client.SetUserAgent("NewsAlphaCLI");
            string           field = "text", filterMsg = "none", limit = "all";
            SearchParameters parameters = new SearchParameters()
            {
                Select  = new[] { "id", "user", "text", "date_published", "no", "links", "identity_hate", "entities", "threat_intent" },
                OrderBy = new [] { "date_published desc" }
            };

            if (threatIntent > 0.0)
            {
                parameters.Filter = "threat_intent gt " + threatIntent;
                filterMsg         = "threat_intent";
            }

            if (identityhate && threatIntent > 0.0)
            {
                parameters.Filter = "and identity_hate eq true";
                filterMsg         = "threat_intent and identity_hate";
            }
            else if (identityhate)
            {
                parameters.Filter = "identity_hate eq true";
                filterMsg         = "identity_hate";
            }

            if (search_links)
            {
                parameters.SearchFields = new[] { "links/uri" };
                field = "links";
            }
            if (top > 0)
            {
                parameters.Top = top;
                limit          = top.ToString();
            }
            DocumentSearchResult <Document> docResults = null;
            List <SocialNewsSearchResult>   results    = new List <SocialNewsSearchResult>();

            using (var op = Begin("Search {0} for {1} containing {2} filtered on {3} limited to {4} results",
                                  index, field, query, filterMsg, limit))
            {
                docResults = await client.Documents.SearchAsync(query, parameters);

                op.Complete();
            }
            Info("Got {0} results.", docResults.Results.Count);
            foreach (var dr in docResults.Results)
            {
                var r = new SocialNewsSearchResult()
                {
                    Id              = (string)dr.Document["id"],
                    User            = (string)dr.Document["user"],
                    DatePublished   = ((DateTimeOffset)dr.Document["date_published"]).UtcDateTime,
                    Text            = (string)dr.Document["text"],
                    HasIdentityHate = dr.Document["identity_hate"] != null ? (bool)dr.Document["identity_hate"] : false,
                    No              = (long)dr.Document["no"],
                    ThreatIntent    = dr.Document["threat_intent"] != null ? (double)dr.Document["threat_intent"] : 0.0,
                };
                try
                {
                    var links = (IEnumerable <Document>)dr.Document["links"];
                    r.Links = links.Select(l => (string)l["uri"]).ToArray();

                    var entities = (object[])dr.Document["entities"];
                    r.Entities = entities.Cast <string>().ToArray();
                }
                catch
                {
                    r.Links = Array.Empty <string>();
                }
                results.Add(r);
            }
            if (results.Count == 0)
            {
                Info("0 social news posts in index {0} matching query {1}.\n", index.Replace("-index", ""), query);
                Exit(ExitResult.SUCCESS);
            }
            Info("Showing social news posts in index {0} matching query {1}.\n", index.Replace("-index", ""), query);
            CO.WriteLine("----");
            foreach (var r in results)
            {
                CO.WriteLineFormatted("Id: {0}\nDate: {1} (UTC) \nUser: {2}\nNo.: {3}\nText: {4}\nLinks: \n{5}\nEntities: \n{6}",
                                      Color.LightGoldenrodYellow, Color.Gray, r.Id, r.DatePublished.ToString(), r.User, r.No, r.Text, "\t" + string.Join(Environment.NewLine + "\t", r.Links),
                                      r.Entities == null ? "" : "\t" + string.Join(Environment.NewLine + "\t", r.Entities));
                if (r.ThreatIntent > 0.91)
                {
                    CO.WriteLineFormatted("Threat Intent: {0}", Color.Red, Color.Gray, r.ThreatIntent);
                }
                else
                {
                    CO.WriteLineFormatted("Threat Intent: {0}", Color.LightGoldenrodYellow, Color.Gray, r.ThreatIntent);
                }
                CO.WriteLine("----");
            }
        }
        /// <summary>
        /// Gets form for updating main master page details.
        /// </summary>
        /// <param name="context">Form context.</param>
        /// <returns>Form for updating main master page details.</returns>
        private Form GetMasterPageForm(string context)
        {
            // Get tenant identifier
            long tenantId = _authenticationService.TenantId;

            // Get possible parent pages for ancestor page
            ISearchParameters searchParameters = new SearchParameters {
                PageIndex = 0, PageSize = 1000
            };                                                                                            // TODO: Need way to return all pages, not have some max bound upper limit
            ISearchResult <Page> result = _pageService.List(tenantId, searchParameters, null, PageSortBy.Name, true, true, PageType.Folder, false);

            // Construct view model
            Form form = new Form {
                Fields = new Dictionary <string, IFormField>(), Id = FormId.ToString(), Context = context
            };

            form.Fields.Add("name", new TextField
            {
                Name                  = "name",
                Label                 = MasterPageResource.NameLabel,
                Required              = true,
                RequiredErrorMessage  = MasterPageResource.NameRequiredMessage,
                MaxLength             = MasterPageLengths.NameMaxLength,
                MaxLengthErrorMessage = string.Format(MasterPageResource.NameMaxLengthMessage, "name", MasterPageLengths.NameMaxLength)
            });
            form.Fields.Add("pageName", new TextField
            {
                Name                  = "pageName",
                Label                 = MasterPageResource.PageNameLabel,
                Required              = true,
                RequiredErrorMessage  = MasterPageResource.PageNameRequiredMessage,
                MaxLength             = MasterPageLengths.PageNameMaxLength,
                MaxLengthErrorMessage = string.Format(MasterPageResource.PageNameMaxLengthMessage, "pageName", MasterPageLengths.PageNameMaxLength)
            });
            form.Fields.Add("pageDescription", new MultiLineTextField
            {
                Name  = "pageDescription",
                Label = MasterPageResource.PageDescriptionLabel,
                Rows  = 4
            });
            form.Fields.Add("ancestorPageId", new SelectListField <string>
            {
                Name  = "ancestorPageId",
                Label = MasterPageResource.AncestorPageIdLabel,
                Items = new List <ListFieldItem <string> > {
                    new ListFieldItem <string> {
                        Name = MasterPageResource.AncestorPageIdDefaultOption, Value = string.Empty
                    }
                }
            });
            foreach (Page page in result.Items)
            {
                ((SelectListField <string>)form.Fields["ancestorPageId"]).Items.Add(new ListFieldItem <string> {
                    Name = page.Name, Value = page.PageId.ToString()
                });
            }
            form.Fields.Add("ancestorPageLevel", new SelectListField <string>
            {
                Name  = "ancestorPageLevel",
                Label = MasterPageResource.AncestorPageLevelLabel,
                Items = new List <ListFieldItem <string> > {
                    new ListFieldItem <string> {
                        Name = MasterPageResource.AncestorPageLevelDefaultOption, Value = string.Empty
                    },
                    new ListFieldItem <string> {
                        Name = _dataAnnotationsService.GetEnumDisplayName <PageLevel>(PageLevel.Parent), Value = ((int)PageLevel.Parent).ToString()
                    },
                    new ListFieldItem <string> {
                        Name = _dataAnnotationsService.GetEnumDisplayName <PageLevel>(PageLevel.Grandparent), Value = ((int)PageLevel.Grandparent).ToString()
                    },
                    new ListFieldItem <string> {
                        Name = _dataAnnotationsService.GetEnumDisplayName <PageLevel>(PageLevel.GreatGrandparent), Value = ((int)PageLevel.GreatGrandparent).ToString()
                    }
                },
                Required             = true,
                RequiredErrorMessage = MasterPageResource.AncestorPageLevelRequiredMessage
            });
            form.Fields.Add("pageType", new SelectListField <string>
            {
                Name  = "pageType",
                Label = MasterPageResource.PageTypeLabel,
                Items = new List <ListFieldItem <string> > {
                    new ListFieldItem <string> {
                        Name = _dataAnnotationsService.GetEnumDisplayName <PageType>(PageType.Document), Value = ((int)PageType.Document).ToString()
                    },
                    new ListFieldItem <string> {
                        Name = _dataAnnotationsService.GetEnumDisplayName <PageType>(PageType.Folder), Value = ((int)PageType.Folder).ToString()
                    }
                },
                Required             = true,
                RequiredErrorMessage = MasterPageResource.PageTypeRequiredMessage
            });
            form.Fields.Add("hasOccurred", new BooleanField
            {
                Name  = "hasOccurred",
                Label = MasterPageResource.HasOccurredLabel
            });
            form.Fields.Add("hasImage", new BooleanField
            {
                Name  = "hasImage",
                Label = MasterPageResource.HasImageLabel
            });
            form.Fields.Add("thumbnailImageWidth", new IntegerField
            {
                Name                 = "thumbnailImageWidth",
                Label                = MasterPageResource.ThumbnailImageWidthLabel,
                Min                  = MasterPageValues.MinThumbnailImageWidth,
                MinErrorMessage      = string.Format(MasterPageResource.ThumbnailImageWidthMinErrorMessage, "thumbnailImageWidth", MasterPageValues.MinThumbnailImageWidth),
                Max                  = MasterPageValues.MaxThumbnailImageWidth,
                MaxErrorMessage      = string.Format(MasterPageResource.ThumbnailImageWidthMaxErrorMessage, "thumbnailImageWidth", MasterPageValues.MaxThumbnailImageWidth),
                Required             = true,
                RequiredErrorMessage = MasterPageResource.ThumbnailImageWidthRequiredMessage
            });
            form.Fields.Add("thumbnailImageHeight", new IntegerField
            {
                Name                 = "thumbnailImageHeight",
                Label                = MasterPageResource.ThumbnailImageHeightLabel,
                Min                  = MasterPageValues.MinThumbnailImageHeight,
                MinErrorMessage      = string.Format(MasterPageResource.ThumbnailImageHeightMinErrorMessage, "thumbnailImageHeight", MasterPageValues.MinThumbnailImageHeight),
                Max                  = MasterPageValues.MaxThumbnailImageHeight,
                MaxErrorMessage      = string.Format(MasterPageResource.ThumbnailImageHeightMaxErrorMessage, "thumbnailImageHeight", MasterPageValues.MaxThumbnailImageHeight),
                Required             = true,
                RequiredErrorMessage = MasterPageResource.ThumbnailImageHeightRequiredMessage
            });
            form.Fields.Add("thumbnailImageResizeMode", new SelectListField <string>
            {
                Name  = "thumbnailImageResizeMode",
                Label = MasterPageResource.ThumbnailImageResizeModeLabel,
                Items = new List <ListFieldItem <string> > {
                    new ListFieldItem <string> {
                        Name = MasterPageResource.ResizeModeDefaultOption, Value = string.Empty
                    },
                    new ListFieldItem <string> {
                        Name = _dataAnnotationsService.GetEnumDisplayName <ResizeMode>(ResizeMode.Simple), Value = ((int)ResizeMode.Simple).ToString()
                    },
                    new ListFieldItem <string> {
                        Name = _dataAnnotationsService.GetEnumDisplayName <ResizeMode>(ResizeMode.MaintainAspect), Value = ((int)ResizeMode.MaintainAspect).ToString()
                    },
                    new ListFieldItem <string> {
                        Name = _dataAnnotationsService.GetEnumDisplayName <ResizeMode>(ResizeMode.Crop), Value = ((int)ResizeMode.Crop).ToString()
                    }
                },
                Required             = true,
                RequiredErrorMessage = MasterPageResource.ThumbnailImageResizeModeRequiredMessage
            });
            form.Fields.Add("previewImageWidth", new IntegerField
            {
                Name                 = "previewImageWidth",
                Label                = MasterPageResource.PreviewImageWidthLabel,
                Min                  = MasterPageValues.MinPreviewImageWidth,
                MinErrorMessage      = string.Format(MasterPageResource.PreviewImageWidthMinErrorMessage, "previewImageWidth", MasterPageValues.MinPreviewImageWidth),
                Max                  = MasterPageValues.MaxPreviewImageWidth,
                MaxErrorMessage      = string.Format(MasterPageResource.PreviewImageWidthMaxErrorMessage, "previewImageWidth", MasterPageValues.MaxPreviewImageWidth),
                Required             = true,
                RequiredErrorMessage = MasterPageResource.PreviewImageWidthRequiredMessage
            });
            form.Fields.Add("previewImageHeight", new IntegerField
            {
                Name                 = "previewImageHeight",
                Label                = MasterPageResource.PreviewImageHeightLabel,
                Min                  = MasterPageValues.MinPreviewImageHeight,
                MinErrorMessage      = string.Format(MasterPageResource.PreviewImageHeightMinErrorMessage, "previewImageHeight", MasterPageValues.MinPreviewImageHeight),
                Max                  = MasterPageValues.MaxPreviewImageHeight,
                MaxErrorMessage      = string.Format(MasterPageResource.PreviewImageHeightMaxErrorMessage, "previewImageHeight", MasterPageValues.MaxPreviewImageHeight),
                Required             = true,
                RequiredErrorMessage = MasterPageResource.PreviewImageHeightRequiredMessage
            });
            form.Fields.Add("previewImageResizeMode", new SelectListField <string>
            {
                Name  = "previewImageResizeMode",
                Label = MasterPageResource.PreviewImageResizeModeLabel,
                Items = new List <ListFieldItem <string> > {
                    new ListFieldItem <string> {
                        Name = MasterPageResource.ResizeModeDefaultOption, Value = string.Empty
                    },
                    new ListFieldItem <string> {
                        Name = _dataAnnotationsService.GetEnumDisplayName <ResizeMode>(ResizeMode.Simple), Value = ((int)ResizeMode.Simple).ToString()
                    },
                    new ListFieldItem <string> {
                        Name = _dataAnnotationsService.GetEnumDisplayName <ResizeMode>(ResizeMode.MaintainAspect), Value = ((int)ResizeMode.MaintainAspect).ToString()
                    },
                    new ListFieldItem <string> {
                        Name = _dataAnnotationsService.GetEnumDisplayName <ResizeMode>(ResizeMode.Crop), Value = ((int)ResizeMode.Crop).ToString()
                    }
                },
                Required             = true,
                RequiredErrorMessage = MasterPageResource.PreviewImageResizeModeRequiredMessage
            });
            form.Fields.Add("imageMinWidth", new IntegerField
            {
                Name                 = "imageMinWidth",
                Label                = MasterPageResource.ImageMinWidthLabel,
                Min                  = MasterPageValues.MinImageMinWidth,
                MinErrorMessage      = string.Format(MasterPageResource.ImageMinWidthMinErrorMessage, "imageMinWidth", MasterPageValues.MinImageMinWidth),
                Max                  = MasterPageValues.MaxImageMinWidth,
                MaxErrorMessage      = string.Format(MasterPageResource.ImageMinWidthMaxErrorMessage, "imageMinWidth", MasterPageValues.MaxImageMinWidth),
                Required             = true,
                RequiredErrorMessage = MasterPageResource.ImageMinWidthRequiredMessage
            });
            form.Fields.Add("imageMinHeight", new IntegerField
            {
                Name                 = "imageMinHeight",
                Label                = MasterPageResource.ImageMinHeightLabel,
                Min                  = MasterPageValues.MinImageMinHeight,
                MinErrorMessage      = string.Format(MasterPageResource.ImageMinHeightMinErrorMessage, "imageMinHeight", MasterPageValues.MinImageMinHeight),
                Max                  = MasterPageValues.MaxImageMinWidth,
                MaxErrorMessage      = string.Format(MasterPageResource.ImageMinHeightMaxErrorMessage, "imageMinHeight", MasterPageValues.MaxImageMinHeight),
                Required             = true,
                RequiredErrorMessage = MasterPageResource.ImageMinHeightRequiredMessage
            });
            form.Fields.Add("creatable", new BooleanField
            {
                Name  = "creatable",
                Label = MasterPageResource.CreatableLabel
            });
            form.Fields.Add("deletable", new BooleanField
            {
                Name  = "deletable",
                Label = MasterPageResource.DeletableLabel
            });
            form.Fields.Add("taggable", new BooleanField
            {
                Name  = "taggable",
                Label = MasterPageResource.TaggableLabel
            });
            form.Fields.Add("administration", new BooleanField
            {
                Name  = "administration",
                Label = MasterPageResource.AdministrationLabel
            });
            form.Fields.Add("beginRender", new MultiLineTextField
            {
                Name  = "beginRender",
                Label = MasterPageResource.BeginRenderLabel,
                Rows  = 4
            });
            form.Fields.Add("endRender", new MultiLineTextField
            {
                Name  = "endRender",
                Label = MasterPageResource.EndRenderLabel,
                Rows  = 4
            });

            // Return form
            return(form);
        }
		/// <summary>
		/// Do a quick find. All entries of the currently opened database are searched
		/// for a string and the results are automatically displayed in the main window.
		/// </summary>
		/// <param name="strSearch">String to search the entries for.</param>
		/// <param name="strGroupName">Group name of the group that receives the search
		/// results.</param>
		private void PerformQuickFind(string strSearch, string strGroupName,
			bool bForceShowExpired, bool bRespectEntrySearchingDisabled)
		{
			Debug.Assert(strSearch != null); if(strSearch == null) return;
			Debug.Assert(strGroupName != null); if(strGroupName == null) return;

			PwGroup pg = new PwGroup(true, true, strGroupName, PwIcon.EMailSearch);
			pg.IsVirtual = true;

			SearchParameters sp = new SearchParameters();
			sp.SearchString = strSearch;
			sp.SearchInTitles = sp.SearchInUserNames =
				sp.SearchInUrls = sp.SearchInNotes = sp.SearchInOther =
				sp.SearchInUuids = sp.SearchInGroupNames = sp.SearchInTags = true;
			sp.SearchInPasswords = Program.Config.MainWindow.QuickFindSearchInPasswords;
			sp.RespectEntrySearchingDisabled = bRespectEntrySearchingDisabled;

			if(!bForceShowExpired)
				sp.ExcludeExpired = Program.Config.MainWindow.QuickFindExcludeExpired;

			SearchUtil.SetTransformation(sp, (Program.Config.MainWindow.QuickFindDerefData ?
				SearchUtil.StrTrfDeref : string.Empty));

			StatusBarLogger sl = null;
			bool bBlock = (strSearch.Length > 0); // Showing all is fast
			if(bBlock)
			{
				Application.DoEvents(); // Finalize UI messages before blocking
				UIBlockInteraction(true);
				sl = CreateStatusBarLogger();
				sl.StartLogging(KPRes.SearchingOp + "...", false);
			}

			PwDatabase pd = m_docMgr.ActiveDatabase;
			PwGroup pgRoot = pd.RootGroup;
			AutoAdjustMemProtSettings(pd, sp);
			pgRoot.SearchEntries(sp, pg.Entries, sl);

			if(bBlock)
			{
				sl.EndLogging();
				UIBlockInteraction(false);
			}

			UpdateEntryList(pg, false);
			SelectFirstEntryIfNoneSelected();

			UpdateUIState(false);
			ShowSearchResultsStatusMessage(bRespectEntrySearchingDisabled ?
				pgRoot : null);

			if(Program.Config.MainWindow.FocusResultsAfterQuickFind &&
				(pg.Entries.UCount > 0))
			{
				ResetDefaultFocus(m_lvEntries);
			}
		}
Exemple #54
0
        SearchOpportunityResponse search(SearchOpportunityRequest request, IEnumerable <Type> types, IList <string> fields, bool matchAll, bool autoComplete)
        {
            SearchOpportunityResponse response   = new SearchOpportunityResponse();
            SearchParameters          parameters = new SearchParameters();

            parameters.Limit      = request.Limit;
            parameters.PageNumber = request.PageNumber == 0 ? 1 : request.PageNumber;
            parameters.Types      = types;
            parameters.MatchAll   = matchAll;
            parameters.AccountId  = request.AccountId;
            parameters.Ids        = request.OpportunityIDs;
            parameters.UserID     = request.UserID;
            parameters.StartDate  = request.StartDate;
            parameters.EndDate    = request.EndDate;

            if (request.SortField != null)
            {
                List <string> sortFields = new List <string>();
                var           maps       = SmartTouch.CRM.ApplicationServices.ObjectMappers.MapperConfigurationProvider.Instance.FindTypeMapFor <OpportunityViewModel, Opportunity>();

                foreach (var propertyMap in maps.GetPropertyMaps())
                {
                    if (request.SortField.Equals(propertyMap.SourceMember.Name))
                    {
                        sortFields.Add(propertyMap.DestinationProperty.MemberInfo.Name);
                        break;
                    }
                }
                parameters.SortDirection = request.SortDirection;
                parameters.SortFields    = sortFields;
            }
            Logger.Current.Informational("Search string:" + request.Query);
            Logger.Current.Informational("Parameters:" + parameters.ToString());
            SearchResult <Opportunity> searchResult;

            bool isAccountAdmin = cachingService.IsAccountAdmin(request.RoleId, request.AccountId);
            bool isPrivate      = cachingService.IsModulePrivate(AppModules.Opportunity, request.AccountId);

            if (isPrivate && !isAccountAdmin)
            {
                int userId = (int)request.RequestedBy;
                searchResult = searchService.Search(request.Query, c => c.OwnerId == userId, parameters);
            }
            else if (request.UserID != null && request.StartDate != null && request.EndDate != null)
            {
                int userId = (int)request.UserID;
                searchResult = searchService.Search(request.Query, c => c.CreatedBy == userId, parameters);
            }
            else
            {
                searchResult = searchService.Search(request.Query, parameters);
            }

            IEnumerable <Opportunity> opportunities = searchResult.Results;

            Logger.Current.Informational("Search complete, total results:" + searchResult.Results.Count());

            if (opportunities == null)
            {
                response.Exception = GetOpportunitiesNotFoundException();
            }
            else
            {
                IEnumerable <OpportunityViewModel> list = Mapper.Map <IEnumerable <Opportunity>, IEnumerable <OpportunityViewModel> >(opportunities);

                IEnumerable <int>     contactIds      = searchResult.Results.SelectMany(o => o.Contacts).Distinct().ToList();
                SearchContactsRequest contactsRequest = new SearchContactsRequest();
                contactsRequest.ContactIDs  = contactIds.ToArray();
                contactsRequest.AccountId   = request.AccountId;
                contactsRequest.RoleId      = request.RoleId;
                contactsRequest.RequestedBy = request.RequestedBy;
                contactsRequest.Limit       = contactIds.Count();
                contactsRequest.PageNumber  = 1;
                contactsRequest.Module      = AppModules.Opportunity;
                SearchContactsResponse <ContactEntry> contactsResponse = contactService.GetAllContacts <ContactEntry>(contactsRequest);
                foreach (Opportunity opportunity in searchResult.Results)
                {
                    var opportunityViewModel = list.SingleOrDefault(o => o.OpportunityID == opportunity.Id);

                    IEnumerable <int> people = opportunity.Contacts;

                    //if (isPrivate && !isAccountAdmin)
                    //{
                    //    IList<int> owncontacts = contactRepository.GetContactByUserId((int)request.RequestedBy);

                    //    var peopleinvoled = opportunity.PeopleInvolved.Where(n => !owncontacts.Contains(n.ContactID));

                    //    foreach (var p in peopleinvoled)
                    //    {
                    //        p.IsPrivate = true;
                    //    }
                    //}

                    var contacts = contactsResponse.Contacts.Where(c => people.Contains(c.Id));
                    opportunityViewModel.Contacts = contacts;
                }


                response.Opportunities = list;
                response.TotalHits     = searchResult.TotalHits;
            }
            return(response);
        }
 public void Constructor_Full_InvalidDocumentTypeTagsElement(string e)
 {
     SearchParameters par = new SearchParameters("query", new string[] { "blah", e }, SearchOptions.ExactPhrase);
 }
Exemple #56
0
        static int DoStuff(ArgumentParser.QcOptions opts)
        {
            Log.Information("Starting QC. Identipy: {Identipy}", opts.Identipy);
            //Console.WriteLine("\n");
            SearchParameters searchParameters;

            QcParameters qcParameters = new QcParameters();

            qcParameters.RawFileDirectory = opts.DirectoryToQc;
            qcParameters.QcDirectory      = opts.QcDirectory;
            qcParameters.QcFile           = Path.Combine(opts.QcDirectory, "QC.xml");


            if (opts.SearchAlgorithm != null & !(new List <string>()
            {
                "identipy", "xtandem"
            }.Contains(opts.SearchAlgorithm)))
            {
                // the search algorithm is not null but it also it not identipy or xtandem
                Log.Error("Invalid search algorithm argument: {Argument}", opts.SearchAlgorithm);
                Console.WriteLine("ERROR: Search algorithm must be one of {identipy, xtandem}");
                return(1);
            }

            if (opts.Identipy)
            {
                opts.SearchAlgorithm = "identipy";
            }

            if (opts.SearchAlgorithm != null)
            {
                if (opts.FastaDatabase == null)
                {
                    Log.Error("No fasta database provided for Identipy search");
                    Console.WriteLine("ERROR: A fasta protein database is required for an Identipy search. Please use the --db parameter to " +
                                      "provide the path to a database.");
                    Environment.Exit(1);
                }

                searchParameters = new SearchParameters
                {
                    PythonExecutable   = opts.PythonExecutable,
                    IdentipyScript     = opts.IdentipyScript,
                    XTandemDirectory   = opts.XTandemDirectory,
                    FastaDatabase      = opts.FastaDatabase,
                    FixedMods          = opts.FixedMods,
                    NMod               = opts.VariableNMod,
                    KMod               = opts.VariableKMod,
                    XMod               = opts.VariableXMod,
                    NumSpectra         = opts.NumberSpectra,
                    MgfIntensityCutoff = opts.IntensityCutoff,
                    MgfMassCutoff      = opts.MassCutOff,
                    FixedScans         = opts.FixedScans
                };

                if (opts.SearchAlgorithm == "identipy")
                {
                    if ((opts.IdentipyScript == null & opts.PythonExecutable != null) | (opts.IdentipyScript != null & opts.PythonExecutable == null))
                    {
                        Log.Error("If providing location of python or identipy, must specify both of them.");
                        Console.WriteLine("ERROR: When invoking the -p or -I options, you must supply both of them.");
                        Environment.Exit(1);
                    }

                    Identipy.CheckIdentipyDependencies(searchParameters);

                    searchParameters.SearchAlgorithm = SearchAlgorithm.IdentiPy;
                }

                if (opts.SearchAlgorithm == "xtandem")
                {
                    if (opts.XTandemDirectory == null)
                    {
                        Log.Error("Path to XTandem directory was not provided");
                        Console.WriteLine("ERROR: You must specify the X! Tandem directory using the -X argument to perform a search using X! Tandem.");
                        return(1);
                    }
                    searchParameters.SearchAlgorithm = SearchAlgorithm.XTandem;
                }
            }
            else
            {
                searchParameters = null;
            }
            qcParameters.searchParameters = searchParameters;

            QC.QC.DoQc(qcParameters);

            return(0);
        }
Exemple #57
0
        private IResults<Publication> GetResults(IEnumerable<Condition> conditions, string freeText)
        {
            ISearchParameters<Publication> searchParameters;
            var selectedFiltersContext = QueryUrlParser.With(FacetConfiguration.FacetHierarchy, UrlOfuscator)
                                                       .Parse(conditions)
                                                       .ExcludeLineals()
                                                       .GetSelectedFilters();

            if (selectedFiltersContext.SelectedFilters.Count == 0)
                searchParameters = new SearchParameters<Publication>(freeText, selectedFiltersContext.Page,
                                                                     selectedFiltersContext.SortField);
            else
                searchParameters = new SearchParameters<Publication>(freeText,
                                                                     selectedFiltersContext,
                                                                     FacetConfiguration.FacetHierarchy.ByName(
                                                                         selectedFiltersContext.SelectedFilters.Last().
                                                                             Name),
                                                                     FacetConfiguration.FacetHierarchy.GetFacetsWith(
                                                                         selectedFiltersContext.SelectedFilters));

            return IndexService.Query(searchParameters);
        }
 public void Constructor_QueryOnly_InvalidQuery(string q)
 {
     SearchParameters par = new SearchParameters(q);
 }
Exemple #59
0
        /// <summary>
        /// Performs search and populates the returned raw data into the internal search service dataset.
        /// </summary>
        /// <param name="query">Text to search</param>
        /// <param name="pageIndex">Zero-based page index</param>
        /// <param name="pageSize">Page size</param>
        /// <param name="numberOfResults">Total number of search results</param>
        private void SearchInternal(string query, int pageIndex, int pageSize, out int numberOfResults)
        {
            var documentCondition = new DocumentSearchCondition(null, mCultureName, mDefaultCulture, mCombineWithDefaultCulture);
            var condition = new SearchCondition(documentCondition: documentCondition);
            var searchExpression = SearchSyntaxHelper.CombineSearchCondition(query, condition);

            var parameters = new SearchParameters
            {
                SearchFor = searchExpression,
                Path = "/%",
                ClassNames = null,
                CurrentCulture = mCultureName,
                DefaultCulture = mDefaultCulture,
                CombineWithDefaultCulture = mCombineWithDefaultCulture,
                CheckPermissions = false,
                SearchInAttachments = false,
                User = MembershipContext.AuthenticatedUser,
                SearchIndexes = mSearchIndexNames.Join(";"),
                StartingPosition = pageIndex * pageSize,
                NumberOfResults = 0,
                NumberOfProcessedResults = 100,
                DisplayResults = pageSize
            };

            // Search and save results
            mRawResults = SearchHelper.Search(parameters);
            numberOfResults = parameters.NumberOfResults;
        }
        private void processContacts(Node node, NodeAttributes attributes,
                                     IEnumerable <FieldViewModel> customFields, int jobId,
                                     IEnumerable <DropdownValueViewModel> dropdownFields, string fileName)
        {
            #region Declarations
            StringBuilder                hash                = new StringBuilder();
            IList <Email>                emails              = new List <Email>();
            var                          guid                = Guid.NewGuid();
            RawContact                   contact             = new RawContact();
            IList <ImportCustomData>     contactCustomData   = new List <ImportCustomData>();
            IList <ImportPhoneData>      contactPhoneData    = new List <ImportPhoneData>();
            StringBuilder                customFieldData     = new StringBuilder();
            bool                         isDuplicateFromFile = false;
            LeadAdapterRecordStatus      status              = LeadAdapterRecordStatus.Undefined;
            SearchResult <Contact>       duplicateResult     = new SearchResult <Contact>();
            Dictionary <string, dynamic> oldNewValues        = new Dictionary <string, dynamic> {
            };
            #endregion

            #region BuilderNumber Validation
            string builderNumber     = attributes[_fieldMappings.GetOrDefault("BuilderNumber")].Value;
            bool   builderNumberPass = leadAdapterAndAccountMap.BuilderNumber.ToLower().Split(',').Contains(builderNumber.ToLower());
            #endregion

            #region Community Number Validation
            string communityNumber     = attributes[_fieldMappings.GetOrDefault("CommunityNumber")].Value;
            bool   communityNumberPass = true;
            #endregion

            #region ContactsProcessing
            string firstName    = attributes[_fieldMappings.GetOrDefault("FirstName")].Value;
            string lastName     = attributes[_fieldMappings.GetOrDefault("LastName")].Value;
            string primaryEmail = attributes[_fieldMappings.GetOrDefault("Email")].Value;
            string companyName  = string.Empty;

            #region HashPreparation
            Action <string> HashAppend = (n) =>
            {
                if (string.IsNullOrEmpty(n))
                {
                    hash.Append("-").Append(string.Empty);
                }
                else
                {
                    hash.Append("-").Append(n);
                }
            };

            if (!string.IsNullOrEmpty(primaryEmail))
            {
                Email _primaryemail = new Email()
                {
                    EmailId   = primaryEmail,
                    AccountID = leadAdapterAndAccountMap.AccountID,
                    IsPrimary = true
                };
                emails.Add(_primaryemail);
                hash.Append("-").Append(primaryEmail);
            }
            else
            {
                hash.Append("-").Append("*****@*****.**");
            }

            HashAppend(firstName);
            HashAppend(lastName);
            HashAppend(companyName);
            #endregion

            Person person = new Person()
            {
                FirstName   = firstName,
                LastName    = lastName,
                CompanyName = companyName,
                Emails      = emails,
                AccountID   = AccountID
            };


            if (builderNumberPass && communityNumberPass)
            {
                bool duplicatEemailCount = hashes.Any(h => !string.IsNullOrEmpty(primaryEmail) && h.Contains(primaryEmail));
                if (duplicatEemailCount ||
                    (string.IsNullOrEmpty(primaryEmail) && hashes.Where(h => h.Contains(hash.ToString())).Any()))
                {
                    isDuplicateFromFile = true;
                }
                else if (!duplicatEemailCount)
                {
                    isDuplicateFromFile = false;
                }
            }

            hashes.Add(hash.ToString());


            if (builderNumberPass && communityNumberPass)
            {
                SearchParameters parameters = new SearchParameters()
                {
                    AccountId = AccountID
                };
                IEnumerable <Contact> duplicateContacts = contactService.CheckIfDuplicate(new CheckContactDuplicateRequest()
                {
                    Person = person
                }).Contacts;
                duplicateResult = new SearchResult <Contact>()
                {
                    Results = duplicateContacts, TotalHits = duplicateContacts != null?duplicateContacts.Count() : 0
                };
            }

            if (!builderNumberPass)
            {
                status = LeadAdapterRecordStatus.BuilderNumberFailed;
            }
            else if (!communityNumberPass)
            {
                status = LeadAdapterRecordStatus.CommunityNumberFailed;
            }
            else if (isDuplicateFromFile)
            {
                status = LeadAdapterRecordStatus.DuplicateFromFile;
            }
            else if (duplicateResult.TotalHits > 0)
            {
                status = LeadAdapterRecordStatus.Updated;
                guid   = duplicateResult.Results.FirstOrDefault().ReferenceId;
            }
            else
            {
                status = LeadAdapterRecordStatus.Added;
            }


            Contact duplicatePerson = default(Person);

            if (status == LeadAdapterRecordStatus.Updated)
            {
                duplicatePerson = duplicateResult.Results.FirstOrDefault();
            }
            else
            {
                duplicatePerson = new Person();
            }

            Func <NodeAttribute, string, bool> checkIfStandardField = (name, field) =>
            {
                return(name.Name.ToLower() == _fieldMappings.GetOrDefault(field).NullSafeToLower());
            };

            try
            {
                foreach (var attribute in attributes)
                {
                    var name  = attribute.Name.ToLower();
                    var value = attribute.Value;

                    ImportCustomData customData = new ImportCustomData();
                    try
                    {
                        var elementValue = string.Empty;
                        if (checkIfStandardField(attribute, "FirstName"))
                        {
                            elementValue      = ((Person)duplicatePerson).FirstName == null ? string.Empty : ((Person)duplicatePerson).FirstName;
                            contact.FirstName = value;
                        }
                        else if (checkIfStandardField(attribute, "LastName"))
                        {
                            elementValue     = ((Person)duplicatePerson).LastName;
                            contact.LastName = value;
                        }
                        else if (checkIfStandardField(attribute, "Email"))
                        {
                            Email primaryemail = duplicatePerson.Emails.IsAny() ? duplicatePerson.Emails.Where(i => i.IsPrimary == true).FirstOrDefault() : null;
                            if (primaryemail != null)
                            {
                                elementValue = primaryemail.EmailId;
                            }
                            contact.PrimaryEmail = value;
                        }
                        else if (checkIfStandardField(attribute, "Company"))
                        {
                            // get company dynamic
                            elementValue        = duplicatePerson.CompanyName;
                            contact.CompanyName = value;
                        }
                        else if (checkIfStandardField(attribute, "PhoneNumber") || checkIfStandardField(attribute, "Phone"))
                        {
                            DropdownValueViewModel dropdownValue = dropdownFields.Where(i => i.DropdownValueTypeID == (short)DropdownValueTypes.MobilePhone).FirstOrDefault();
                            var             mobilephone          = default(Phone);
                            ImportPhoneData phoneData            = new ImportPhoneData();
                            phoneData.ReferenceID = guid;
                            if (dropdownValue != null)
                            {
                                if (!string.IsNullOrEmpty(value))
                                {
                                    string phoneNumber = GetNonNumericData(value);
                                    if (IsValidPhoneNumberLength(phoneNumber))
                                    {
                                        contact.PhoneData     = dropdownValue.DropdownValueID.ToString() + "|" + phoneNumber;
                                        phoneData.PhoneType   = (int?)dropdownValue.DropdownValueID;
                                        phoneData.PhoneNumber = phoneNumber;
                                        contactPhoneData.Add(phoneData);
                                    }
                                }
                                mobilephone = duplicatePerson.Phones.IsAny() ? duplicatePerson.Phones.Where(i => i.PhoneType == dropdownValue.DropdownValueID).FirstOrDefault() : null;
                            }

                            if (mobilephone != null)
                            {
                                elementValue = mobilephone.Number;
                            }
                        }
                        else if (checkIfStandardField(attribute, "Country"))
                        {
                            var countryvalue = value.Replace(" ", string.Empty).ToLower();
                            if (countryvalue == "usa" || countryvalue == "us" || countryvalue == "unitedstates" || countryvalue == "unitedstatesofamerica")
                            {
                                contact.Country = "US";
                            }
                            else if (countryvalue == "ca" || countryvalue == "canada")
                            {
                                contact.Country = "CA";
                            }
                            else
                            {
                                contact.Country = value;
                            }
                        }
                        else if (checkIfStandardField(attribute, "StreetAddress"))
                        {
                            contact.AddressLine1 = value;
                        }
                        else if (checkIfStandardField(attribute, "City"))
                        {
                            contact.City = value;
                        }
                        else if (checkIfStandardField(attribute, "State"))
                        {
                            contact.State = value;
                        }
                        else if (checkIfStandardField(attribute, "PostalCode"))
                        {
                            contact.ZipCode = value;
                        }
                        else
                        {
                            var customField = customFields.Where(i => i.Title.Replace(" ", string.Empty).ToLower() == (name + "(" + leadAdapterType.ToString().ToLower() + ")")).FirstOrDefault();
                            if (customField != null)
                            {
                                var customfielddata = duplicatePerson.CustomFields == null ? null : duplicatePerson.CustomFields.Where(i => i.CustomFieldId == customField.FieldId).FirstOrDefault();
                                if (customfielddata != null)
                                {
                                    elementValue = customfielddata.Value;
                                }
                                customData.FieldID     = customField.FieldId;
                                customData.FieldTypeID = (int?)customField.FieldInputTypeId;
                                customData.ReferenceID = guid;

                                if (customField.FieldInputTypeId == FieldType.date || customField.FieldInputTypeId == FieldType.datetime || customField.FieldInputTypeId == FieldType.time)
                                {
                                    DateTime converteddate;
                                    if (DateTime.TryParse(value, out converteddate))
                                    {
                                        customFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + converteddate.ToString("MM/dd/yyyy hh:mm tt"));
                                        customData.FieldValue = converteddate.ToString("MM/dd/yyyy hh:mm tt");
                                    }
                                }
                                else if (customField.FieldInputTypeId == FieldType.number)
                                {
                                    double number;
                                    if (double.TryParse(value, out number))
                                    {
                                        customFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + number.ToString());
                                        customData.FieldValue = number.ToString();
                                    }
                                }
                                else if (customField.FieldInputTypeId == FieldType.url)
                                {
                                    if (IsValidURL(value.Trim()))
                                    {
                                        customFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + value.Trim());
                                        customData.FieldValue = value.Trim();
                                    }
                                }
                                else
                                {
                                    customFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + value.Trim());
                                    customData.FieldValue = value.Trim();
                                }
                                contactCustomData.Add(customData);
                            }
                        }
                        if (!oldNewValues.ContainsKey(attribute.Name))
                        {
                            oldNewValues.Add(attribute.Name, new { OldValue = string.IsNullOrEmpty(elementValue) ? string.Empty : elementValue, NewValue = value });
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Current.Error("An exception occured in Genereating old new values element in Trulia : " + attribute.Name, ex);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Current.Error("An exception occured in Genereating old new values element in Trulia : ", ex);
            }
            #endregion

            if (customFieldData.Length > 0)
            {
                customFieldData.Remove(0, 1);
            }
            contact.CustomFieldsData = customFieldData.ToString();

            contact.ReferenceId               = guid;
            contact.AccountID                 = AccountID;
            contact.IsBuilderNumberPass       = builderNumberPass;
            contact.IsCommunityNumberPass     = communityNumberPass;
            contact.LeadAdapterRecordStatusId = (byte)status;
            contact.JobID           = jobId;
            contact.ContactStatusID = 1;
            contact.ContactTypeID   = 1;
            JavaScriptSerializer js = new JavaScriptSerializer();
            contact.LeadAdapterSubmittedData = js.Serialize(oldNewValues);
            contact.LeadAdapterRowData       = node.Current != null?node.Current.ToString() : string.Empty;

            personCustomFieldData.AddRange(contactCustomData);
            personPhoneData.AddRange(contactPhoneData);

            contact.ValidEmail = ValidateEmail(contact);

            RawContact duplicate_data = null;
            if (!string.IsNullOrEmpty(contact.PrimaryEmail))
            {
                duplicate_data = persons.Where(p => string.Compare(p.PrimaryEmail, contact.PrimaryEmail, true) == 0).FirstOrDefault();
            }
            else
            {
                duplicate_data = persons.Where(p => string.Compare(p.FirstName, contact.FirstName, true) == 0 &&
                                               string.Compare(p.LastName, contact.LastName, true) == 0).FirstOrDefault();
            }

            if (duplicate_data != null)
            {
                contact.IsDuplicate = true;
                //RawContact updatedperson = MergeDuplicateData(duplicate_data, contact, guid);
                //duplicate_data = updatedperson;
            }

            persons.Add(contact);
        }