コード例 #1
0
ファイル: SearchResultTests.cs プロジェクト: clarkcb/xsearch
 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);
 }
コード例 #2
0
ファイル: SearchService.cs プロジェクト: rizwan3d/elalang
        public void Replace(string textToFind, string textToReplace, Document doc, SearchFlags flags, SearchScope scope, int startPosition, int endPosition)
        {
            var ed = App.Editor(doc.GetType()) as ITextEditor;

            if (lastSettings != null &&
                (lastSettings.LastDocument != doc || ed.SelectionStart != lastSettings.LastStartPosition || ed.SelectionEnd != lastSettings.LastEndPosition))
                lastSettings = null;

            if (lastSettings != null)
            {
                ed.ReplaceText(lastSettings.LastStartPosition, lastSettings.LastEndPosition, lastSettings.TextToReplace);
                lastSettings.LastEndPosition = lastSettings.LastStartPosition + lastSettings.TextToReplace.Length;
            }

            var res = Search(textToFind, doc, flags, scope, (d,r) => {
                var editor = (ITextEditor)App.GetService<IEditorService>().GetEditor(d.GetType()).Instance;

                var docServ = App.GetService<IDocumentService>();

                if (docServ.GetActiveDocument() != d)
                    docServ.SetActiveDocument(d);

                editor.SelectText(r.StartPosition, r.EndPosition - r.StartPosition);
                lastSettings.LastStartPosition = r.StartPosition;
                lastSettings.TextToReplace = textToReplace;
                var sci = editor.Control as ScintillaControl;

                if (sci != null)
                    sci.PutArrow(sci.GetLineFromPosition(r.StartPosition));
                return true;
            }, false, lastSettings != null ? lastSettings.LastEndPosition : startPosition, endPosition, null);
            IsFinished(res);
        }
コード例 #3
0
 public void SearchSettings_AddPatterns_HasPatterns()
 {
     var settings = new SearchSettings();
     settings.AddSearchPattern("Search");
     Assert.AreEqual(settings.SearchPatterns.Count, 1);
     Assert.IsTrue(settings.SearchPatterns.First().ToString() == "Search");
 }
コード例 #4
0
 public void SearchSettings_SetDebug_HasVerbose()
 {
     var settings = new SearchSettings();
     settings.SetDebug();
     Assert.IsTrue(settings.Debug);
     Assert.IsTrue(settings.Verbose);
 }
コード例 #5
0
 public void SearchSettings_SetArchivesOnly_HasSearchArchives()
 {
     var settings = new SearchSettings();
     settings.SetArchivesOnly();
     Assert.IsTrue(settings.ArchivesOnly);
     Assert.IsTrue(settings.SearchArchives);
 }
コード例 #6
0
        public List<BGSearchResult> searchBoardGame(SearchSettings settings, string searchInput)
        {
            string requestUrl = builder.buildSearchUrl(settings, searchInput);

            XDocument result = XDocument.Load(requestUrl);

            return parser.parseSearchXML(result);
        }
コード例 #7
0
        /// <summary>
        /// Constructor of <see cref="SearchLayerCreator"/>
        /// </summary>
        /// <param name="map">Map</param>
        /// <param name="searchResult">Search result</param>
        /// <param name="searchSettings">Seacrh settings </param>
        public SearchLayerCreator(IMap map, SearchResult searchResult, SearchSettings searchSettings)
        {
            if (map == null) throw new ArgumentNullException("map");
            if (searchResult == null) throw new ArgumentNullException("searchResult");
            if (searchSettings == null) throw new ArgumentNullException("searchSettings");

            _map = map;
            _searchResult = searchResult;
            _searchSettings = searchSettings;
        }
コード例 #8
0
 public void SearchSettings_AddExtensions_HasExtensions()
 {
     var settings = new SearchSettings();
     settings.AddInExtension("cs");
     Assert.AreEqual(settings.InExtensions.Count, 1);
     Assert.IsTrue(settings.InExtensions.Contains(".cs"));
     settings.AddInExtension("java,scala");
     Assert.AreEqual(settings.InExtensions.Count, 3);
     Assert.IsTrue(settings.InExtensions.Contains(".java"));
     Assert.IsTrue(settings.InExtensions.Contains(".scala"));
 }
コード例 #9
0
ファイル: SearchResultTests.cs プロジェクト: clarkcb/xsearch
        public void SearchResultBinaryFile_ToString_EqualsExpected()
        {
            var settings = new SearchSettings();
            var pattern = new Regex("Search");
            var searchFile = new SearchFile(CsSearchPath, "Searcher.exe", FileType.Binary);
            var lineNum = 0;
            var matchStartIndex = 0;
            var matchEndIndex = 0;
            string line = null;
            var searchResult = new SearchResult(pattern, searchFile, lineNum,
                matchStartIndex, matchEndIndex, line);
            var expectedPath = CsSearchPath + "/Searcher.exe";
            var expectedOutput = string.Format("{0} matches", expectedPath);

            Assert.AreEqual(searchResult.ToString(settings), expectedOutput);
        }
コード例 #10
0
ファイル: SearchResultTests.cs プロジェクト: clarkcb/xsearch
        public void SearchResultSingleLine_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\n";
            var searchResult = new SearchResult(pattern, searchFile, lineNum,
                matchStartIndex, matchEndIndex, line);
            var expectedPath = CsSearchPath + "/Searcher.cs";
            var expectedOutput = string.Format("{0}: {1}: [{2}:{3}]: {4}", expectedPath,
                lineNum, matchStartIndex, matchEndIndex, line.Trim());

            Assert.AreEqual(searchResult.ToString(settings), expectedOutput);
        }
コード例 #11
0
        public SearchResults SearchSegment(SearchSettings settings, Segment segment)
        {
            var results = new SearchResults();
            if (DisableMt) return results;

            foreach (var provider in _provider.MtProviders)
            {
                if (SearchShouldExecute(provider, settings))
                {
                    ITranslationProviderLanguageDirection languageDirection = provider.GetLanguageDirection(_languagePair);
                    var innerSearchResult = languageDirection.SearchSegment(settings, segment);
                    SetResultInSearchResults(ref results, innerSearchResult);
                }
            }
            OnTranslationFinished();
            return results;
        }
コード例 #12
0
 public void GetNewSearchSettings_NoModifications_HasDefaultValues()
 {
     var settings = new SearchSettings();
     Assert.IsFalse(settings.ArchivesOnly);
     Assert.IsFalse(settings.Debug);
     Assert.IsTrue(settings.ExcludeHidden);
     Assert.IsFalse(settings.FirstMatch);
     Assert.AreEqual(settings.LinesAfter, 0);
     Assert.AreEqual(settings.LinesBefore, 0);
     Assert.IsFalse(settings.ListDirs);
     Assert.IsFalse(settings.ListFiles);
     Assert.IsFalse(settings.ListLines);
     Assert.AreEqual(settings.MaxLineLength, 150);
     Assert.IsFalse(settings.MultiLineSearch);
     Assert.IsFalse(settings.PrintResults);
     Assert.IsFalse(settings.PrintUsage);
     Assert.IsFalse(settings.PrintVersion);
     Assert.IsTrue(settings.Recursive);
     Assert.IsFalse(settings.SearchArchives);
     Assert.IsFalse(settings.UniqueLines);
     Assert.IsFalse(settings.Verbose);
 }
コード例 #13
0
ファイル: SearchOptions.cs プロジェクト: clarkcb/xsearch
		public SearchSettings SettingsFromArgs(IEnumerable<string> args)
		{
			var settings = new SearchSettings();
			// default to PrintResults = true since this is called from CLI functionality
			settings.PrintResults = true;
			var queue = new Queue<string>(args);

			while (queue.Count > 0)
			{
				var s = queue.Dequeue();
				if (s.StartsWith("-"))
				{
					try
					{
						while (s.StartsWith("-"))
						{
							s = s.Substring(1);
						}
					}
					catch (InvalidOperationException e)
					{
						throw new SearchException(e.Message);
					}
					if (string.IsNullOrWhiteSpace(s))
					{
						throw new SearchException("Invalid option: -");
					}
					if (ArgDictionary.ContainsKey(s))
					{
						try
						{
							((SearchArgOption)ArgDictionary[s]).Action(queue.Dequeue(), settings);
						}
						catch (InvalidOperationException e)
						{
							throw new SearchException(e.Message);
						}
					}
					else if (FlagDictionary.ContainsKey(s))
					{
						try
						{
							((SearchFlagOption)FlagDictionary[s]).Action(true, settings);
						}
						catch (InvalidOperationException e)
						{
							throw new SearchException(e.Message);
						}
					}
					else
					{
						throw new SearchException("Invalid option: " + s);
					}
				}
				else
				{
					settings.StartPath = s;
				}
			}
			return settings;
		}
 public SearchResults[] SearchTranslationUnitsMasked(SearchSettings settings, TranslationUnit[] translationUnits, bool[] mask)
 {
     throw new NotImplementedException();
 }
 public SearchResults SearchTranslationUnit(SearchSettings settings, TranslationUnit translationUnit)
 {
     throw new NotImplementedException();
 }
 public SearchResults[] SearchSegmentsMasked(SearchSettings settings, Segment[] segments, bool[] mask)
 {
     throw new NotImplementedException();
 }
        public SearchResults[] SearchTranslationUnitsMasked(SearchSettings settings, TranslationUnit[] translationUnits,
                                                            bool[] mask)
        {
            // bug LG-15128 where mask parameters are true for both CM and the actual TU to be updated which cause an unnecessary call for CM segment

            var noOfResults = mask.Length;

            var results          = new List <SearchResults>(noOfResults);
            var preTranslateList = new List <PreTranslateSegment>(noOfResults);

            for (int i = 0; i < noOfResults; i++)
            {
                results.Add(null);
                preTranslateList.Add(null);
            }

            // plugin is called from pre-translate batch task
            //we receive the data in chunk of 10 segments
            if (translationUnits.Length > 2)
            {
                var i = 0;
                foreach (var tu in translationUnits)
                {
                    if (mask[i])
                    {
                        var preTranslate = new PreTranslateSegment
                        {
                            SearchSettings  = settings,
                            TranslationUnit = tu
                        };
                        preTranslateList.RemoveAt(i);
                        preTranslateList.Insert(i, preTranslate);
                    }
                    i++;
                }
                if (preTranslateList.Count > 0)
                {
                    //Create temp file with translations
                    var translatedSegments        = PrepareTempData(preTranslateList).Result;
                    var preTranslateSearchResults = GetPreTranslationSearchResults(translatedSegments);

                    foreach (var result in preTranslateSearchResults)
                    {
                        if (result != null)
                        {
                            var index = preTranslateSearchResults.IndexOf(result);
                            results.RemoveAt(index);
                            results.Insert(index, result);
                        }
                    }
                }
            }
            else
            {
                var i = 0;
                foreach (var tu in translationUnits)
                {
                    if (mask[i])
                    {
                        var result = SearchTranslationUnit(settings, tu);
                        results.RemoveAt(i);
                        results.Insert(i, result);
                    }
                    i++;
                }
            }
            return(results.ToArray());
        }
コード例 #18
0
 public SearchResults[] SearchTranslationUnits(SearchSettings settings, TranslationUnit[] translationUnits)
 {
     _translationUnits.Clear();
     _translationUnits.AddRange(translationUnits);
     return(null);
 }
コード例 #19
0
 public BingBotService(ILogger <BingBotService> logger, IOptions <SearchSettings> options, IHttpApiClient httpApiClient) : base(logger, httpApiClient)
 {
     _searchSettings = options.Value;
 }
コード例 #20
0
 public SearchResults SearchTranslationUnit(SearchSettings settings, TranslationUnit translationUnit)
 {
     return(SearchSegment(settings, translationUnit.SourceSegment));
 }
コード例 #21
0
 public SearchResults SearchSegment(SearchSettings settings, Segment segment)
 {
     return(null);
 }
コード例 #22
0
        public IQueryable <SearchResultItem> Query <T>(IQueryable <SearchResultItem> queryable, SearchSettings settings = null) where T : SearchResultItem
        {
            if (settings.Queries == null)
            {
                return(queryable);
            }

            var rootPredicates = PredicateBuilder.False <SearchHit <SearchResultItem> >();

            foreach (var _unsupportedQuery in _unsupportedQueryList)
            {
                var pred = _unsupportedQuery.Query <T>(queryable, settings);
                if (pred != null)
                {
                    rootPredicates = rootPredicates.Or(pred);
                }
            }

            if (rootPredicates.ToString() == "param => False")
            {
                return(queryable);
            }
            return(queryable.GetResults().Hits.Where(rootPredicates.Compile()).Select(d => d.Document).AsQueryable());
        }
コード例 #23
0
 public Expression <Func <SearchResultItem, bool> > Query <T>(SearchSettings settings = null) where T : SearchResultItem
 {
     throw new NotImplementedException();
 }
コード例 #24
0
 /// <summary>
 /// Translate an array of translation units using their source segments.
 /// </summary>
 /// <param name="settings"></param>
 /// <param name="translationUnits"></param>
 /// <returns></returns>
 public SearchResults[] SearchTranslationUnits(SearchSettings settings, TranslationUnit[] translationUnits)
 {
     _logger.Trace("");
     return(SearchSegments(settings, translationUnits.Select(tu => tu.SourceSegment).ToArray()));
 }
コード例 #25
0
ファイル: SearchService.cs プロジェクト: rizwan3d/elalang
 public void SearchNext()
 {
     if (lastSettings != null)
     {
         if (lastSettings.LastDocument.IsAlive)
             Search(lastSettings.Text, lastSettings.LastDocument, lastSettings.Flags, lastSettings.Scope, lastSettings.LastEndPosition, lastSettings.MaxPosition);
         else
             lastSettings = null;
     }
 }
コード例 #26
0
 public void SetSearchSettings(List <SearchSettingsItem> items)
 {
     SearchSettings.Set(items);
 }
コード例 #27
0
        public void ShouldReturnGlobalSearch(ISearchResults searchResults, [Substitute] SearchService service, [Substitute] SearchSettings settings, ISearchServiceRepository serviceRepository, ISearchSettingsRepository settingsRepository, QueryRepository queryRepository, IRenderingPropertiesRepository renderingPropertiesRepository, string query)
        {
            service.Search(Arg.Any <IQuery>()).Returns(searchResults);
            serviceRepository.Get().Returns(service);
            settingsRepository.Get().Returns(settings);
            var controller = new SearchController(serviceRepository, settingsRepository, queryRepository, renderingPropertiesRepository);
            var result     = controller.GlobalSearch() as ViewResult;

            result.Model.Should().As <ISearchResults>();
        }
 public WordsPercentageMatchCovenantSearchStrategy(SearchSettings searchSettings)
 {
     this.SearchSettings = searchSettings;
 }
コード例 #29
0
        /// <summary>
        /// searches for matches in files and performs replace of found ones
        /// </summary>
        /// <param name="_settings"></param>
        public void ReplaceInFiles(SearchSettings _settings)
        {
            validateSetts(_settings, true);

            _fileResults = new List <FileData>();

            foreach (string filePath in _files)
            {
                validateFile(filePath);

                createBackupFile(filePath);


                var fileTypeManager = DefaultFileTypeManager.CreateInstance(true);
                var extensionPoint  = PluginManager.DefaultPluginRegistry.GetExtensionPoint <FileTypeComponentBuilderAttribute>();
                //IFileExtractor parser = null;
                IBilingualDocumentGenerator writer = null;
                foreach (IExtension extension in extensionPoint.Extensions)
                {
                    IFileTypeComponentBuilder extensionFileTypeComponentBuilder = (IFileTypeComponentBuilder)extension.CreateInstance();
                    extensionFileTypeComponentBuilder.FileTypeManager = fileTypeManager;
                    IFileTypeInformation extensionFileTypeInformation = extensionFileTypeComponentBuilder.BuildFileTypeInformation(string.Empty);
                    string extensionFileTypeDefinitionId   = extensionFileTypeInformation.FileTypeDefinitionId.Id;
                    FileTypeComponentBuilderAttribute attr = extension.ExtensionAttribute as FileTypeComponentBuilderAttribute;

                    if (Equals(extensionFileTypeDefinitionId, "SDL XLIFF 1.0 v 1.0.0.0"))
                    {
                        //parser = extensionFileTypeComponentBuilder.BuildFileExtractor(filePath);
                        writer = extensionFileTypeComponentBuilder.BuildBilingualGenerator(filePath);
                    }
                }
                //XliffFileReader parser = new XliffFileReader(filePath);
                // var parser = FileReaderHelper.FileReader(filePath);

                var extractor = GetFileExtractor(filePath);
                if (extractor != null)
                {
                    var converter = fileTypeManager.GetConverter(extractor.BilingualParser);

                    SetFileExtractorProperties(extractor, converter);

                    var parserProperties = extractor.BilingualParser as INativeContentCycleAware;

                    var fileProperties = GetFileProperties(converter, filePath);

                    parserProperties?.SetFileProperties(fileProperties);

                    // var extractor = fileTypeManager.BuildFileExtractor(parser.BilingualParser, null);

                    // var writer = FileWriterHelper.FileWriter(filePath);

                    // create object to update file to replace found text
                    FileReplaceProcessor replaceProcessor = new FileReplaceProcessor(filePath, _settings);

                    // set extractor and processors
                    //  extractor.BilingualParser = parser.BilingualParser;
                    // converter.AddExtractor(extractor);

                    converter.SynchronizeDocumentProperties();
                    converter.AddBilingualProcessor(replaceProcessor);

                    if (writer != null)
                    {
                        converter.AddBilingualProcessor(new BilingualContentHandlerAdapter(writer.Input));
                    }

                    // start parsing the file
                    converter.Parse();

                    // save replace results
                    FileData fData = new FileData(filePath, replaceProcessor.ResultSource, replaceProcessor.ResultTarget);
                    fData.ReplaceResults = replaceProcessor.ResultOfReplace;
                    fData.Warnings       = replaceProcessor.Warnings;
                    _fileResults.Add(fData);

                    if (fData.ReplaceResults.Count < 1)
                    {
                        removeCreatedFile(filePath);
                    }
                    else if (!_settings.MakeBackup)
                    {
                        removeBackupFile(filePath);
                    }
                }
            }
        }
コード例 #30
0
        public Expression <Func <SearchHit <SearchResultItem>, bool> > BuildCondition(SearchSettings settings, Expression <Func <SearchHit <SearchResultItem>, bool> > predicateBuilder)
        {
            var compareFileds = GetCompareFileds(settings, Identifier);

            if (settings.CompareFiledType == "Date")
            {
                var fDate = DateTime.Parse(compareFileds.FirstOrDefault().filedToCompareWith);
                predicateBuilder = predicateBuilder.Or(i => DateTimeConverter.ToStringDate(i.Document.GetItem().Fields[compareFileds.FirstOrDefault().filedToGetFromItem].Value) <= fDate);
            }
            else if (settings.CompareFiledType == "Number")
            {
                var fNumber = Int32.Parse(compareFileds.FirstOrDefault().filedToCompareWith);
                predicateBuilder = predicateBuilder.Or(i => Int32.Parse(i.Document.GetItem().Fields[compareFileds.FirstOrDefault().filedToGetFromItem].Value) <= fNumber);
            }
            return(predicateBuilder);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="WordsPercentageMatchCovenantSearchStrategy"/> class.
 /// </summary>
 public WordsPercentageMatchCovenantSearchStrategy()
 {
     this.SearchSettings = new SearchSettings();
 }
コード例 #32
0
 protected void ClearIndexDataStoreClick(object sender, EventArgs e)
 {
     SearchSettings.GetDynamicDataStore().DeleteAll();
     this.ReIndex.Enabled = true;
 }
 public SearchResults SearchTranslationUnit(SearchSettings settings, TranslationUnit translationUnit)
 {
     //need to use the tu confirmation level in searchsegment method
     return(SearchSegment(settings, translationUnit.SourceSegment));
 }
コード例 #34
0
        public SearchResults[] SearchSegments(SearchSettings settings, Segment[] segments)
        {
            return _fileBasedTranslationProviderLanguageDirection.SearchSegments(settings, segments);

        }
 public SearchResults[] SearchSegments(SearchSettings settings, Segment[] segments)
 {
     throw new NotImplementedException();
 }
コード例 #36
0
        public SearchResults[] SearchSegmentsMasked(SearchSettings settings, Segment[] segments, bool[] mask)
        {
            return _fileBasedTranslationProviderLanguageDirection.SearchSegmentsMasked(settings, segments, mask);

        }
 public SearchResults SearchText(SearchSettings settings, string segment)
 {
     throw new NotImplementedException();
 }
コード例 #38
0
        public SearchResults SearchText(SearchSettings settings, string segment)
        {
            return _fileBasedTranslationProviderLanguageDirection.SearchText(settings, segment);

        }
 public SearchResults[] SearchTranslationUnits(SearchSettings settings, TranslationUnit[] translationUnits)
 {
     throw new NotImplementedException();
 }
コード例 #40
0
 public SearchResults SearchTranslationUnit(SearchSettings settings, TranslationUnit translationUnit)
 {
     return _fileBasedTranslationProviderLanguageDirection.SearchTranslationUnit(settings, translationUnit);
 }
コード例 #41
0
 public void SearchResultModelCanBeInitialized(SearchSettings settings, [NoAutoProperties] SearchResults results)
 {
 }
コード例 #42
0
 public SearchResults[] SearchTranslationUnits(SearchSettings settings, TranslationUnit[] translationUnits)
 {
     return _fileBasedTranslationProviderLanguageDirection.SearchTranslationUnits(settings, translationUnits);
 }
コード例 #43
0
ファイル: SearchService.cs プロジェクト: rizwan3d/elalang
        public void SearchAll(string text, Document doc, SearchFlags flags, SearchScope scope)
        {
            lastSettings = null;
            scanned = null;
            var items = new List<ResultItem>();
            var sw = new Stopwatch();
            sw.Start();
            var sm = default(SearchManager);
            var status = "{0} element(s) found. Search took: {1:F2} s.";
            var rootEditor = (ITextEditor)App.GetService<IEditorService>().GetEditor(doc.GetType()).Instance;
            var startPos = scope == SearchScope.Selection ? rootEditor.SelectionStart :
                scope == SearchScope.Current ? rootEditor.CaretPosition : 0;
            var endPos = scope == SearchScope.Selection ? rootEditor.SelectionEnd : 0;

            for(;;)
            {
                var res = Search(text, lastSettings != null ? lastSettings.LastDocument : doc, flags, scope, (d,r) =>
                    {
                        var editor = (ITextEditor)App.GetService<IEditorService>().GetEditor(d.GetType()).Instance;
                        var loc = editor.GetLocationFromPosition(d, r.StartPosition);
                        var txt = editor.GetContent(d, loc.Line).TrimStart(' ', '\t');
                        var item = new ResultItem(txt, d, loc.Line, loc.Column, r.EndPosition - r.StartPosition);

                        if (items.Count >= 1000)
                        {
                            status = "Too many entries found. Showing first {0}. Search took: {1:F2} s.";
                            return false;
                        }
                        else if (items.Contains(item))
                            return false;
                        else
                        {
                            items.Add(item);
                            return true;
                        }
                    }, true,
                    lastSettings != null ? lastSettings.LastEndPosition : 0,
                    lastSettings != null ? lastSettings.MaxPosition : endPos, sm);

                if (!res)
                    break;

                sm = lastSettings.SearchManager;
            }

            sw.Stop();
            var s = (Single)sw.ElapsedMilliseconds / 1000;

            var svc = App.GetService<IResultGridService>();
            svc.AddItems(items);
            App.OpenView("ResultGrid");
            App.GetService<IStatusBarService>().SetStatusString(StatusType.Information, status, items.Count, s);
        }
コード例 #44
0
    /// <summary>
    /// Loads data.
    /// </summary>
    private void LoadData()
    {
        // Initialize properties
        ArrayList     itemList  = null;
        FormFieldInfo formField = null;

        attributes.Clear();

        // Load DataClass
        dci = DataClassInfoProvider.GetDataClass(this.ItemID);

        DataClassInfo tree = null;

        // For 'cms.document' add 'ecommerce.sku' fields, too
        if ((dci != null) && (dci.ClassName == "cms.document"))
        {
            // For 'cms.document' add 'ecommerce.sku' fields, too
            tree = DataClassInfoProvider.GetDataClass("ecommerce.sku");

            if (tree != null)
            {
                // Load XML definition
                fi = FormHelper.GetFormInfo(tree.ClassName, false);
                // Get all fields
                itemList = fi.GetFormElements(true, true);
            }

            if (itemList != null)
            {
                // Store each field to array
                foreach (object item in itemList)
                {
                    if (item is FormFieldInfo)
                    {
                        formField = ((FormFieldInfo)(item));
                        object[] obj = { formField.Name, FormHelper.GetDataType(formField.DataType) };
                        attributes.Add(obj);
                    }
                }
            }
        }

        if (dci != null)
        {
            // Load XML definition
            fi = FormHelper.GetFormInfo(dci.ClassName, false);
            // Get all fields
            itemList = fi.GetFormElements(true, true);
            ss       = new SearchSettings();
            ss.LoadData(dci.ClassSearchSettings);
        }

        if (itemList != null)
        {
            // Store each field to array
            foreach (object item in itemList)
            {
                if (item is FormFieldInfo)
                {
                    formField = ((FormFieldInfo)(item));
                    object[] obj = { formField.Name, FormHelper.GetDataType(formField.DataType) };
                    attributes.Add(obj);
                }
            }
        }

        // For 'cms.document' add 'cms.tree' fields, too
        if ((dci != null) && (dci.ClassName == "cms.document"))
        {
            tree = DataClassInfoProvider.GetDataClass("cms.tree");

            if (tree != null)
            {
                // Load XML definition
                fi = FormHelper.GetFormInfo(tree.ClassName, false);
                // Get all fields
                itemList = fi.GetFormElements(true, true);
            }

            if (itemList != null)
            {
                // Store each field to array
                foreach (object item in itemList)
                {
                    if (item is FormFieldInfo)
                    {
                        formField = ((FormFieldInfo)(item));
                        object[] obj = { formField.Name, FormHelper.GetDataType(formField.DataType) };
                        attributes.Add(obj);
                    }
                }
            }
        }


        // For 'cms.user' add 'cms.usersettings' fields, too
        if ((dci != null) && (dci.ClassName.ToLower() == "cms.user"))
        {
            tree = DataClassInfoProvider.GetDataClass("cms.usersettings");

            if (tree != null)
            {
                // Load XML definition
                fi = FormHelper.GetFormInfo(tree.ClassName, false);
                // Get all fields
                itemList = fi.GetFormElements(true, true);
            }

            if (itemList != null)
            {
                // Store each field to array
                foreach (object item in itemList)
                {
                    if (item is FormFieldInfo)
                    {
                        formField = ((FormFieldInfo)(item));
                        object[] obj = { formField.Name, FormHelper.GetDataType(formField.DataType) };
                        attributes.Add(obj);
                    }
                }
            }
        }
    }
コード例 #45
0
ファイル: SearchService.cs プロジェクト: rizwan3d/elalang
        private bool Search(string textToFind, Document doc, SearchFlags flags, SearchScope scope, Func<Document,SearchResult,Boolean> foundAction, bool silent, 
            int startPosition, int endPosition, SearchManager sm)
        {
            lastSettings = null;
            var editor = (ITextEditor)App.Editor(doc.GetType());
            sm = sm ?? new SearchManager(editor.GetContent(doc));

            var sp = startPosition;
            var ep = endPosition;

            var res = sm.Search(flags, textToFind, sp, ep);

            if (res.Found)
            {
                lastSettings = new SearchSettings
                {
                    Text = textToFind,
                    Flags = flags,
                    Scope = scope,
                    LastEndPosition = res.EndPosition,
                    LastDocument = doc,
                    MaxPosition = ep,
                    SearchManager = silent ? sm : null
                };

                if (!silent)
                    sm.Dispose();

                return foundAction(doc, res);
            }
            else if (scope == SearchScope.AllDocuments)
            {
                sm.Dispose();
                sm = null;

                var srv = App.GetService<IDocumentService>();
                var newDoc = GetNextDocument(doc);

                if (newDoc != null)
                {
                    if (scanned == null)
                        scanned = new List<Document>();

                    if (scanned.IndexOf(newDoc) != -1)
                        return false;
                    else
                        scanned.Add(newDoc);

                    if (!silent)
                        srv.SetActiveDocument(newDoc);

                    if (silent)
                        sm = new SearchManager(editor.GetContent(newDoc));

                    return Search(textToFind, newDoc, flags, scope, foundAction, silent, 0, 0, sm);
                }

                return false;
            }
            else
            {
                sm.Dispose();
                return false;
            }
        }
 public SearchResults[] SearchSegments(SearchSettings settings, Segment[] segments)
 {
     SearchResults[] results = new SearchResults[segments.Length];
     for (int p = 0; p < segments.Length; ++p)
     {
         results[p] = SearchSegment(settings, segments[p]);
     }
     return results;
 }
コード例 #47
0
ファイル: SearchService.cs プロジェクト: rizwan3d/elalang
        public void ReplaceAll(string text, string textToReplace, Document doc, SearchFlags flags, SearchScope scope)
        {
            lastSettings = null;
            scanned = null;
            var items = new List<ResultItem>();
            var sw = new Stopwatch();
            sw.Start();
            var rootEditor = (ITextEditor)App.GetService<IEditorService>().GetEditor(doc.GetType()).Instance;
            rootEditor.BeginUndoAction();

            var startPos = scope == SearchScope.Selection ? rootEditor.SelectionStart :
                scope == SearchScope.Current ? rootEditor.CaretPosition : 0;
            var endPos = scope == SearchScope.Selection ? rootEditor.SelectionEnd : 0;

            for (;;)
            {
                var res = Search(text, lastSettings != null ? lastSettings.LastDocument : doc, flags, scope, (d, r) => {
                    var editor = (ITextEditor)App.GetService<IEditorService>().GetEditor(d.GetType()).Instance;
                    var loc = editor.GetLocationFromPosition(d, r.StartPosition);
                    var txt = editor.GetContent(d, loc.Line).TrimStart(' ', '\t');
                    var item = new ResultItem(txt, d, loc.Line, loc.Column, r.EndPosition - r.StartPosition);

                    var docSrv = App.GetService<IDocumentService>();

                    if (docSrv.GetActiveDocument() != d)
                    {
                        rootEditor.EndUndoAction();
                        docSrv.SetActiveDocument(d);
                        editor.BeginUndoAction();
                        rootEditor = editor;
                    }

                    var sci = editor.Control as ScintillaControl;

                    if (sci != null)
                        sci.ReplaceText(r.StartPosition, r.EndPosition, textToReplace);
                    else
                        editor.ReplaceText(r.StartPosition, r.EndPosition, textToReplace);

                    lastSettings.LastStartPosition = r.StartPosition;
                    lastSettings.TextToReplace = textToReplace;
                    lastSettings.LastEndPosition = r.StartPosition + textToReplace.Length;

                    if (items.Contains(item))
                        return false;
                    else
                    {
                        items.Add(item);
                        return true;
                    }
                }, true,
                lastSettings != null ? lastSettings.LastEndPosition : startPos,
                lastSettings != null ? lastSettings.MaxPosition : endPos, null);

                if (!res)
                    break;
            }

            rootEditor.EndUndoAction();
            sw.Stop();
            var s = (Single)sw.ElapsedMilliseconds / 1000;

            var svc = App.GetService<IResultGridService>();
            svc.AddItems(items);
            App.OpenView("ResultGrid");
            App.GetService<IStatusBarService>().SetStatusString(StatusType.Information, "{0} entries replaced. Replace took: {1:F2} s.", items.Count, s);
        }
 public SearchResults SearchText(SearchSettings settings, string segment)
 {
     Segment s = new Sdl.LanguagePlatform.Core.Segment(_languageDirection.SourceCulture);
     s.Add(segment);
     return SearchSegment(settings, s);
 }
 public SearchResults[] SearchTranslationUnits(SearchSettings settings, TranslationUnit[] translationUnits)
 {
     SearchResults[] results = new SearchResults[translationUnits.Length];
     for (int p = 0; p < translationUnits.Length; ++p)
     {
         //need to use the tu confirmation level in searchsegment method
         inputTu = translationUnits[p];
         results[p] = SearchSegment(settings, translationUnits[p].SourceSegment); //changed this to send whole tu
     }
     return results;
 }
コード例 #50
0
        protected override bool SetSettingItemValue(SettingBase setting, System.Reflection.PropertyInfo property)
        {
            if (property.Name == "SearchType")
            {
                SearchType searchType = _Request.Get <SearchType>("SearchType", Method.Post, SearchType.LikeStatement);

                if (searchType != AllSettings.Current.SearchSettings.SearchType)
                {
                    if (searchType == SearchType.FullTextIndex)
                    {
                        if (false == PostBOV5.Instance.StartPostFullTextIndex())
                        {
                            MsgDisplayForSaveSettings.AddError("开启全文索引失败,可能由于您没有足够的数据库权限");
                            return(false);
                        }
                    }
                    else
                    {
                        if (false == PostBOV5.Instance.StopPostFullTextIndex())
                        {
                            MsgDisplayForSaveSettings.AddError("关闭全文索引失败,可能由于您没有足够的数据库权限");
                            return(false);
                        }
                    }
                }
            }
            else if (property.Name == "EnableSearch")
            {
                SearchSettings temp = (SearchSettings)setting;
                temp.EnableSearch = new ExceptableSetting.ExceptableItem_bool().GetExceptable("EnableSearch", MsgDisplayForSaveSettings);

                if (MsgDisplayForSaveSettings.HasAnyError())
                {
                    return(false);
                }
                return(true);
            }

            else if (property.Name == "CanSearchTopicContent")
            {
                SearchSettings temp = (SearchSettings)setting;
                temp.CanSearchTopicContent = new ExceptableSetting.ExceptableItem_bool().GetExceptable("CanSearchTopicContent", MsgDisplayForSaveSettings);

                if (MsgDisplayForSaveSettings.HasAnyError())
                {
                    return(false);
                }
                return(true);
            }

            else if (property.Name == "CanSearchAllPost")
            {
                SearchSettings temp = (SearchSettings)setting;
                temp.CanSearchAllPost = new ExceptableSetting.ExceptableItem_bool().GetExceptable("CanSearchAllPost", MsgDisplayForSaveSettings);

                if (MsgDisplayForSaveSettings.HasAnyError())
                {
                    return(false);
                }
                return(true);
            }

            else if (property.Name == "CanSearchUserTopic")
            {
                SearchSettings temp = (SearchSettings)setting;
                temp.CanSearchUserTopic = new ExceptableSetting.ExceptableItem_bool().GetExceptable("CanSearchUserTopic", MsgDisplayForSaveSettings);

                if (MsgDisplayForSaveSettings.HasAnyError())
                {
                    return(false);
                }
                return(true);
            }

            else if (property.Name == "CanSearchUserPost")
            {
                SearchSettings temp = (SearchSettings)setting;
                temp.CanSearchUserPost = new ExceptableSetting.ExceptableItem_bool().GetExceptable("CanSearchUserPost", MsgDisplayForSaveSettings);

                if (MsgDisplayForSaveSettings.HasAnyError())
                {
                    return(false);
                }
                return(true);
            }

            else if (property.Name == "MaxResultCount")
            {
                SearchSettings temp = (SearchSettings)setting;
                temp.MaxResultCount = new ExceptableSetting.ExceptableItem_Int_MoreThenZero().GetExceptable("MaxResultCount", MsgDisplayForSaveSettings);

                if (MsgDisplayForSaveSettings.HasAnyError())
                {
                    return(false);
                }
                return(true);
            }

            else if (property.Name == "SearchTime")
            {
                SearchSettings temp = (SearchSettings)setting;
                temp.SearchTime = new ExceptableSetting.ExceptableItem_Int_MoreThenZero().GetExceptable("SearchTime", MsgDisplayForSaveSettings);

                if (MsgDisplayForSaveSettings.HasAnyError())
                {
                    return(false);
                }
                return(true);
            }

            return(base.SetSettingItemValue(setting, property));
        }
コード例 #51
0
        public SearchResults[] SearchTranslationUnitsMasked(SearchSettings settings, TranslationUnit[] translationUnits, bool[] mask)
        {
            return _fileBasedTranslationProviderLanguageDirection.SearchTranslationUnitsMasked(settings,
                translationUnits, mask);

        }
コード例 #52
0
    /// <summary>
    /// Stores data and raises OnSaved event.
    /// </summary>
    public void SaveData()
    {
        // Clear old values
        this.fields = new SearchSettings();
        SearchSettingsInfo ssi;
        CheckBox           chk;
        TextBox            txt;

        changed = false;

        // Create new SearchSettingInfos
        foreach (object[] item in attributes)
        {
            object[] obj = item;
            ssi = new SearchSettingsInfo();
            SearchSettingsInfo ssiOld = null;
            ssi.ID   = Guid.NewGuid();
            ssi.Name = obj[0].ToString();

            // Return old data to compare changes
            if (infos != null)
            {
                DataRow[] dr = infos.Tables[0].Select("name = '" + (string)obj[0] + "'");
                if ((dr != null) && (dr.Length > 0) && (ss != null))
                {
                    ssiOld = ss.GetSettingsInfo((string)dr[0]["id"]);
                }
            }

            // Store 'Content' value
            chk = (CheckBox)pnlContent.FindControl(obj[0] + CONTENT);
            if (chk != null)
            {
                // Check change
                if ((ssiOld != null) && (ssiOld.Content != chk.Checked))
                {
                    changed = true;
                }

                ssi.Content = chk.Checked;
            }

            // Store 'Searchable' value
            chk = (CheckBox)pnlContent.FindControl(obj[0] + SEARCHABLE);
            if (chk != null)
            {
                // Check change
                if ((ssiOld != null) && (ssiOld.Searchable != chk.Checked))
                {
                    changed = true;
                }

                ssi.Searchable = chk.Checked;
            }

            // Store 'Tokenized' value
            chk = (CheckBox)pnlContent.FindControl(obj[0] + TOKENIZED);
            if (chk != null)
            {
                // Check change
                if ((ssiOld != null) && (ssiOld.Tokenized != chk.Checked))
                {
                    changed = true;
                }

                ssi.Tokenized = chk.Checked;
            }

            // Store 'iFieldname' value
            txt = (TextBox)pnlContent.FindControl(obj[0] + IFIELDNAME);
            if (txt != null)
            {
                string fieldname = ValidationHelper.GetCodeName(txt.Text.Trim(), null, null);
                if (fieldname.Length > 200)
                {
                    fieldname = fieldname.Substring(0, 200);
                }
                if (!String.IsNullOrEmpty(fieldname))
                {
                    // Check change
                    if ((ssiOld != null) && (ssiOld.FieldName != fieldname))
                    {
                        changed = true;
                    }

                    ssi.FieldName = fieldname;
                }
            }

            this.fields.SetSettingsInfo(ssi);
        }

        // Store values to DB
        if (dci != null)
        {
            dci.ClassSearchSettings = this.fields.GetData();
            DataClassInfoProvider.SetDataClass(dci);
        }

        if (this.DisplaySaved)
        {
            lblInfo.Visible = true;
        }
        RaiseOnSaved();
    }
        public SearchResults SearchSegment(SearchSettings settings, Segment segment)
        {
            //FUTURE: consider making GT and MT lookup classes static utility classes

            Segment translation = new Segment(_languageDirection.TargetCulture);//this will be the target segment

            #region "SearchResultsObject"
            SearchResults results = new SearchResults();
            results.SourceSegment = segment.Duplicate();

            #endregion

            #region "Confirmation Level"
            if (!_options.ResendDrafts && inputTu.ConfirmationLevel != ConfirmationLevel.Unspecified) //i.e. if it's status is other than untranslated
            { //don't do the lookup, b/c we don't need to pay google to translate text already translated if we edit a segment
                translation.Add(PluginResources.TranslationLookupDraftNotResentMessage);
                //later get these strings from resource file
                results.Add(CreateSearchResult(segment, translation, segment.ToString()));
                return results;
            }
            #endregion

            // Look up the currently selected segment in the collection (normal segment lookup).
            #region "SegmentLookup"
            string sourceLang = SourceLanguage.ToString();
            string targetLang = TargetLanguage.ToString();
            string translatedText = "";
            //a new seg avoids modifying the current segment object
            Segment newseg = segment.Duplicate();

            //do preedit if checked
            bool sendTextOnly = _options.SendPlainTextOnly || !newseg.HasTags;
            if (!sendTextOnly)
            {
                //do preedit with tagged segment
                if (_options.UsePreEdit)
                {
                    if (preLookupSegmentEditor == null) preLookupSegmentEditor = new SegmentEditor(_options.PreLookupFilename);
                    newseg = getEditedSegment(preLookupSegmentEditor, newseg);
                }
                //return our tagged target segment
                MtTranslationProviderTagPlacer tagplacer = new MtTranslationProviderTagPlacer(newseg);
                ////tagplacer is constructed and gives us back a properly marked up source string for google
                if (_options.SelectedProvider == MtTranslationOptions.ProviderType.GoogleTranslate)
                {
                    translatedText = LookupGT(tagplacer.PreparedSourceText, _options, "html");
                }
                else if (_options.SelectedProvider == MtTranslationOptions.ProviderType.MicrosoftTranslator)
                {
                    translatedText = LookupMST(tagplacer.PreparedSourceText, _options, "text/html");
                }
                //now we send the output back to tagplacer for our properly tagged segment
                translation = tagplacer.GetTaggedSegment(translatedText).Duplicate();

                //now do post-edit if that option is checked
                if (_options.UsePostEdit)
                {
                    if (postLookupSegmentEditor == null) postLookupSegmentEditor = new SegmentEditor(_options.PostLookupFilename);
                    translation = getEditedSegment(postLookupSegmentEditor, translation);
                }
            }
            else //only send plain text
            {
                string sourcetext = newseg.ToPlain();
                //do preedit with string
                if (_options.UsePreEdit)
                {
                    if (preLookupSegmentEditor == null) preLookupSegmentEditor = new SegmentEditor(_options.PreLookupFilename);
                    sourcetext = getEditedString(preLookupSegmentEditor, sourcetext);
                    //change our source segment so it gets sent back with modified text to show in translation results window that it was changed before sending
                    newseg.Clear();
                    newseg.Add(sourcetext);
                }

                //now do lookup
                if (_options.SelectedProvider == MtTranslationOptions.ProviderType.GoogleTranslate)
                {
                    translatedText = LookupGT(sourcetext, _options, "html"); //plain??
                }
                else if (_options.SelectedProvider == MtTranslationOptions.ProviderType.MicrosoftTranslator)
                {
                    translatedText = LookupMST(sourcetext, _options, "text/plain");
                }

                //now do post-edit if that option is checked
                if (_options.UsePostEdit)
                {
                    if (postLookupSegmentEditor == null) postLookupSegmentEditor = new SegmentEditor(_options.PostLookupFilename);
                    translatedText = getEditedString(postLookupSegmentEditor, translatedText);
                }
                translation.Add(translatedText);
            }

            results.Add(CreateSearchResult(newseg, translation, newseg.ToPlain()));

            #endregion

            #region "Close"
            return results;
            #endregion
        }
コード例 #54
0
        private void ProcessGetThreads()
        {
            SearchSettings setting = AllSettings.Current.SearchSettings;

            isShowResult = true;

            PostBOV5.Instance.SearchTopics(m_SearchID, setting.SearchPageSize, _Request.Get <int>("page", Method.Get, 1), setting.SearchType, m_MaxResultCount, out TotalCount, out searchText, out mode, out threadList, out postList);

            searchString = searchText;
            if (mode == SearchMode.UserPost || mode == SearchMode.UserThread)
            {
                User user = UserBO.Instance.GetUser(int.Parse(searchText));
                searchText = string.Empty;
                if (user != null)
                {
                    searchString = user.Username;
                }
            }

            if (threadList == null && postList == null)
            {
                ShowError("非法的searchID");
            }

            else if (mode == SearchMode.Content || mode == SearchMode.TopicContent || mode == SearchMode.UserPost)
            {
                List <int> threadIDs = new List <int>();
                foreach (PostV5 post in postList)
                {
                    if (threadIDs.Contains(post.ThreadID) == false)
                    {
                        threadIDs.Add(post.ThreadID);
                    }
                }

                searchThreads = PostBOV5.Instance.GetThreads(threadIDs);

                WaitForFillSimpleUsers <PostV5>(postList, 1);

                CheckThreads();
            }

            List <int> forumIDs = new List <int>();

            if (threadList != null)
            {
                foreach (BasicThread thread in threadList)
                {
                    if (forumIDs.Contains(thread.ForumID) == false)
                    {
                        ManageForumPermissionSetNode managePermission = AllSettings.Current.ManageForumPermissionSet.Nodes.GetPermission(thread.ForumID);
                        if (managePermission.HasPermissionForSomeone(My, ManageForumPermissionSetNode.ActionWithTarget.DeleteAnyThreads) ||
                            managePermission.HasPermissionForSomeone(My, ManageForumPermissionSetNode.ActionWithTarget.SetThreadsRecycled))
                        {
                            isShowActionButton = true;
                            break;
                        }
                        forumIDs.Add(thread.ForumID);
                    }
                }
            }

            if (isShowActionButton == false && postList != null)
            {
                foreach (PostV5 post in postList)
                {
                    if (forumIDs.Contains(post.ForumID) == false)
                    {
                        ManageForumPermissionSetNode managePermission = AllSettings.Current.ManageForumPermissionSet.Nodes.GetPermission(post.ForumID);

                        if (managePermission.HasPermissionForSomeone(My, ManageForumPermissionSetNode.ActionWithTarget.DeletePosts))
                        {
                            isShowActionButton = true;
                            break;
                        }
                        forumIDs.Add(post.ForumID);
                    }
                }
            }

            PostBOV5.Instance.ProcessKeyword(threadList, ProcessKeywordMode.TryUpdateKeyword);
            PostBOV5.Instance.ProcessKeyword(postList, ProcessKeywordMode.TryUpdateKeyword);

            SetPager("list", UrlHelper.GetSearchUrl() + "?searchID=" + m_SearchID.ToString() + "&page={0}", _Request.Get <int>("page", Method.Get, 1), setting.SearchPageSize, TotalCount);
        }
        public SearchResults[] SearchSegmentsMasked(SearchSettings settings, Segment[] segments, bool[] mask)
        {
            if (segments == null)
            {
                throw new ArgumentNullException("segments in SearchSegmentsMasked");
            }
            if (mask == null || mask.Length != segments.Length)
            {
                throw new ArgumentException("mask in SearchSegmentsMasked");
            }

            SearchResults[] results = new SearchResults[segments.Length];
            for (int p = 0; p < segments.Length; ++p)
            {
                if (mask[p])
                {
                    results[p] = SearchSegment(settings, segments[p]);
                }
                else
                {
                    results[p] = null;
                }
            }

            return results;
        }
コード例 #56
0
        private void ProcessSearch()
        {
            SearchSettings setting = AllSettings.Current.SearchSettings;

            mode = (SearchMode)_Request.Get <int>("Mode", Method.Post, 1);

            int[] forumIDs = _Request.GetList <int>("forumIDs", Method.Post, null);

            searchText = _Request.Get("SearchText", Method.Post, string.Empty, false);

            int  searchtime = _Request.Get <int>("searchtime", Method.Post, 0);
            bool isbefore   = _Request.Get <bool>("isbefore", Method.Post, false);
            bool isdesc     = _Request.Get <bool>("isdesc", Method.Post, true);

            DateTime?postDate = null;

            if (searchtime > 0)
            {
                postDate = DateTimeUtil.Now.AddDays(0 - searchtime);
            }

            if (forumIDs != null)
            {
                bool isAll = false;
                foreach (int id in forumIDs)
                {
                    if (id == 0)
                    {
                        isAll = true;
                        break;
                    }
                }
                if (isAll)
                {
                    forumIDs = null;
                }
            }

            Guid searchResultID;

            using (ErrorScope es = new ErrorScope())
            {
                try
                {
                    searchResultID = PostBOV5.Instance.SearchTopics(My, forumIDs, searchText, mode, setting.SearchType, postDate, isbefore, isdesc, m_MaxResultCount);
                }
                catch (Exception ex)
                {
                    AlertError(ex.Message);
                    return;
                }
                if (searchResultID == Guid.Empty)
                {
                    es.CatchError <ErrorInfo>(delegate(ErrorInfo error)
                    {
                        //ShowError(error.Message);
                        AlertError(error.Message);
                    });
                }
                else
                {
                    m_SearchID = searchResultID;
                    //isShowResult = true;
                    ProcessGetThreads();
                    //Response.Redirect(BbsUrlHelper.GetSearchIndexUrl() + "?searchID=" + searchResultID.ToString());
                    AlertSuccess(searchResultID.ToString());
                }
            }

            //string url = BbsUrlHelper.GetSearchIndexUrl() + "?searchID=" + searchResultID.ToString();

            //ShowSuccess("搜索完毕, 稍后将转到搜索结果页面", url);
        }
 public SearchResults SearchTranslationUnit(SearchSettings settings, TranslationUnit translationUnit)
 {
     //need to use the tu confirmation level in searchsegment method
     inputTu = translationUnit;
     return SearchSegment(settings, translationUnit.SourceSegment);
 }
コード例 #58
0
        protected void Page_Load(object sender, System.EventArgs e)
        {
            AddNavigationItem("搜索");

            SearchSettings setting = AllSettings.Current.SearchSettings;

            if (IsLogin == false && setting.EnableGuestSearch == false)
            {
                ShowError("您是游客不允许使用搜索帖子的功能");
            }
            else if (IsLogin && setting.EnableSearch[My] == false)
            {
                ShowError("您所在的用户组不允许使用搜索帖子的功能");
            }

            canVisitForumIDs = ForumBO.Instance.GetForumIdsForVisit(My);

            if (canVisitForumIDs != null && canVisitForumIDs.Count == 0)
            {
                ShowError("您所在的用户组没有搜索帖子的权限");
            }

            //int maxResultCount = 0;

            if (IsLogin == false)
            {
                m_MaxResultCount = setting.GuestMaxResultCount;
            }
            else
            {
                m_MaxResultCount = setting.MaxResultCount[My];
            }

            if (_Request.Get("searchID", Method.Get) != null)
            {
                m_SearchID = _Request.Get <Guid>("searchID", Method.Get, Guid.Empty);
                if (m_SearchID == Guid.Empty)
                {
                    ShowError("非法的searchID");
                }
            }

            if (_Request.IsClick("SearchSubmit"))
            {
                ProcessSearch();
            }
            else
            {
                if (m_SearchID == Guid.Empty)
                {
                    mode = (SearchMode)_Request.Get <int>("Mode", Method.Get, 1);
                    string searchText = _Request.Get("SearchText", Method.Get, string.Empty, false);

                    if (mode == SearchMode.ThreadUserID || mode == SearchMode.PostUserID)
                    {
                        int userID;
                        if (int.TryParse(searchText, out userID) == false)
                        {
                            ShowError("用户ID必须为整数!");
                            return;
                        }

                        User user = UserBO.Instance.GetUser(userID);
                        if (user == null)
                        {
                            ShowError("不存在该用户!");
                            return;
                        }
                        else
                        {
                            if (mode == SearchMode.ThreadUserID)
                            {
                                mode = SearchMode.UserThread;
                            }
                            else
                            {
                                mode = SearchMode.UserPost;
                            }

                            m_SearchID = PostBOV5.Instance.SearchTopics(My, null, user.Username, mode, setting.SearchType, null, false, true, m_MaxResultCount);
                        }
                    }
                    else if (mode == SearchMode.Subject || mode == SearchMode.Content)
                    {
                        m_SearchID = PostBOV5.Instance.SearchTopics(My, null, HttpUtility.HtmlEncode(searchText), mode, setting.SearchType, null, false, true, m_MaxResultCount);
                    }
                    else if (mode == SearchMode.UserThread && searchText != string.Empty)
                    {
                        User user = UserBO.Instance.GetUser(searchText);
                        if (user == null)
                        {
                            ShowError("不存在该用户!");
                            return;
                        }
                        m_SearchID = PostBOV5.Instance.SearchTopics(My, null, searchText, mode, setting.SearchType, null, false, true, m_MaxResultCount);
                    }
                    if (m_SearchID != Guid.Empty)
                    {
                        string url = BbsUrlHelper.GetSearchIndexUrl() + "?searchID=" + m_SearchID.ToString();
                        ShowSuccess("搜索完毕, 稍后将转到搜索结果页面", url);
                    }
                }
                else
                {
                    ProcessGetThreads();
                }
            }
        }
        public SearchResults[] SearchTranslationUnitsMasked(SearchSettings settings, TranslationUnit[] translationUnits, bool[] mask)
        {
            List<SearchResults> results = new List<SearchResults>();

            List<KeyValuePair<string, string>> errors = new List<KeyValuePair<string, string>>();

            int i = 0;
            foreach (var tu in translationUnits)
            {
                if (mask == null || mask[i])
                {
                    var result = SearchTranslationUnit(settings, tu);
                    results.Add(result);
                }
                else
                {
                    results.Add(null);
                }
                i++;
            }

            if (errors.Count > 0)
            {
                string messages = "";
                foreach (KeyValuePair<string, string> pair in errors)
                    messages += pair.Key + ":  " + pair.Value + "\n";
                MessageBox.Show(messages);
            }

            return results.ToArray();
        }
コード例 #60
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SearchSignaturesRequest"/> class.
 /// </summary>
 /// <param name="searchSettings">Signatures search settings</param>
 public SearchSignaturesRequest(SearchSettings searchSettings)
 {
     this.searchSettings = searchSettings;
 }