/// <summary> /// 添加某一用户的检索历史 /// </summary> /// <param name="sp"></param> /// <returns></returns> public bool addSearchHis(SearchPattern sp) { FileMode f; string hisFilePath = UserPath + "\\" + sp.DbType; string hisFile = hisFilePath + "\\SearchHistory.lst"; //创建目录 if (!Directory.Exists(hisFilePath)) { Directory.CreateDirectory(hisFilePath); } if (File.Exists(hisFile)) { f = FileMode.Append; } else { f = FileMode.OpenOrCreate; } //创建流 using (StreamWriter sw = new StreamWriter(new FileStream(hisFile, f))) { sw.WriteLine("(" + sp.SearchNo + ")" + sp.Pattern); } return true; }
/// <summary> /// Return True if the string to test matches the value according to sthe pattern /// </summary> public bool Match(string stringToTest, string value, SearchPattern pattern) { switch (pattern) { case SearchPattern.Contains: return stringToTest.Contains(value); case SearchPattern.StartsWith: return stringToTest.StartsWith(value); case SearchPattern.Exact: return stringToTest.Equals(value); } return false; }
/// <summary> /// Returns a list of object in an area specified by the search pattern. /// SearchPattern.Touching -> you are in direct contact with an object /// </summary> public static IEnumerable<Sprite> GetObjects(Sprite origin, SearchPattern pattern) { var objectsFound = new List<Sprite>(); foreach (var obj in allObjects) { // Exclude the searching object from the list of found objects if (obj.GetType().Name != origin.GetType().Name) { Point overlap = OverLap(origin.Rectangle, obj.Rectangle); if (pattern == SearchPattern.Touching) { if (overlap.X <= tileSize / 4 && overlap.Y <= tileSize / 4) { objectsFound.Add(obj); } } else if (pattern == SearchPattern.Right) { if (overlap.Y <= 0 && origin.Rectangle.Right < obj.Rectangle.Left && NoWallsBetween(origin, obj)) { objectsFound.Add(obj); } } else if (pattern == SearchPattern.Left && NoWallsBetween(origin, obj)) { if (overlap.Y <= 0 && origin.Rectangle.Left > obj.Rectangle.Right && NoWallsBetween(origin, obj)) { objectsFound.Add(obj); } } else if (pattern == SearchPattern.Up) { if (overlap.X <= 0 && origin.Rectangle.Top > obj.Rectangle.Bottom && NoWallsBetween(origin, obj)) { objectsFound.Add(obj); } } else if (pattern == SearchPattern.Down) { if (overlap.X <= 0 && origin.Rectangle.Bottom < obj.Rectangle.Top && NoWallsBetween(origin, obj)) { objectsFound.Add(obj); } } } } return objectsFound; }
/// <summary> /// 得到某一结果文件的某一页数据 并按某一字段排序 /// </summary> /// <param name="sp">检索式</param> /// <param name="PageIndex">要取的页数</param> /// <param name="PageSize">页数大小</param> /// <param name="SortExpression">排序字段</param> /// <returns>list(int)</int></returns> public IEnumerable GetResultList(SearchPattern sp, int PageSize, int PageIndex, string SortExpression) { try { ResultServices res = new ResultServices(); List<int> lstNo = res.GetResultListByEnd(sp, PageSize, PageIndex, SortExpression); IEnumerable ien = GetResult(lstNo); return ien; } catch (Exception ex) { logger.Error(ex.ToString()); return null; } }
/// <summary> /// Returns all the client of the bank where filled in fields (name and/or firstname) matches with the pattern. /// If nothing there is no criteria, returns all the client /// </summary> /// <returns></returns> public IList<Client> FindClients(string firstname, string lastname, SearchPattern pattern) { Expression<Func<Client,bool>> expression = null; if (string.IsNullOrEmpty(firstname) && string.IsNullOrEmpty(lastname)) expression = (x => true); if (!string.IsNullOrEmpty(firstname) && string.IsNullOrEmpty(lastname)) expression = (x => _helper.Match(x.FirstName, firstname, pattern)); if (string.IsNullOrEmpty(lastname) && !string.IsNullOrEmpty(lastname)) expression = (x => _helper.Match(x.LastName, lastname, pattern)); if (!string.IsNullOrEmpty(lastname) && !string.IsNullOrEmpty(lastname)) expression = (x => _helper.Match(x.LastName, lastname, pattern) && _helper.Match(x.FirstName, firstname, pattern)); return _clientRepository.Find(expression); }
protected virtual void OnButton1Clicked(object sender, System.EventArgs e) { string expresion = this.entrExpresion.Text; if (!String.IsNullOrEmpty(expresion)) { SearchPattern sp = GetSearchPattern(); if (cbPlace.Active == 0) { MainClass.MainWindow.EditorNotebook.SearchNext(); } else { sp.ReplaceExpresion = null; StartFindReplaceInFiles(sp); } } }
/// <summary> /// Gets the path of the <see cref="FileExtensions.Nuspec"/> file in the directory. /// </summary> public static NuspecFilePath GetNuspecFilePath(DirectoryPath versionDirectoryPath) { var searchPattern = SearchPattern.AllFilesWithFileExtension(FileExtensions.Nuspec); var nuspecFilePaths = versionDirectoryPath.EnumerateFiles(searchPattern).ToArray(); if (nuspecFilePaths.Length < 1) { throw new IOException($"No {FileExtensions.Nuspec} file found in version directory: {versionDirectoryPath}"); } if (nuspecFilePaths.Length > 1) { throw new IOException($"More than one {FileExtensions.Nuspec} file found in version directory: {versionDirectoryPath}"); } var nuspecFilePath = nuspecFilePaths.First().AsNuspecFilePath(); return(nuspecFilePath); }
public string[] GetFiles(string path) { var result = new List <string>(); var fullPath = Path.GetFullPath(Path.Combine(path, RelativePath)); if (IsWildcard) { var split = SearchPattern.Split(';'); foreach (var s in split) { var files = Directory.GetFiles(fullPath, s, RecursiveSearch ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly); foreach (var file in files) { var excluded = Exclusions.Any(x => file.Contains(x)); if (!excluded) { result.Add(file); } } } } else { var files = Directory.GetFiles(fullPath, SearchPattern, RecursiveSearch ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly); foreach (var file in files) { var excluded = Exclusions.Any(x => file.Contains(x)); if (!excluded) { result.Add(file); } } } return(result.ToArray()); }
public string getResultFilePath(SearchPattern sp, bool _bExistsAndCreat) { string ResultFilePath; string ResultFileDir; //如果结果文件已经存在 直接返回路径 if (!string.IsNullOrEmpty(sp.StrCnpFile) && sp.StrCnpFile.EndsWith(".CNP")) { return strDY_CnpFileBasePath + "\\" + sp.StrCnpFile; } else { //如果没有 去Set×××目录下合成 新的***.cnp文件 ResultFilePath = string.Format(resultfile, CprsConfig.GetUserPath(sp.UserId, sp.GroupName), Enum.GetName(typeof(SearchDbType), sp.DbType), sp.SearchNo); if (_bExistsAndCreat && !File.Exists(ResultFilePath)) { ResultFileDir = string.Format(resultfiledir, CprsConfig.GetUserPath(sp.UserId, sp.GroupName), Enum.GetName(typeof(SearchDbType), sp.DbType), sp.SearchNo); string[] files = Directory.GetFiles(ResultFileDir, "*.CNP",SearchOption.AllDirectories); byte[] by; int readLength; using (FileStream fsw = new FileStream(ResultFilePath, FileMode.CreateNew, FileAccess.Write)) { foreach (string f in files) { if (File.Exists(f)) { using (FileStream fsr = new FileStream(f, FileMode.Open, FileAccess.Read)) { if (fsr.Length > 0) { by = new byte[fsr.Length]; readLength = fsr.Read(by, 0, (int)fsr.Length); fsw.Write(by, 0, readLength); } } } } } } return ResultFilePath; } }
RowReadHierarchical[] Files(DirectoryInfo di, IRowReceive parent) { var ret = new List <RowReadHierarchical>(); foreach (var searchSplitPattern in SearchPattern.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { foreach (var file in di.EnumerateFiles(searchSplitPattern)) { var item = new RowReadHierarchical(); item.Values.Add("Name", file.Name); item.Values.Add("FullName", file.FullName); item.Values.Add("RowType", "file"); item.Values.Add("CreationTimeUtc", file.CreationTimeUtc); item.Values.Add("LastAccessTimeUtc", file.LastAccessTimeUtc); item.Values.Add("LastWriteTimeUtc", file.LastWriteTimeUtc); item.Parent = parent as IRowReceiveHierarchicalParent; ret.Add(item); } } return(ret.ToArray()); }
public IEnumerable <ExternalLink> ParseRevisionPart(Match remoteMatch, string part, GitRevision revision) { if (SearchPattern.IsNullOrEmpty() || SearchPatternRegex.Value == null || part == null) { yield break; } IList <Match> allMatches = new List <Match>(); MatchCollection matches = SearchPatternRegex.Value.Matches(part); for (var i = 0; i < matches.Count; i++) { var match = matches[i]; if (match.Success) { if (NestedSearchPattern.IsNullOrEmpty()) { allMatches.Add(match); } else if (NestedSearchPatternRegex.Value != null && match.Value != null) { MatchCollection nestedMatches = NestedSearchPatternRegex.Value.Matches(match.Value); for (var n = 0; n < nestedMatches.Count; n++) { allMatches.Add(nestedMatches[n]); } } } } foreach (var match in allMatches.Where(m => m.Success)) { foreach (var format in LinkFormats) { yield return(format.ToGitExtLink(remoteMatch, match, revision)); } } }
// ---------------------------------------------- // Search API // ---------------------------------------------- /// <inheritdoc /> protected override IEnumerable <UPath> EnumeratePathsImpl(UPath path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget) { SearchPattern.Parse(ref path, ref searchPattern); var entries = new SortedSet <UPath>(); var fileSystems = new List <IFileSystem>(); if (Fallback != null) { fileSystems.Add(Fallback); } // Query all filesystems just once fileSystems.AddRange(_fileSystems); for (var i = fileSystems.Count - 1; i >= 0; i--) { var fileSystem = fileSystems[i]; if (!fileSystem.DirectoryExists(path)) { continue; } foreach (var item in fileSystem.EnumeratePaths(path, searchPattern, searchOption, searchTarget)) { if (entries.Contains(item)) { continue; } entries.Add(item); } } // Return entries foreach (var entry in entries) { yield return(entry); } }
protected virtual void OnEntrExpresionKeyReleaseEvent(object o, Gtk.KeyReleaseEventArgs args) { //if(cbPlace.Active != 0) return; if (args.Event.Key == Gdk.Key.Return) { string expresion = entrExpresion.Text; if (!String.IsNullOrEmpty(expresion)) { SearchPattern sp = GetSearchPattern(); if (cbPlace.Active == 0) { MainClass.MainWindow.EditorNotebook.SearchNext(); } else { sp.ReplaceExpresion = null; StartFindReplaceInFiles(sp); } } } }
/// <summary> /// Returns true if ComDayCqWcmDesignimporterImplEntryPreprocessorImplProperties instances are equal /// </summary> /// <param name="other">Instance of ComDayCqWcmDesignimporterImplEntryPreprocessorImplProperties to be compared</param> /// <returns>Boolean</returns> public bool Equals(ComDayCqWcmDesignimporterImplEntryPreprocessorImplProperties other) { if (other is null) { return(false); } if (ReferenceEquals(this, other)) { return(true); } return (( SearchPattern == other.SearchPattern || SearchPattern != null && SearchPattern.Equals(other.SearchPattern) ) && ( ReplacePattern == other.ReplacePattern || ReplacePattern != null && ReplacePattern.Equals(other.ReplacePattern) )); }
/// <summary> /// Returns all boundaries matching the pattern in a text /// </summary> /// <param name="pattern">Search pattern</param> /// <param name="text">Text</param> /// <returns>List of boundaries</returns> private List <Boundary> MatchPattern(SearchPattern pattern, string text) { List <Boundary> matchList = new List <Boundary>(); MatchCollection matches = pattern.Expression.Matches(text); if (matches.Count > 0) { foreach (Match m in matches) { Boundary bound = new Boundary() { Index = m.Index, Length = m.Length }; if (ScopeMatch(pattern, bound, text)) { matchList.Add(bound); } } } return(matchList); }
internal void SetCurrentPath(BasePath bp) { //foreach(BasePath path in this.backupRootDrive.paths){ var pathSnapshot = backupRootDrive.Snapshot; //Console.WriteLine("SetCurrentPath() : basepath="+bp.Path+",pathSnapshot.Name="+pathSnapshot.Name+", pathSnapshot.Path="+pathSnapshot.Path); //currentPath = bp.Path; currentPath = bp; // handle unix special case of '/' if (pathSnapshot.Path == "/" /*&& (this.backupRootDrive.SystemDrive.MountPoint == this.backupRootDrive.SystemDrive.OriginalMountPoint)*/) { snapshottedPath = pathSnapshot.MountPoint + bp.Path; } else { if (!pathSnapshot.MountPoint.EndsWith("" + Path.DirectorySeparatorChar)) { pathSnapshot.MountPoint += Path.DirectorySeparatorChar; } snapshottedPath = bp.Path.Replace(pathSnapshot.Path, pathSnapshot.MountPoint /*+Path.DirectorySeparatorChar*/); } Logger.Append(Severity.TRIVIA, "Handler for FS " + backupRootDrive.Snapshot.MountPoint + " : Path " + currentPath.Path + " replaced by " + snapshottedPath + " in " + bp.Path); fsprov = FSEnumeratorProvider.GetFSEnumeratorProvider().GetFSEnumerator(snapshottedPath); if (itemIterator == null) // initialize on first Basepath. For next Basepaths, Calling SetCurrentPath() is enough { itemIterator = GetFilesToBackup().GetEnumerator(); } //Console.WriteLine("SetCurrentPath() : got enumerator for "+snapshottedPath); includeSp = new SearchPattern(bp.IncludePolicy, true); excludeSp = new SearchPattern(bp.ExcludePolicy, false); //Console.WriteLine("SetCurrentPath() : got search pattern"+Environment.NewLine); }
/// <summary> /// 解析检索式 /// </summary> public void Init() { _Result = new Result(); int index; char PreOperator = ' '; int PreOperatorIndex = 0; int tmpindx = 0; ///堆栈 用来验证括号是否成对出现 System.Collections.Generic.Stack<char> stKuoHao = new Stack<char>(); char[] chrcommand; string Command = SearchCommand.Replace("F XX ", "").Replace("F YY ", ""); if (Command.StartsWith("F ")) { Command = Command.TrimStart("F ".ToCharArray()).Trim(); } //没有括号 判断有没有+-*运算 if (Command.IndexOf("+") < 0 && Command.IndexOf("*") < 0 && Command.IndexOf("-") < 0) //最简单的检索命令 { #region 没有括号 判断有没有+-*运算 的简单检索式 //F XX 20080101/GN Command = Command.Trim().TrimStart('(').TrimEnd(')'); index = Command.LastIndexOf("/"); if (index > 0) { #region 20080101/GN if (Command.Substring(0, 2) == "IC" || Command.Substring(0, 2) == "EC") { SearchEnter = Command.Substring(0, 2); SearchValue = Command.Substring(2).Trim().Replace("/", "").ToUpper(); } else { SearchEnter = Command.Substring(index + 1); SearchValue = Command.Substring(0, index).Trim().Replace("/", "").ToUpper(); } #endregion } else { #region GN 20080101 SearchEnter = Command.Substring(0, 2); SearchValue = Command.Substring(2).Trim().ToUpper(); #endregion } #region 默认前方一直的检索入口有 switch (SearchEnter) { case "AN": case "PN": case "GN": case "IC": case "EC": case "AD": case "PD": case "GD": case "PR": case "IN": case "PA": SearchValue = SearchValue.TrimEnd('$'); IsLeft = true; break; default: if (SearchValue.EndsWith("$")) { SearchValue = SearchValue.TrimEnd('$'); IsLeft = true; } break; } #endregion #region 如果有需要切词的 Cpic.Cprs2010.Index.SearchEnter se = Config.GetSearchEnter(SearchEnter); if (se.WordSplit == WordSplitType.Cn) { #region 处理中文切词 if (SearchValue.Length > 3) { List<string> Sentence; //切成没有符号的短句 Sentence = WordSplit.getSentenceList(SearchValue); Sentence = Sentence.Distinct<string>().ToList<string>(); List<string> ThreeWord = new List<string>(); List<char> tmpOneWord; //循环每个短句 for (int i = 0; i <= Sentence.Count - 1; i++) { //如果为空进行下次循环 if (string.IsNullOrEmpty(Sentence[i])) { continue; } if (Sentence[i].Length <= 3) { ThreeWord.Add(Sentence[i]); } else { //短句中的一字词 tmpOneWord = WordSplit.getOneWordList(Sentence[i]); //短句中的三字词 ThreeWord.AddRange(WordSplit.getThreeWordList1(tmpOneWord)); } } if (ThreeWord.Count > 0) { SubSearchPattern = new List<SearchPattern>(); } for (int i = 0; i <= ThreeWord.Count - 1; i++) { //得到第一个运算符 SearchPattern subsp = new SearchPattern(Config); subsp.Id = tmpindx; subsp.SearchCommand = SearchEnter + " " + ThreeWord[i]; subsp.Operator = "*"; subsp.Init(); SubSearchPattern.Add(subsp); } } else if(SearchValue.Length <3) { IsLeft = true; } #endregion } else if(se.WordSplit == WordSplitType.English) { #region 处理英文切词 List<string> EnWord; EnWord = WordSplit.getEnglistWordList(SearchValue); if (EnWord.Count == 1) { SearchValue = EnWord[0]; } else { SubSearchPattern = new List<SearchPattern>(); if (EnWord.Count == 0) { //得到第一个运算符 SearchPattern subsp = new SearchPattern(Config); subsp.Id = tmpindx; subsp.SearchCommand = SearchEnter + " " + "xxxxxxxxxxxxxxxx"; subsp.Operator = "*"; subsp.Init(); SubSearchPattern.Add(subsp); } for (int i = 0; i <= EnWord.Count - 1; i++) { //得到第一个运算符 SearchPattern subsp = new SearchPattern(Config); subsp.Id = tmpindx; subsp.SearchCommand = SearchEnter + " " + EnWord[i]; subsp.Operator = "*"; subsp.Init(); SubSearchPattern.Add(subsp); } } #endregion } #endregion #endregion } else { #region 处理复杂检索式 //F XX 20080101/GN +(200220/AN + 计算机/TI) SubSearchPattern = new List<SearchPattern>(); chrcommand = Command.Trim().ToCharArray(); for (int i = 0; i <= chrcommand.Length - 1; i++) { if (chrcommand[i] == '(') { stKuoHao.Push(chrcommand[i]); } if (chrcommand[i] == ')') { stKuoHao.Pop(); } if (chrcommand[i] == '+' || chrcommand[i] == '*' || chrcommand[i] == '-') { if (stKuoHao.Count > 0) { continue; } //得到第一个运算符 SearchPattern subsp = new SearchPattern(Config); subsp.Id = tmpindx; subsp.SearchCommand = Command.Substring(PreOperatorIndex, i - PreOperatorIndex).Trim(); if (subsp.SearchCommand.StartsWith("(")) { subsp.SearchCommand = subsp.SearchCommand.Substring(1, subsp.SearchCommand.Length - 2).Trim(); } subsp.Operator = PreOperator.ToString().Trim(); PreOperator = chrcommand[i]; PreOperatorIndex = i + 1; subsp.Init(); SubSearchPattern.Add(subsp); tmpindx += 1; } //如果是最后一个检索项目 if (i == chrcommand.Length - 1) { if (stKuoHao.Count > 0) { throw new Exception("检索式括号没有成对出现!"); } SearchPattern subsp = new SearchPattern(Config); subsp.Id = tmpindx; subsp.SearchCommand = Command.Substring(PreOperatorIndex).Trim(); if (subsp.SearchCommand.StartsWith("(")) { subsp.SearchCommand = subsp.SearchCommand.Substring(1, subsp.SearchCommand.Length - 2).Trim(); } subsp.Operator = PreOperator.ToString(); subsp.Init(); SubSearchPattern.Add(subsp); tmpindx += 1; } } #endregion } }
/// <summary> /// Returns all boundaries matching the pattern /// </summary> /// <param name="pattern">Search pattern</param> /// <returns>List of boundaries</returns> public List <Boundary> MatchPattern(SearchPattern pattern) { return(MatchPattern(pattern, _content)); }
/// <summary> /// 更新专题库节点绑定的检索式 /// </summary> /// <param name="id">检索式id</param> /// <param name="SearchPattern">检索式</param> /// <param name="Hit">命中篇数</param> /// <param name="nodeid">节点id</param> /// <param name="type">数据类型 cn en</param> /// <returns></returns> public static string UpdateSearchPattern(string id, string SearchPattern, int Hit, string nodeid, string type) { string result = "succ"; try { //检索 int intCount = 0; //int userid = Convert.ToInt32(System.Web.HttpContext.Current.Session["Userid"].ToString()); int userid = 1; SearchInterface.ClsSearch search = new SearchInterface.ClsSearch(); string strHits = search.GetSearchDataHits("", SearchPattern, userid, type.ToUpper()); if (strHits == "ERROR") return "ERROR"; string strNo = string.Empty; if (strHits.IndexOf("(") >= 0 && strHits.IndexOf(")") > 0) { strNo = strHits.Substring(strHits.IndexOf("(") + 1, strHits.IndexOf(")") - strHits.IndexOf("(") - 1); } if (strHits.IndexOf("<hits:") >= 0 && strHits.IndexOf(">") > 0) { intCount = Convert.ToInt32(strHits.Substring(strHits.IndexOf("<hits:") + 6, strHits.IndexOf(">") - strHits.IndexOf("<hits:") - 6).Trim()); } //判断结果是否太大 if (intCount > 5000) { result = "对不起,检索式检索结果大于5000,请修改检索式,缩小检索结果范围"; return result; } //获取检索结果 SearchPattern schPatItem = new SearchPattern(); schPatItem.SearchNo = strNo; ; //检索编号[001-999] //检索式:F XX 2010/AD schPatItem.UserId = userid; //用户ID if (type.ToUpper() == "CN") { schPatItem.DbType = SearchDbType.Cn; } else { schPatItem.DbType = SearchDbType.DocDB; } ResultServices res = new ResultServices(); List<int> lst = res.GetResultList(schPatItem, ""); List<string> nodids = new List<string>(); nodids.Add(nodeid); // // 更新 除了核心专利+来源是 “检索式” 的删除标记 // using (SqlConnection conn = DBA.SqlDbAccess.GetSqlConnection()) { conn.Open(); ////删除旧的数据 SqlTransaction trans = conn.BeginTransaction(); //string delztdb = string.Format("update ztdb set isdel=1 where (iscore =0 and [Form] ='检索式') and Nid='{0}' and type='{1}'", nodeid, type); //DBA.SqlDbAccess.ExecNoQuery(trans, CommandType.Text, delztdb); ////添加新的数据 //AddToTH(trans, lst, nodids, "检索式", userid.ToString(), type); WriteZTCNP(nodeid, type, "0", lst); //更新检索式 string SQL = string.Format("update ztsp set sp ='{0}',Hit={1} where id={2}", SearchPattern.Replace("'", "''"), intCount, id.Replace("'", "''")); DBA.SqlDbAccess.ExecNoQuery(trans, CommandType.Text, SQL); trans.Commit(); } } catch (Exception ex) { result = "failed"; } return result; }
public bool ReplaceAll(SearchPattern expresion) { return false; //throw new NotImplementedException (); }
public List<FindResult> FindReplaceAll(SearchPattern expresion) { return null; }
new FileFilterPipe( SearchPattern: SearchPattern, SearchOption: SearchOption, FileFilter: FileFilter, IEnumerable: IEnumerable),
public bool ReplaceAll(SearchPattern expresion) { if (expresion != null) { SetSearchPattern(expresion); int number = this.editor.ReplaceAll(expresion.ReplaceExpresion.ToString()); this.editor.QueueDraw(); if (number == 0) { return false; } return true; } return false; }
public async Task <List <Tour> > Search([FromQuery] SearchPattern pattern) { return(await _searchService.Search(pattern)); }
/// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="query"></param> /// <param name="searchTypes"></param> /// <param name="searchPattern"></param> /// <returns></returns> public static IQueryable <T> CreateFilters <T>(this IQueryable <T> query, SearchTypes searchTypes, SearchPattern searchPattern = SearchPattern.And) { //string Search if (!ReferenceEquals(searchTypes.TextSearch, null)) { query = query.ApplySearchCriterias(searchTypes.TextSearch, searchPattern); } //Numeric Search if (!ReferenceEquals(searchTypes.NumericSearch, null)) { query = query.ApplySearchCriterias(searchTypes.NumericSearch, searchPattern); } //date Search if (!ReferenceEquals(searchTypes.DateSearch, null)) { query = query.ApplySearchCriterias(searchTypes.DateSearch, searchPattern); } //Boolean Search if (!ReferenceEquals(searchTypes.BooleanSearch, null)) { query = query.ApplySearchCriterias(searchTypes.BooleanSearch, searchPattern); } //Decimal Search if (!ReferenceEquals(searchTypes.DecimalSearch, null)) { query = query.ApplySearchCriterias(searchTypes.DecimalSearch, searchPattern); } //Enum Search Search if (!ReferenceEquals(searchTypes.EnumSearch, null)) { query = query.ApplySearchCriterias(searchTypes.EnumSearch, searchPattern); } return(query); }
private void SetSearchPattern(SearchPattern sp) { searchPattern = sp; Mono.TextEditor.SearchRequest sr = new Mono.TextEditor.SearchRequest(); sr.CaseSensitive = searchPattern.CaseSensitive; sr.SearchPattern = searchPattern.Expresion.ToString(); sr.WholeWordOnly = searchPattern.WholeWorlds; this.editor.SearchEngine.SearchRequest = sr; }
public void Initialize(object dataObject) { if (dataObject.GetType() == typeof(SearchPattern) ){ searchPatern = (SearchPattern)dataObject; } }
public SourceEditor(string filePath) { if(MainClass.Settings.SourceEditorSettings == null){ MainClass.Settings.SourceEditorSettings = new Moscrif.IDE.Option.Settings.SourceEditorSetting(); } errors = new List<ErrorMarker>(); lastPrecompile = DateTime.Now; control = new Gtk.ScrolledWindow(); (control as Gtk.ScrolledWindow).ShadowType = Gtk.ShadowType.Out; editorAction = new Gtk.ActionGroup("sourceeditor"); searchPattern = null; editor = new TextEdit(); LoadSetting(); SyntaxMode mode = new SyntaxMode(); string extension = System.IO.Path.GetExtension(filePath); //editor.AccelCanActivate switch (extension) { case ".ms": { try{ mode = SyntaxModeService.GetSyntaxMode("text/moscrif"); }catch(Exception ex){ MessageDialogs msd = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("error_load_syntax"), MainClass.Languages.Translate("error_load_syntax_f1"), Gtk.MessageType.Error,null); msd.ShowDialog(); Tool.Logger.Error(ex.Message); } isCompileExtension = true; (editor as ICompletionWidget).BanCompletion = false; break; } case ".js": { try{ mode = SyntaxModeService.GetSyntaxMode("text/x-java"); }catch(Exception ex){ MessageDialogs msd = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("error_load_syntax"), MainClass.Languages.Translate("error_load_syntax_f1"), Gtk.MessageType.Error,null); msd.ShowDialog(); Tool.Logger.Error(ex.Message); } isCompileExtension = true; (editor as ICompletionWidget).BanCompletion = false; break; } case ".mso": { try{ mode = SyntaxModeService.GetSyntaxMode("text/moscrif"); }catch(Exception ex){ MessageDialogs msd = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("error_load_syntax"), MainClass.Languages.Translate("error_load_syntax_f1"), Gtk.MessageType.Error,null); msd.ShowDialog(); Tool.Logger.Error(ex.Message); } isCompileExtension = true; break; } case ".xml": { mode = SyntaxModeService.GetSyntaxMode("application/xml"); break; } case ".txt": case ".app": break; default: break; } //editor.Document. editor.Document.SyntaxMode = mode; //modified = true; editor.Document.LineChanged += delegate(object sender, LineEventArgs e) { OnBookmarkUpdate(); OnModifiedChanged(true); }; editor.Caret.PositionChanged+= delegate(object sender, DocumentLocationEventArgs e) { OnWriteToStatusbar(String.Format(statusFormat,editor.Caret.Location.Line+1,editor.Caret.Location.Column,editor.Caret.Offset)); }; FileAttributes fa = File.GetAttributes(filePath); if ((fa & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { onlyRead = true; //editor.Document.ReadOnly= true; } try { using (StreamReader file = new StreamReader(filePath)) { editor.Document.Text = file.ReadToEnd(); file.Close(); file.Dispose(); } } catch (Exception ex) { MessageDialogs ms = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("file_cannot_open", filePath), ex.Message, Gtk.MessageType.Error,null); ms.ShowDialog(); return; } //Console.WriteLine(editor.Document.Text.Replace("\r","^").Replace("\n","$")); (control as Gtk.ScrolledWindow).Add(editor); control.ShowAll(); fileName = filePath; fileSeting = MainClass.Workspace.WorkspaceUserSetting.FilesSetting.Find(x=> x.FileName == fileName); if(fileSeting == null) fileSeting = new FileSetting( fileName ); editor.TextViewMargin.ButtonPressed += OnTextMarginButtonPress; editor.IconMargin.ButtonPressed += OnIconMarginButtonPress; //editor.KeyPressEvent += OnKeyPressEvent; editor.KeyReleaseEvent += OnKeyReleaseEvent; editor.ButtonPressEvent += OnButtonPressEvent; bookmarkActions = new IdeBookmarkActions(editor,fileSeting); breakpointActions = new IdeBreakpointActions(editor); autoCompleteActions = new IdeAutocompleteAction(editor, editor); editAction = new IdeEditAction(editor); Gtk.Action act = new Gtk.Action("sourceeditor_togglebookmark", ""); act.Activated += bookmarkActions.ToggleBookmark; editorAction.Add(act); Gtk.Action act2 = new Gtk.Action("sourceeditor_clearbookmark", ""); act2.Activated += bookmarkActions.ClearBookmarks; editorAction.Add(act2); Gtk.Action act3 = new Gtk.Action("sourceeditor_nextbookmark", ""); act3.Activated += bookmarkActions.NextBookmark; editorAction.Add(act3); Gtk.Action act4 = new Gtk.Action("sourceeditor_prevbookmark", ""); act4.Activated += bookmarkActions.PreviousBookmark; editorAction.Add(act4); Gtk.Action act5 = new Gtk.Action("sourceeditor_addbreakpoint", ""); act5.Activated += breakpointActions.AddBreakpoints; editorAction.Add(act5); Gtk.Action act6 = new Gtk.Action("sourceeditor_inserttemplate", ""); act6.Activated += autoCompleteActions.InsertTemplate; editorAction.Add(act6); Gtk.Action act7 = new Gtk.Action("sourceeditor_insertautocomplete", ""); act7.Activated += autoCompleteActions.InsertCompletion; editorAction.Add(act7); Gtk.Action act8 = new Gtk.Action("sourceeditor_pasteClipboard", ""); act8.Activated += editAction.PasteText; editorAction.Add(act8); Gtk.Action act9 = new Gtk.Action("sourceeditor_copyClipboard", ""); act9.Activated += editAction.CopyText; editorAction.Add(act9); Gtk.Action act10 = new Gtk.Action("sourceeditor_cutClipboard", ""); act10.Activated += editAction.CutText; editorAction.Add(act10); Gtk.Action act11 = new Gtk.Action("sourceeditor_gotoDefinition", ""); act11.Activated += editAction.GoToDefinition; editorAction.Add(act11); Gtk.Action act12 = new Gtk.Action("sourceeditor_commentUncomment", ""); act12.Activated += editAction.CommentUncomment; editorAction.Add(act12); List<FoldSegment> list = editor.GetFolding(); foreach(SettingValue sv in fileSeting.Folding){ FoldSegment foldS = list.Find(x=>x.Offset.ToString() == sv.Display); if(foldS != null){ bool isfolding = false; if( Boolean.TryParse(sv.Value, out isfolding)) foldS.IsFolded = isfolding; } } this.editor.Document.UpdateFoldSegments(list,true); //foreach (int bm in fileSeting.Bookmarks){ foreach (MyBookmark bm in fileSeting.Bookmarks2){ LineSegment ls = this.editor.Document.GetLine(bm.Line); if(ls != null) ls.IsBookmarked = true; //this.editor.Document.Lines[bm].IsBookmarked = true; } }
public bool SearchPreviu(SearchPattern expresion) { if (expresion != null) { SetSearchPattern(expresion); this.editor.FindPrevious(true); return true; } return false; }
public bool SearchExpression(SearchPattern expresion) { this.editor.HighlightSearchPattern = true; this.editor.TextViewMargin.RefreshSearchMarker(); SetSearchPattern(expresion); //Mono.TextEditor.SearchResult ser = this.editor.FindNext(true); SearchResult sr = this.editor.SearchForward(this.editor.Document.LocationToOffset(this.editor.Caret.Location)); GotoResult(sr); //this.editor.GrabFocus (); return true; }
private Expression <Func <T, bool> > CreatePredicateWithNullCheck <T>(Expression searchExpression, ParameterExpression arg, MemberExpression targetProperty, SearchPattern searchPattern = SearchPattern.And) { string[] parts = this.Property.Split('.'); Expression nullCheckExpression = null; if (parts.Length > 1) { MemberExpression property = Expression.Property(arg, parts[0]); nullCheckExpression = Expression.NotEqual(property, Expression.Constant(null)); for (int i = 1; i < parts.Length - 1; i++) { property = Expression.Property(property, parts[i]); Expression innerNullCheckExpression = Expression.NotEqual(property, Expression.Constant(null)); nullCheckExpression = searchPattern == SearchPattern.And ? Expression.AndAlso(nullCheckExpression, innerNullCheckExpression) : Expression.Or(nullCheckExpression, innerNullCheckExpression); } } if (!targetProperty.Type.IsValueType || (targetProperty.Type.IsGenericType && targetProperty.Type.GetGenericTypeDefinition() == typeof(Nullable <>))) { var innerNullCheckExpression = Expression.NotEqual(targetProperty, Expression.Constant(null)); if (nullCheckExpression == null) { nullCheckExpression = innerNullCheckExpression; } else { nullCheckExpression = Expression.AndAlso(nullCheckExpression, innerNullCheckExpression); } } if (nullCheckExpression == null) { return(Expression.Lambda <Func <T, bool> >(searchExpression, arg)); } else { var combinedExpression = Expression.AndAlso(nullCheckExpression, searchExpression); var predicate = Expression.Lambda <Func <T, bool> >(combinedExpression, arg); return(predicate); } }
public List<FindResult> FindReplaceAll(SearchPattern searchPattern) { return this.editor.FindReplaceAll(searchPattern); }
private static string Merge(SearchPattern sp, string NodeId, string type, string stype) { ResultServices res = new ResultServices(); List<int> fResult = res.GetResultList(sp, ""); List<int> dbResult = ztHelper.GetResultList(NodeId,type); List<int> sresult ; if (stype == "1") { sresult = dbResult.Intersect(fResult).ToList<int>(); } else { sresult = dbResult.Except(fResult).ToList<int>(); } //结果文件绝对目录 string file = res.getResultFilePath(sp).Replace(sp.SearchNo+ ".cnp","998.cnp"); if (File.Exists(file)) File.Delete(file); using (FileStream fs = new System.IO.FileStream(file, FileMode.CreateNew)) { foreach (var id in sresult) { byte[] fmlNo = BitConverter.GetBytes(id); fs.Write(fmlNo, 0, fmlNo.Length); } } return sresult.Count().ToString(); }
bool IEditor.SearchPreviu(SearchPattern expresion) { return(false); //throw new NotImplementedException(); }
/// <nodoc/> public override int GetHashCode() { return(HashCodeHelper.Combine(Root.GetHashCode(), SearchPattern.GetHashCode(), Recursive.GetHashCode())); }
bool IEditor.ReplaceAll(SearchPattern expresion) { return(false); //throw new NotImplementedException(); }
public IEnumerable<string> FindMatchingEntries([NotNull] string pattern) { Validate.ArgumentNotNull(pattern, "pattern"); var sp = new SearchPattern(pattern); foreach (var entry in DirectoryList) { if (entry.Name == SpecialNameCurrentDir || entry.Name == SpecialNameNavigateUp) { // skip special names, as framework does continue; } if (sp.Match(entry.Name)) { yield return entry.Name; } } }
public List <FindResult> FindReplaceAll(SearchPattern expresion) { return(null); }
public bool SearchPreviu(SearchPattern expresion) { return false; //throw new NotImplementedException (); }
/// <summary> /// 检索 /// </summary> /// <param name="_searchPattern">检索式</param> /// <returns>检索结果</returns> public List<int> Search(SearchPattern _searchPattern) { ///1.解析检索式 如果是复杂检索 则拆分成小的检索式 ///2.把所有的小检索式送到对应的索引类中检索 ///3.对所有结果的合并 ///4.与 或 非 运算 return new List<int>(); }
/// <summary> /// 对专题库节点添加检索式&并对检索式进行检索入库。 /// 注:大于5000条的检索式 不允许插入。 /// </summary> /// <param name="NodeId">节点id</param> /// <param name="SearchPattern">检索式</param> /// <param name="Hit">命中篇数</param> /// <param name="type">数据类型 cn en</param> /// <returns></returns> public static string addSearchPattern1(string NodeId, string SearchPattern, string Hit, string type, string zid) { string result = "succ"; try { //检索 int intCount = 0; //int userid = Convert.ToInt32(System.Web.HttpContext.Current.Session["Userid"].ToString()); int userid = 1; SearchInterface.ClsSearch search = new SearchInterface.ClsSearch(); string strHits = search.GetSearchDataHits("", SearchPattern, userid, type.ToUpper()); if (strHits == "ERROR") return "ERROR"; string strNo = string.Empty; if (strHits.IndexOf("(") >= 0 && strHits.IndexOf(")") > 0) { strNo = strHits.Substring(strHits.IndexOf("(") + 1, strHits.IndexOf(")") - strHits.IndexOf("(") - 1); } if (strHits.IndexOf("<hits:") >= 0 && strHits.IndexOf(">") > 0) { intCount = Convert.ToInt32(strHits.Substring(strHits.IndexOf("<hits:") + 6).Trim('>').Trim()); } //判断结果是否太大 if (intCount > 50000) { result = "对不起,检索式检索结果大于50000,请缩小修改检索式,缩小检索结果范围"; return result; } //获取检索结果 SearchPattern schPatItem = new SearchPattern(); schPatItem.SearchNo = strNo; ; //检索编号[001-999] //检索式:F XX 2010/AD schPatItem.UserId = userid; //用户ID if (type.ToUpper() == "CN") { schPatItem.DbType = SearchDbType.Cn; } else { schPatItem.DbType = SearchDbType.DocDB; } ResultServices res = new ResultServices(); List<int> lst = res.GetResultList(schPatItem, ""); List<string> nodids = new List<string>(); nodids.Add(NodeId); //添加到ztdb中 using (SqlConnection conn = DBA.SqlDbAccess.GetSqlConnection()) { conn.Open(); SqlTransaction tran = conn.BeginTransaction(); if (intCount > 0) { //AddToTH(tran, lst, nodids, "检索式", userid.ToString(), type); WriteZTCNP(NodeId, type, "0", lst); } string SQL = string.Format("insert into ztsp (Nid,sp,Hit,Type,isdel,zid) values ('{0}','{1}',{2},'{3}',0,'{4}')", NodeId, SearchPattern, intCount, type, zid); DBA.SqlDbAccess.ExecNoQuery(tran, CommandType.Text, SQL); tran.Commit(); } } catch (Exception ex) { result = "失败:" + ex.Message; } return result; }
/// <summary> /// 获取结果文件路径 /// </summary> /// <param name="sp"></param> /// <returns></returns> public string getResultFilePath(SearchPattern sp) { string ResultFilePath = getResultFilePath(sp, true); return ResultFilePath; }
public List<Company> Search(SearchPattern pattern) { List<Company> result = new List<Company>(); using (var sqlConnection = new SqlConnection(ConnectionString)) { sqlConnection.Open(); SqlCommand cmd = new SqlCommand("select Id,FullName,Name,INN,OGRN,Rating from Companies where Region=@region and ActivityType=@atype", sqlConnection); cmd.Parameters.AddWithValue("region", pattern.Region); cmd.Parameters.AddWithValue("atype", pattern.ActivityType); using (var reader = cmd.ExecuteReader()) { while(reader.Read()) { Company c = new Company(); c.Id = reader.GetInt32(0); c.FullName = reader.GetString(1); c.Name = reader.GetString(2); c.INN = reader.GetInt64(3); c.OGRN = reader.GetInt64(4); c.Rating = float.Parse(reader.GetValue(5).ToString()); result.Add(c); } } } return result; }
/// <summary> /// 添加某一用户的检索历史,添加内容为strHis /// </summary> /// <param name="sp"></param> /// <returns></returns> public bool addSearchHis(SearchPattern sp, string strHis) { string _strHis = validateFormat(strHis); if (_strHis == "") return false; FileMode f; string hisFilePath = UserPath + "\\" + sp.DbType; string hisFile = hisFilePath + "\\SearchHistory.lst"; //创建目录 if (!Directory.Exists(hisFilePath)) { Directory.CreateDirectory(hisFilePath); } if (File.Exists(hisFile)) { f = FileMode.Append; } else { f = FileMode.OpenOrCreate; } //创建流 using (StreamWriter sw = new StreamWriter(new FileStream(hisFile, f))) { sw.WriteLine(strHis); } return true; }
// ---------------------------------------------- // Search API // ---------------------------------------------- /// <inheritdoc /> protected override IEnumerable <UPath> EnumeratePathsImpl(UPath path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget) { // Special case for Windows as we need to provide list for: // - the root folder / (which should just return the /drive folder) // - the drive folders /drive/c, drive/e...etc. var search = SearchPattern.Parse(ref path, ref searchPattern); if (IsOnWindows) { if (IsWithinSpecialDirectory(path)) { if (!SpecialDirectoryExists(path)) { throw NewDirectoryNotFoundException(path); } var searchForDirectory = searchTarget == SearchTarget.Both || searchTarget == SearchTarget.Directory; // Only sub folder "/drive/" on root folder / if (path == UPath.Root) { if (searchForDirectory) { yield return(PathDrivePrefixOnWindows); if (searchOption == SearchOption.AllDirectories) { foreach (var subPath in EnumeratePathsImpl(PathDrivePrefixOnWindows, searchPattern, searchOption, searchTarget)) { yield return(subPath); } } } yield break; } // When listing for /drive, return the list of drives available if (path == PathDrivePrefixOnWindows) { var pathDrives = new List <UPath>(); foreach (var drive in DriveInfo.GetDrives()) { if (drive.Name.Length < 2 || drive.Name[1] != ':') { continue; } var pathDrive = PathDrivePrefixOnWindows / char.ToLowerInvariant(drive.Name[0]).ToString(); if (search.Match(pathDrive)) { pathDrives.Add(pathDrive); if (searchForDirectory) { yield return(pathDrive); } } } if (searchOption == SearchOption.AllDirectories) { foreach (var pathDrive in pathDrives) { foreach (var subPath in EnumeratePathsImpl(pathDrive, searchPattern, searchOption, searchTarget)) { yield return(subPath); } } } yield break; } } } IEnumerable <string> results; switch (searchTarget) { case SearchTarget.File: results = Directory.EnumerateFiles(ConvertPathToInternal(path), searchPattern, searchOption); break; case SearchTarget.Directory: results = Directory.EnumerateDirectories(ConvertPathToInternal(path), searchPattern, searchOption); break; case SearchTarget.Both: results = Directory.EnumerateFileSystemEntries(ConvertPathToInternal(path), searchPattern, searchOption); break; default: yield break; } foreach (var subPath in results) { // Windows will truncate the search pattern's extension to three characters if the filesystem // has 8.3 paths enabled. This means searching for *.docx will list *.doc as well which is // not what we want. Check against the search pattern again to filter out those false results. if (!IsOnWindows || search.Match(Path.GetFileName(subPath))) { yield return(ConvertPathFromInternal(subPath)); } } }
/// <summary> /// 删除指定编号的检索历史 /// 同时删除相关文件,例如删除002.txt以及002.Cnp文件 /// searchNum 必须为002格式 /// </summary> /// <param name="sp"></param> /// <param name="searchNum"></param> /// <returns></returns> public bool deleteSearchHis(SearchPattern sp, string searchNum) { FileMode f = FileMode.Create; string hisFilePath = UserPath + "\\" + sp.DbType; string hisFile = hisFilePath + "\\SearchHistory.lst"; //创建目录 if (!Directory.Exists(hisFilePath)) { Directory.CreateDirectory(hisFilePath); } try { string[] strText; // 读取文件内容 strText = File.ReadAllLines(hisFile); // 寻找对应的检索编号并删除 using (StreamWriter sw = new StreamWriter(new FileStream(hisFile, f))) { foreach (string item in strText) { string pat = @"(" + searchNum + ")"; if (item.IndexOf(pat) == -1) // 找不到,则写文件 sw.WriteLine(item); } } // 删除相关文件 string strTxt = hisFilePath + "\\" + searchNum + ".txt"; foreach (string strItm in Directory.GetFiles(hisFilePath, searchNum + ".*.cnp", SearchOption.TopDirectoryOnly)) { try { File.Delete(strItm); } catch (Exception er) { } } string strCnp = hisFilePath + "\\" + searchNum + ".Cnp"; File.Delete(strTxt); } catch (Exception e) { } return true; }
// ---------------------------------------------- // Search API // ---------------------------------------------- /// <inheritdoc /> protected override IEnumerable <UPath> EnumeratePathsImpl(UPath path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget) { var search = SearchPattern.Parse(ref path, ref searchPattern); var directoryToVisit = new List <UPath>(); directoryToVisit.Add(path); var entries = new SortedSet <UPath>(UPath.DefaultComparerIgnoreCase); var sortedDirectories = new SortedSet <UPath>(UPath.DefaultComparerIgnoreCase); var fileSystems = new List <IFileSystem>(); if (NextFileSystem != null) { fileSystems.Add(NextFileSystem); } // Query all filesystems just once lock (_fileSystems) { fileSystems.AddRange(_fileSystems); } while (directoryToVisit.Count > 0) { var pathToVisit = directoryToVisit[0]; directoryToVisit.RemoveAt(0); int dirIndex = 0; entries.Clear(); sortedDirectories.Clear(); for (var i = fileSystems.Count - 1; i >= 0; i--) { var fileSystem = fileSystems[i]; if (fileSystem.DirectoryExists(pathToVisit)) { foreach (var item in fileSystem.EnumeratePaths(pathToVisit, "*", SearchOption.TopDirectoryOnly, SearchTarget.Both)) { if (!entries.Contains(item)) { var isFile = fileSystem.FileExists(item); var isDirectory = fileSystem.DirectoryExists(item); var isMatching = search.Match(item); if (isMatching && ((isFile && searchTarget != SearchTarget.Directory) || (isDirectory && searchTarget != SearchTarget.File))) { entries.Add(item); } if (searchOption == SearchOption.AllDirectories && isDirectory) { sortedDirectories.Add(item); } } } } } // Enqueue directories and respect order foreach (var nextDir in sortedDirectories) { directoryToVisit.Insert(dirIndex++, nextDir); } // Return entries foreach (var entry in entries) { yield return(entry); } } }
private void cmbFileTypes_SelectedIndexChanged(object sender, EventArgs e) { selectedPattern = Settings.SearchPatterns[cmbFileTypes.SelectedIndex]; }
/// <inheritdoc /> protected override IEnumerable <UPath> EnumeratePathsImpl(UPath path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget) { // Use the search pattern to normalize the path/search pattern var search = SearchPattern.Parse(ref path, ref searchPattern); var originalSrcPath = path; // Internal method used to retrieve the list of root directories SortedSet <UPath> GetRootDirectories() { var directories = new SortedSet <UPath>(UPath.DefaultComparerIgnoreCase); lock (_mounts) { foreach (var mountName in _mounts.Keys) { directories.Add(mountName); } } if (NextFileSystem != null) { foreach (var dir in NextFileSystem.EnumeratePaths(path, "*", SearchOption.TopDirectoryOnly, SearchTarget.Directory)) { if (!directories.Contains(dir)) { directories.Add(dir); } } } return(directories); } IEnumerable <UPath> EnumeratePathFromFileSystem(UPath subPath, bool failOnInvalidPath) { var fs = TryGetMountOrNext(ref subPath, out var mountPath); if (fs == null) { if (failOnInvalidPath) { throw NewDirectoryNotFoundException(originalSrcPath); } yield break; } if (fs != NextFileSystem) { // In the case of a mount, we need to return the full path Debug.Assert(!mountPath.IsNull); foreach (var entry in fs.EnumeratePaths(subPath, searchPattern, searchOption, searchTarget)) { yield return(mountPath / entry.ToRelative()); } } else { foreach (var entry in fs.EnumeratePaths(subPath, searchPattern, searchOption, searchTarget)) { yield return(entry); } } } // Special case for the root as we have to return the list of mount directories // and merge them with the underlying FileSystem if (path == UPath.Root) { var entries = new SortedSet <UPath>(UPath.DefaultComparerIgnoreCase); // Return the list of dircetories var directories = GetRootDirectories(); // Process the files first if (NextFileSystem != null && (searchTarget == SearchTarget.File || searchTarget == SearchTarget.Both)) { foreach (var file in NextFileSystem.EnumeratePaths(path, searchPattern, SearchOption.TopDirectoryOnly, SearchTarget.File)) { entries.Add(file); } } if (searchTarget != SearchTarget.File) { foreach (var dir in directories) { if (search.Match(dir)) { entries.Add(dir); } } } // Return all entries sorted foreach (var entry in entries) { yield return(entry); } if (searchOption == SearchOption.AllDirectories) { foreach (var dir in directories) { foreach (var entry in EnumeratePathFromFileSystem(dir, false)) { yield return(entry); } } } } else { foreach (var entry in EnumeratePathFromFileSystem(path, true)) { yield return(entry); } } }
protected async override Task <Action <AsyncCodeActivityContext> > ExecuteAsync(AsyncCodeActivityContext context, CancellationToken token) { var folder = Folder.Get(context); var patterns = SearchPattern?.GetAsArray <string>(context) ?? new[] { "*" }; var lastWriteTime = LastWriteTime?.Get(context) ?? DateTime.Now; int filesDeleted = 0; int foldersDeleted = 0; await Task.Run(() => { foreach (var p in patterns) { foreach (var f in Directory.EnumerateFiles(folder, p, SearchOption.AllDirectories).Reverse()) { try { if (File.GetLastWriteTime(f) > lastWriteTime) { continue; } File.Delete(f); filesDeleted++; } catch (Exception e) { Trace.WriteLine($"{f}: {e.Message}"); } } } if (DeleteEmptyFolders) { foreach (var f in Directory.EnumerateDirectories(folder, "*", SearchOption.AllDirectories).Reverse()) { if (Directory.EnumerateFileSystemEntries(f, "*").Any()) { continue; } try { Directory.Delete(f); foldersDeleted++; } catch (Exception e) { Trace.WriteLine($"{f}: {e.Message}"); } } } }).ConfigureAwait(false); return(ctx => { Result.Set(ctx, new CleanUpFolderResult { FilesDeleted = filesDeleted, FoldersDeleted = foldersDeleted }); }); }
public static IEnumerable tableSearch(string strSearchQuery, string NodeId,string type,string stype) { string strResutlMsg = ""; try { // string strQuery = System.Web.HttpUtility.UrlDecode(strSearchQuery.Trim()); string strQuery =strSearchQuery.Trim(); //检索 int intCount = 0; int userid = Convert.ToInt32(System.Web.HttpContext.Current.Session["UserID"]); SearchInterface.ClsSearch search = new SearchInterface.ClsSearch(); string strHits = search.GetSearchDataHits(SearchInterface.XmPatentComm.strWebSearchGroupName,strQuery, userid, type.ToUpper()); string strNo = string.Empty; if (strHits == "ERROR") { return "请求错误"; } if (strHits.IndexOf("(") >= 0 && strHits.IndexOf(")") > 0) { strNo = strHits.Substring(strHits.IndexOf("(") + 1, strHits.IndexOf(")") - strHits.IndexOf("(") - 1); } if (strHits.IndexOf("<hits:") >= 0 && strHits.IndexOf(">") > 0) { intCount = Convert.ToInt32(strHits.Substring(strHits.IndexOf("<hits:") + 6, strHits.IndexOf(">") - strHits.IndexOf("<hits:") - 6).Trim()); } if (intCount == 0) return "0"; SearchPattern sp = new SearchPattern(); sp.SearchNo = strNo; sp.Pattern = strQuery; if (type.ToUpper() == "CN") { sp.DbType = SearchDbType.Cn; } else { sp.DbType = SearchDbType.DocDB; } sp.UserId = userid; strResutlMsg = Merge(sp, NodeId, type, stype); } catch (Exception ex) { strResutlMsg = "请求错误"; } return strResutlMsg; }
public void SetSearchExpresion(SearchPattern expresion) { searchPatern = expresion; }
/// <inheritdoc /> protected override IEnumerable <UPath> EnumeratePathsImpl(UPath path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget) { // Use the search pattern to normalize the path/search pattern var search = SearchPattern.Parse(ref path, ref searchPattern); // Query all mounts just once List <KeyValuePair <UPath, IFileSystem> > mounts; lock (_mounts) { mounts = _mounts.ToList(); } // Internal method used to retrieve the list of search locations List <SearchLocation> GetSearchLocations(UPath basePath) { var locations = new List <SearchLocation>(); var matchedMount = false; foreach (var kvp in mounts) { // Check if path partially matches a mount name var remainingPath = GetRemaining(basePath, kvp.Key); if (!remainingPath.IsNull && remainingPath != UPath.Root) { locations.Add(new SearchLocation(this, basePath, remainingPath)); continue; } if (!matchedMount) { // Check if path fully matches a mount name remainingPath = GetRemaining(kvp.Key, basePath); if (!remainingPath.IsNull) { matchedMount = true; // don't check other mounts, we don't want to merge them together if (kvp.Value.DirectoryExists(remainingPath)) { locations.Add(new SearchLocation(kvp.Value, kvp.Key, remainingPath)); } } } } if (!matchedMount && NextFileSystem != null && NextFileSystem.DirectoryExists(basePath)) { locations.Add(new SearchLocation(NextFileSystem, null, basePath)); } return(locations); } var directoryToVisit = new List <UPath>(); directoryToVisit.Add(path); var entries = new SortedSet <UPath>(UPath.DefaultComparerIgnoreCase); var sortedDirectories = new SortedSet <UPath>(UPath.DefaultComparerIgnoreCase); var first = true; while (directoryToVisit.Count > 0) { var pathToVisit = directoryToVisit[0]; directoryToVisit.RemoveAt(0); var dirIndex = 0; entries.Clear(); sortedDirectories.Clear(); var locations = GetSearchLocations(pathToVisit); // Only need to search within one filesystem, no need to sort or do other work if (locations.Count == 1 && locations[0].FileSystem != this && (!first || searchOption == SearchOption.AllDirectories)) { var last = locations[0]; foreach (var item in last.FileSystem.EnumeratePaths(last.Path, searchPattern, searchOption, searchTarget)) { yield return(CombinePrefix(last.Prefix, item)); } } else { for (var i = locations.Count - 1; i >= 0; i--) { var location = locations[i]; var fileSystem = location.FileSystem; var searchPath = location.Path; if (fileSystem == this) { // List a single part of a mount name, queue it to be visited if needed var mountPart = new UPath(searchPath.GetFirstDirectory(out _)).ToRelative(); var mountPath = location.Prefix / mountPart; var isMatching = search.Match(mountPath); if (isMatching && searchTarget != SearchTarget.File) { entries.Add(mountPath); } if (searchOption == SearchOption.AllDirectories) { sortedDirectories.Add(mountPath); } } else { // List files in the mounted filesystems, merged and sorted into one list foreach (var item in fileSystem.EnumeratePaths(searchPath, "*", SearchOption.TopDirectoryOnly, SearchTarget.Both)) { var publicName = CombinePrefix(location.Prefix, item); if (entries.Contains(publicName)) { continue; } var isFile = fileSystem.FileExists(item); var isDirectory = fileSystem.DirectoryExists(item); var isMatching = search.Match(publicName); if (isMatching && ((isFile && searchTarget != SearchTarget.Directory) || (isDirectory && searchTarget != SearchTarget.File))) { entries.Add(publicName); } if (searchOption == SearchOption.AllDirectories && isDirectory) { sortedDirectories.Add(publicName); } } } } } if (first) { if (locations.Count == 0 && path != UPath.Root) { throw NewDirectoryNotFoundException(path); } first = false; } // Enqueue directories and respect order foreach (var nextDir in sortedDirectories) { directoryToVisit.Insert(dirIndex++, nextDir); } // Return entries foreach (var entry in entries) { yield return(entry); } } }
public static IQueryable <T> ApplySearchCriterias <T>(this IQueryable <T> query, IEnumerable <AbstractSearch> searchCriterias, SearchPattern searchPattern = SearchPattern.And) { foreach (var criteria in searchCriterias) { query = criteria.ApplyToQuery(query, searchPattern); } //var result = query.ToArray(); return(query); }
/// <summary> /// Returns true if the string matches the pattern which may contain * and ? wildcards. /// </summary> /// <param name="pattern">Pattern to match.</param> /// <param name="fileName">Filename to match.</param> /// <param name="caseSensitive">If the match is case sensitive or not.</param> /// <returns>True if the patterna and the fileName match, false if not.</returns> /// <remarks> /// Based on robagar C# port of Jack Handy Codeproject article: /// http://www.codeproject.com/string/wildcmp.asp#xx1000279xx /// </remarks> private bool Match(string pattern, string fileName, bool caseSensitive) { // if not concerned about case, convert both string and pattern // to lower case for comparison if (!caseSensitive) { pattern = pattern.ToLower(); fileName = fileName.ToLower(); } if (string.IsNullOrEmpty(pattern)) { return(false); //如果空字符 返回没有 } if (pattern.CompareTo("*") == 0 || pattern.CompareTo("*.*") == 0) { return(true);//快速匹配 } // if pattern doesn't actually contain any wildcards, use simple equality //if (pattern.IndexOfAny(Wildcards) == -1)//不存在匹配符号 // return (fileName == pattern); bool findP = false; foreach (var v1 in Wildcards) { foreach (var v2 in pattern) { if (v1.CompareTo(v2) == 0) { findP = true; break; } } } if (!findP) { return(fileName == pattern); } // otherwise do pattern matching SearchPattern mSearchPattern = new SearchPattern(pattern); return(mSearchPattern.IsMatch(fileName)); //下面逻辑可能有点问题 int i = 0; int j = 0; while (i < fileName.Length && j < pattern.Length && pattern[j] != '*') { if ((pattern[j] != fileName[i]) && (pattern[j] != '?')) { return(false); } i++; j++; } // if we have reached the end of the pattern without finding a * wildcard, // the match must fail if the string is longer or shorter than the pattern if (j == pattern.Length) { return(fileName.Length == pattern.Length); } int cp = 0; int mp = 0; while (i < fileName.Length) { if (j < pattern.Length && pattern[j] == '*') { if ((j++) >= pattern.Length) { return(true); } mp = j; cp = i + 1; } else if (j < pattern.Length && (pattern[j] == fileName[i] || pattern[j] == '?')) { j++; i++; } else { j = mp; i = cp++; } } while (j < pattern.Length && pattern[j] == '*') { j++; } return(j >= pattern.Length); }
public bool Replace(SearchPattern expresion) { if (expresion != null) { SetSearchPattern(expresion); return this.editor.Replace(expresion.ReplaceExpresion.ToString()); } return false; }
/// <summary> /// 删除指定编号的检索历史 /// 同时删除相关文件,例如删除002.txt以及002.Cnp文件 /// searchNum 必须为002格式 /// </summary> /// <param name="sp"></param> /// <param name="searchNum"></param> /// <returns></returns> public bool deleteBatchSearchHis(SearchPattern sp, string[] searchNumArr) { FileMode f = FileMode.Create; string hisFilePath = UserPath + "\\" + sp.DbType; string hisFile = hisFilePath + "\\SearchHistory.lst"; //创建目录 if (!Directory.Exists(hisFilePath)) { Directory.CreateDirectory(hisFilePath); } try { string[] strText; // 读取文件内容 strText = File.ReadAllLines(hisFile); // 寻找对应的检索编号并删除 using (StreamWriter sw = new StreamWriter(new FileStream(hisFile, f))) { foreach (string item in strText) { // 如果该检索式跟所有待删除的编号都不匹配,则保留。跟一个匹配,都与删除 bool bDelete = false; foreach (string searchNum in searchNumArr) { string pat = @"(" + searchNum + ")"; if (item.IndexOf(pat) != -1) // 删除编号对应的检索式 bDelete = true; } if (bDelete == false) sw.WriteLine(item); } } // 删除相关文件 foreach (string searchNum in searchNumArr) { string strTxt = hisFilePath + "\\" + searchNum + ".txt"; string strCnp = hisFilePath + "\\" + searchNum + ".Cnp"; File.Delete(strTxt); File.Delete(strCnp); //add xiwl 再册除与此编号相关的所有文件 foreach (string strItm in Directory.GetFiles(hisFilePath, searchNum + ".*.cnp", SearchOption.TopDirectoryOnly)) { try { File.Delete(strItm); } catch (Exception er) { } } } } catch (Exception e) { } return true; }
public bool IsAvailable(SearchPattern pattern) => (pattern & SearchPattern.FIND_USAGES) != 0;
protected override void ProcessRecord() { var missedWebResourcesCount = 0; var resourceFiles = new HashSet <string>(); var patterns = (string.IsNullOrWhiteSpace(SearchPattern)) ? new string[1] { "*" } : SearchPattern.Split(','); foreach (var pattern in patterns) { WriteVerbose($"Processing pattern {pattern}..."); Directory.GetFiles(Path, pattern.Trim(), SearchOption.AllDirectories).ToList() .ForEach((item) => resourceFiles.Add(item)); } if (resourceFiles.Count == 0) { WriteVerbose($"There are no files in folder '{Path}' matching patterns {SearchPattern}"); return; } else { WriteVerbose($"Found {resourceFiles.Count} resource files."); } using (var context = new CIContext(OrganizationService)) { WriteVerbose($"Retrieving web resources from CRM..."); var query = from resource in context.WebResourceSet select resource; var solutionId = GetSolutionId(context, SolutionName); if (!solutionId.Equals(Guid.Empty)) { query = from resource in context.WebResourceSet join sol in context.SolutionComponentSet on resource.Id equals sol.ObjectId where sol.SolutionId.Equals(solutionId) select resource; } var allWebResources = query.ToList(); WriteVerbose($"Found {allWebResources.Count}"); var importexportxml = new StringBuilder(); var webResource = default(WebResource); foreach (var resourceFile in resourceFiles) { WriteVerbose($"Processing file: {System.IO.Path.GetFileName(resourceFile)}"); try { webResource = allWebResources.Single(CompareCondition(resourceFile)); WriteVerbose($"Found web resource: {webResource.Name}"); } catch (Exception ex) { missedWebResourcesCount++; WriteWarning($"Cannot process {resourceFile}: {ex.Message}"); continue; } // update in context var fileContent = Convert.ToBase64String(File.ReadAllBytes(resourceFile)); if (webResource.Content?.GetHashCode() != fileContent.GetHashCode()) { webResource.Content = fileContent; //context.UpdateObject(webResource); // update web resource then add to a solution. UpdateRequest update = new UpdateRequest { Target = webResource }; update.Parameters.Add("SolutionUniqueName", SolutionName); context.Execute(update); // add id to publish xml if (Publish) { importexportxml.Append($"<webresource>{webResource.Id}</webresource>"); } } } // Update WriteVerbose("Saving changes..."); context.SaveChanges(); // Publish if (Publish) { WriteVerbose("Publishing web resources..."); PublishXmlRequest req = new PublishXmlRequest() { ParameterXml = $"<importexportxml><webresources>{importexportxml.ToString()}</webresources></importexportxml>" }; OrganizationService.Execute(req); } WriteObject($"{resourceFiles.Count - missedWebResourcesCount} out of {resourceFiles.Count} web resources were processed"); if (FailIfWebResourceNotFound && missedWebResourcesCount > 0) { ThrowTerminatingError(new ErrorRecord( new RuntimeException($"{missedWebResourcesCount} web resources were not found"), "", ErrorCategory.ObjectNotFound, null)); } } }
internal bool PathMatches(string pathToMatch) { if (String.IsNullOrEmpty(pathToMatch)) { return(false); } bool result = false; string[] handlerPaths = Path.Split(','); int slash = pathToMatch.LastIndexOf('/'); string origPathToMatch = pathToMatch; string noLeadingSlashPathToMatch = null; if (slash != -1) { pathToMatch = pathToMatch.Substring(slash); } SearchPattern sp = null; foreach (string handlerPath in handlerPaths) { if (handlerPath.Length == 0) { continue; } if (handlerPath == "*") { result = true; break; } string matchExact = null; string endsWith = null; if (handlerPath.Length > 0) { if (handlerPath [0] == '*' && (handlerPath.IndexOf('*', 1) == -1)) { endsWith = handlerPath.Substring(1); } if (handlerPath.IndexOf('*') == -1) { if (handlerPath [0] != '/') { HttpContext ctx = HttpContext.Current; HttpRequest req = ctx != null ? ctx.Request : null; string vpath = req != null ? req.BaseVirtualDir : HttpRuntime.AppDomainAppVirtualPath; if (vpath == "/") { vpath = String.Empty; } matchExact = String.Concat(vpath, "/", handlerPath); } } } if (matchExact != null) { result = matchExact.Length == origPathToMatch.Length && StrUtils.EndsWith(origPathToMatch, matchExact, true); if (result == true) { break; } else { continue; } } else if (endsWith != null) { result = StrUtils.EndsWith(pathToMatch, endsWith, true); if (result == true) { break; } else { continue; } } string pattern; if (handlerPath [0] == '/') { pattern = handlerPath.Substring(1); } else { pattern = handlerPath; } if (sp == null) { sp = new SearchPattern(pattern, true); } else { sp.SetPattern(pattern, true); } if (noLeadingSlashPathToMatch == null) { if (origPathToMatch [0] == '/') { noLeadingSlashPathToMatch = origPathToMatch.Substring(1); } else { noLeadingSlashPathToMatch = origPathToMatch; } } if (pattern.IndexOf('/') >= 0) { noLeadingSlashPathToMatch = AdjustPath(pattern, noLeadingSlashPathToMatch); } if (sp.IsMatch(noLeadingSlashPathToMatch)) { result = true; break; } } return(result); }