Esempio n. 1
1
        public List<SearchResult> Search(string searchQuery)
        {
            string url = "http://www.imdb.com/find?q={0}&s=all".Fmt(searchQuery);

            string html = new WebClient().DownloadString(url);

            CQ dom = html;

            var searchResults = new List<SearchResult>();

            foreach (var fragment in dom.Select("table.findList tr.findResult"))
            {
                var searchResult = new SearchResult();
                searchResult.ImageUrl = fragment.Cq().Find(".primary_photo > a > img").Attr("src");
                searchResult.Text = fragment.Cq().Find(".result_text").Html();
                searchResult.Text = StringEx.RemoveHtmlTags(searchResult.Text);

                string filmUrl = fragment.Cq().Find(".result_text > a").Attr("href");
                filmUrl = filmUrl.Replace("/title/", "");
                searchResult.FilmId = filmUrl.Substring(0, filmUrl.IndexOf("/"));

                searchResults.Add(searchResult);
            }

            return searchResults;
        }
Esempio n. 2
0
 public MediaValues(SearchResult result)
 {
     if (result == null) throw new ArgumentNullException("result");
     Name = result.Fields["nodeName"];
     Values = result.Fields;
     NiceUrl = Values["umbracoFile"];
 }
        protected void btnAddBook_Click(object sender, EventArgs e)
        {
            Model.Books model = new Model.Books();
            model.AurhorDescription = "jlkfdjf";
            model.Author = "王承伟";
            model.CategoryId = 1;
            model.Clicks = 1;
            model.ContentDescription = "老王是大好人!老王是大好人!老王是大好人!老王是大好人!老王是大好人!";
            model.EditorComment = "adfsadfsadf";
            model.ISBN = "123452222222355553003333266222";
            model.PublishDate = DateTime.Now;
            model.PublisherId = 72;
            model.Title = "老王是大好人";
            model.TOC = "aaaaaaaaaaaaaaaa";
            model.UnitPrice = 22.3m;
            model.WordsCount = 1234;
            BLL.BooksBLL bll = new BLL.BooksBLL();
            int id = bll.Add(model);

            SearchResult result = new SearchResult();
            result.Id = id;
            result.ISBN = model.ISBN;
            result.PublishDate = model.PublishDate;
            result.Title = model.Title;
            result.UnitPrice = model.UnitPrice;
            result.ContentDescription = model.ContentDescription;
            result.Author = model.Author;
            Common.IndexManage.myManage.Add(result);
        }
Esempio n. 4
0
        public Post GetSinglePost(SearchResult result)
        {
            Post post = new Post(result);
            int currentChild = 1;
            var document = RetrieveDocumentAsync(result.Link);

            var body = document.GetElementbyId("ContainerMain");

            var content = body.ChildNodes.Where(node => node.Attributes.Contains("class") &&
                                             node.Attributes["class"].Value.Contains("content-border"))
                                      .FirstOrDefault();
            if (content == null)
            {
                throw new Exception("Couldn't find any div with a .content-border class");
            }
            // HAP Parses text as a #text node. ChildNodes[0] is always a #text node.
            // The next one is the one we're interested in.
            //Debug.WriteLine("Parsing the content");
            content = content.ChildNodes[1].ChildNodes.Where(node => node.Attributes.Contains("class") &&
                                                                     node.Attributes["class"].Value.Contains("lbcContainer"))
                                                      .FirstOrDefault();

            if (content == null)
            {
                throw new Exception("Couldn't find .lbcContainer");
            }

            // -- User Info
            post.UserName = StripLBCSpaces(content.ChildNodes[1].ChildNodes[3].ChildNodes[1].InnerText);
            post.UserMail = StripLBCSpaces(content.ChildNodes[1].ChildNodes[3].ChildNodes[1].Attributes["href"].Value);

            // -- Images
            // If there is no image, there will be an empty div in place of the image container
            // However, .print-lbcImages won't be there. We need to go up one div, or we'd try to access an unexistant div
            currentChild = 1;
            if (String.IsNullOrWhiteSpace(StripLBCSpaces(content.ChildNodes[5].ChildNodes[currentChild].InnerHtml)))
            {
                currentChild = 3;
                Debug.WriteLine("No images on node :" + result.Title);
            }
            else
            {
                currentChild = 5;
            }

            var infos = content.ChildNodes[5].ChildNodes[currentChild].ChildNodes[1];
            foreach (var node in infos.ChildNodes)
            {
                if (node.Name.Equals("tr"))
                {
                    //Debug.WriteLine("Found a tr");
                    post.Properties.Add(new Tuple<string, string>(StripLBCSpaces(node.ChildNodes[1].InnerText),
                                                                  StripLBCSpaces(node.ChildNodes[3].InnerText)));
                }
            }
            currentChild += 2;
            post.Description = StripLBCSpaces(content.ChildNodes[5].ChildNodes[currentChild].ChildNodes[3].InnerText);

            return post;
        }
        public void BasicSearch_NonDefault_Parameters()
        {
            //arrange
            var mockLogic = new Mock<IProjectLogic>();
            var obj = new SearchResult<ProjectObj>
            {
                HasMore = false,
                HasPrevious = true,
                Results = new List<ProjectObj>()
                {
                    new ProjectObj()
                    {
                        Id = 2
                    }
                }
            };
            mockLogic.Setup(l => l.Search("query", 5, 10)).Returns(obj);
            var controller = new ProjectController(mockLogic.Object);

            //act
            var actual = controller.BasicSearch("query", 5, 10) as ViewResult;

            //assert
            Assert.IsNotNull(actual);
            var model = actual.Model as BasicSearchModel;
            Assert.IsNotNull(model);
            Assert.AreEqual(5, model.CurrentPage);
            Assert.AreEqual(false, model.HasMoreResults);
            Assert.AreEqual(true, model.HasPriorResults);
            Assert.AreEqual("Project", model.ModelName);
            Assert.AreEqual(10, model.PageSize);
            Assert.AreEqual("query", model.Query);
            Assert.AreEqual(1, model.Results.Count);
            Assert.AreEqual(2, model.Results[0].Id);
        }
Esempio n. 6
0
 internal RenameLocations(ISet<RenameLocation> locations, ISymbol symbol, Solution solution, IEnumerable<ISymbol> referencedSymbols, IEnumerable<ReferenceLocation> implicitLocations, OptionSet options)
 {
     _symbol = symbol;
     _solution = solution;
     _mergedResult = new SearchResult(locations, implicitLocations, referencedSymbols);
     Options = options;
 }
 public async Task<SearchResult> Search(string key)
 {
     key = key.Trim();
     var res = new SearchResult
     {
         Items = new List<IMusic>(),
         Keyword = key,
         SearchType = EnumSearchType.url,
         Page = 1,
     };
     var url = string.Format(search_url, Uri.EscapeDataString(key));
     var response = await NetAccess.DownloadStringAsync(url);
     var json = response.ToDynamicObject();
     if (json.song.Count > 0)
         foreach (var obj in json.song)
         {
             var s = new Song
             {
                 Id = "b" + MusicHelper.Get(obj, "songid"),
                 ArtistName = MusicHelper.Get(obj, "artistname"),
                 AlbumName = "",
                 Name = MusicHelper.Get(obj, "songname"),
                 WriteId3 = false,
             };
             res.Items.Add(s);
             s.UrlMp3 =await getDownloadUrl(s.Id.Substring(1));
         }
     return res;
 }
Esempio n. 8
0
        public SearchResult[] Search(string query)
        {
            Hits hits = _doSearch(query);

            List<SearchResult> results = new List<SearchResult>();
            for (int i = 0; i < hits.Length(); i++)
            {
                Document doc = hits.Doc(i);
                string contents = doc.Get("contents");
                SimpleHTMLFormatter formatter = new SimpleHTMLFormatter("<span class=\"highlight\">", "</span>");
                SimpleFragmenter fragmenter = new SimpleFragmenter(_fragmentSize);
                Highlighter hiliter = new Highlighter(formatter, new QueryScorer(QueryParser.Parse(query, "contents", _analyzer)));
                hiliter.SetTextFragmenter(fragmenter);
                int numfragments = contents.Length / fragmenter.GetFragmentSize() + 1;
                TokenStream tokenstream = _analyzer.TokenStream("contents", new StringReader(contents));
                TextFragment[] frags = hiliter.GetBestTextFragments(tokenstream, contents, false, numfragments);
                SearchResult sr = new SearchResult(doc, _analyzer, query, _fragmentSize);
                foreach (TextFragment frag in frags)
                {

                    if (frag.GetScore() > 0)
                        sr.AddFragment(frag.ToString());

                }
                results.Add(sr);

            }

            return results.ToArray();
        }
Esempio n. 9
0
        private static void SetAcl(string path, SearchResult user, FileSystemRights right)
        {
            var userId = user.Properties["userPrincipalName"][0].ToString();
            var fullUserName = user.Properties["name"][0].ToString();
            var fullPath = path + fullUserName;
            var dir = new DirectoryInfo(fullPath);
            var ds = new DirectorySecurity();
            ds.SetAccessRuleProtection(true, false);

            var uacl = new FileSystemAccessRule(userId,
                right,
                InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                PropagationFlags.None,
                AccessControlType.Allow);
            ds.AddAccessRule(uacl);

            var domainAdmins = new SecurityIdentifier(WellKnownSidType.AccountDomainAdminsSid, AppSettings.GeneralSettings.DomainSid);
            var pacl = new FileSystemAccessRule(domainAdmins,
                FileSystemRights.FullControl,
                InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                PropagationFlags.None,
                AccessControlType.Allow);
            ds.AddAccessRule(pacl);

            var system = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null);
            var sacl = new FileSystemAccessRule(system,
                FileSystemRights.FullControl,
                InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                PropagationFlags.None,
                AccessControlType.Allow);
            ds.AddAccessRule(sacl);

            dir.SetAccessControl(ds);
        }
    protected void WriteLog(string path,string searchwords,string index,int recNum,SearchResult sr)
    {
        try
        {
            FileStream fs = new FileStream(path, FileMode.Append);
            StreamWriter sw = new StreamWriter(fs);
            string str = "[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fffffff") + "]" ;
            sw.WriteLine(str);
            sw.WriteLine("SearchWords=\t" + searchwords);
            sw.WriteLine("Index=\t" + index);
            sw.WriteLine("Search Record:\t" + recNum.ToString());
            sw.WriteLine("PageNum:\t"+sr.PageNum);
            foreach (SearchRecord record in sr.Records)
            {
                sw.WriteLine("==============================================");
                sw.WriteLine("Caption:\t" + record.Caption);
                foreach (SearchField field in record.Fields)
                {
                    sw.WriteLine(field.Caption + "\t\t" + field.Name + "\t\t" + field.Value);
                }
            }
            sw.WriteLine("#########################################################################");
            sw.Flush();
            sw.Close();
            fs.Close();
        }
        catch (Exception e)
        {
            throw e;
        }

    }
Esempio n. 11
0
 public NetSuiteSearch(SearchResult results)
 {
     this.Id = results.searchId;
     this.LastPage = results.pageIndex;
     this.records = this.getSearchResults(results);
     this.needsMore = results.pageIndex != results.totalPages;
 }
 public void Caching_search_with_apikey_does_not_pass_auth_info_to_lucene() {
     var searchMock = CreateMocks().Item1;
     var responseXml = new XDoc("response");
     var luceneXml = new XDoc("lucene");
     var searchQuery = new SearchQuery("raw", "processed", new LuceneClauseBuilder(), null);
     var searchResult = new SearchResult();
     searchMock.Setup(x => x.BuildQuery("foo", "", SearchQueryParserType.BestGuess, true)).Returns(searchQuery).AtMostOnce().Verifiable();
     searchMock.Setup(x => x.GetCachedQuery(searchQuery)).Returns((SearchResult)null).AtMostOnce().Verifiable();
     XUri luceneUriCalled = null;
     MockPlug.Register(Utils.Settings.LuceneMockUri, (p, v, u, req, res) => {
         luceneUriCalled = u;
         res.Return(DreamMessage.Ok(luceneXml));
     });
     searchMock.Setup(x => x.CacheQuery(It.Is<XDoc>(v => v == luceneXml), It.IsAny<SearchQuery>(), It.IsAny<TrackingInfo>()))
         .Returns(searchResult);
     searchMock.Setup(x => x.FormatResultSet(
             searchResult,
             It.IsAny<SetDiscriminator>(),
             false,
             It.IsAny<TrackingInfo>(),
             It.IsAny<Result<XDoc>>()
         ))
         .Returns(new Result<XDoc>().WithReturn(responseXml));
     var response = _search
         .With("q", "foo")
         .With("apikey", Utils.Settings.ApiKey)
         .Get(new Result<DreamMessage>()).Wait();
     Assert.IsTrue(response.IsSuccessful, response.ToErrorString());
     Assert.IsNotNull(luceneUriCalled, "lucene was not called");
     Assert.AreEqual(Utils.Settings.LuceneMockUri.At("compact"), luceneUriCalled.WithoutQuery(), "lucene was called at wrong uri");
     Assert.IsNull(luceneUriCalled.GetParam("apiuri"), "lucene request contained an apiuri parameter");
     Assert.IsNull(luceneUriCalled.GetParam("userid"), "lucene request contained a userid parameter");
     Assert.AreEqual(searchQuery.LuceneQuery, luceneUriCalled.GetParam("q"), "lucene request had incorrect q parameter");
 }
Esempio n. 13
0
        public Task<SearchResult<UserListItem>> GetUsersAsync(string pagingToken = null)
        {
            var path = GetObjectPath() + "/items";
            return Client.CallServiceMethod<SearchResult<IDictionary<string, object>>>("GET", path, new
            {
                token = pagingToken
            }).WrapTask<BuddyResult<SearchResult<IDictionary<string,object>>>,SearchResult<UserListItem>>(t2 => {

                var r = t2.Result;

                var sr = new SearchResult<UserListItem>();

                if (r.IsSuccess) {
                    sr.NextToken = r.Value.NextToken;
                    sr.PreviousToken = r.Value.PreviousToken;
                    sr.CurrentToken = r.Value.CurrentToken;

                    sr.PageResults = r.Value.PageResults.Select(i => new UserListItem(i));
                }
                else {
                    sr.Error = r.Error;

                }
                return sr;
            });
        }
Esempio n. 14
0
 private static All GetAllDogsFromContentfulResult(SearchResult<Entry> results)
 {
     return new All
     {
         DogsItems = results.Items
             // Retrieve the ImageId from the linked 'mainPicture' asset
             // NOTE: We could merge all of these Select() statements into one, but this way we only have to call dog.GetLink() and dog.GetString()
             //       once, which improves performance.
             .Select(dog => new
             {
                 dog.SystemProperties.Id,
                 ImageId = dog.GetLink("mainPicture").SystemProperties.Id,
                 Type = dog.GetString("dogType")
             })
             // Now find the included 'Asset' details from the corresponding ImageId
             .Select(dog => new
             {
                 dog.Id,
                 ImageUrl =
                     results.Includes.Assets.First(asset => asset.SystemProperties.Id == dog.ImageId)
                         .Details.File.Url,
                 dog.Type
             })
             // Now we map our calculated data to our model
             .Select(dog => new DogItem
             {
                 Id = dog.Id,
                 LargeImageUrl =
                     ImageHelper.GetResizedImageUrl(dog.ImageUrl, 500, 500, ImageHelper.ImageType.Jpg, 75),
                 ThumbnailImageUrl =
                     ImageHelper.GetResizedImageUrl(dog.ImageUrl, 150, 150, ImageHelper.ImageType.Png),
                 Type = dog.Type
             })
     };
 }
        public string Execute(TransitionContext context)
        {
            string retEvent = Events.Error;

            try {
                if (context.Request.Items[this.AccountItemNameIn] == null ||
                    !(context.Request.Items[this.AccountItemNameIn] is SearchResult<Account>) ||
                    context.Request.GetItem<SearchResult<Account>>(this.AccountItemNameIn).Items.Length != 1) {

                    throw new MissingFieldException("Could not retrieve an account or the more than one account was returned.");
                }

                Account account = context.Request.GetItem<SearchResult<Account>>(this.AccountItemNameIn).Items[0];

                /* Hmm whats better... one line or 3...
                    context.Request.Items[this.AccountsItemNameIn] = new SearchResult<Account>( new[] { Deserialize.Populate(context.Request, accounts.Items[0]) });
                    */

                Account toReturn = Deserialize.Populate(context.Request, account);

                SearchResult<Account> result = new SearchResult<Account>(new Account[] {toReturn});

                context.Request.Items[this.AccountItemNameOut] = result;

                retEvent = Events.Ok;
            } catch (Exception ex) {
                this.logger.Error("Error occured in Execute.", ex);
            }

            return retEvent;
        }
        public string Execute(TransitionContext context)
        {
            string retEvent = Events.Error;

            try {
                if (context.Request.Items[this.AttributeTypeItemNameIn] == null &&
                    !(context.Request.Items[this.AttributeTypeItemNameIn] is SearchResult<AttributeType>) &&
                    context.Request.GetItem<SearchResult<AttributeType>>(this.AttributeTypeItemNameIn).Items.Length != 1) {
                    throw new MissingFieldException("Could not retrieve an attribute type or the more than one attribute type was returned.");
                }

                AttributeType account = context.Request.GetItem<SearchResult<AttributeType>>(this.AttributeTypeItemNameIn).Items[0];

                AttributeType toReturn = Deserialize.Populate(context.Request, account);

                SearchResult<AttributeType> result = new SearchResult<AttributeType>(new AttributeType[] {toReturn});

                context.Request.Items[this.AttributeTypeItemNameOut] = result;

                retEvent = Events.Ok;
            } catch (Exception ex) {
                this.logger.Error("Error occured in Execute.", ex);
            }

            return retEvent;
        }
Esempio n. 17
0
        /// <summary>
        /// Execute Alpha - Beta Negemax search to find the next best cell.
        /// </summary>
        /// <returns>
        /// The best cell and its score.
        /// </returns>
        /// <param name='board'>
        /// The Game Board.
        /// </param>
        /// <param name='cell'>
        /// The last taken <see cref="Yavalath.cell"/>.
        /// </param>
        /// <param name='height'>
        /// The Height to which the search should be run until.
        /// </param>
        /// <param name='achievable'>
        /// The Achievable Cell.
        /// </param>
        /// <param name='hope'>
        /// Hope.
        /// </param>
        /// <param name='player'>
        /// Player.
        /// </param>
        public static SearchResult ABNegamax(Board board, Cell cell, int height, 
			SearchResult achievable, SearchResult hope, int player)
        {
            var emptyCells = board.EmptyCells ();
            if (height == 0 || emptyCells.Length == 0) {
                return new SearchResult {
                    Score = Evaluation (board, cell, player),
                    Cell = cell,
                    Count = 1
                };
            } else {
                SearchResult temp;
                var score = Evaluation (board, cell, player);
                achievable.Count += 1;

                foreach (var _cell in emptyCells)
                {
                    _cell.Player = player;
                    temp = -ABNegamax (board, _cell, height-1, -hope, -achievable, -player);
                    temp.Score += score;
                    _cell.Player = 0;
                    if (temp.Score >= hope.Score) {
                        return temp;
                    }
                    achievable.Count = temp.Count = achievable.Count + temp.Count;
                    achievable = temp.Score >= achievable.Score ? temp : achievable;
                }
                return achievable;
            }
        }
Esempio n. 18
0
        /**
         * Get the results from browsing and put it into the sharedFileList folder of the peer.
         * Should maybe change the key to a Peer , but since implementation is unknown
         * no assurance that hashcode will be the same ...
         * */
        public void BrowsingTerminated(Peer peer, SearchResult Results, List<G2PacketQH2> resultPackets)
        {
            if (resultPackets.Count == 0)
            {
                RegroupResults(Results); // if no results from browsing directly sends results
                return;
            }
            Results.PeerCollection.Add(peer);
            Peer p = Results.PeerCollection.Find(peer);

            int fileCount = 0;
            // add results !!
            foreach(G2PacketQH2 qh2 in resultPackets)
            {
                foreach(G2Packet child in qh2.children)
                {
                    if (!child.type.Equals(G2PacketType.H))
                        continue;
                    G2PacketH hit = child as G2PacketH;
                    G2File file = G2File.ParseHit(hit,FileLocationFound.SharedLocalComputer);
                    if (file == null) continue;
                    p.SharedLocalfilesList.Add(file);
                    file.PeerDiffusedFiles.Add(p);
                    SharedTotalFiles++;
                    fileCount++;
                }
            }

            G2Log.Write("SearchResults : New Browsing Result from " + p.Ip + ":" + p.Port + " ==> " + p.Files.Count + " files && " + p.SharedLocalfilesList.Count + " shared files ...");

            RegroupResults(Results);
        }
Esempio n. 19
0
        private RenameLocationSet(ISymbol symbol, Solution solution, OptionSet optionSet, SearchResult originalSymbolResult, List<SearchResult> overloadsResult, IEnumerable<RenameLocation> stringsResult, IEnumerable<RenameLocation> commentsResult)
        {
            _symbol = symbol;
            _solution = solution;
            _optionSet = optionSet;
            _originalSymbolResult = originalSymbolResult;
            _overloadsResult = overloadsResult;
            _stringsResult = stringsResult;
            _commentsResult = commentsResult;

            var mergedLocations = new HashSet<RenameLocation>();
            var mergedReferencedSymbols = new List<ISymbol>();
            var mergedImplicitLocations = new List<ReferenceLocation>();

            if (optionSet.GetOption(RenameOptions.RenameInStrings))
            {
                mergedLocations.AddRange(stringsResult);
            }

            if (optionSet.GetOption(RenameOptions.RenameInComments))
            {
                mergedLocations.AddRange(commentsResult);
            }

            var overloadsToMerge = (optionSet.GetOption(RenameOptions.RenameOverloads) ? overloadsResult : null) ?? SpecializedCollections.EmptyEnumerable<SearchResult>();
            foreach (var result in overloadsToMerge.Concat(originalSymbolResult))
            {
                mergedLocations.AddRange(result.Locations);
                mergedImplicitLocations.AddRange(result.ImplicitLocations);
                mergedReferencedSymbols.AddRange(result.ReferencedSymbols);
            }

            _mergedResult = new SearchResult(mergedLocations, mergedImplicitLocations, mergedReferencedSymbols);
        }
Esempio n. 20
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string queryStr = Request.QueryString["query"];
                Hits hits = MyLucene.Search(queryStr);

                // Iterate over the results and build the list
                int nResults = hits.Length();
                List<SearchResult> results = new List<SearchResult>();
                for (int i = 0; i < nResults; i++)
                {
                    Document foundDoc = hits.Doc(i);
                    float score = hits.Score(i);
                    SearchResult r = new SearchResult();
                    r.ArticleId = foundDoc.Get("ArticleId");
                    r.Title = foundDoc.Get("Title");
                    r.Author = foundDoc.Get("Author");
                    r.Date = TransformDate(foundDoc.Get("PubDate"));
                    results.Add(r);
                }

                // Build resulting list to repeater control
                rptSearchResults.DataSource = results;
                rptSearchResults.DataBind();
            }
        }
 public void Add(SearchResult item)
 {
     if (!this.Contains(item))
     {
         _list.Add(item);
     }
 }
Esempio n. 22
0
 public SearchResult SearchKey(string key)
 {
     var search = new SearchResult() { Key = key };
     if (!string.IsNullOrWhiteSpace(key))
     {
         SearchKeywordManager.Search(key);        //用于统计搜索关键字的方法
         IList<Duty_c> list = new List<Duty_c>();
         list = BLL.Search.SearchGoods(key);
         if (list.Count == 0)
         {
             search.Error = true;
         }
         else if (list.Count == 1)
         {
             search.Duty = list[0];
             //goods_type = "<li class='one'>您输入的物品属于:  " + duty.type.overname + "--->" + duty.type.midname + "--->" + duty.type.name + "</li><br/>";
             //name = "<li class='one'>您输入的物品相关的品名是:  " + duty.name + "</li><br/>";
             //relatedwords = "<li class='one'>该品目相关的关键词:  " + duty.relatedwords.ToString() + "</li><br/>";
             //price = "<li class='one'>完税价格是:  " + duty.price.ToString() + "元/" + duty.unit + "</li><br/>";
             //rate = "<li class='one'>税率是:  " + duty.rate.ToString() + "</li><br/>";
             //lister = goods_type + name + relatedwords + price + rate;
         }
         else if (list.Count > 1)
         {
             search.SearchTakes = list.Select(r => r.name).ToList();
             //lister = "你搜索结果大于一条,请在下列项中选择: </br>";
             //for (int i = 0; i < list.Count; i++)
             //{
             //    lister += "<a href=default.aspx?KeyWord=" + list[i].name + ">" + list[i].name + "</a>  ";
             //}
         }
     }
     return search;
 }
	static async Task<SearchResult> SearchAll(string key)
	{
		string url = XiamiUrl.UrlSearchAll(key);
		string json = await NetAccess.DownloadStringAsync(url);
		/////////////
		dynamic obj = json.ToDynamicObject();
		var items = new List<IMusic>();
		foreach(var type in new string[] { "song", "album", "artist", "collect" })
		{
			var data = obj[type + "s"] as ArrayList;
			if(data == null) continue;
			foreach(dynamic x in data)
			{
				items.Add(MusicFactory.CreateFromJson(x, (EnumMusicType)Enum.Parse(typeof(EnumMusicType), type)));
			}
		}
		var sr = new SearchResult
		{
			Items = items,
			Keyword = key,
			Page = -1,
			SearchType = EnumSearchType.key
		};
		return sr;
	}
Esempio n. 24
0
 public void TestIntegerConversion()
 {
     SearchResult result1 = new SearchResult() { Index = 0 };
     Assert.AreEqual<int>(result1.Index, result1, "The result converted to the wrong index."); // implicit conversion
     SearchResult result2 = new SearchResult() { Index = 2 };
     Assert.AreEqual<int>(result2.Index, result2, "The result converted to the wrong index."); // implicit conversion
 }
Esempio n. 25
0
 public void TestToString()
 {
     SearchResult result1 = new SearchResult() { Index = 0, Exists = true };
     Assert.AreEqual("Exists = True, Index = 0", result1.ToString(), "The wrong string representation was returned."); // implicit conversion
     SearchResult result2 = new SearchResult() { Index = 1, Exists = false };
     Assert.AreEqual("Exists = False, Index = 1", result2.ToString(), "The wrong string representation was returned."); // implicit conversion
 }
Esempio n. 26
0
 public void SearchResultMultiLine_ToString_EqualsExpected()
 {
     var settings = new SearchSettings();
     var pattern = new Regex("Search");
     var searchFile = new SearchFile(CsSearchPath, "Searcher.cs", FileType.Text);
     var lineNum = 10;
     var matchStartIndex = 15;
     var matchEndIndex = 23;
     var line = "\tpublic class Searcher";
     var linesBefore = new List<string> { "namespace CsSearch", "{" };
     var linesAfter = new List<string> {"\t{", "\t\tprivate readonly FileTypes _fileTypes;"};
     var searchResult = new SearchResult(pattern, searchFile, lineNum,
                                         matchStartIndex, matchEndIndex,
                                         line, linesBefore, linesAfter);
     var expectedPath = CsSearchPath + "/Searcher.cs";
     var expectedOutput = string.Format(new string('=', 80) + "\n" +
                          "{0}: {1}: [{2}:{3}]\n" +
                          new string('-', 80) + "\n" +
                          "   8 | namespace CsSearch\n" +
                          "   9 | {{\n" +
                          "> 10 | 	public class Searcher\n" +
                          "  11 | 	{{\n" +
                          "  12 | 		private readonly FileTypes _fileTypes;\n",
                          expectedPath, lineNum, matchStartIndex, matchEndIndex);
     Assert.AreEqual(searchResult.ToString(settings), expectedOutput);
 }
Esempio n. 27
0
 public void TestBooleanConversion()
 {
     SearchResult result1 = new SearchResult() { Exists = true };
     Assert.IsTrue(result1, "The value should have existed."); // implicit conversion
     SearchResult result2 = new SearchResult() { Exists = false };
     Assert.IsFalse(result2, "The value should not have existed."); // implicit conversion
 }
        public string Execute(TransitionContext context)
        {
            string retEvent = "error";
            try {
                //for now this just returns all the states
                List<State> states = new List<State>(DaoFactory.GetDao<IStateDao>().Get(new State{
                                                                                                 	IsTerritory = false
                                                                                                 }));

                SearchResult<State> results = new SearchResult<State>(states.ToArray());

                switch (results.Items.Length) {
                    case 0:
                        retEvent = "zero";
                        break;
                    case 1:
                        retEvent = "one";
                        break;
                    default:
                        retEvent = "multiple";
                        break;
                }

                context.Request.Items[(this.RequestItemName ?? ADDRESS_STATES)] = results;
            } catch (Exception ex) {
                LogManager.GetLogger(typeof (GetStatesAction)).Error(
                            errorMessage => errorMessage("GetPropertyAction: Execute", ex));
            }

            return retEvent;
        }
        public string Execute(TransitionContext context)
        {
            string retEvent = Events.Error;

            try {
                if (context.Request.Items[this.RoleItemNameIn] == null ||
                    !(context.Request.Items[this.RoleItemNameIn] is SearchResult<Role>) ||
                    context.Request.GetItem<SearchResult<Role>>(this.RoleItemNameIn).Items.Length != 1) {
                    throw new MissingFieldException("Could not retrieve an role or the more than one role was returned.");
                }

                Role role = context.Request.GetItem<SearchResult<Role>>(this.RoleItemNameIn).Items[0];

                Role toReturn = Deserialize.Populate(context.Request, role);

                SearchResult<Role> result = new SearchResult<Role>(new Role[] {toReturn});

                context.Request.Items[this.RoleItemNameOut] = result;

                retEvent = Events.Ok;
            } catch (Exception ex) {
                this.logger.Error("Error occured in Execute.", ex);
            }

            return retEvent;
        }
Esempio n. 30
0
        /// <summary>
        /// Parses the various properties from the XML document and populates the given SearchResult.
        /// </summary>
        /// <param name="result">The Google.CustomSearch.SearchResult to populate.</param>
        /// <param name="nav">The XPathNavigator for the response document.</param>
        private void ParseResponseProperties(SearchResult result, XPathNavigator nav)
        {
            XPathNavigator timeNode = nav.SelectSingleNode("/GSP/TM");
            if (timeNode != null)
                result.Time = timeNode.Value;

            XPathNavigator titleNode = nav.SelectSingleNode("/GSP/Context/title");
            if (titleNode != null)
                result.Title = titleNode.Value;

            XPathNavigator resultContainer = nav.SelectSingleNode("/GSP/RES");
            if (resultContainer != null)
            {
                // See http://www.google.com/cse/docs/resultsxml.html#results_xml_tag_XT
                result.Exact = resultContainer.SelectSingleNode("XT") != null;

                result.Filtered = resultContainer.SelectSingleNode("FI") != null;

                int startIndex;
                string start = resultContainer.GetAttribute("SN", string.Empty);
                if (int.TryParse(start, out startIndex))
                {
                    result.StartIndex = startIndex;
                }

                int endIndex;
                string end = resultContainer.GetAttribute("EN", string.Empty);
                if (int.TryParse(end, out endIndex))
                {
                    result.EndIndex = endIndex;
                }

                // Next and previous URLs
                XPathNavigator navigation = resultContainer.SelectSingleNode("NB");
                if (null != navigation)
                {
                    XPathNavigator nextLink = navigation.SelectSingleNode("NU");
                    if (null != nextLink)
                        result.NextPageLink = nextLink.Value;

                    XPathNavigator previousLink = navigation.SelectSingleNode("NP");
                    if (null != previousLink)
                        result.PreviousPageLink = previousLink.Value;
                }

                XPathNavigator totalNode = resultContainer.SelectSingleNode("M");
                if (totalNode != null)
                {
                    int total;
                    if (int.TryParse(totalNode.Value, out total))
                    {
                        result.Total = total;
                    }
                }
            }

            this.ParseSpellings(result, nav);

            this.ParseFacets(result, nav);
        }
        /// <summary>
        /// Helper method to create an active directory account
        /// </summary>
        /// <param name="userName">The username field as set in Microsoft Dynamics CRM</param>
        /// <param name="firstName">The first name of the system user to be retrieved</param>
        /// <param name="lastName">The last name of the system user to be retrieved</param>
        /// <param name="serviceProxy">The OrganizationServiceProxy object to your Microsoft
        /// Dynamics CRM environment</param>
        /// <param name="ldapPath">The LDAP path for your network - you can either call
        /// ConsolePromptForLDAPPath() to prompt the user or provide a value in code</param>
        /// <returns>Return true if new account is created or return false if account already exist.</returns>
        public static Boolean CreateADAccount(String userName,
                                              String firstName,
                                              String lastName,
                                              OrganizationServiceProxy serviceProxy,
                                              ref String ldapPath)
        {
            // Check to make sure this is not Microsoft Dynamics CRM Online.
            if (serviceProxy.ServiceConfiguration.AuthenticationType == AuthenticationProviderType.LiveId ||
                serviceProxy.ServiceConfiguration.AuthenticationType == AuthenticationProviderType.OnlineFederation)
            {
                throw new Exception(String.Format("To run this sample, {0} {1} must be an active system user " +
                                                  "\nin your Microsoft Dynamics CRM Online organization.", firstName, lastName));
            }

            if (String.IsNullOrEmpty(ldapPath))
            {
                ldapPath = SystemUserProvider.ConsolePromptForLDAPPath();
            }

            // Create an Active Directory user account if it doesn't exist already.
            if (String.IsNullOrEmpty(ldapPath))
            {
                throw new ArgumentException("Required argument ldapPath was not provided.");
            }

            DirectoryEntry directoryEntry;

            if (serviceProxy.ClientCredentials.Windows != null)
            {
                string LUser = serviceProxy.ClientCredentials.Windows.ClientCredential.UserName;
                string LPwd  = serviceProxy.ClientCredentials.Windows.ClientCredential.Password;
                directoryEntry = new DirectoryEntry(ldapPath, LUser, LPwd);
            }
            else
            {
                directoryEntry = new DirectoryEntry(ldapPath);
            }

            DirectoryEntry userADAccount = null;

            // Search AD to see if the user already exists.
            DirectorySearcher search = new DirectorySearcher(directoryEntry);

            search.Filter = String.Format("(sAMAccountName={0})", userName);
            search.PropertiesToLoad.Add("samaccountname");
            search.PropertiesToLoad.Add("givenname");
            search.PropertiesToLoad.Add("sn");
            search.PropertiesToLoad.Add("cn");
            SearchResult result         = search.FindOne();
            Boolean      accountCreated = false;

            if (result == null)
            {
                // Create the Active Directory account.
                userADAccount = directoryEntry.Children.Add("CN= " + userName, "user");
                userADAccount.Properties["samAccountName"].Value = userName;
                userADAccount.Properties["givenName"].Value      = firstName;
                userADAccount.Properties["sn"].Value             = lastName;
                userADAccount.CommitChanges();
                accountCreated = true;
            }
            else
            {
                // Use the existing AD account.
                userADAccount  = result.GetDirectoryEntry();
                accountCreated = false;
            }

            // Set the password for the account.
            String password = "******";

            userADAccount.Invoke("SetPassword", new object[] { password });
            userADAccount.CommitChanges();
            directoryEntry.Close();
            userADAccount.Close();

            // Enable the newly created Active Directory account.
            userADAccount.Properties["userAccountControl"].Value =
                (int)userADAccount.Properties["userAccountControl"].Value & amp; ~0x2;
            userADAccount.CommitChanges();

            // Wait 10 seconds for the AD account to propagate.
            Thread.Sleep(10000);
            return(accountCreated);
        }
        public ActionResult <List <StockFull> > Search(string query, string type)
        {
            SearchResult <StockFull> searchResult = _searchService.Search(query, type);

            return(Ok(searchResult.Results));
        }
Esempio n. 33
0
        /// <summary>
        /// GetDirectoryEntry() method implmentation
        /// </summary>
        internal static DirectoryEntry GetDirectoryEntry(string domainname, string account, string password, SearchResult sr)
        {
            DirectoryEntry entry = sr.GetDirectoryEntry();

            entry.Path = sr.Path; // Take SearchResult path
            if (!string.IsNullOrEmpty(account))
            {
                entry.Username = account;
            }
            if (!string.IsNullOrEmpty(password))
            {
                entry.Password = password;
            }
            return(entry);
        }
Esempio n. 34
0
 /// <summary>
 /// Returns a period-separated concatenation of all of the domain components (fully-qualified) of the path
 /// </summary>
 /// <param name="result">The result.</param>
 public static string GetDomainPath(this SearchResult result) => GetDomainPath(result.Path);
Esempio n. 35
0
        public static void ChangeAllPasswords(string userName, string currentPassword, string newPassword, string domainName = "dublinschool.org", bool force = false)
        {
            AssertPasswordRequirements(newPassword);
            State.log.WriteLine("Password Requirements Met.");
            WebhostEventLog.Syslog.LogInformation("Password Requirements are met for {0} new password.", userName);
            if (force)
            {
                WebhostEventLog.Syslog.LogInformation("Forcibly changing password for {0}", userName);
                ForceChangeADPassword(userName, newPassword);
            }
            else
            {
                try
                {
                    State.log.WriteLine("Connecting LDAP.");
                    DirectoryEntry directionEntry = new DirectoryEntry("LDAP://192.168.76.3", domainName + "\\" + userName, currentPassword);
                    if (directionEntry != null)
                    {
                        DirectorySearcher search = new DirectorySearcher(directionEntry);
                        State.log.WriteLine("LDAP Connected, searching directory for SAMAccountName");
                        search.Filter = "(SAMAccountName=" + userName + ")";
                        SearchResult result = search.FindOne();
                        if (result != null)
                        {
                            State.log.WriteLine("Getting User Entry.");
                            DirectoryEntry userEntry = result.GetDirectoryEntry();
                            if (userEntry != null)
                            {
                                State.log.WriteLine("Setting Password");
                                if (force)
                                {
                                    userEntry.Invoke("SetPassword", new[] { newPassword });
                                }
                                else
                                {
                                    // Windows update broke this August 2016
                                    // userEntry.Invoke("ChangePassword", new object[] { currentPassword, newPassword });

                                    // This is a fix that should work...
                                    ForceChangeADPassword(userName, newPassword);
                                }
                                userEntry.CommitChanges();
                                State.log.WriteLine("Changes Committed to ActiveDirectory.");
                                WebhostEventLog.Syslog.LogInformation("Changes committed to ActiveDirectory for {0}", userName);
                            }
                            else
                            {
                                State.log.WriteLine("Could not get user Entry...");
                                WebhostEventLog.Syslog.LogError("Could not get user entry for {0}.", userName);
                            }
                        }
                        else
                        {
                            State.log.WriteLine("Search returned no results.");
                            WebhostEventLog.Syslog.LogError("Directory Search returned no results for {0}.", userName);
                        }
                    }
                    else
                    {
                        State.log.WriteLine("Could not connect to LDAP with given username and passwd");
                        WebhostEventLog.Syslog.LogError("Could not connect to LDAP with the given password for {0}.", userName);
                    }
                }
                catch (Exception ex)
                {
                    WebhostEventLog.Syslog.LogError("Could not reset Windows password for {0}.{1}{2}", userName, Environment.NewLine, ex.Message);
                    throw new PasswordException(String.Format("Failed to reset Windows Password for {0}.", userName), ex);
                }
            }
            try
            {
                State.log.WriteLine("Initiating Google API Call");
                WebhostEventLog.GoogleLog.LogInformation("Connecting to Google API for a password change for {0}.", userName);
                using (GoogleDirectoryCall google = new GoogleDirectoryCall())
                {
                    State.log.WriteLine("Google API Call instantiated.  Calling SetPassword");
                    WebhostEventLog.GoogleLog.LogInformation("Connected successfully with {0}.", userName);
                    google.SetPassword(userName, newPassword);
                    WebhostEventLog.GoogleLog.LogInformation("Successfully changed {0} password for Gmail.", userName);
                    State.log.WriteLine("SetPassword Completed.");
                }
            }
            catch (GoogleAPICall.GoogleAPIException gae)
            {
                WebhostEventLog.GoogleLog.LogError("Failed to change password for {0}.{1}{2}", userName, Environment.NewLine, gae.Message);
                throw gae;
            }
        }
Esempio n. 36
0
        /// <summary>
        /// Search database for content and find a match from results.
        /// </summary>
        /// <param name="search">Search string to match content to</param>
        /// <param name="folderPath">Path of folder containing content</param>
        /// <param name="rootFolder">Root folder containing content folder</param>
        /// <param name="year">Year to match to content</param>
        /// <param name="result">resulting match found from search</param>
        /// <returns>whether match was successful</returns>
        private bool DoMatch(string search, string folderPath, string rootFolder, int year, ContentSearchMod baseMods, out List <SearchResult> matches, Content knownContent)
        {
            /// Debug notification
            OnDebugNotificationd("Performing database search for: " + search);

            // Search for content
            List <Content> searchResults;

            if (knownContent == null)
            {
                searchResults = PerformSearch(search, false);
            }
            else
            {
                searchResults = new List <Content>()
                {
                    knownContent
                }
            };

            // Initialize resutls
            matches = new List <SearchResult>();

            // Go through results
            if (searchResults != null)
            {
                foreach (Content searchResult in searchResults)
                {
                    OnDebugNotificationd("Attempting to match to database entry: " + searchResult);

                    SearchResult result = new SearchResult();
                    result.Mods = baseMods;

                    // Verify year in result matches year from folder (if any)
                    if (year != -1 && Math.Abs(year - searchResult.DatabaseYear) > 2)
                    {
                        continue;
                    }

                    // Check if search string match results string
                    string simplifiedSearch = FileHelper.SimplifyFileName(search);
                    string dbContentName    = FileHelper.SimplifyFileName(searchResult.DatabaseName);

                    bool theAddedToMatch;
                    bool singleLetterDiff;

                    // Try basic match
                    bool match = FileHelper.CompareStrings(simplifiedSearch, dbContentName, out theAddedToMatch, out singleLetterDiff);
                    result.MatchedString = simplifiedSearch;

                    // Try match with year removed
                    if (!match)
                    {
                        simplifiedSearch     = FileHelper.SimplifyFileName(search, true, true, false);
                        dbContentName        = FileHelper.SimplifyFileName(searchResult.DatabaseName, true, true, false);
                        match                = FileHelper.CompareStrings(simplifiedSearch, dbContentName, out theAddedToMatch, out singleLetterDiff);
                        result.MatchedString = simplifiedSearch;
                    }

                    // Try match with country removed
                    if (!match)
                    {
                        simplifiedSearch = FileHelper.SimplifyFileName(search, true, true, true);
                        dbContentName    = FileHelper.SimplifyFileName(searchResult.DatabaseName, true, true, true);
                        match            = FileHelper.CompareStrings(simplifiedSearch, dbContentName, out theAddedToMatch, out singleLetterDiff);
                        if (match)
                        {
                            result.Mods |= ContentSearchMod.WordsRemoved;
                        }
                        result.MatchedString = simplifiedSearch;
                    }

                    // Try match with spaces removed
                    if (!match)
                    {
                        string dirNoSpc  = simplifiedSearch.Replace(" ", "");
                        string nameNoSpc = dbContentName.Replace(" ", "");
                        match = FileHelper.CompareStrings(dirNoSpc, nameNoSpc, out theAddedToMatch, out singleLetterDiff);
                        result.MatchedString = simplifiedSearch;
                        if (match)
                        {
                            result.Mods |= ContentSearchMod.SpaceRemoved;
                        }
                    }

                    // Try match with year added to content name
                    if (!match)
                    {
                        simplifiedSearch     = FileHelper.SimplifyFileName(search);
                        dbContentName        = FileHelper.SimplifyFileName(searchResult.DatabaseName + " " + searchResult.DatabaseYear.ToString());
                        match                = FileHelper.CompareStrings(simplifiedSearch, dbContentName, out theAddedToMatch, out singleLetterDiff);
                        result.MatchedString = simplifiedSearch;
                    }


                    if (theAddedToMatch)
                    {
                        result.Mods |= ContentSearchMod.TheAdded;
                    }
                    if (singleLetterDiff)
                    {
                        result.Mods |= ContentSearchMod.SingleLetterAdded;
                    }

                    // Match notification
                    if (match)
                    {
                        OnDebugNotificationd("Matched with following mods: " + result.Mods);
                    }

                    // No match, next result!
                    if (!match)
                    {
                        continue;
                    }

                    // Set results folder/path
                    result.Content            = searchResult;
                    result.Content.RootFolder = rootFolder;
                    if (string.IsNullOrEmpty(folderPath))
                    {
                        result.Content.Path = result.Content.BuildFolderPath();
                    }
                    else
                    {
                        result.Content.Path = folderPath;
                    }

                    // Save results
                    matches.Add(result);
                }
            }

            return(matches.Count > 0);
        }
Esempio n. 37
0
        /// <summary>
        /// LogUserLogin - This method retrieves data from LDAP and update the UserData object in the database
        /// </summary>
        /// <param name="userData">UserData - users data from UserData table</param>
        /// <param name="UpdateLastLogin">bool - default value is true</param>
        /// <returns>UserData - updated with current LDAP data</returns>
        public UserData LogUserLogin(UserData userData, bool UpdateLastLogin = true)
        {
            string         ManagerDNID = null;
            string         ManagerEID  = null;
            string         EmployeeEID = null;
            LdapProcessing LDAP        = new LdapProcessing();

            string domainID = userData.UserDomain.ToString() + ":" + userData.UserNTID.ToString();

            try
            {
                // Define Properties to Return
                // These properties are defined in your local LDAP and the values are returned from the directory search

                string ADManagerEmailProperty = "manager";
                string ADOProperty            = "hpOrganizationChart";
                string ABUProperty            = "hpBusinessGroup";
                string ADCNProperty           = "cn";
                string ADCNManagerNum         = "managerEmployeeNumber";
                string ADEmailProperty        = "mail";

                // Load the Properties into a list of strings
                List <string> loadProperties = new List <string>();
                loadProperties.Add(ADManagerEmailProperty);
                loadProperties.Add(ADOProperty);
                loadProperties.Add(ABUProperty);
                loadProperties.Add(ADCNProperty);
                loadProperties.Add(ADCNManagerNum);
                loadProperties.Add(ADEmailProperty);

                // Search for the User
                SearchResult result = LDAP.FormatAndSearchForUser("ntuserdomainid", domainID, loadProperties);

                // Found the User
                if (result != null)
                {
                    // Parse name into first/last
                    string[] names     = result.Properties[ADCNProperty][0].ToString().Split(' ');
                    string   firstName = null;
                    string   lastName  = null;

                    foreach (string name in names)
                    {
                        if (firstName != null)
                        {
                            lastName = lastName + name + " ";
                        }
                        else
                        {
                            firstName = name;
                        }
                    }

                    if (firstName != null)
                    {
                        userData.FirstName = firstName.Trim();
                    }
                    else
                    {
                        userData.FirstName = "";
                    }

                    if (lastName != null)
                    {
                        userData.LastName = lastName.Trim();
                    }
                    else
                    {
                        userData.LastName = "";
                    }


                    // Get Manager, Organization, Business Unit
                    ManagerDNID           = result.Properties[ADManagerEmailProperty][0].ToString();
                    userData.OrgName      = result.Properties[ADOProperty][0].ToString();
                    userData.BusinessUnit = result.Properties[ABUProperty][0].ToString();

                    userData.ManagerEID = result.Properties[ADCNManagerNum][0].ToString();
                    ManagerEID          = result.Properties[ADCNManagerNum][0].ToString();
                    EmployeeEID         = result.Properties[ADEmailProperty][0].ToString();
                }
                else
                {
                    // User Not Found
                    logger.ErrorFormat("User {0} Not Found in LDAP", domainID);
                    throw new ApplicationException("User Not Found in LDAP: " + domainID);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                throw new ApplicationException("Error LDAPInterface.GetUserWithDomainIdentity: " + Environment.NewLine + "User: "******"ntuserdomainid";
                    string ADMgrCNProperty     = "cn";

                    // Load the Properties to Load
                    List <string> loadProperties = new List <string>();
                    loadProperties.Add(ADManagerIDProperty);
                    loadProperties.Add(ADMgrCNProperty);

                    // Search for the Manager info using Employee Number
                    SearchResult result = LDAP.FormatAndSearchForEID("employeeNumber", ManagerEID, loadProperties);

                    // Found the User
                    if (result != null)
                    {
                        string[] names        = result.Properties[ADMgrCNProperty][0].ToString().Split(' ');
                        string   MGRfirstName = null;
                        string   MGRlastName  = null;

                        foreach (string name in names)
                        {
                            if (MGRfirstName != null)
                            {
                                MGRlastName = MGRlastName + name + " ";
                            }
                            else
                            {
                                MGRfirstName = name;
                            }
                        }

                        if (MGRfirstName != null)
                        {
                            userData.MgrFirstName = MGRfirstName.Trim();
                        }
                        else
                        {
                            userData.MgrFirstName = "";
                        }

                        if (MGRlastName != null)
                        {
                            userData.MgrLastName = MGRlastName.Trim();
                        }
                        else
                        {
                            userData.MgrLastName = "";
                        }

                        userData.ManagerID = result.Properties[ADManagerIDProperty][0].ToString().Replace(@":", @"\").ToUpper();
                    }
                    else
                    {
                        // User Not Found
                        throw new ApplicationException("Manager Not Found in AD: " + ManagerEID);
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(ex);

                    // Error in Search
                    throw new ApplicationException("Error LDAPInterface.FormatAndSearchForEmail: " + Environment.NewLine + "Mgr Email: " + ManagerEID, ex);
                }
            }


            // Now check to see if the user belongs to either the Admin Group or the Business Unit Owner LDAP groups
            bool GCSOwaspSAMMUser = false;

            List <string> SAMMGroups = new List <string>();

            SAMMGroups.Add(System.Web.Configuration.WebConfigurationManager.AppSettings["LDAPAdminGroup"]);

            SortedList <string, List <string> > tempSAMMGroupsMembers = new SortedList <string, List <string> >(StringComparer.OrdinalIgnoreCase);

            // Get the Members
            LDAP.GetMembers(SAMMGroups, tempSAMMGroupsMembers);

            // Process all the Groups for the Role
            foreach (string SAMMGroup in SAMMGroups)
            {
                // Find the Group in the Group/Members List
                List <string> members = tempSAMMGroupsMembers[SAMMGroup];

                // Interrogate the list for this group to see if the current users email is in it
                foreach (string member in members)
                {
                    // If users email is found set Boolean to true
                    if (member == EmployeeEID)
                    {
                        GCSOwaspSAMMUser = true;
                    }
                }
            }


            // Business Unit Owner LDAP group
            bool GCSSAMMBURep = false;

            SAMMGroups = new List <string>();
            SAMMGroups.Add(System.Web.Configuration.WebConfigurationManager.AppSettings["LDAPBUOwnerGroup"]);

            tempSAMMGroupsMembers = new SortedList <string, List <string> >(StringComparer.OrdinalIgnoreCase);

            // Get the Members
            LDAP.GetMembers(SAMMGroups, tempSAMMGroupsMembers);

            // Process all the Groups for the Role
            foreach (string SAMMGroup in SAMMGroups)
            {
                // Find the Group in the Group/Members List
                List <string> members = tempSAMMGroupsMembers[SAMMGroup];

                // Interrogate the list for this group to see if the current users email is in it
                foreach (string member in members)
                {
                    // If users email is found set Boolean to true
                    if (member == EmployeeEID)
                    {
                        GCSSAMMBURep = true;
                    }
                }
            }

            userData.Manager       = DAL.IsUserAManager(userData.UserID);
            userData.BUOwner       = GCSSAMMBURep;
            userData.Administrator = GCSOwaspSAMMUser;

            if (UpdateLastLogin)
            {
                userData.LastLoginDate = DateTime.Now;
            }

            var success = DAL.UpdateUserData(userData);

            return(userData);
        }
Esempio n. 38
0
 public bool TryDequeueResult(out SearchResult searchResult)
 {
     searchResult = null;
     return(false);
 }
 public override SymbolReference CreateReference<T>(SearchResult<T> searchResult)
 {
     return new ProjectSymbolReference(
         searchResult.WithSymbol<INamespaceOrTypeSymbol>(searchResult.Symbol), _project.Id);
 }
 public override SymbolReference CreateReference<T>(SearchResult<T> searchResult)
 {
     return new MetadataSymbolReference(
         searchResult.WithSymbol<INamespaceOrTypeSymbol>(searchResult.Symbol),
         _metadataReference);
 }
 public abstract SymbolReference CreateReference<T>(SearchResult<T> symbol) where T : INamespaceOrTypeSymbol;
Esempio n. 42
0
        public IActionResult Index(SearchOption searchOption)
        {
            if (string.IsNullOrWhiteSpace(searchOption.Query))
            {
                return(Redirect("~/"));
            }

            var brand = _brandRepository.Query().FirstOrDefault(x => x.Name == searchOption.Query && x.IsPublished);

            if (brand != null)
            {
                return(Redirect(string.Format("~/{0}", brand.Slug)));
            }

            var model = new SearchResult
            {
                CurrentSearchOption = searchOption,
                FilterOption        = new FilterOption()
            };

            var query = _productRepository.Query().Where(x => x.Name.Contains(searchOption.Query) && x.IsPublished && x.IsVisibleIndividually);

            if (!query.Any())
            {
                model.TotalProduct = 0;
                return(View(model));
            }

            AppendFilterOptionsToModel(model, query);

            if (searchOption.MinPrice.HasValue)
            {
                query = query.Where(x => x.Price >= searchOption.MinPrice.Value);
            }

            if (searchOption.MaxPrice.HasValue)
            {
                query = query.Where(x => x.Price <= searchOption.MaxPrice.Value);
            }

            if (string.Compare(model.CurrentSearchOption.Category, "all", StringComparison.OrdinalIgnoreCase) != 0)
            {
                var categories = searchOption.GetCategories();
                if (categories.Any())
                {
                    var categoryIds = _categoryRepository.Query().Where(x => categories.Contains(x.Slug)).Select(x => x.Id).ToList();
                    query = query.Where(x => x.Categories.Any(c => categoryIds.Contains(c.CategoryId)));
                }
            }

            var brands = searchOption.GetBrands();

            if (brands.Any())
            {
                var brandIs = _brandRepository.Query().Where(x => brands.Contains(x.Slug)).Select(x => x.Id).ToList();
                query = query.Where(x => x.BrandId.HasValue && brandIs.Contains(x.BrandId.Value));
            }

            model.TotalProduct = query.Count();
            var currentPageNum = searchOption.Page <= 0 ? 1 : searchOption.Page;
            var offset         = (_pageSize * currentPageNum) - _pageSize;

            while (currentPageNum > 1 && offset >= model.TotalProduct)
            {
                currentPageNum--;
                offset = (_pageSize * currentPageNum) - _pageSize;
            }

            SaveSearchQuery(searchOption, model);

            query = query
                    .Include(x => x.ThumbnailImage);

            query = AppySort(searchOption, query);

            var products = query
                           .Select(x => ProductThumbnail.FromProduct(x))
                           .Skip(offset)
                           .Take(_pageSize)
                           .ToList();

            foreach (var product in products)
            {
                product.Name                   = _contentLocalizationService.GetLocalizedProperty(nameof(Product), product.Id, nameof(product.Name), product.Name);
                product.ThumbnailUrl           = _mediaService.GetThumbnailUrl(product.ThumbnailImage);
                product.CalculatedProductPrice = _productPricingService.CalculateProductPrice(product);
            }

            model.Products = products;
            model.CurrentSearchOption.PageSize = _pageSize;
            model.CurrentSearchOption.Page     = currentPageNum;

            return(View(model));
        }
Esempio n. 43
0
        public void Populate(SearchResult result)
        {
            if (result == null)
            {
                return;
            }

            if (result.MatchedByType && result.WordsInFields.Count == 0)
            {
                Highlights.Add(new HighlightedText {
                    Text = OriginalType
                });
                Highlights.Add(" " + TextUtilities.ShortenValue(result.Node.ToString(), "..."));

                AddDuration(result);

                return;
            }

            Highlights.Add(OriginalType);

            //NameValueNode is speial case: have to show name=value when seached only in one (name or value)
            var  named      = SearchResult.Node as NameValueNode;
            bool nameFound  = false;
            bool valueFound = false;

            if (named != null)
            {
                foreach (var fieldText in result.WordsInFields.GroupBy(t => t.field))
                {
                    if (fieldText.Key.Equals(named.Name))
                    {
                        nameFound = true;
                    }

                    if (fieldText.Key.Equals(named.Value))
                    {
                        valueFound = true;
                    }
                }
            }

            foreach (var wordsInField in result.WordsInFields.GroupBy(t => t.field, t => t.match))
            {
                Highlights.Add(" ");

                var fieldText = wordsInField.Key;

                if (named != null && wordsInField.Key.Equals(named.Value) && !nameFound)
                {
                    Highlights.Add(named.Name + " = ");
                }

                fieldText = TextUtilities.ShortenValue(fieldText, "...");

                var highlightSpans = TextUtilities.GetHighlightedSpansInText(fieldText, wordsInField);
                int index          = 0;
                foreach (var span in highlightSpans)
                {
                    if (span.Start > index)
                    {
                        Highlights.Add(fieldText.Substring(index, span.Start - index));
                    }

                    Highlights.Add(new HighlightedText {
                        Text = fieldText.Substring(span.Start, span.Length)
                    });
                    index = span.End;
                }

                if (index < fieldText.Length)
                {
                    Highlights.Add(fieldText.Substring(index, fieldText.Length - index));
                }

                if (named != null && wordsInField.Key.Equals(named.Name))
                {
                    if (!valueFound)
                    {
                        Highlights.Add(" = " + TextUtilities.ShortenValue(named.Value, "..."));
                    }
                    else
                    {
                        Highlights.Add(" = ");
                    }
                }
            }

            AddDuration(result);
        }
Esempio n. 44
0
 private void SearchProcessor_CurrentSearchReqestCompleted(SearchResult result, string searchId, bool updateExistingResults, string connectionId)
 {
     _hubContext.Clients.Client(connectionId).SendAsync("ReceiveCurrentResult", result).Wait();
     SaveSearchResults(result, searchId, updateExistingResults);
 }
Esempio n. 45
0
        private bool SaveSearchResults(SearchResult searchResult, string searchId, bool updateExistingResults)
        {
            bool isSucessful;

            using (ProDBContext db = new ProDBContext())
            {
                try
                {
                    if (updateExistingResults)
                    {
                        var searchToUpdate = db.Searches.Where(s => s.SearchId == searchId).SingleOrDefault();
                        searchToUpdate.Date = DateTime.Now;
                        var resultToUpdate = db.Results
                                             .Where(r => r.SearchId == searchId &&
                                                    r.PartId == searchResult.Id &&
                                                    r.Brand == searchResult.Brand)
                                             .SingleOrDefault();
                        resultToUpdate.FirstPrice   = searchResult.FirstPrice;
                        resultToUpdate.SecondPrice  = searchResult.SecondPrice;
                        resultToUpdate.IsSuccessful = searchResult.IsSuccessful;
                        db.SaveChanges();
                        isSucessful = true;
                    }
                    else
                    {
                        var result = new Result();
                        if (!db.Searches.Any(s => s.SearchId == searchId))
                        {
                            Search search = new Search {
                                SearchId = searchId, Date = DateTime.Now
                            };
                            db.Searches.AddAsync(search);
                            result = new Result
                            {
                                PartId        = searchResult.Id,
                                Brand         = searchResult.Brand,
                                OriginalPrice = searchResult.OriginalPrice,
                                FirstPrice    = searchResult.FirstPrice,
                                SecondPrice   = searchResult.SecondPrice,
                                SearchId      = search.SearchId,
                                IsSuccessful  = searchResult.IsSuccessful
                            };
                        }
                        else
                        {
                            result = new Result
                            {
                                PartId        = searchResult.Id,
                                Brand         = searchResult.Brand,
                                OriginalPrice = searchResult.OriginalPrice,
                                FirstPrice    = searchResult.FirstPrice,
                                SecondPrice   = searchResult.SecondPrice,
                                SearchId      = searchId,
                                IsSuccessful  = searchResult.IsSuccessful
                            };
                        }

                        db.Results.AddAsync(result);
                        db.SaveChanges();
                        isSucessful = true;
                    }
                }
                catch (Exception e)
                {
                    isSucessful = false;
                }
            }
            return(isSucessful);
        }
 public void ReportResult(SearchResult result)
 {
     lock (Results)
         Results.Add(result);
 }
Esempio n. 47
0
        private static GroupEntry BuildGroup(SearchResult item, Dictionary <string, string> userIndex)
        {
            var group = new GroupEntry
            {
                ReferenceId = DNFromPath(item.Path)
            };

            if (group.ReferenceId == null)
            {
                return(null);
            }

            // External Id
            if (item.Properties.Contains("objectGUID") && item.Properties["objectGUID"].Count > 0)
            {
                group.ExternalId = item.Properties["objectGUID"][0].FromGuidToString();
            }
            else
            {
                group.ExternalId = group.ReferenceId;
            }

            // Name
            if (item.Properties.Contains(SettingsService.Instance.Sync.Ldap.GroupNameAttribute) &&
                item.Properties[SettingsService.Instance.Sync.Ldap.GroupNameAttribute].Count > 0)
            {
                group.Name = item.Properties[SettingsService.Instance.Sync.Ldap.GroupNameAttribute][0].ToString();
            }
            else if (item.Properties.Contains("cn") && item.Properties["cn"].Count > 0)
            {
                group.Name = item.Properties["cn"][0].ToString();
            }
            else
            {
                return(null);
            }

            // Dates
            group.CreationDate = item.Properties.ParseDateTime(SettingsService.Instance.Sync.Ldap.CreationDateAttribute);
            group.RevisionDate = item.Properties.ParseDateTime(SettingsService.Instance.Sync.Ldap.RevisionDateAttribute);

            // Members
            if (item.Properties.Contains(SettingsService.Instance.Sync.Ldap.MemberAttribute) &&
                item.Properties[SettingsService.Instance.Sync.Ldap.MemberAttribute].Count > 0)
            {
                foreach (var member in item.Properties[SettingsService.Instance.Sync.Ldap.MemberAttribute])
                {
                    var memberDn = member.ToString();
                    if (userIndex.ContainsKey(memberDn) && !group.UserMemberExternalIds.Contains(userIndex[memberDn]))
                    {
                        group.UserMemberExternalIds.Add(userIndex[memberDn]);
                    }
                    else if (!group.GroupMemberReferenceIds.Contains(memberDn))
                    {
                        group.GroupMemberReferenceIds.Add(memberDn);
                    }
                }
            }

            return(group);
        }
Esempio n. 48
0
 /// <summary>
 /// Updates the date fields for an IEntity from a SearchResult
 /// </summary>
 /// <param name="e"></param>
 /// <param name="r"></param>
 internal static void SetEntityDatesFromSearchResult(IEntity e, SearchResult r)
 {
     e.UtcCreated       = FromExamineDateTime(r.Fields, FixedIndexedFields.UtcCreated).Value;
     e.UtcModified      = FromExamineDateTime(r.Fields, FixedIndexedFields.UtcModified).Value;
     e.UtcStatusChanged = FromExamineDateTime(r.Fields, FixedIndexedFields.UtcStatusChanged).Value;
 }
Esempio n. 49
0
        /// <summary>
        /// Queries Active Directory server to retrieve the user's Windows domain groups.
        /// Throws an exception if the username does not have the current domain prefix.
        /// Returns null if the user is not found on Active Directory (returns empty list is the user exists, but has no membership records).
        /// </summary>
        public IEnumerable<string> GetIdentityMembership(string username)
        {
            var stopwatch = Stopwatch.StartNew();

            string accountName = RemoveDomainPrefix(username);

            // Search user's domain groups:

            var userNestedMembership = new List<string>();

            DirectoryEntry domainConnection = new DirectoryEntry("LDAP://" + Environment.UserDomainName);
            DirectorySearcher searcher = new DirectorySearcher(domainConnection);
            searcher.Filter = "(samAccountName=" + accountName + ")";
            searcher.PropertiesToLoad.Add("name");

            SearchResult searchResult = null;
            try
            {
                searchResult = searcher.FindOne();
            }
            catch (Exception ex)
            {
                throw new FrameworkException("Active Directory server is not available. To run Rhetos under IISExpress without AD: a) IISExpress must be run as administrator, b) user connecting to Rhetos service must be local administrator, c) 'BuiltinAdminOverride' must be set to 'True' in config file.", ex);
            }

            if (searchResult != null)
            {
                _logger.Trace("Found Active Directory entry: " + searchResult.Path);

                userNestedMembership.Add(accountName);

                DirectoryEntry theUser = searchResult.GetDirectoryEntry();
                theUser.RefreshCache(new[] { "tokenGroups" });

                foreach (byte[] resultBytes in theUser.Properties["tokenGroups"])
                {
                    // Search domain group's name and displayName:

                    var mySID = new SecurityIdentifier(resultBytes, 0);

                    _logger.Trace(() => string.Format("User '{0}' is a member of group with objectSid '{1}'.", accountName, mySID.Value));

                    DirectorySearcher sidSearcher = new DirectorySearcher(domainConnection);
                    sidSearcher.Filter = "(objectSid=" + mySID.Value + ")";
                    sidSearcher.PropertiesToLoad.Add("name");
                    sidSearcher.PropertiesToLoad.Add("displayname");

                    SearchResult sidResult = sidSearcher.FindOne();
                    if (sidResult != null)
                    {
                        string name = sidResult.Properties["name"][0].ToString();
                        userNestedMembership.Add(name);
                        _logger.Trace(() => string.Format("Added membership to group with name '{0}' for user '{1}'.", name, accountName));

                        var displayNameProperty = sidResult.Properties["displayname"];
                        if (displayNameProperty.Count > 0)
                        {
                            string displayName = displayNameProperty[0].ToString();
                            if (!string.Equals(name, displayName))
                            {
                                userNestedMembership.Add(displayName);
                                _logger.Trace(() => string.Format("Added membership to group with display name '{0}' for user '{1}'.", displayName, accountName));
                            }
                        }
                    }
                    else
                        _logger.Trace(() => string.Format("Cannot find the active directory entry for user's '{0}' parent group with objectSid '{1}'.", accountName, mySID.Value));
                }
            }
            else
                _logger.Trace(() => string.Format("Account name '{0}' not found on Active Directory for domain '{1}'.", accountName, Environment.UserDomainName));

            _performanceLogger.Write(stopwatch, "DomainPrincipalProvider.GetIdentityMembership() done.");
            return userNestedMembership;
        }
Esempio n. 50
0
        public void FindRequirements(ArrayList anKeys, string strSearchExpr, bool bUseRegEx,
                                     bool bSearchTag, bool bSearchName, bool bSearchText,
                                     bool bIgnoreCase,
                                     out SearchResult [] [] searchResult, out int [] anKeysOut)
        {
            ReqProRequirementPrx reqPrx;
            bool bFound;

            SearchResult []       res;
            string                strCmpStr;
            ArrayList             listKeysOut = new ArrayList();
            List <SearchResult[]> listSResult = new List <SearchResult[]>();

            res = new SearchResult [3];

            if (!bUseRegEx)
            {
                if (bIgnoreCase)
                {
                    strCmpStr = strSearchExpr.ToLower();
                }
                else
                {
                    strCmpStr = strSearchExpr;
                }
            }
            else
            {
                strCmpStr = strSearchExpr;
            }

            foreach (int nKey in anKeys)
            {
                bFound = false;
                reqPrx = GetRequirementPrx(nKey);
                if (reqPrx != null)
                {
                    res[0] = new SearchResult(reqPrx.Tag);
                    if (bSearchTag)
                    {
                        bFound |= FindInText(ref res[0], strCmpStr, bUseRegEx, bIgnoreCase);
                    }
                    res[1] = new SearchResult(reqPrx.Name);
                    if (bSearchTag)
                    {
                        bFound |= FindInText(ref res[1], strCmpStr, bUseRegEx, bIgnoreCase);
                    }
                    res[2] = new SearchResult(reqPrx.Text);
                    if (bSearchText)
                    {
                        bFound |= FindInText(ref res[2], strCmpStr, bUseRegEx, bIgnoreCase);
                    }
                    if (bFound)
                    {
                        listKeysOut.Add(nKey);
                        listSResult.Add(res);
                        res = new SearchResult[3];
                    }
                }
            }
            searchResult = listSResult.ToArray();

            anKeysOut = new int[listKeysOut.Count];
            for (int i = 0; i < listKeysOut.Count; i++)
            {
                anKeysOut[i] = (int)listKeysOut[i];
            }
        }
Esempio n. 51
0
        //或查询
        public List <SearchResult> LenuceOrSearch(string kw, int pageNo, int pageLen, out int recCount)
        {
            FSDirectory        directory = FSDirectory.Open(new DirectoryInfo(IndexPath), new NoLockFactory());
            IndexReader        reader    = IndexReader.Open(directory, true);
            IndexSearcher      searcher  = new IndexSearcher(reader);
            List <PhraseQuery> lstQuery  = new List <PhraseQuery>();
            List <string>      lstkw     = PanGuSplitWord(kw);//对用户输入的搜索条件进行拆分。

            foreach (string word in lstkw)
            {
                PhraseQuery query = new PhraseQuery();      //查询条件
                query.Slop = 100;                           //两个词的距离大于100(经验值)就不放入搜索结果,因为距离太远相关度就不高了
                query.Add(new Term("Content", word));       //contains("Content",word)

                PhraseQuery titleQuery = new PhraseQuery(); //查询条件
                titleQuery.Add(new Term("Title", word));

                lstQuery.Add(query);
                lstQuery.Add(titleQuery);
            }

            BooleanQuery bq = new BooleanQuery();

            foreach (var v in lstQuery)
            {
                //Occur.Should 表示 Or , Must 表示 and 运算
                bq.Add(v, Occur.SHOULD);
            }
            TopScoreDocCollector collector = TopScoreDocCollector.Create(1000, true);                //盛放查询结果的容器

            searcher.Search(bq, null, collector);                                                    //使用query这个查询条件进行搜索,搜索结果放入collector

            recCount = collector.TotalHits;                                                          //总的结果条数
            ScoreDoc[] docs = collector.TopDocs((pageNo - 1) * pageLen, pageNo * pageLen).ScoreDocs; //从查询结果中取出第m条到第n条的数据

            List <SearchResult> resultList = new List <SearchResult>();
            string msg   = string.Empty;
            string title = string.Empty;

            for (int i = 0; i < docs.Length; i++)          //遍历查询结果
            {
                int docId = docs[i].Doc;                   //拿到文档的id,因为Document可能非常占内存(思考DataSet和DataReader的区别)
                //所以查询结果中只有id,具体内容需要二次查询
                Document     doc    = searcher.Doc(docId); //根据id查询内容。放进去的是Document,查出来的还是Document
                SearchResult result = new SearchResult();
                result.Id = Convert.ToInt32(doc.Get("Id"));
                msg       = doc.Get("Content");//只有 Field.Store.YES的字段才能用Get查出来
                title     = doc.Get("Title");
                //将搜索的关键字高亮显示。
                foreach (string word in lstkw)
                {
                    title = title.Replace(word, "<span style='color:red;'>" + word + "</span>");
                }
                result.Msg        = CreateHightLight(kw, msg);
                result.Title      = title;
                result.CreateTime = Convert.ToDateTime(doc.Get("CreateTime"));
                result.Url        = "/Article/Details?Id=" + result.Id + "&kw=" + kw;
                resultList.Add(result);
            }
            return(resultList);
        }
Esempio n. 52
0
 /// <summary>
 /// The domain object constructure with AD operator and SearchResult params.
 /// </summary>
 /// <param name="adOperator">The AD operator.</param>
 /// <param name="searchResult">The SearchResult.</param>
 public DomainObject(IADOperator adOperator, SearchResult searchResult)
     : base(adOperator, searchResult)
 {
     this.groupPolicyMinimumPasswordLength = -1;
 }
Esempio n. 53
0
    protected override void loadDataFromConcierge(IConciergeAPIService proxy)
    {
        base.loadDataFromConcierge(proxy);

        Search s = new Search("DiscussionContents");

        s.AddOutputColumn("ID");
        s.AddOutputColumn("Name");
        s.AddOutputColumn("ContentType");
        s.AddOutputColumn("DiscussionPost_Count");
        s.AddOutputColumn("LastDiscussionPost");
        s.AddOutputColumn("LastDiscussionPost.Topic");
        s.AddOutputColumn("LastDiscussionPost.Name");
        s.AddOutputColumn("LastDiscussionPost.CreatedDate");
        s.AddOutputColumn("LastDiscussionPost.PostedBy.Name");
        s.AddOutputColumn("DiscussionBoard");
        s.AddOutputColumn("Forum");
        s.AddOutputColumn("DiscussionTopic");

        SearchOperationGroup sogActive = new SearchOperationGroup()
        {
            FieldName = "Forum.IsActive",
            GroupType = SearchOperationGroupType.Or
        };

        sogActive.Criteria.Add(Expr.IsBlank("Forum"));
        sogActive.Criteria.Add(Expr.Equals("Forum.IsActive", 1));

        s.AddCriteria(sogActive);

        if (!MembershipLogic.IsActiveMember())
        {
            SearchOperationGroup sogMembersOnly = new SearchOperationGroup()
            {
                FieldName = "Forum.MembersOnly",
                GroupType = SearchOperationGroupType.Or
            };
            sogMembersOnly.Criteria.Add(Expr.IsBlank("Forum"));
            sogMembersOnly.Criteria.Add(Expr.Equals("Forum.MembersOnly", false));
        }

        if (TargetDiscussionBoard != null)
        {
            s.AddCriteria(Expr.Equals("DiscussionBoard", TargetDiscussionBoard.ID));
        }

        if (targetForum != null)
        {
            s.AddCriteria(Expr.Equals("Forum", targetForum.ID));
        }

        if (targetDiscussionTopic != null)
        {
            s.AddCriteria(Expr.Equals("DiscussionTopic", targetDiscussionTopic.ID));
        }

        if (!string.IsNullOrWhiteSpace(Keywords))
        {
            s.AddCriteria(Expr.Contains("Keywords", Keywords));
        }

        SearchResult sr = proxy.GetSearchResult(s, PageStart, PAGE_SIZE);

        dtSearchResults = sr.Table;

        for (int i = 0; i < dtSearchResults.Columns.Count; i++)
        {
            dtSearchResults.Columns[i].ColumnName = dtSearchResults.Columns[i].ColumnName.Replace(".", "_");
        }

        SetCurrentPageFromResults(sr, hlFirstPage, hlPrevPage, hlNextPage, lNumPages, null, null,
                                  null, lCurrentPage);
    }
Esempio n. 54
0
        /// <summary>
        /// 取得データの取り込み
        /// </summary>
        /// <param name="message"></param>
        public override void OnReceivedResponseData(CommunicationObject message)
        {
            var       data = message.GetResultData();
            DataTable tbl  = (data is DataTable) ? (data as DataTable) : null;

            switch (message.GetMessageName())
            {
            case TabelNm:
                //Gridのバインド変数に代入
                SearchResult = tbl;

                DataRow r = null;
                //かな読みの条件で抽出
                if (!string.IsNullOrEmpty(かな読み))
                {
                    DataTable dt = SearchResult.Clone();

                    foreach (DataRow dtRow in SearchResult.Select("かな読み LIKE '%" + かな読み + "%'"))
                    {
                        r = dt.NewRow();
                        for (int n = 0; n < dtRow.ItemArray.Length; n++)
                        {
                            r[n] = dtRow[n];
                        }
                        dt.Rows.Add(r);
                    }
                    SearchResult = dt;
                }

                DataView view = new DataView(SearchResult);
                switch (OrderColumn_Copy.SelectedIndex)
                {
                case 0:         //コード
                default:
                    view.Sort = COLUM_ID;
                    break;

                case 1:         //商品名
                    view.Sort = COLUM_NAME;
                    break;

                case 2:         //商品よみ
                    view.Sort = COLUM_KANA;
                    break;
                }

                SearchResult             = view.ToTable();
                SearchGrid.SelectedIndex = -1;

                break;

            case TabelNm1:
                //Gridのバインド変数に代入
                SearchResult = tbl;

                DataRow r1 = null;
                //かな読みの条件で抽出
                if (!string.IsNullOrEmpty(かな読み))
                {
                    DataTable dt = SearchResult.Clone();

                    foreach (DataRow dtRow in SearchResult.Select("かな読み LIKE '%" + かな読み + "%'"))
                    {
                        r1 = dt.NewRow();
                        for (int n = 0; n < dtRow.ItemArray.Length; n++)
                        {
                            r1[n] = dtRow[n];
                        }
                        dt.Rows.Add(r1);
                    }
                    SearchResult = dt;
                }

                DataView view1 = new DataView(SearchResult);
                switch (OrderColumn_Copy.SelectedIndex)
                {
                case 0:         //コード
                default:
                    view1.Sort = COLUM_ID;
                    break;

                case 1:         //商品名
                    view1.Sort = COLUM_NAME;
                    break;

                case 2:         //商品よみ
                    view1.Sort = COLUM_KANA;
                    break;
                }

                SearchResult             = view1.ToTable();
                SearchGrid.SelectedIndex = -1;

                break;

            case TabelNm2:
                //Gridのバインド変数に代入
                SearchResult = tbl;

                DataRow r2 = null;
                //かな読みの条件で抽出
                if (!string.IsNullOrEmpty(かな読み))
                {
                    DataTable dt = SearchResult.Clone();

                    foreach (DataRow dtRow in SearchResult.Select("かな読み LIKE '%" + かな読み + "%'"))
                    {
                        r2 = dt.NewRow();
                        for (int n = 0; n < dtRow.ItemArray.Length; n++)
                        {
                            r2[n] = dtRow[n];
                        }
                        dt.Rows.Add(r2);
                    }
                    SearchResult = dt;
                }
                DataView view2 = new DataView(SearchResult);
                switch (OrderColumn_Copy.SelectedIndex)
                {
                case 0:         //コード
                default:
                    view2.Sort = COLUM_ID;
                    break;

                case 1:         //商品名
                    view2.Sort = COLUM_NAME;
                    break;

                case 2:         //商品よみ
                    view2.Sort = COLUM_KANA;
                    break;
                }

                SearchResult             = view2.ToTable();
                SearchGrid.SelectedIndex = -1;

                break;

            case TabelNm3:
                //Gridのバインド変数に代入
                SearchResult = tbl;

                DataRow r3 = null;
                //かな読みの条件で抽出
                if (!string.IsNullOrEmpty(かな読み))
                {
                    DataTable dt = SearchResult.Clone();

                    foreach (DataRow dtRow in SearchResult.Select("かな読み LIKE '%" + かな読み + "%'"))
                    {
                        r3 = dt.NewRow();
                        for (int n = 0; n < dtRow.ItemArray.Length; n++)
                        {
                            r3[n] = dtRow[n];
                        }
                        dt.Rows.Add(r3);
                    }
                    SearchResult = dt;
                }
                DataView view3 = new DataView(SearchResult);
                switch (OrderColumn_Copy.SelectedIndex)
                {
                case 0:         //コード
                default:
                    view3.Sort = COLUM_ID;
                    break;

                case 1:         //商品名
                    view3.Sort = COLUM_NAME;
                    break;

                case 2:         //商品よみ
                    view3.Sort = COLUM_KANA;
                    break;
                }

                SearchResult             = view3.ToTable();
                SearchGrid.SelectedIndex = -1;

                break;

            case TabelNm4:
                //Gridのバインド変数に代入
                SearchResult = tbl;

                DataRow r4 = null;
                //かな読みの条件で抽出
                if (!string.IsNullOrEmpty(かな読み))
                {
                    DataTable dt = SearchResult.Clone();

                    foreach (DataRow dtRow in SearchResult.Select("かな読み LIKE '%" + かな読み + "%'"))
                    {
                        r4 = dt.NewRow();
                        for (int n = 0; n < dtRow.ItemArray.Length; n++)
                        {
                            r4[n] = dtRow[n];
                        }
                        dt.Rows.Add(r4);
                    }
                    SearchResult = dt;
                }
                DataView view4 = new DataView(SearchResult);
                switch (OrderColumn_Copy.SelectedIndex)
                {
                case 0:         //コード
                default:
                    view4.Sort = COLUM_ID;
                    break;

                case 1:         //商品名
                    view4.Sort = COLUM_NAME;
                    break;

                case 2:         //商品よみ
                    view4.Sort = COLUM_KANA;
                    break;
                }

                SearchResult             = view4.ToTable();
                SearchGrid.SelectedIndex = -1;

                break;

            default:
                break;
            }
            // 追加 ST 取引停止区分をグリッドデータとして持たせた為
            if (SearchResult == null)
            {
                return;
            }
            else
            {
                SearchGrid.SelectedIndex = -1;
                Suspension();
            }
            // 追加 ED
        }
Esempio n. 55
0
        public ActionResult GetJobQuotes(QuotesSearchViewModel model)
        {
            if (model.SortOrder == null)
            {
                model.SortOrder = "Latest Listing";
            }
            var data = db.JobQuote.Where(x => x.Status.ToLower() == "opening")
                       .Select(x => new {
                Model = new JobQuoteModel
                {
                    Id           = x.Id,
                    JobRequestId = x.JobRequestId,
                    Amount       = x.Amount,
                    Status       = x.Status,
                    Note         = x.Note,
                    IsViewed     = x.IsViewed,
                    MediaFiles   = x.JobQuoteMedia.Select(y => new MediaModel
                    {
                        Id          = y.Id,
                        OldFileName = y.FileName.Substring(36),
                        NewFileName = y.FileName,
                    }).ToList(),
                },
                CreatedOn    = x.CreatedOn,
                ProviderName = x.ServiceProvider != null ? x.ServiceProvider.Person != null ? x.ServiceProvider.Person.FirstName : "" : "",
                CompanyName  = x.ServiceProvider != null ? x.ServiceProvider.Company != null ? x.ServiceProvider.Company.Name : "" : "",
            });

            if (model.MarketJobId.HasValue)
            {
                data = data.Where(x => x.Model.JobRequestId == model.MarketJobId);
                var mJob = db.TenantJobRequest.FirstOrDefault(x => x.Id == model.MarketJobId);
                model.MarketJob = mJob.MapTo <MarketJobModel>();
            }
            var allItems = data.OrderByDescending(x => x.CreatedOn).ToPagedList(model.Page, 10);

            switch (model.SortOrder)
            {
            case "Company (A-Z)":
                data = data.OrderBy(s => s.CompanyName);
                break;

            case "Company (Z-A)":
                data = data.OrderByDescending(s => s.CompanyName);
                break;

            case "Lowest Amount":
                data = data.OrderBy(s => s.Model.Amount);
                break;

            case "Higest Amount":
                data = data.OrderByDescending(s => s.Model.Amount);
                break;

            default:
                data = data.OrderByDescending(s => s.Model.Amount);
                break;
            }
            if (!String.IsNullOrWhiteSpace(model.SearchString))
            {
                SearchTool searchTool   = new SearchTool();
                int        searchType   = searchTool.CheckDisplayType(model.SearchString);
                string     formatString = searchTool.ConvertString(model.SearchString);

                switch (searchType)
                {
                case 1:
                    data = data.Where(x => x.Model.Amount.ToString() == formatString ||
                                      x.CompanyName.ToLower().StartsWith(formatString) ||
                                      x.Model.Note.ToLower().StartsWith(formatString));
                    break;

                case 2:
                    data = data.Where(x => x.Model.Amount.ToString() == formatString ||
                                      x.CompanyName.ToLower().EndsWith(formatString) ||
                                      x.Model.Note.ToLower().EndsWith(formatString));
                    break;

                case 3:
                    double number;
                    if (Double.TryParse(formatString, out number))
                    {
                        data = data.Where(y => double.Parse(y.Model.Amount.ToString().Split(',')[0]) <= double.Parse(formatString.Split(',')[0]));
                    }
                    else
                    {
                        data = data.Where(y => y.Model.Note.ToLower().Contains(formatString));
                    }
                    break;
                }
            }
            var items = data.ToPagedList(model.Page, 10);
            var count = items.Count;

            items = count == 0 ? allItems : items;
            items.ToList().ForEach(x => x.Model.MediaFiles.ForEach(y => y.InjectMediaModelViewProperties()));
            var result = new SearchResult {
                SearchCount = items.Count, Items = count == 0 ? allItems : items
            };

            model.PagedInput = new PagedInput
            {
                ActionName      = "GetJobQuotes",
                ControllerName  = "Home",
                PagedLinkValues = new RouteValueDictionary(new { SortOrder = model.SortOrder, SearchString = model.SearchString, MarketJobId = model.MarketJobId })
            };
            var formInputs = new List <SearchInput>();

            formInputs.Add(new SearchInput {
                Name = "MarketJobId", Value = model.MarketJobId.ToString()
            });
            model.InputValues = formInputs;
            var rvr        = new RouteValueDictionary(new { SearchString = model.SearchString, MarketJobId = model.MarketJobId });
            var sortOrders = new List <SortOrderModel>();

            sortOrders.Add(new SortOrderModel {
                SortOrder = "Company (A-Z)", ActionName = "GetJobQuotes", RouteValues = rvr.AddRouteValue("SortOrder", "Name")
            });
            sortOrders.Add(new SortOrderModel {
                SortOrder = "Company (Z-A)", ActionName = "GetJobQuotes", RouteValues = rvr.AddRouteValue("SortOrder", "Company (Z-A)")
            });
            sortOrders.Add(new SortOrderModel {
                SortOrder = "Lowest Amount", ActionName = "GetJobQuotes", RouteValues = rvr.AddRouteValue("SortOrder", "Lowest Amount")
            });
            sortOrders.Add(new SortOrderModel {
                SortOrder = "Higest Amount", ActionName = "GetJobQuotes", RouteValues = rvr.AddRouteValue("SortOrder", "Higest Amount")
            });
            model.SortOrders  = sortOrders;
            model.SearchCount = result.SearchCount;
            if (String.IsNullOrWhiteSpace(model.SearchString))
            {
                model.Page = 1;
            }
            model.PageCount = result.Items.PageCount;
            model.Items     = result.Items;
            var currentJob = db.TenantJobRequest.Where(x => x.Id == model.MarketJobId).FirstOrDefault();

            model.Address = currentJob.Property.Address?.ToAddressString() ?? "";
            return(View(model));
        }
Esempio n. 56
0
 /// <summary>Initializes a new instance of the NavigateEventArgs class.</summary>
 /// <param name="result">The SearchResult to navigate to.</param>
 internal NavigateEventArgs(SearchResult result)
 {
     this.Result = result;
 }
Esempio n. 57
0
        public UserRecord SearchUser(string userId)
        {
            //user id must supplied to search
            if (userId.Length < 1)
            {
                throw (new Exception("Please provide a UserId to search."));
            }

            UserRecord ldapUser = new UserRecord();

            DirectoryEntry dirEntry = new DirectoryEntry(_serverPath + "/" + _searchPath);

            dirEntry.AuthenticationType = AuthenticationTypes.ServerBind;
            DirectorySearcher dirSearch = new DirectorySearcher(dirEntry);

            dirSearch.Filter = "(" + _userAttr + "=" + userId + ")";;

            dirSearch.PropertiesToLoad.Add("givenname");
            dirSearch.PropertiesToLoad.Add("sn");
            dirSearch.PropertiesToLoad.Add("mail");
            dirSearch.PropertiesToLoad.Add("departmentnumber");
            dirSearch.PropertiesToLoad.Add("departmentname");
            dirSearch.PropertiesToLoad.Add("initials");
            dirSearch.PropertiesToLoad.Add("manager");

            SearchResult sr = dirSearch.FindOne();

            if (null != sr)
            {
                foreach (string propKey in sr.Properties.PropertyNames)
                {
                    ResultPropertyValueCollection propItems = sr.Properties[propKey];

                    foreach (Object propItem in propItems)
                    {
                        switch (propKey)
                        {
                        case "givenname":
                            ldapUser.FirstName = propItem.ToString();
                            break;

                        case "sn":
                            ldapUser.LastName = propItem.ToString();
                            break;

                        case "mail":
                            ldapUser.Email = propItem.ToString();
                            break;

                        case "departmentnumber":
                            ldapUser.OrganizationCode = propItem.ToString();
                            break;

                        case "departmentname":
                            ldapUser.DepartmentName = propItem.ToString();
                            break;

                        case "manager":
                            string _manager = propItem.ToString();
                            int    _i       = _manager.IndexOf("=");
                            int    _j       = _manager.IndexOf(",");
                            ++_i;
                            _j = _j - 4;
                            ldapUser.ManagerId = _manager.Substring(_i, _j);
                            break;

                        default:
                            break;
                        }
                    }
                }
                return(ldapUser);
            }
            else
            {
                //throw user not found exception
                throw(new Exception("User Not Found!"));
            }
        }
Esempio n. 58
0
        public void GetUser()
        {
            try
            {
                using (var entry = new DirectoryEntry())
                {
                    entry.Path = $"LDAP://{Domain}";
                    entry.AuthenticationType = AuthenticationTypes.Secure;
                    using (var searcher = new DirectorySearcher(entry))
                    {
                        searcher.CacheResults = false;
                        searcher.Filter       = $"(&(objectClass=user)(|(cn={UserName})(sAMAccountName={UserName})))";
                        SearchResult result = searcher.FindOne();

                        if (result != null)
                        {
                            DirectoryEntry directoryObject = result.GetDirectoryEntry();

                            if (directoryObject.Properties["distinguishedName"].Value != null)
                            {
                                DistinguishedName = "LDAP://" + directoryObject.Properties["distinguishedName"].Value.ToString();
                            }
                            if (directoryObject.Properties["displayname"].Value != null)
                            {
                                Displayname = directoryObject.Properties["displayname"].Value.ToString();
                            }
                            if (directoryObject.Properties["mail"].Value != null)
                            {
                                Mail = directoryObject.Properties["mail"].Value.ToString();
                            }
                            if (directoryObject.Properties["SAMAccountName"].Value != null)
                            {
                                SAMAccountName = directoryObject.Properties["SAMAccountName"].Value.ToString();
                            }
                            if (directoryObject.Properties["givenName"].Value != null)
                            {
                                GivenName = directoryObject.Properties["givenName"].Value.ToString();
                            }
                            if (directoryObject.Properties["IsAccountLocked"].Value != null)
                            {
                                IsAccountLocked = Convert.ToBoolean(directoryObject.Properties["IsAccountLocked"].Value);
                            }
                            if (directoryObject.Properties["badPwdCount"].Value != null)
                            {
                                BadPwdCount = Convert.ToInt32(directoryObject.Properties["badPwdCount"].Value);
                            }
                            if (directoryObject.Properties["PasswordExpirationDate"].Value != null)
                            {
                                if (PasswordExpirationDate != null)
                                {
                                    PasswordExpirationDate = Convert.ToDateTime(directoryObject.Properties["PasswordExpirationDate"].Value);
                                }
                            }
                            if (directoryObject.Properties["lastLogin"].Value != null)
                            {
                                LastLogin = Convert.ToDateTime(directoryObject.Properties["lastLogin"].Value);
                            }
                            if (directoryObject.Properties["userAccountControl"].Value != null)
                            {
                                switch (Convert.ToInt32(directoryObject.Properties["userAccountControl"].Value))
                                {
                                case 512:
                                    AccountStatus = "Enabled";
                                    break;

                                case 514:
                                    AccountStatus = "Disabled";
                                    break;

                                case 544:
                                    AccountStatus = "Account Enabled - User required to change password at next logon";
                                    break;

                                case 4096:
                                    AccountStatus = "Workstation/Server";
                                    break;

                                case 66048:
                                    AccountStatus = "Enabled, password never expires";
                                    break;

                                case 66050:
                                    AccountStatus = "Disabled, password never expires";
                                    break;

                                case 532480:
                                    AccountStatus = "Domain controller";
                                    break;

                                case 262656:
                                    AccountStatus = "Smart Card logon required";
                                    break;

                                default:
                                    AccountStatus = "Unavailable";
                                    break;
                                }
                            }

                            // SID
                            if (directoryObject.Properties["objectSid"].Value != null)
                            {
                                dynamic sidInBytes = (byte[])directoryObject.Properties["objectSid"].Value;
                                dynamic sid        = new System.Security.Principal.SecurityIdentifier(sidInBytes, 0);
                                ObjectSid = sid.ToString;
                            }



                            //    'Password expires
                            //    Const MAXPASSWDAGE As Integer = 90
                            //    'PasswordLastChanged
                            //    Dim liPasswdLastSet As LargeInteger = TryCast(directoryObject.Properties("pwdLastSet").Value, LargeInteger)

                            //    'Convert the highorder/loworder parts to a long
                            //    Dim datePasswdLastSet As Long = ((CLng(liPasswdLastSet.HighPart) << 32) + CLng(liPasswdLastSet.LowPart))

                            //    'and convert it from FileTime to DateTime string
                            //    Dim datePasswdLastSetVal As DateTime = DateTime.FromFileTime(datePasswdLastSet)

                            //    Try
                            //        If directoryObject.Properties("pwdLastSet").Value IsNot Nothing Then
                            //            "Password Expires", datePasswdLastSetVal.AddDays(MAXPASSWDAGE).ToString()
                            //            "Password last changed", DateTime.FromFileTime(datePasswdLastSet).ToString()
                            //            "Password age", (CInt((DateTime.Now.Ticks / 1000 - datePasswdLastSetVal.Ticks / 1000) / (1000 * 3600 * 24)) / 10).ToString() + " days"
                            //        Else
                            //            "Password Expires", ""
                            //            "Password last changed", ""
                            //            "Password age", ""
                            //        End If
                            //    Catch ErrorMessage As Exception
                            //        MessageBox.Show("Error querying PWDLastSet: " + ErrorMessage)
                            //    End Try

                            //    'AccountExpiration
                            //    'return the expiration date if account is set to expire.
                            //    'accounts not set to expire will have 12/31/1600 7:00:00 PM

                            //    Dim liAcctExpiration As LargeInteger = TryCast(uEntry.Properties("accountExpires").Value, LargeInteger)

                            //    'Convert the highorder/loworder parts to a long
                            //    Dim dateAcctExpiration As Long = ((CLng(liAcctExpiration.HighPart) << 32) + CLng(liAcctExpiration.LowPart))

                            //    'and convert it from FileTime to DateTime
                            //    Dim strAcctExpiration As String = DateTime.FromFileTime(dateAcctExpiration).ToString()
                            //    Try
                            //        If directoryObject.Properties("accountExpires").Value IsNot Nothing Then
                            //            If strAcctExpiration.IndexOf("1600") > 0 Then
                            //                "Account Expires", "No"
                            //            Else
                            //                "Account Expires", strAcctExpiration
                            //            End If
                            //        Else
                            //            "Account Expires", ""
                            //        End If
                            //    Catch ErrorMessage As Exception
                            //        MessageBox.Show("Error querying the Account Expiration: " + ErrorMessage)
                            //    End Try
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
        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);
        }
Esempio n. 60
0
        /// <summary>
        /// Given a string, returns start and end points in the buffer that contain that text
        /// </summary>
        public int FindText(string txt)
        {
            LastSearch          = txt;
            CurrentSearchResult = -1;

            if (string.IsNullOrEmpty(txt))
            {
                LastSearchResults = Array.Empty <SearchResult> ();
                return(0);
            }

            // simple search for now, we might be able to just do a single scan of the buffer
            // but if we want to support regex then this might be the better way
            // a quick look at xterm.js and they still get a copy of the buffer and translate it to string
            // so this is similar, maybe(?) caching more than we ultimately need.
            var results = new List <SearchResult> ();

            int baseLineIndex = 0;
            int baseCount     = 0;
            var index         = Text.IndexOf(txt, 0, StringComparison.CurrentCultureIgnoreCase);

            while (index >= 0)
            {
                // found a result
                var result = new SearchResult();
                // whats the start and end pos of this text
                // we can assume that it's on the same line, unless we are doing a regex because
                // the user can't enter a \n as part of the seach term without regex

                // count the lines up to index
                int count = baseCount;
                for (int i = baseLineIndex; i < lines.Length; i++)
                {
                    count += lines [i].Length;
                    if (count > index)
                    {
                        // found text is on line i
                        // the x position is the delta between the line start and index
                        // we can assume for now that the end is on the same line, since we do not yet support regex

                        int lineStartCount = count - lines [i].Length;

                        // we need to offset the points depending on whether the line fragment is wrapped or not
                        int          startFragmentIndex = lines [i].GetFragmentIndexForPosition(index - lineStartCount);
                        LineFragment startFragment      = lines [i].GetFragment(startFragmentIndex);

                        // number of chars before this fragment, but on this line
                        int startOffset = 0;
                        for (int fi = 0; fi < startFragmentIndex; fi++)
                        {
                            startOffset += lines [i].GetFragment(fi).Length;
                        }


                        result.Start = new Point(index - lineStartCount - startOffset, startFragment.Line);

                        int          endFragmentIndex = lines [i].GetFragmentIndexForPosition(index - lineStartCount + txt.Length - 1);
                        LineFragment endFragment      = lines [i].GetFragment(endFragmentIndex);

                        int endOffset = 0;
                        for (int fi = 0; fi < endFragmentIndex; fi++)
                        {
                            endOffset += lines [i].GetFragment(fi).Length;
                        }

                        result.End = new Point(index - lineStartCount + txt.Length - endOffset, endFragment.Line);

                        // now, we need to fix up the end points because we might be on wrapped line
                        // which line fragment is the text on

                        results.Add(result);

                        break;
                    }

                    // update base counts so that next time we loop we don't have to count these lines again
                    baseCount += lines [i].Length;
                    baseLineIndex++;
                }

                // search again
                index = Text.IndexOf(txt, index + txt.Length, StringComparison.CurrentCultureIgnoreCase);
            }

            LastSearchResults   = results.ToArray();
            CurrentSearchResult = -1;

            return(LastSearchResults.Length);
        }