//--------------------------------------------------------------------- internal bool InternalSearch(string conditionType, object conditionValue, Param1Handler <Transform> handler, object[] datas) { if (handler == null) { return(false); } SearchInfo searchInfo = new SearchInfo( conditionType, conditionValue, handler); if (datas == null || datas.Length == 0) { PushRequest(RequestType.Search, searchInfo); } else { object[] newDatas = new object[datas.Length + 1]; datas.CopyTo(newDatas, 0); newDatas[newDatas.Length - 1] = searchInfo; PushRequest(RequestType.Search, newDatas); } return(true); }
public void Update(SearchInfo searchInfo) { IDataParameter[] parms = null; var sqlUpdate = BaiRongDataProvider.TableStructureDao.GetUpdateSqlString(searchInfo.ToNameValueCollection(), ConnectionString, TableName, out parms); ExecuteNonQuery(sqlUpdate, parms); }
public IActionResult RecipeList(string searchingString, int recipePage = 1) { SearchInfo.setSearchInfo(searchingString); var recipes = from r in repository.Recipes select r; if (!string.IsNullOrEmpty(searchingString)) { recipes = repository.Recipes.Where(r => r.Name.Contains(searchingString) || r.Ingredients.Contains(searchingString) || r.Category.Contains(searchingString) || r.Instruction.Contains(searchingString)); } string filterItem = Request.Form["Category"].ToString(); if (!string.IsNullOrEmpty(filterItem)) { recipes = repository.Recipes.Where(r => r.Category.Contains(filterItem)); } return(View(new RecipeListViewModel { Recipes = recipes .OrderBy(r => r.Name) .Skip((recipePage - 1) * PageSize) .Take(PageSize), PagingInfo = new PagingInfo { CurrentPage = recipePage, ItemsPerPage = PageSize, TotalItems = recipes.Count() } })); }
public int Insert(SearchInfo searchInfo) { var searchId = 0; IDataParameter[] parms = null; var sqlInsert = BaiRongDataProvider.TableStructureDao.GetInsertSqlString(searchInfo.ToNameValueCollection(), ConnectionString, TableName, out parms); using (var conn = GetConnection()) { conn.Open(); using (var trans = conn.BeginTransaction()) { try { searchId = ExecuteNonQueryAndReturnId(trans, sqlInsert, parms); trans.Commit(); } catch { trans.Rollback(); throw; } } } return(searchId); }
// this is similar to searchwithinscreenrect, but the rect constructed is a map rectangle // as opposed to a screen rectangle (try both and see the difference) private void menuItemSearchWithinRect_Click(object sender, System.EventArgs e) { try { Cursor.Current = Cursors.WaitCursor; System.Drawing.Rectangle rect = mapControl1.Bounds; rect.X += rect.Width / 3; rect.Width = rect.Width / 3; rect.Y += rect.Height / 3; rect.Height = rect.Height / 3; DRect mapRect = new DRect(); // use csys and transform of feature layer, because that is the // layer we are doing the search on FeatureLayer layer = _map.Layers["uscty_1k"] as FeatureLayer; layer.DisplayTransform.FromDisplay(rect, out mapRect); SearchInfo si = MapInfo.Data.SearchInfoFactory.SearchWithinRect(mapRect, layer.CoordSys, ContainsType.Centroid); IResultSetFeatureCollection fc = _catalog.Search(layer.Table, si); // show search geometry on screen for visual confirmation DPoint [] pts = new DPoint[4]; mapRect.GetCornersOfRect(pts); FeatureGeometry g = new MapInfo.Geometry.MultiPolygon(layer.CoordSys, CurveSegmentType.Linear, pts); ShowSearchGeometry(g); SelectFeatureCollection(fc); } finally { Cursor.Current = Cursors.Default; } }
public SearchInfo[] SearchMultiTag(string[] tag, int idx) { string json = ""; //string realTag = BooruSearch.StaticTagAlias(tag); using (var wb = new WebClient()) { var uri = $"{url}/{post_url}{ tag[0].ToLower().Replace(' ', '_') }"; for (int i = 1; i < tag.Length; i++) { uri += $"+{tag[i].ToLower().Replace(' ', '_')}"; } json = wb.DownloadString(uri + $"&pid={idx / 100}"); } try { var t = JsonConvert.DeserializeObject <SearchResult[]>(json); var results = new SearchInfo[t.Length]; for (int i = 0; i < t.Length; i++) { results[i].URL = t[i].file_url; results[i].Tags = t[i].tags.Split(' '); } return(results); } catch (Exception) { return(null); } }
private void buttonSearch_Click(object sender, EventArgs e) //-----Search Button Click { groupBox1.Enabled = false; //can't make multiply search queries dataGridView.Visible = false; //dataGridView is being blocked checkBoxFollow.Visible = false; buttonExcel.Visible = false; AddToBDbutton.Visible = false; int mark_id = 0; try { mark_id = Convert.ToInt32(comboBoxBrand.SelectedValue.ToString()); } catch {} int year1 = Convert.ToInt32(comboBoxYear1.SelectedValue.ToString()); int year2 = Convert.ToInt32(comboBoxYear2.SelectedValue.ToString()); int region = 0; try { region = Convert.ToInt32(comboBoxRegion.SelectedValue.ToString()); } catch {} SearchInfo asyncInfo = new SearchInfo();//made an object of Information for Async asyncInfo.setInfo(mark_id, year1, year2, region); backgroundWorkerSearch.RunWorkerAsync(asyncInfo); //sent information to backgroundWorker1_DoWork pictureBox1.Visible = true; //loading.gif }
public IActionResult Validate([FromBody] PlantaValidator rep) { try { string Guid = System.Guid.NewGuid().ToString(); List <SearchInfo> files = _planta.fGetFiles(); rep.ImageName = Guid; rep.status = false; if (files.Count > 0) { SearchInfo oSearchModel = PlantaProvider.fSearch(rep.Image, files); if (oSearchModel != null && oSearchModel.Porcentaje < 15) { var omodel = _planta.findPlanta(oSearchModel.Id); rep.Id = omodel.Id; rep.status = true; } } return(Ok(rep)); } catch (Exception ex) { ExceptionLogging.SendErrorToText(ex, _env); throw new PlantaException(ex.Message, ex.InnerException); } }
/// <summary> /// Fires the specified info to each subscribed <see cref="IAnalysisWriter"/>. /// </summary> /// <param name="info">The info to pass to each subscriber.</param> public static void Fire(SearchInfo info) { List <IAnalysisWriter> writers = null; lock (syncRoot) writers = new List <IAnalysisWriter>(analysisWriters); if (writers == null) { return; } int totalWriters = writers.Count; if (totalWriters == 0) { return; } if (totalWriters % 2 == 1) { writers[totalWriters - 1].AddSearchInfo(info); totalWriters--; } for (int i = 0; i < totalWriters; i += 2) { writers[i].AddSearchInfo(info); writers[i + 1].AddSearchInfo(info); } }
public void LoadViews() { searchOrderView = new SearchInfo(DataBase, this); ViewDictionary.Add("SearchOrder", searchOrderView); searchOrderView.Dock = DockStyle.Fill; panel1.Controls.Add(searchOrderView); searchOrderView.Hide(); searchComponentView = new SearchComponent(DataBase, this); ViewDictionary.Add("SearchComponent", searchComponentView); searchComponentView.Dock = DockStyle.Fill; panel1.Controls.Add(searchComponentView); searchComponentView.Hide(); createComponentView = new CreateComponent(DataBase, this); ViewDictionary.Add("CreateComponent", createComponentView); createComponentView.Dock = DockStyle.Fill; panel1.Controls.Add(createComponentView); createComponentView.Hide(); OrderSuppliersView = new OrderSuppliers(DataBase, this); ViewDictionary.Add("OrderSuppliersView", OrderSuppliersView); OrderSuppliersView.Dock = DockStyle.Fill; panel1.Controls.Add(OrderSuppliersView); OrderSuppliersView.Hide(); }
public async Task Test_PlayMusic_Action_With_Input() { var actionInput = new SearchInfo() { MusicInfo = PlayMusicDialogUtterances.DefaultArtist }; await GetSkillTestFlow() .Send(new Activity(type: ActivityTypes.Event, name: Events.PlayMusic, value: JObject.FromObject(actionInput))) .AssertReply((activity) => { var a = (Activity)activity; Assert.AreEqual(ActivityTypes.Event, a.Type); Assert.AreEqual(typeof(OpenDefaultApp), a.Value.GetType()); Assert.AreEqual(PlayMusicDialogUtterances.DefaultArtistUri, (a.Value as OpenDefaultApp).MusicUri); }) .AssertReply((activity) => { var a = (Activity)activity; Assert.AreEqual(ActivityTypes.EndOfConversation, a.Type); Assert.AreEqual(typeof(ActionResult), a.Value.GetType()); Assert.AreEqual(true, (a.Value as ActionResult).ActionSuccess); }) .StartTestAsync(); }
// search through all tables to find objects that intersect // the states bordering KS private void menuItemSearchMultipleTables_Click(object sender, System.EventArgs e) { try { Cursor.Current = Cursors.WaitCursor; // find states that intersect KS // then combine them and search all layers within // also uses search for feature Feature fKS = _catalog.SearchForFeature("usa", MapInfo.Data.SearchInfoFactory.SearchWhere("State='KS'")); SearchInfo si = MapInfo.Data.SearchInfoFactory.SearchIntersectsFeature(fKS, IntersectType.Geometry); IResultSetFeatureCollection fc = _catalog.Search("usa", si); MapInfo.FeatureProcessing.FeatureProcessor fp = new MapInfo.FeatureProcessing.FeatureProcessor(); Feature f = fp.Combine(fc); si = MapInfo.Data.SearchInfoFactory.SearchWithinFeature(f, ContainsType.Centroid); MultiResultSetFeatureCollection mfc = _catalog.Search(_catalog.EnumerateTables(TableFilterFactory.FilterMappableTables()), si); // set map view to show search results _map.SetView(f); ShowSearchGeometry(f.Geometry); // show results as selection SelectFeatureCollection(fc); } finally { Cursor.Current = Cursors.Default; } }
public SearchViewModel(SearchInfo info, Action<SearchViewModel> removeAction) { _info = info; RemoveCommand = new Command(()=> removeAction(this)); var counter = _info.Latest .Select(lp => lp.Count) .Subscribe(count => Count = count); var counterTextFormatter = _info.Latest .Select(lp => { var limited = lp as IHasLimitationOfLines; if (limited == null) return $"{lp.Count.ToString("#,###0")}"; return limited.HasReachedLimit ? $"{limited.Maximum.ToString("#,###0")}+" : $"{lp.Count.ToString("#,###0")}"; }) .Subscribe(countText => CountText = countText); var progressMonitor = _info.Latest.OfType<IProgressInfo>().Subscribe(result => { Searching = result.IsSearching; Segments = result.Segments; SegmentsSearched = result.SegmentsCompleted; }); _cleanUp = new CompositeDisposable(progressMonitor, counter, counterTextFormatter); }
/// <summary>Constructs the <see cref="EnumerationPathState"/>.</summary> /// /// <param name="search">The search information to use.</param> public EnumerationPathState(SearchInfo search) { Search = search; Enumerator = new CurrentPathEnumerator(search); SubdirCount = 0; //IsSubdirSearch = false; }
public async Task <AnsInfo> SearchAns(SearchInfo si, Guid guid) { var searchgrain = GrainClient.GrainFactory.GetGrain <ISearchGrain>(guid); AnsInfo ai = searchgrain.SearchAns(si).Result; return(await Task.FromResult(ai)); }
// uses intersect filter to get states that intersect florida private void menuItemIntersectFeature_Click(object sender, System.EventArgs e) { try { Feature fFlorida = _catalog.SearchForFeature("usa", MapInfo.Data.SearchInfoFactory.SearchWhere("State='FL'")); // build up a search info by hand (not using the factory) QueryFilter filter = new IntersectFilter(fFlorida.Geometry, IntersectType.Bounds); QueryDefinition qd = new QueryDefinition(filter, "*"); SearchInfo si = new SearchInfo(null, qd); IResultSetFeatureCollection fc = _catalog.Search("usa", si); // set map view to show search results _map.SetView(fc.Envelope); ShowSearchGeometry(fFlorida.Geometry); // show results as selection SelectFeatureCollection(fc); } finally { Cursor.Current = Cursors.Default; } }
// find nearest city to center of map private void menuItemSearchNearest_Click(object sender, System.EventArgs e) { try { Cursor.Current = Cursors.WaitCursor; // to compare to SearchWithinScreenRadius, we are calculating // the search distance the same way it does System.Drawing.Rectangle rect = mapControl1.Bounds; System.Drawing.Point pt = new System.Drawing.Point(rect.Left, rect.Top); pt.X += rect.Width / 2; pt.Y += rect.Height / 2; DPoint dpt1 = new DPoint(); // convert center point to map coords (could use map.Center) _map.DisplayTransform.FromDisplay(pt, out dpt1); Distance d = MapInfo.Mapping.SearchInfoFactory.ScreenToMapDistance(_map, 3); SearchInfo si = MapInfo.Data.SearchInfoFactory.SearchNearest(dpt1, _map.GetDisplayCoordSys(), d); IResultSetFeatureCollection fc = _catalog.Search("uscty_1k", si); MapInfo.Geometry.Point p = new MapInfo.Geometry.Point(_map.GetDisplayCoordSys(), dpt1); FeatureGeometry buffer = p.Buffer(d.Value, d.Unit, 20, DistanceType.Spherical); ShowSearchGeometry(buffer); SelectFeatureCollection(fc); } finally { Cursor.Current = Cursors.Default; } }
// find and select cities with Georgia and Florida using geometry private void menuItemSearchWithinGeometry_Click(object sender, System.EventArgs e) { try { Cursor.Current = Cursors.WaitCursor; // find and select cities with Georgia and Florida using geometry // also uses search for feature Feature fFlorida = _catalog.SearchForFeature("usa", MapInfo.Data.SearchInfoFactory.SearchWhere("State='FL'")); Feature fGeorgia = _catalog.SearchForFeature("usa", MapInfo.Data.SearchInfoFactory.SearchWhere("State='GA'")); FeatureGeometry g = fFlorida.Geometry.Combine(fGeorgia.Geometry); SearchInfo si = MapInfo.Data.SearchInfoFactory.SearchWithinGeometry(g, ContainsType.Centroid); IResultSetFeatureCollection fc = _catalog.Search("uscty_1k", si); // set map view to show search results _map.SetView(fc.Envelope); ShowSearchGeometry(g); // show results as selection SelectFeatureCollection(fc); } finally { Cursor.Current = Cursors.Default; } }
public List <SearchInfo> GetSearchInfoListByKeywordId(int publishmentSystemId, int keywordId) { var searchInfoList = new List <SearchInfo>(); string sqlWhere = $"WHERE {SearchAttribute.PublishmentSystemId} = {publishmentSystemId} AND {SearchAttribute.IsDisabled} <> '{true}'"; if (keywordId > 0) { sqlWhere += $" AND {SearchAttribute.KeywordId} = {keywordId}"; } var sqlSelect = BaiRongDataProvider.TableStructureDao.GetSelectSqlString(ConnectionString, TableName, 0, SqlUtils.Asterisk, sqlWhere, null); using (var rdr = ExecuteReader(sqlSelect)) { while (rdr.Read()) { var searchInfo = new SearchInfo(rdr); searchInfoList.Add(searchInfo); } rdr.Close(); } return(searchInfoList); }
private void menuItemSetColumns_Click(object sender, System.EventArgs e) { try { // build up a search info by hand (not using the factory) QueryFilter filter = new SqlExpressionFilter("POP_90 < 1000000"); QueryDefinition qd = new QueryDefinition(filter, "MI_Key"); // to Add Columns qd.AppendColumns("State", "MI_Geometry"); // to set all new set of columns // not using MI_Geometry here string[] cols = new string[] { "MI_Key", "MI_Style", "State_Name", "POP_90", "Households_90" }; qd.Columns = cols; // Note: if you are doing a multi table search, the columns must apply to each table // alternatively, you can derive a new class from QueryDefinition and // override the GetColumns() method to return different columns for each table being searched SearchInfo si = new SearchInfo(null, qd); IResultSetFeatureCollection fc = _catalog.Search("mexico", si); // set map view to show search results _map.SetView(_map.Layers["mexico"] as FeatureLayer); // show results as selection SelectFeatureCollection(fc); } finally { Cursor.Current = Cursors.Default; } }
// find cities nearest to center within 3 pixel radius private void menuItemMapSearchNearest_Click(object sender, System.EventArgs e) { try { Cursor.Current = Cursors.WaitCursor; System.Drawing.Rectangle rect = mapControl1.Bounds; System.Drawing.Point pt = new System.Drawing.Point(rect.Left, rect.Top); pt.X += rect.Width / 2; pt.Y += rect.Height / 2; SearchInfo si = MapInfo.Mapping.SearchInfoFactory.SearchNearest(_map, pt, 3); IResultSetFeatureCollection fc = _catalog.Search("uscty_1k", si); rect.X = pt.X; rect.Y = pt.Y; rect.Width = 0; rect.Height = 0; rect.Inflate(3, 3); // show search geometry on screen for visual confirmation MapInfo.Geometry.MultiPolygon p = MapInfo.Mapping.SearchInfoFactory.CreateScreenRect(_map, rect); ShowSearchGeometry(p); SelectFeatureCollection(fc); } finally { Cursor.Current = Cursors.Default; } }
private SearchInfo GetSearchInfo(string searchKeyword, int?pageNumber, string facetValues, string sortField, int?pageSize, CommerceConstants.SortDirection?sortDirection) { if (this.CurrentSiteContext.Items[CurrentSearchInfoKeyName] != null) { return((SearchInfo)this.CurrentSiteContext.Items[CurrentSearchInfoKeyName]); } var searchManager = CommerceTypeLoader.CreateInstance <ICommerceSearchManager>(); var searchInfo = new SearchInfo { SearchKeyword = searchKeyword ?? string.Empty, RequiredFacets = searchManager.GetFacetFieldsForItem(this.Item), SortFields = searchManager.GetSortFieldsForItem(this.Item), Catalog = StorefrontManager.CurrentStorefront.DefaultCatalog, ItemsPerPage = pageSize ?? searchManager.GetItemsPerPageForItem(this.Item) }; if (searchInfo.ItemsPerPage == 0) { searchInfo.ItemsPerPage = StorefrontConstants.Settings.DefaultItemsPerPage; } var productSearchOptions = new CommerceSearchOptions(searchInfo.ItemsPerPage, pageNumber.GetValueOrDefault(0)); this.UpdateOptionsWithFacets(searchInfo.RequiredFacets, facetValues, productSearchOptions); this.UpdateOptionsWithSorting(sortField, sortDirection, productSearchOptions); searchInfo.SearchOptions = productSearchOptions; this.CurrentSiteContext.Items[CurrentSearchInfoKeyName] = searchInfo; return(searchInfo); }
public ActionResult BookedDetails(HotelBooking booking) { try { CreateSession(); SearchInfo info = searchManager.GetSearchInfo(); booking.BookingDate = DateTime.Now; booking.TotalCost = (decimal)TempData["TotalCost"]; booking.HotelBookingContacts = new HotelBookingContact() { ContactName = booking.HotelBookingContacts.ContactName, EmailID = booking.HotelBookingContacts.EmailID, PhoneNo = booking.HotelBookingContacts.PhoneNo }; booking.SearchInfos = new SearchInfo() { CheckInDate = info.CheckInDate, CheckOutDate = info.CheckOutDate, NoOfNight = info.NoOfNight, NoOfPeople = info.NoOfPeople, NoOfRooms = info.NoOfRooms, HotelId = info.HotelId, ExtraCost = info.ExtraCost }; searchManager.SaveBookingDummy(booking); } catch (Exception ex) { Console.WriteLine(ex.Message); } return(RedirectToAction("CreatePayment", "Payment")); }
/// <summary> /// Get data. /// </summary> /// <param name="searchInfo">The search info.</param> /// <param name="predicate">The predicate.</param> /// <returns></returns> private List <OrderView> GetData(SearchInfo searchInfo, Expression <Func <Order, bool> > predicate) { if (searchInfo.Take != null && searchInfo.Skip != null) { return(_orderRepository.GetOrders(predicate) .Skip(searchInfo.Skip.Value) .Take(searchInfo.Take.Value) .Select(order => Mapper.Map <OrderView>(order)) .OrderBy(order => order.OrderID) .ToList()); } if (searchInfo.Take == null && searchInfo.Skip.HasValue) { return(_orderRepository.GetOrders(predicate) .Skip(searchInfo.Skip.Value) .Select(order => Mapper.Map <OrderView>(order)) .OrderBy(order => order.OrderID) .ToList()); } if (searchInfo.Skip == null && searchInfo.Take.HasValue) { return(_orderRepository.GetOrders(predicate) .Take(searchInfo.Take.Value) .Select(order => Mapper.Map <OrderView>(order)) .OrderBy(order => order.OrderID) .ToList()); } return(_orderRepository.GetOrders(predicate) .Select(order => Mapper.Map <OrderView>(order)) .ToList()); }
public async Task <AnsInfo> SearchAns(SearchInfo Searchwords) { try { AnsInfo ai = new AnsInfo(); string search = Searchwords.SearchString + "&" + Searchwords.page + "&" + Searchwords.filter + "&" + Searchwords.filetype; if (Cache.CacheServices.cache.Exists(search)) { var cat = Cache.CacheServices.cache.Get(search); ai = (AnsInfo)cat; DeactivateOnIdle(); return(await Task.FromResult(ai)); } else { Cache.CacheServices cs = new Cache.CacheServices(); ai = cs.SearchforCache(Searchwords); DeactivateOnIdle(); return(await Task.FromResult(ai)); } throw new NotImplementedException(); } catch (Exception e) { Console.WriteLine(e.Data); throw; } }
private List <NewsModel> GetSearchResult(out int MatchCount, out int PageCount) { SearchInfo InputInfo = new SearchInfo() { ConfigElement = Config.Searches["news"], PageIndex = PageIndex, PageSize = PageSize, QueryString = SearchWord }; Searcher s = new NewsSearcher(InputInfo); List <ISearchEntity> RawResult = s.GetSearchResult(out MatchCount); //在这里排序 List <NewsModel> SearchResult = new List <NewsModel>(); int PageLowerBound = (InputInfo.PageIndex - 1) * PageSize; int PageUpperBound = PageLowerBound + PageSize; PageCount = (int)(MatchCount / PageSize) + 1; for (int i = 0; i < RawResult.Count; i++) { if (i > PageLowerBound && i <= PageUpperBound) { SearchResult.Add((NewsModel)RawResult[i]); } } return(SearchResult); }
private void btn_ric_Click(Object sender, EventArgs arg) { SearchInfo searchInfo = new SearchInfo(); searchInfo.RequestedPage = 1; searchInfo.PageSize = 10; searchInfo.Descrizione = this.txt_descr.Text; searchInfo.Codice = this.txt_codice.Text; SearchInfo = searchInfo; SearchOutput res = null; try { res = IntegrationAdapter.Search(searchInfo); bindDataGrid(res, 0); } catch (SearchException e) { if (e.Code == SearchExceptionCode.SERVICE_UNAVAILABLE) { handleDisservizio(); } if (e.Code == SearchExceptionCode.SERVER_ERROR) { Response.Write("<script language='javascript'>alert('" + e.Message + "')</script>"); } } catch (Exception e) { handleDisservizio(); } }
CallTreeNodeViewModel GetViewModelFromPath(IEnumerable <NodePath> paths, SearchInfo info) { CallTreeNodeViewModel result = null; var parent = list.Roots.FirstOrDefault(i => i.Node.Equals(info.ResultRoot)); foreach (var path in paths) { var items = parent.Children; foreach (var pathId in path.Skip(1)) { foreach (var item in items) { if (item.Node.NameMapping.Id == pathId) { items = item.Children; result = item; break; } } if (result == null) { break; } } } return(result); }
public SearchViewModel(SearchInfo tail, Action <SearchViewModel> removeAction) { _tail = tail; RemoveCommand = new Command(() => removeAction(this)); var counter = _tail.Latest .Select(lp => lp.Count) .Subscribe(count => Count = count); var counterTextFormatter = _tail.Latest .Select(lp => { var limited = lp as IHasLimitationOfLines; if (limited == null) { return($"{lp.Count.ToString("#,###0")}"); } return(limited.HasReachedLimit ? $"{limited.Maximum.ToString("#,###0")}+" : $"{lp.Count.ToString("#,###0")}"); }) .Subscribe(countText => CountText = countText);; var progressMonitor = _tail.Latest.OfType <IProgressInfo>().Subscribe(result => { Searching = result.IsSearching; Segments = result.Segments; SegmentsSearched = result.SegmentsCompleted; }); _cleanUp = new CompositeDisposable(progressMonitor, counter, counterTextFormatter); }
/// <summary> /// Adds the search result for direct flights into the schedule for travel /// </summary> /// <param name="searchInformation"></param> /// <param name="scheduleCollection"></param> /// <param name="result"></param> /// <exception cref="DirectFlightsNotAvailableException">Throws the exception when direct flights are not available for given search information</exception> private void AddSearchResultForDirectFlights(SearchInfo searchInformation, Schedules scheduleCollection, SearchResult result) { TravelSchedule scheduleForTravel = null; foreach (Schedule s in scheduleCollection) { if (s.RouteInfo.FromCity.CityId == searchInformation.FromCity.CityId && s.RouteInfo.ToCity.CityId == searchInformation.ToCity.CityId) { //Create a new TravelSchedule scheduleForTravel = CreateTravelSchedule(ScheduleType.Direct); //Add schedules to Travel Schedule AddScheduleForTravel(scheduleForTravel, s); //Compute total cost for the Travel Schedule CalculateTotalCostForTravel(scheduleForTravel); //Add the travel schedule defined to the search result AddTravelScheduleToResult(scheduleForTravel, result); } } if (scheduleForTravel == null) { throw new DirectFlightsNotAvailableException("Direct Flights Not Available"); } }
public override bool LoadData(ActivityInfo ai) { if (ai == null) { return(false); } switch (ai.ActivityType) { case PredefinedActivityType.EXTERNAL_SEARCH: case PredefinedActivityType.INTERNAL_SEARCH: break; default: return(false); } // Load additional info SearchInfo si = SearchInfoProvider.GetSearchInfoByActivityID(ai.ActivityID); if (si == null) { return(false); } ucDetails.AddRow("om.activitydetails.keywords", si.SearchKeywords); if (ai.ActivityType == PredefinedActivityType.EXTERNAL_SEARCH) { ucDetails.AddRow("om.activitydetails.provider", si.SearchProvider); } return(ucDetails.IsDataLoaded); }
private void btnSearchClick(object sender, EventArgs e) { OpenFileDialog o = new OpenFileDialog(); o.CheckFileExists = true; if (o.ShowDialog() != DialogResult.OK) return; searchInfo = new SearchInfo( o.FileName, txtEntry.Text, Encoding.GetEncoding(comboEnc.Text), comboCharSize.Text); worker.RunWorkerAsync(searchInfo); }
protected void Page_Load(object sender, EventArgs e) { string searchWords = Request.QueryString["SearchWords"]; string indexNames = Request.QueryString["IndexNames"]; //Response.Write(searchWords); string hostname = ConfigurationManager.AppSettings["HostName"]; int port = int.Parse(ConfigurationManager.AppSettings["PortNum"]); TcpClient client; NetworkStream ns; BinaryFormatter formater; DateTime now = DateTime.Now; try { client = new TcpClient(hostname, port); ns = client.GetStream(); formater = new BinaryFormatter(); SearchInfo sinfo = new SearchInfo(); QueryInfo info = new QueryInfo(); info.IndexNames = ""; info.SearchWords = searchWords; info.IndexNames = indexNames; sinfo.Query = info; sinfo.PageSize = 10; formater.Serialize(ns, sinfo); SearchResult sr = (SearchResult)formater.Deserialize(ns); //WriteLog(Server.MapPath(".") + "searchutils.log", searchWords, indexNames, sr.Records.Count, sr); XmlSerializer xmlSerializer = new XmlSerializer(typeof(SearchResult)); StringBuilder builder = new StringBuilder(); StringWriter writer = new StringWriter(builder); xmlSerializer.Serialize(writer, sr); XmlDocument doc = new XmlDocument(); doc.LoadXml(builder.ToString()); writer.Close(); ns.Close(); Response.Write(doc.DocumentElement.OuterXml); //FileStream fs = new FileStream(@"result.xml", FileMode.Truncate); //xmlSerializer.Serialize(writer, fs); //fs.Close(); } catch (Exception se) { Response.Write(se.StackTrace.ToString()); return; } }
/// <summary> /// Fires the specified info to each subscribed <see cref="IAnalysisWriter"/>. /// </summary> /// <param name="info">The info to pass to each subscriber.</param> public static void Fire(SearchInfo info) { List<IAnalysisWriter> writers = null; lock (syncRoot) writers = new List<IAnalysisWriter>(analysisWriters); if (writers == null) return; int totalWriters = writers.Count; if (totalWriters == 0) return; if (totalWriters % 2 == 1) { writers[totalWriters - 1].AddSearchInfo(info); totalWriters--; } for (int i = 0; i < totalWriters; i += 2) { writers[i].AddSearchInfo(info); writers[i + 1].AddSearchInfo(info); } }
private static SearchInfo BuildSearchInfo(string blob) { if (blob.Contains("***")) throw new Exception("Invalid blob string"); var searchInfo = new SearchInfo { FileName = blob }; var blobIndex = blob.IndexOf("*"); if (blobIndex > -1) { var beforeBlob = blob.Substring(0, blobIndex); var directoryPart = blobIndex == 0 ? "." : Path.GetDirectoryName(beforeBlob); var patternPart = blob.Substring(directoryPart.Length).TrimStart('\\'); var afterBlob = blob.Substring(blobIndex); searchInfo.FileName = null; searchInfo.Directory = Path.GetFullPath(blobIndex == 0 ? "." : Path.GetDirectoryName(beforeBlob)); searchInfo.Pattern = new Regex(Regex.Escape(Path.Combine(searchInfo.Directory, patternPart)).Replace(@"\*\*", ".*").Replace(@"\*", @"[^\\]*")); } return searchInfo; }
public PassiveSearch() { UpdateBase = new FlowLib.Events.FmdcEventHandler(PassiveSearch_UpdateBase); HubSetting settings = new HubSetting(); settings.Address = "127.0.0.1"; settings.Port = 411; settings.DisplayName = "FlowLib"; settings.Protocol = "Auto"; Hub hubConnection = new Hub(settings,this); hubConnection.ProtocolChange += new FmdcEventHandler(hubConnection_ProtocolChange); hubConnection.Connect(); // Wait 5 seconds (We should really listen on ConnectionStatusChange instead. System.Threading.Thread.Sleep(5 * 1000); // Send Search SearchInfo searchInfo = new SearchInfo(); searchInfo.Set(SearchInfo.SEARCH, "Ubuntu"); UpdateBase(this, new FlowLib.Events.FmdcEventArgs(Actions.Search, searchInfo)); }
void SearchCompleted(SearchInfo? result, AdornerLayer layer, OverlayAdorner ad) { if (!result.HasValue) return; CallTreeNodeViewModel item = GetViewModelFromPath(result.Value.Result.GetPathRelativeTo(result.Value.ResultRoot), result.Value); if (item != null) { item.IsSelected = true; if (oldSearchResult != null) oldSearchResult.IsSelected = false; oldSearchResult = item; } layer.Remove(ad); }
void hubConnection_Update(object sender, FlowLib.Events.FmdcEventArgs e) { Hub hub = sender as Hub; if (hub == null) return; switch (e.Action) { case Actions.SearchResult: if (e.Data is SearchResultInfo) { SearchResultInfo srInfo = (SearchResultInfo)e.Data; // This is if we want to enable auto adding of sources to a downloaditem. //FlowLib.Managers.DownloadManager dm = new FlowLib.Managers.DownloadManager(); //DownloadItem tmpDownloadItem = new DownloadItem(srInfo.Info); //// Do downloadItem exist? //if (dm.ContainsDownload(tmpDownloadItem)) //{ // // Add Source to the existing downloaditem. Note that we first check if it exist. // dm.AddDownload(tmpDownloadItem, srInfo.Source); //} } break; case Actions.UserOnline: bool hasMe = (hub.GetUserById(hub.Me.ID) != null); if (!sentRequest && hasMe) { // Send Search SearchInfo searchInfo = new SearchInfo(); searchInfo.Set(SearchInfo.SEARCH, "Ubuntu"); //searchInfo.Set(SearchInfo.SIZE, "1000"); //searchInfo.Set(SearchInfo.SIZETYPE, "1"); UpdateBase(this, new FlowLib.Events.FmdcEventArgs(Actions.Search, searchInfo)); sentRequest = true; } break; } }
public static List<SearchInfo> SearchDocuments(string DmtLabel) { if (InstSQLite==null) return new List<SearchInfo>(); List<SearchInfo> ret=new List<SearchInfo>(); string sqlCommand=String.Format("SELECT * FROM gtjlteMain WHERE DmtLabel LIKE\"%{0}%\";", DmtLabel); DataTable InstDataTable=InstSQLite.ExecuteQuery(sqlCommand); foreach (DataRow i in InstDataTable.Rows) { SearchInfo tmp = new SearchInfo(); tmp.DmtLabel=i["DmtLabel"].ToString(); tmp.DmtIndex=(int)(long)(i["IndexID"]); tmp.DmtCategory=(int)(long)(i["DmtCategory"]); ret.Add(tmp); } return ret; }
public ProductSearcher(SearchInfo info) { searchInfo = info; }
/// <summary> /// Adds a <see cref="IndexLibrary.SearchInfo"/> to this summary /// </summary> /// <param name="info">The info to add.</param> public void AddSearchInfo(SearchInfo info) { if (info == null) throw new ArgumentNullException("info", "info cannot be null"); if (info.IsEmpty) throw new ArgumentNullException("info", "info cannot be empty"); this.totalSearches += 1L; if ((info.TotalResultsFound > 0) && (this.features & SearchInfoSummaryFeature.TotalSearches) == SearchInfoSummaryFeature.TotalSearches) this.totalSearchesWithResults += 1L; if (info.Canceled && (this.features & SearchInfoSummaryFeature.CanceledSearches) == SearchInfoSummaryFeature.CanceledSearches) this.totalCanceledSearches += 1L; if ((this.features & SearchInfoSummaryFeature.TotalSearchesByMethod) == SearchInfoSummaryFeature.TotalSearchesByMethod) { Dictionary<SearchMethodType, int> dictionary; SearchMethodType type; (dictionary = this.totalSearchesFromEachMethod)[type = info.SearchMethodType] = dictionary[type] + 1; } if ((this.features & SearchInfoSummaryFeature.TotalSearchesByIndex) == SearchInfoSummaryFeature.TotalSearchesByIndex) { if (!this.totalSearchesFromEachIndex.ContainsKey(info.IndexName)) this.totalSearchesFromEachIndex.Add(info.IndexName, 0); this.totalSearchesFromEachIndex[info.IndexName]++; } if ((this.features & SearchInfoSummaryFeature.SearchTimeSpread) == SearchInfoSummaryFeature.SearchTimeSpread) { DateTime key = new DateTime(info.CreatedTime.Year, info.CreatedTime.Month, info.CreatedTime.Day, info.CreatedTime.Hour, info.CreatedTime.Minute, 0); if (!this.searchSpread.ContainsKey(key)) this.searchSpread.Add(key, 0); this.searchSpread[key]++; } bool flag = (this.features & SearchInfoSummaryFeature.UniqueQueries) == SearchInfoSummaryFeature.UniqueQueries; bool flag2 = (this.features & SearchInfoSummaryFeature.UniqueClauses) == SearchInfoSummaryFeature.UniqueClauses; if (!string.IsNullOrEmpty(info.Query) && (flag || flag2)) { try { BooleanQuery query = new BooleanQuery(); query.Add(this.parser.Parse(info.Query), BooleanClause.Occur.SHOULD); if (flag) { string str = query.ToString(); if (!this.totalUniqueSearchesAndTotalTimesUsed.ContainsKey(str)) this.totalUniqueSearchesAndTotalTimesUsed.Add(str, 0); this.totalUniqueSearchesAndTotalTimesUsed[str]++; str = null; } if (flag2) { System.Collections.Hashtable terms = new System.Collections.Hashtable(); query.ExtractTerms(terms); // its okay to fail, if its a term with something like Field:Value~0.5 we don't want the primitives, the list would be too large string value = null; foreach (var term in terms) { value = ((System.Collections.DictionaryEntry)term).Key.ToString(); if (!this.totalUniqueClausesAndTotalTimesUsed.ContainsKey(value)) this.totalUniqueClausesAndTotalTimesUsed.Add(value, 0); this.totalUniqueClausesAndTotalTimesUsed[value]++; } } } catch { } } }
public NewsSearcher(SearchInfo info) { searchInfo = info; }
/// <summary> /// Adds a <see cref="IndexLibrary.SearchInfo"/> to the analysis stack /// </summary> /// <param name="info">The information being reported.</param> public void AddSearchInfo(SearchInfo info) { if (this.trackSearches) this.searches.Enqueue(info); }
private void menuItemSqlExpressionFilter_Click(object sender, System.EventArgs e) { try { // build up a search info by hand (not using the factory) QueryFilter filter = new SqlExpressionFilter("Buses_91 * 3 < Trucks_91"); QueryDefinition qd = new QueryDefinition(filter, "*"); SearchInfo si = new SearchInfo(null, qd); IResultSetFeatureCollection fc = _catalog.Search("mexico", si); // set map view to show search results _map.SetView(fc.Envelope); // show results as selection SelectFeatureCollection(fc); } finally { Cursor.Current = Cursors.Default; } }
private void menuItemSetColumns_Click(object sender, System.EventArgs e) { try { // build up a search info by hand (not using the factory) QueryFilter filter = new SqlExpressionFilter("POP_90 < 1000000"); QueryDefinition qd = new QueryDefinition(filter, "MI_Key"); // to Add Columns qd.AppendColumns("State", "MI_Geometry"); // to set all new set of columns // not using MI_Geometry here string[] cols = new string[] {"MI_Key", "MI_Style", "State_Name", "POP_90", "Households_90"}; qd.Columns = cols; // Note: if you are doing a multi table search, the columns must apply to each table // alternatively, you can derive a new class from QueryDefinition and // override the GetColumns() method to return different columns for each table being searched SearchInfo si = new SearchInfo(null, qd); IResultSetFeatureCollection fc = _catalog.Search("mexico", si); // set map view to show search results _map.SetView(_map.Layers["mexico"] as FeatureLayer); // show results as selection SelectFeatureCollection(fc); } finally { Cursor.Current = Cursors.Default; } }
// shows how to combine filters using logical And private void menuItemLogicalFilter_Click(object sender, System.EventArgs e) { try { Feature fChicago = _catalog.SearchForFeature("uscty_1k", MapInfo.Data.SearchInfoFactory.SearchWhere("City='Chicago'")); // build up a search info by hand (not using the factory) Distance d1 = new Distance(35, DistanceUnit.Mile); Distance d2 = new Distance(125, DistanceUnit.Mile); QueryFilter filterA = new MyCustomFilter(fChicago.Geometry, d1, d2); // build up a search info by hand (not using the factory) QueryFilter filterB = new SqlExpressionFilter("State='IL'"); QueryFilter filter = new LogicalFilter(LogicalOperation.And, filterA, filterB); QueryDefinition qd = new QueryDefinition(filter, "*"); SearchInfo si = new SearchInfo(null, qd); IResultSetFeatureCollection fc = _catalog.Search("uscty_1k", si); // set map view to show search results _map.SetView(fc.Envelope); // make a search geometry to show what we are doing FeatureGeometry buffer1 = fChicago.Geometry.Buffer(d1.Value, d1.Unit, 20, DistanceType.Spherical); FeatureGeometry buffer2 = fChicago.Geometry.Buffer(d2.Value, d2.Unit, 20, DistanceType.Spherical); ShowSearchGeometry(buffer1); ShowSearchGeometry(buffer2, false); Feature fIL = _catalog.SearchForFeature("usa", MapInfo.Data.SearchInfoFactory.SearchWhere("State='IL'")); ShowSearchGeometry(fIL.Geometry, false); // show results as selection SelectFeatureCollection(fc); } finally { Cursor.Current = Cursors.Default; } }
public void ActOnInMessage(IConMessage conMsg) { StrMessage message = (StrMessage)conMsg; #region INF if (message is INF) { INF inf = (INF)message; if (hub != null && inf.Type.Equals("I")) { if (hub.RegMode < 0) hub.RegMode = 0; UpdateInf(); Info = inf.UserInfo; if (hub != null && Info.Description == null) Update(con, new FmdcEventArgs(Actions.Name, new Containers.HubName(Info.DisplayName))); else if (hub != null) Update(con, new FmdcEventArgs(Actions.Name, new Containers.HubName(Info.DisplayName, Info.Description))); } else if (trans != null && inf.Type.Equals("C")) { string token = null; // CINF IDE3VACJVAXNOQLGRFQS7D5HYH4A6GLZDO3LJ33HQ TO2718662518 if (trans.Me != null && trans.Me.ContainsKey("TO")) token = trans.Me.Get("TO"); else if (inf.UserInfo.ContainsKey("TO")) token = inf.UserInfo.Get("TO"); TransferRequest req = new TransferRequest(token, null, inf.UserInfo); FmdcEventArgs eArgs = new FmdcEventArgs(0, req); RequestTransfer(trans, eArgs); req = eArgs.Data as TransferRequest; if (!eArgs.Handled || req == null) { // Can't see user/connection on my allow list trans.Disconnect("No match for Request"); return; } if (!((req.User.ContainsKey(UserInfo.CID) && inf.UserInfo.ContainsKey(UserInfo.CID)) && req.User.Get(UserInfo.CID).Equals(inf.UserInfo.Get(UserInfo.CID)))) { // For some reason user is trying to tell us it is a diffrent user. We dont like that. FmdcEventArgs e = new FmdcEventArgs((int)TransferErrors.USERID_MISMATCH); Error(trans, e); if (!e.Handled) { trans.Disconnect("User Id Mismatch"); return; } } if (trans.Me == null) trans.Me = req.Me; trans.User = req.User; info = trans.User; trans.Share = req.Share; trans.Source = req.Source; download = req.Download; con.Send(new INF(con, trans.Me)); if (download) { EnsureCurrentSegmentCancelation(); // Request new segment from user. IF we have found one. ELSE disconnect. if (GetSegment(true)) { OnDownload(); } else trans.Disconnect("All content downloaded"); } } else if (hub != null) { User usr = null; if ((usr = hub.GetUserById(inf.Id)) == null) { if (inf.UserInfo.Mode == ConnectionTypes.Unknown) { inf.UserInfo.Mode = ConnectionTypes.Passive; } Update(con, new FmdcEventArgs(Actions.UserOnline, inf.UserInfo)); } else { usr.UserInfo = inf.UserInfo; Update(con, new FmdcEventArgs(Actions.UserInfoChange, usr.UserInfo)); } // This is so we update our own reg/op hub count. if (string.Equals(hub.Me.ID,inf.Id)) { // Should we be marked with key? bool regmodeChanged = false; if (hub.RegMode < 2) { if (((UserInfo.ACCOUNT_FLAG_OPERATOR & inf.UserInfo.Account) == UserInfo.ACCOUNT_FLAG_OPERATOR)) { hub.RegMode = 2; regmodeChanged = true; } else if (((UserInfo.ACCOUNT_FLAG_SUPERUSER & inf.UserInfo.Account) == UserInfo.ACCOUNT_FLAG_SUPERUSER)) { hub.RegMode = 2; regmodeChanged = true; } else if (((UserInfo.ACCOUNT_FLAG_HUBOWNER & inf.UserInfo.Account) == UserInfo.ACCOUNT_FLAG_HUBOWNER)) { hub.RegMode = 2; regmodeChanged = true; } } // Should we be marked as reg? if (hub.RegMode < 1) { if (((UserInfo.ACCOUNT_FLAG_REGISTERED & inf.UserInfo.Account) == UserInfo.ACCOUNT_FLAG_REGISTERED)) { hub.RegMode = 1; regmodeChanged = true; } } if (regmodeChanged) UpdateInf(); IsReady = true; } } } #endregion #region MSG else if (message is MSG && hub != null) { MSG msg = (MSG)message; if (msg.PmGroup == null) { MainMessage main = new MainMessage(msg.From, msg.Content); Update(con, new FmdcEventArgs(Actions.MainMessage, main)); } else { PrivateMessage pm = new PrivateMessage(msg.To, msg.From, msg.Content, msg.PmGroup); Update(con, new FmdcEventArgs(Actions.PrivateMessage, pm)); } } #endregion #region SID else if (message is SID && hub != null) { SID sid = (SID)message; hub.Me.Set(UserInfo.SID, sid.Id); } #endregion #region STA else if (message is STA) { STA sta = (STA)message; if (hub != null) { MainMessage main = new MainMessage(info.ID, sta.Content); Update(con, new FmdcEventArgs(Actions.MainMessage, main)); } } #endregion #region GPA else if (message is GPA) { GPA gpa = (GPA)message; this.gpaString = gpa.RandomData; if (trans != null) { Update(con, new FmdcEventArgs(Actions.Password, null)); } if (hub != null && hub.HubSetting.Password.Length == 0) { Update(con, new FmdcEventArgs(Actions.Password, null)); } else hub.Send(new PAS(hub, gpa.RandomData, hub.HubSetting.Password)); } #endregion #region QUI else if (message is QUI && hub != null) { QUI qui = (QUI)message; User usr = null; if ((usr = hub.GetUserById(qui.Id)) != null) { Update(con, new FmdcEventArgs(Actions.UserOffline, usr.UserInfo)); if (usr.ID == hub.Me.ID) { // TODO : Banning and redirect handling hub.Disconnect(); // Redirect if (!string.IsNullOrEmpty(qui.Address)) Update(con, new FmdcEventArgs(Actions.Redirect, new RedirectInfo(qui.Address, qui.Message, qui.DisconnectedBy))); // Banned else { if (qui.Time != -1) // Sets reconnect attempt to infinite hub.KeepAliveInterval = 0; else hub.KeepAliveInterval = qui.Time; Update(con, new FmdcEventArgs(Actions.Banned, new BannedInfo(qui.Time, qui.Message, qui.DisconnectedBy))); } } } } #endregion #region SUP else if (message is SUP) { if (trans != null && !hasSentSUP) { con.Send(new SUP(con)); } supports = (SUP)message; // TODO : We should really care about what hub support. if (!supports.BASE && !supports.TIGR) { // We will just simply disconnect if hub doesnt support this right now con.Disconnect("Connection doesnt support BASE or BAS0"); } #if !COMPACT_FRAMEWORK // Encrypted transfers if (supports.ADCS) { if ( (hub != null && hub.Me.ContainsKey(UserInfo.SECURE)) || (trans != null && trans.Me.ContainsKey(UserInfo.SECURE)) ) { con.SecureProtocol = SecureProtocols.TLS; } } #endif } #endregion #region RES else if (message is RES) { RES res = (RES)message; SearchResultInfo srinfo = new SearchResultInfo(res.Info, res.Id, res.Token); if (hub != null) Update(con, new FmdcEventArgs(Actions.SearchResult, srinfo)); } #endregion #region SCH else if (message is SCH) { SCH sch = (SCH)message; UserInfo usr = null; if (hub != null) { User u = hub.GetUserById(sch.Id); if (u != null) usr = u.UserInfo; } else if (trans != null) usr = trans.User; SendRES(sch.Info, usr); } #endregion #region CTM else if (message is CTM && hub != null) { CTM ctm = (CTM)message; // We really hate buggy hubsofts. Only reason we will get this message is because hubsoft dont know diffrent between E and D messages. if (ctm.Id == hub.Me.ID) return; User usr = null; string addr = null; // Do we support same protocol? double version = 0.0; if (ctm.Protocol != null && (ctm.Protocol.StartsWith("ADC/") || ctm.Protocol.StartsWith("ADCS/"))) { try { version = double.Parse(ctm.Protocol.Substring( ctm.Protocol.IndexOf("/") +1), CultureInfo.GetCultureInfo("en-GB").NumberFormat); } catch { } } if (version > 1.0) { hub.Send(new STA(hub, ctm.Id, hub.Me.ID, "241", "Protocol is not supported. I only support ADC 1.0/ADCS 0.10 and prior", "TO" + ctm.Token + " PR" + ctm.Protocol)); return; } if ((usr = hub.GetUserById(ctm.Id)) != null && usr.UserInfo.ContainsKey(UserInfo.IP)) { addr = usr.UserInfo.Get(UserInfo.IP); Transfer trans = new Transfer(addr, ctm.Port); trans.Share = hub.Share; // We are doing this because we want to filter out PID and so on. User me = hub.GetUserById(hub.Me.ID); trans.Me = new UserInfo(me.UserInfo); trans.Protocol = new AdcProtocol(trans); #if !COMPACT_FRAMEWORK if (ctm.Secure) trans.SecureProtocol = SecureProtocols.TLS; #endif // Support for prior versions of adc then 1.0 string token = ctm.Token; if (version < 1.0 && ctm.Token.StartsWith("TO")) token = ctm.Token.Substring(2); trans.Me.Set("TO", token); Update(con, new FmdcEventArgs(Actions.TransferRequest, new TransferRequest(token, hub, usr.UserInfo,false))); Update(con, new FmdcEventArgs(Actions.TransferStarted, trans)); } } #endregion #region RCM else if (message is RCM && hub != null) { RCM rcm = (RCM)message; // We really hate buggy hubsofts. Only reason we will get this message is because hubsoft dont know diffrent between E and D messages. if (rcm.Id == hub.Me.ID) return; if (hub.Me.Mode != FlowLib.Enums.ConnectionTypes.Passive && hub.Share != null) { User usr = null; if ((usr = hub.GetUserById(rcm.Id)) != null) { // Do we support same protocol? double version = 0.0; if (rcm.Protocol != null && (rcm.Protocol.StartsWith("ADC/") || rcm.Protocol.StartsWith("ADCS/"))) { try { version = double.Parse(rcm.Protocol.Substring(rcm.Protocol.IndexOf("/") + 1), CultureInfo.GetCultureInfo("en-GB").NumberFormat); } catch { } if (version <= 1.0) { // Support for prior versions of adc then 1.0 string token = rcm.Token; if (version < 1.0 && rcm.Token.StartsWith("TO")) token = rcm.Token.Substring(2); Update(con, new FmdcEventArgs(Actions.TransferRequest, new TransferRequest(token, hub, usr.UserInfo, false))); if (rcm.Secure && hub.Me.ContainsKey(UserInfo.SECURE)) hub.Send(new CTM(hub, rcm.Id, rcm.IDTwo, rcm.Protocol, int.Parse(0 + hub.Me.Get(UserInfo.SECURE)), token)); else hub.Send(new CTM(hub, rcm.Id, rcm.IDTwo, rcm.Protocol, hub.Share.Port, token)); } else { hub.Send(new STA(hub, rcm.Id, hub.Me.ID, "241", "Protocol is not supported. I only support ADC 1.0 and prior", "TO" + rcm.Token + " PR" + rcm.Protocol)); return; } } } } else { // TODO : we should probably return a STA message. } } #endregion #region GFI else if (message is GFI && this.trans != null) { GFI gfi = (GFI)message; if (gfi.Identifier != null) { trans.Content = new ContentInfo(); switch (gfi.ContentType) { case "file": // Requesting file // This is because we have support for old DC++ client and mods like (DCDM who has ASCII encoding) if (gfi.Identifier.Equals("files.xml.bz2")) { trans.Content.Set(ContentInfo.FILELIST, Utils.FileLists.BaseFilelist.XMLBZ); trans.Content.Set(ContentInfo.VIRTUAL, System.Text.Encoding.UTF8.WebName + gfi.Identifier); } else if (gfi.Identifier.StartsWith("TTH/")) { trans.Content.Set(ContentInfo.TTH, gfi.Identifier.Substring(4)); } else { trans.Content.Set(ContentInfo.VIRTUAL, gfi.Identifier); } break; case "list": // TODO : We dont care about what subdirectoy user whats list for trans.Content.Set(ContentInfo.FILELIST, Utils.FileLists.BaseFilelist.XML); trans.Content.Set(ContentInfo.VIRTUAL, System.Text.Encoding.UTF8.WebName + "files.xml"); break; default: // We are not supporting type. Disconnect con.Send(new STA(con, "251", "Type not known:" + gfi.ContentType, null)); con.Disconnect(); return; } SearchInfo si = new SearchInfo(); if (trans.Content.ContainsKey(ContentInfo.TTH)) si.Set(SearchInfo.TYPE, trans.Content.Get(ContentInfo.TTH)); si.Set(SearchInfo.SEARCH, trans.Content.Get(ContentInfo.VIRTUAL)); SendRES(si, trans.User); } } #endregion #region GET else if (message is GET && this.trans != null) { GET get = (GET)message; // If we are supposed to download and other client tries to download. Disconnect. if (trans != null && this.download) { trans.Disconnect(); return; } bool firstTime = true; if (get.Identifier != null) { trans.Content = new ContentInfo(); switch (get.ContentType) { case "file": // Requesting file // This is because we have support for old DC++ client and mods like (DCDM who has ASCII encoding) if (get.Identifier.Equals("files.xml.bz2")) { trans.Content.Set(ContentInfo.FILELIST, Utils.FileLists.BaseFilelist.XMLBZ); trans.Content.Set(ContentInfo.VIRTUAL, System.Text.Encoding.UTF8.WebName + get.Identifier); } else if (get.Identifier.StartsWith("TTH/")) { trans.Content.Set(ContentInfo.TTH, get.Identifier.Substring(4)); } else { trans.Content.Set(ContentInfo.VIRTUAL, get.Identifier); } break; case "list": // TODO : We dont care about what subdirectoy user whats list for trans.Content.Set(ContentInfo.FILELIST, Utils.FileLists.BaseFilelist.XML); trans.Content.Set(ContentInfo.VIRTUAL, System.Text.Encoding.UTF8.WebName + "files.xml"); break; case "tthl": // TTH/DQSGG2MYKKLXX4N2P7TBPKSC5HVBO3ISYZPLMWA if (get.Identifier.StartsWith("TTH/")) { trans.Content.Set(ContentInfo.TTH, get.Identifier.Substring(4)); ContentInfo tmp = trans.Content; if (con.Share != null && con.Share.ContainsContent(ref tmp) && tmp.ContainsKey(ContentInfo.TTHL)) { byte[] bytes = Utils.Convert.Base32.Decode(tmp.Get(ContentInfo.TTHL)); #if !COMPACT_FRAMEWORK trans.CurrentSegment = new SegmentInfo(-1, 0, bytes.LongLength); #else trans.CurrentSegment = new SegmentInfo(-1, 0, bytes.Length); #endif con.Send(new SND(trans, get.ContentType, get.Identifier, new SegmentInfo(-1, trans.CurrentSegment.Start, trans.CurrentSegment.Length))); // Send content to user System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes); ms.Flush(); bytes = ms.ToArray(); con.Send(new BinaryMessage(con, bytes, bytes.Length)); System.Console.WriteLine("TTH Leaves:" + FlowLib.Utils.Convert.Base32.Encode(bytes)); firstTime = true; } } if (!firstTime) { // We should not get here if file is in share. con.Send(new STA(con, "251", "File not available", null)); con.Disconnect(); } return; default: // We are not supporting type. Disconnect con.Send(new STA(con, "251", "Type not known:" + get.ContentType, null)); con.Disconnect(); return; } trans.CurrentSegment = get.SegmentInfo; byte[] bytesToSend = null; try { // TODO : ZLib compression here doesnt work as we want. It takes much memory and much cpu //Util.Compression.ZLib zlib = null; //if (adcget.ZL1) // zlib = new Fmdc.Util.Compression.ZLib(); while (connectionStatus != TcpConnection.Disconnected && (bytesToSend = GetContent(System.Text.Encoding.UTF8, trans.CurrentSegment.Position, trans.CurrentSegment.Length - trans.CurrentSegment.Position)) != null) { if (firstTime) { con.Send(new SND(trans, get.ContentType, get.Identifier, new SegmentInfo(-1, get.SegmentInfo.Start, trans.CurrentSegment.Length))); firstTime = false; } trans.CurrentSegment.Position += bytesToSend.Length; // We want to compress content with ZLib //if (zlib != null) //{ // zlib.Compress2(bytesToSend); // bytesToSend = zlib.Read(); //} con.Send(new BinaryMessage(trans, bytesToSend, bytesToSend.Length)); bytesToSend = null; } // If we compressing data with zlib. We need to send ending bytes too. //if (zlib != null && connectionStatus != Connection.Disconnected) // trans.Send(new ConMessage(trans, zlib.close())); } catch (System.Exception e) { System.Console.WriteLine("ERROR:" + e); } } trans.CurrentSegment = new SegmentInfo(-1); trans.Content = null; if (firstTime) { // We should not get here if file is in share. con.Send(new STA(con, "251", "File not available", null)); con.Disconnect(); } } #endregion #region SND else if (message is SND) { SND snd = (SND)message; if (!trans.Content.Get(ContentInfo.REQUEST).Equals(snd.Identifier)) { trans.Disconnect("I want my bytes.."); return; } if (trans.DownloadItem.ContentInfo.Size == -1) { trans.DownloadItem.ContentInfo.Size = snd.SegmentInfo.Length; trans.DownloadItem.SegmentSize = snd.SegmentInfo.Length; EnsureCurrentSegmentCancelation(); GetSegment(false); } else if (trans.CurrentSegment != null && trans.CurrentSegment.Length != snd.SegmentInfo.Length) { trans.Disconnect("Why would i want to get a diffrent length of bytes then i asked for?"); return; } this.IsRawData = true; trans.ShouldBlockOnSend = true; } #endregion }
public Search(Hub hub, string raw) : base(hub, raw) { bool validAddress = false; int searchPos = 0; #region Get From int pos1 =0, pos2 = 0; if (Utils.StringOperations.Find(raw, "Hub:", " ", ref pos1, ref pos2)) { searchPos = pos2; pos1 += 4; pos2 -= 1; from = raw.Substring(pos1, pos2 - pos1); validAddress = true; } else if (((pos1=0) == 0) && Utils.StringOperations.Find(raw, "$Search ", " ", ref pos1, ref pos2)) { searchPos = pos2; pos1 += 8; pos2 -= 1; string[] tmp = raw.Substring(pos1, pos2 - pos1).Split(':'); if (tmp.Length == 2) { System.Net.IPAddress ip = null; int port = -1; try { ip = System.Net.IPAddress.Parse(tmp[0]); } catch { } int.TryParse(tmp[1], out port); //if (port < || port > System.Net.IPEndPoint.MaxPort) // port = -1; if (ip != null && (System.Net.IPEndPoint.MinPort <= port && port <= System.Net.IPEndPoint.MaxPort)) { address = new System.Net.IPEndPoint(ip, port); validAddress = true; } } } #endregion #region Search Info if (searchPos != 0) { info = new SearchInfo(); string[] sections = raw.Substring(searchPos).Split('?'); if (sections.Length == 5) { #region Size Info info.Set(SearchInfo.SIZETYPE, "0"); if (sections[0] == "T") { info.Set(SearchInfo.SIZETYPE, (sections[1] == "F" ? "1" : "2")); } long size = 0; try { size = long.Parse(sections[2]); } catch { size = 0; } info.Set(SearchInfo.SIZE, size.ToString()); #endregion #region Extention string ext = string.Empty; System.Text.StringBuilder sb = new System.Text.StringBuilder(7); switch (sections[3]) { case "2": // Audio sb.Append("mp3 "); sb.Append("mp2 "); sb.Append("wav "); sb.Append("au "); sb.Append("rm "); sb.Append("mid "); sb.Append("sm"); break; case "3": // Compressed sb.Append("zip "); sb.Append("arj "); sb.Append("rar "); sb.Append("lzh "); sb.Append("gz "); sb.Append("z "); sb.Append("arc "); sb.Append("pak"); break; case "4": // Documents sb.Append("doc "); sb.Append("txt "); sb.Append("wri "); sb.Append("pdf "); sb.Append("ps "); sb.Append("tex"); break; case "5": // Executables sb.Append("exe "); sb.Append("pm "); sb.Append("bat "); sb.Append("com"); break; case "6": // Pictures sb.Append("gif "); sb.Append("jpg "); sb.Append("jpeg "); sb.Append("bmp "); sb.Append("pcx "); sb.Append("png "); sb.Append("wmf "); sb.Append("psd"); break; case "7": // Videos sb.Append("mpg "); sb.Append("mpeg "); sb.Append("avi "); sb.Append("asf "); sb.Append("mov"); break; case "8": // Folders sb.Append("$0"); info.Set(SearchInfo.TYPE, "1"); break; case "9": // TTH Search sb.Append("$1"); info.Set(SearchInfo.TYPE, "2"); break; } info.Set(SearchInfo.EXTENTION, sb.ToString()); #endregion #region Search String if (sections[4].StartsWith("TTH:")) info.Set(SearchInfo.SEARCH, sections[4].Substring(4)); else info.Set(SearchInfo.SEARCH, sections[4]); #endregion // A search is only valid if it has a valid Adress if (validAddress) { valid = true; } } } #endregion }
public Search(Hub hub, SearchInfo info) : base(hub,null) { this.info = info; #region Id string id = null; switch (hub.Me.Mode) { case FlowLib.Enums.ConnectionTypes.Direct: case FlowLib.Enums.ConnectionTypes.UPnP: case FlowLib.Enums.ConnectionTypes.Forward: string port = hub.Share.Port.ToString(); if (hub.Me.ContainsKey(UserInfo.UDPPORT)) port = hub.Me.Get(UserInfo.UDPPORT); if (hub.Me.ContainsKey(UserInfo.IP)) { id = string.Format("{0}:{1}", hub.Me.Get(UserInfo.IP), port); } else { id = string.Format("{0}:{1}", hub.LocalAddress.Address, port); } break; default: id = string.Format("Hub:{0}", hub.Me.ID); break; } #endregion string search = string.Empty; #region Size string size = "F?F?0"; if (info.ContainsKey(SearchInfo.SIZETYPE)) { switch (info.Get(SearchInfo.SIZETYPE)) { case "1": // Min Size size = "T?F" + info.Get(SearchInfo.SIZE); break; case "2": // Max Size size = "T:T" + info.Get(SearchInfo.SIZE); break; } } #endregion #region Extention string type = "?1"; switch (info.Get(SearchInfo.EXTENTION)) { case "mp3": case "mp2": case "wav": case "au": case "rm": case "mid": case "sm": type = "?2"; break; case "zip": case "arj": case "rar": case "lzh": case "gz": case "z": case "arc": case "pak": type = "?3"; break; case "doc": case "txt": case "wri": case "pdf": case "ps": case "tex": type = "?4"; break; case "pm": case "exe": case "bat": case "com": type = "?5"; break; case "gif": case "jpg": case "jpeg": case "bmp": case "pcx": case "png": case "wmf": case "psd": type = "?6"; break; case "mpg": case "mpeg": case "avi": case "asf": case "mov": type = "?7"; break; case "$0": type = "?8"; break; case "$1": type = "?9"; break; } #endregion string schStr = info.Get(SearchInfo.SEARCH); schStr = schStr.Replace(" ", "$"); #region Is TTH Search? switch (info.Get(SearchInfo.TYPE)) { case "1": // Directory type = "?8"; break; case "2": // TTH type = "?9"; schStr = "TTH:" + schStr; break; } #endregion search = string.Format("{0}{1}?{2}", size, type, schStr); Raw = string.Format("$Search {0} {1}|", id, search); }
private static void ProcessMatrix(AType searchWhat, SearchInfo searchInfo) { if (searchWhat.Shape.Count > searchInfo.SearchWhere[0].Shape.Count) { // Travers down to the correct cells foreach (AType item in searchWhat) { if (item.IsArray) { // Found an array, lets see if we can process it further ProcessMatrix(item, searchInfo); } else { // Simple Scalar found searchInfo.Result.AddWithNoUpdate(ProcessScalar(item, searchInfo)); } } } else if (searchWhat.Shape.SequenceEqual<int>(searchInfo.SearchWhere[0].Shape)) { // search for the cell int found = searchInfo.SearchWhere.Any(item => searchWhat.EqualsWithTolerance(item)) ? 1 : 0; searchInfo.Result.AddWithNoUpdate(AInteger.Create(found)); } else { throw new Error.Length(searchInfo.ErrorText); } }
private SearchInfo BranchTo(SearchInfo current, IDirectedGraphConnection connection) { //var connections = current.Connections.Concat(new List<IDirectedGraphConnection>() { connection }); return new SearchInfo() { TargetId = connection.TargetId, //Connections = connections, Cost = CalculateCost(current.Cost, connection), NumConnections = current.NumConnections + 1 }; }
/// <summary> /// Search the <see cref="left"/> argument in the <see cref="right"/> argument. /// </summary> /// <param name="right">The data where the search should be performed.</param> /// <param name="left">Element to search in the right argument.</param> /// <param name="environment"></param> /// <returns></returns> public override AType Execute(AType right, AType left, Aplus environment = null) { if (right.Length == 0) { switch (left.Rank) { case 0: return AInteger.Create(0); default: return DyadicFunctionInstance.Reshape.Execute(AInteger.Create(0), left.Shape.ToAArray()); } } else if (!(left.IsNumber && right.IsNumber) && (right.Type != left.Type)) { throw new Error.Type(this.TypeErrorText); } SearchInfo searchInfo = new SearchInfo() { // convert the right argument to an array (make life easier..) SearchWhere = right.IsArray ? right : AArray.Create(right.Type, right), ErrorText = this.LengthErrorText }; if (left.Rank < searchInfo.SearchWhere[0].Rank) { // The item we are looking for have a lesser rank than the items of the right argument throw new Error.Rank(this.RankErrorText); } AType result; if (!left.IsArray) { // Process a simple scalar result = ProcessScalar(left, searchInfo); } else { searchInfo.Result = AArray.Create(ATypes.AInteger); ProcessMatrix(left, searchInfo); searchInfo.Result.UpdateInfo(); // Check how many elements we need to return int elementCount = left.Shape.Count - Math.Max(right.Rank - 1, 0); if ((elementCount == 0) && searchInfo.Result.TryFirstScalar(out result)) { // need to return a simple scalar // 'result' contains the desired value } else { // reshape the result to the required shape List<int> desiredShape = left.Shape.GetRange(0, elementCount); result = DyadicFunctionInstance.Reshape.Execute(searchInfo.Result, desiredShape.ToAArray()); } } return result; }
public SCH(IConnection con, SearchInfo info, string userId) : base(con, null) { this.info = info; // BSCH NRQF TRUDHPNB4BUIQV2LAI4HDWRL3KLJTUSXCTAMJHNII TOauto System.Text.StringBuilder sb = new System.Text.StringBuilder(); #region EX if (info.ContainsKey(SearchInfo.EXTENTION)) { string[] ext = info.Get(SearchInfo.EXTENTION).Split(' '); foreach (string extention in ext) { sb.Append(" EX" + AdcProtocol.ConvertOutgoing(extention)); } } #endregion #region TY if (info.ContainsKey(SearchInfo.TYPE)) { switch (info.Get(SearchInfo.TYPE)) { case "0": sb.Append(" TY" + AdcProtocol.ConvertOutgoing("1")); break; case "1": sb.Append(" TY" + AdcProtocol.ConvertOutgoing("2")); break; case "2": sb.Append(" AN" + info.Get(SearchInfo.SEARCH)); break; } } #endregion #region AN if (info.ContainsKey(SearchInfo.SEARCH) && info.ContainsKey(SearchInfo.TYPE)) sb.Append(" AN" + AdcProtocol.ConvertOutgoing(info.Get(SearchInfo.SEARCH))); #endregion #region NO if (info.ContainsKey(SearchInfo.NOSEARCH)) sb.Append(" NO" + AdcProtocol.ConvertOutgoing(info.Get(SearchInfo.NOSEARCH))); #endregion #region TO if (info.ContainsKey(SearchInfo.TOKEN)) sb.Append(" TO" + AdcProtocol.ConvertOutgoing(info.Get(SearchInfo.TOKEN))); #endregion #region Size Type if (info.ContainsKey(SearchInfo.SIZETYPE)) { string size = info.Get(SearchInfo.SIZE); switch (info.Get(SearchInfo.SIZETYPE)) { case "1": sb.Append(" GE" + size); break; case "2": sb.Append(" LE" + size); break; case "3": sb.Append(" EQ" + size); break; } } #endregion Raw = string.Format("BSCH {0}{1}\n", userId, sb.ToString()); }
protected void SendRES(SearchInfo info, UserInfo usr) { IShare share = null; if (hub != null || hub.Share != null || usr != null) { share = hub.Share; } else if (trans != null || trans.Share != null || usr != null) { share = trans.Share; } else { return; } // If we dont have a share object. break here. if (share == null) return; int maxReturns = 10; string token = null; if (info.ContainsKey(SearchInfo.TOKEN)) token = info.Get(SearchInfo.TOKEN); System.Collections.Generic.List<ContentInfo> ret = new System.Collections.Generic.List<ContentInfo>(maxReturns); // TODO : This lookup can be done nicer lock (share) { foreach (System.Collections.Generic.KeyValuePair<string, Containers.ContentInfo> var in share) { if (var.Value == null) continue; bool foundEnough = false; string ext = info.Get(SearchInfo.EXTENTION); string sch = info.Get(SearchInfo.SEARCH); if (ext != null && sch != null) { ContentInfo contentInfo = new ContentInfo(); if (info.ContainsKey(SearchInfo.TYPE)) { switch (info.Get(SearchInfo.TYPE)) { case "2": contentInfo.Set(ContentInfo.TTH, info.Get(SearchInfo.SEARCH)); if (hub.Share.ContainsContent(ref contentInfo)) { ret.Add(contentInfo); } // We are looking through whole share here. // If no TTH matching. Ignore. foundEnough = true; break; case "1": default: if (var.Value.ContainsKey(ContentInfo.VIRTUAL) && (System.IO.Path.GetDirectoryName(var.Value.Get(ContentInfo.VIRTUAL)).IndexOf(sch, System.StringComparison.OrdinalIgnoreCase) != -1)) ret.Add(var.Value); break; } } if (!foundEnough) { string infoExt = System.IO.Path.GetExtension(var.Value.Get(ContentInfo.VIRTUAL)).TrimStart('.'); if ( var.Value.ContainsKey(ContentInfo.VIRTUAL) && (var.Value.Get(ContentInfo.VIRTUAL).IndexOf(sch, System.StringComparison.OrdinalIgnoreCase) != -1) && (ext.Length == 0 || ext.Contains(infoExt)) ) ret.Add(var.Value); } } if (foundEnough || ret.Count >= maxReturns) break; } } int x = 0; // Test against size restrictions for (int i = 0; i < ret.Count; i++) { bool send = true; long size = -1; try { size = long.Parse(info.Get(SearchInfo.SIZE)); } catch { } if (info.ContainsKey(SearchInfo.SIZETYPE) && size != -1) { switch (info.Get(SearchInfo.SIZETYPE)) { case "1": // Min Size send = (size <= ret[i].Size); break; case "2": // Max Size send = (size >= ret[i].Size); break; case "3": // Equal Size send = (size == ret[i].Size); break; } } // Should this be sent? if (send) { RES res = new RES(con, ret[i], token, usr); if (res.Address != null && hub != null) { if (10 > x++) { // Send with UDP try { UdpConnection.Send(res, res.Address); } catch { } } } else { if (5 > x++) { if (hub != null) { // Send through hub hub.Send(res); } else if (trans != null) { trans.Send(res); } } } } } }
private static AType ProcessScalar(AType searchWhat, SearchInfo searchInfo) { int found = searchInfo.SearchWhere.Any(item => (item.IsNumber && Utils.ComparisonTolerance(item.asFloat, searchWhat.asFloat)) || item.Equals(searchWhat)) ? 1 : 0; return AInteger.Create(found); }
// return the first 10 rows from cities sorted by state in reverse private void menuItemCustomProcessor_Click(object sender, System.EventArgs e) { try { QueryFilter filter = new SqlExpressionFilter(null); // all rows QueryDefinition qd = new QueryDefinition(filter, "*"); string [] orderby = new string[1]; orderby[0] = "State Desc"; qd.OrderBy = orderby; SearchResultProcessor srp = new MySearchResultProcessor(10); // stop after 10 rows SearchInfo si = new SearchInfo(srp, qd); IResultSetFeatureCollection fc = _catalog.Search("usa", si); // set map view to show search results _map.SetView(fc.Envelope); // show results as selection SelectFeatureCollection(fc); } finally { Cursor.Current = Cursors.Default; } }
protected void Page_Load(object sender, EventArgs e) { if (Page.IsPostBack) { return; } string szWordsAllContains=""; string szExactPhraseContain=""; string szOneOfWordsAtLeastContain=""; string szWordNotInclude=""; if (Request.QueryString["Word"] != null) szWordsAllContains = Decode(Request.QueryString["Word"]); if (Request.QueryString["Exact"] != null) szExactPhraseContain = Decode(Request.QueryString["Exact"]); if (Request.QueryString["One"] != null) szOneOfWordsAtLeastContain = Decode(Request.QueryString["One"]); if (Request.QueryString["Not"] != null) szWordNotInclude = Decode(Request.QueryString["Not"]); if (IsNullOrEmpty(szWordsAllContains, szExactPhraseContain, szOneOfWordsAtLeastContain, szWordNotInclude)) { string searchWords = GetCookie("SearchWords"); if (string.IsNullOrEmpty(searchWords)) return; txtSearch.Text = searchWords; RunSearch(); return; } int pageNum = 1; if (Request.QueryString["Page"] != null) pageNum = int.Parse(Request.QueryString["Page"]); string filter = ""; if (Request.QueryString["Filter"] != null) filter = Decode(Request.QueryString["Filter"]); searchFilter = filter; SetSearchWords(szWordsAllContains, szExactPhraseContain, szOneOfWordsAtLeastContain, szWordNotInclude); TcpClient client; NetworkStream ns; BinaryFormatter formater; string hostname = ConfigurationManager.AppSettings["HostName"]; int port = int.Parse(ConfigurationManager.AppSettings["PortNum"]); HttpCookie userCookie = Request.Cookies[ConfigurationManager.AppSettings["CookieName"]]; int pageSize = 10; string area = ""; string content = ""; bool allCon = true; bool allArea = true; if (userCookie != null) { try { pageSize = int.Parse(Decode(userCookie.Values["PageSize"])); area = Decode(userCookie.Values["Area"]); content = Decode(userCookie.Values["Content"]); allCon = bool.Parse(Decode(userCookie.Values["AllContent"])); allArea = bool.Parse(Decode(userCookie.Values["AllArea"])); } catch (Exception ) { } } try { client = new TcpClient(hostname, port); ns = client.GetStream(); formater = new BinaryFormatter(); SearchInfo sinfo = new SearchInfo(); QueryInfo info = new QueryInfo(); if (!string.IsNullOrEmpty(szWordsAllContains)) info.WordsAllContains=szWordsAllContains; if (!string.IsNullOrEmpty(szExactPhraseContain)) info.ExactPhraseContain = szExactPhraseContain; if (!string.IsNullOrEmpty(szOneOfWordsAtLeastContain)) info.OneOfWordsAtLeastContain = szOneOfWordsAtLeastContain; if (!string.IsNullOrEmpty(szWordNotInclude)) info.WordNotInclude = szWordsAllContains; if(!allCon) info.IndexNames = GetIndexNames(content); sinfo.PageSize = pageSize; sinfo.PageNum = pageNum; sinfo.Query = info; sinfo.HighLight = true; sinfo.Filter = filter; formater.Serialize(ns, sinfo); //searchInfo = sinfo.ToString(); SearchResult sr = (SearchResult)formater.Deserialize(ns); StringBuilder buffer = new StringBuilder(); StringBuilder statis = new StringBuilder(); XmlSerializer xmlSerializer = new XmlSerializer(typeof(SearchRecord)); Number.InnerText = GetStatisticString(sr.Statistics, txtSearch.Text.Trim(),filter, pageSize, sr.PageNum); #region Title and Content //DataBaseLibrary.GraphicsManagementHandle gmh = new DataBaseLibrary.GraphicsManagementHandle(); foreach (SearchRecord record in sr.Records) { if (record.Caption.Equals("文件", StringComparison.CurrentCultureIgnoreCase)) { string type, fvalue; GetFileTypeValue(record["路径"].Value, out type, out fvalue); buffer.Append("<span class=\"LargeTitle\" >" + type + "<a href=\"" + GetFileUrl(record["路径"].Value) + "\" target=\"_blank\" >" + GetColorString(record["文件名"].Result) + " 得分:" + record.Score.ToString() + "</a></span><br>"); buffer.Append("<span class=\"SmallTitle\" >" + fvalue + "</span><br>"); if(!string.IsNullOrEmpty(record["内容"].Value)) buffer.Append("<span class=\"SmallTitle\" >" + GetColorString(record["内容"].Result) + "</span><br>"); buffer.Append("<br>"); } else { string title, detail, xmlRecord; xmlRecord = GetXmlRecord(xmlSerializer, record); record.GetWebInfo(out title, out detail, true,false); detail = detail + "......"; //标题,点击调用序列化 if(!string.IsNullOrEmpty(title)) buffer.Append("<a href=\"#\" class=\"LargeTitle\" onclick=\"OpenMessage('" + GetRedirectUrl(record) + "')\"><span class=\"LargeTitle\" onmouseover=\"this.className='MouseDown'\" onmouseout=\"this.className='LargeTitle'\">" + record.Caption + ":" + title.Replace("</B><B>", "").Replace("<B>", "<font color=\"Red\">").Replace("</B>", "</font>") + " 得分:" + record.Score.ToString() + "</span></a><br />"); else buffer.Append("<a href=\"#\" class=\"LargeTitle\" onclick=\"OpenMessage('" + GetRedirectUrl(record) + "')\"><span class=\"LargeTitle\" onmouseover=\"this.className='MouseDown'\" onmouseout=\"this.className='LargeTitle'\">" + record.Caption + " 得分:" + record.Score.ToString() + "</span></a><br />"); buffer.Append("<span class=\"SmallTitle\" style=\"line-height:20px\">" + detail.Replace("</B><B>", "").Replace("<B>", "<font color=\"Red\">").Replace("</B>", "</font>") + "</span><br />"); buffer.Append("<img src=\"action_import.gif\" width=\"16px\" height=\"16px\" /> <a href=\"#\" onclick=\"TransferString('" + Encode(xmlRecord) + "')\" class=\"SmallTitle\" >搜索关系</a>"); //查看图形 string ID = GetPGLValue(record); if (!string.IsNullOrEmpty(ID)) { SearchField sf = record["GraphicsLabel"]; //bool IsImg = gmh.GetProjectGraphicsLabel(record.Caption, ID); //if (IsImg) if(sf!=null && !string.IsNullOrEmpty(sf.Value) && bool.Parse(sf.Value)) { if (record.Caption == "遥感卫片监测调查") { string TBH = record["JCTBH"].Value; buffer.Append(" <img src=\"icon_solutions_16px.gif\" width=\"16px\" height=\"16px\" /> <a href=\"#\" onclick=\"OpenMessage('" + ConfigurationManager.AppSettings["MapPath_WP"] + "&TBH=" + TBH + "')\" class=\"SmallTitle\" >查看图形</a><br /><br />"); } else { buffer.Append(" <img src=\"icon_solutions_16px.gif\" width=\"16px\" height=\"16px\" /> <a href=\"#\" onclick=\"OpenMessage('" + ConfigurationManager.AppSettings["MapPath"] + "?BusinessName=" + Server.UrlEncode(record.Caption) + "&ProjectID=" + ID + "')\" class=\"SmallTitle\" >查看图形</a><br /><br />"); } } else { buffer.Append("<br /><br />"); } } else { buffer.Append("<br /><br />"); } } } tdResult.InnerHtml = buffer.ToString(); #endregion #region Statistics statis.Append("<table class=\"TableStyle\" width=\"100%\"><tr height=\"35px\"><td class=\"TableText\" colspan=\"2\" style=\"font-size:9pt; font-weight:bold\">分类统计信息</td></tr>"); string url; foreach (string key in sr.Statistics.Keys) { if(sr.Statistics[key]>0) { url=GetUrl(szWordsAllContains,szExactPhraseContain,szOneOfWordsAtLeastContain,szWordNotInclude,key,1); string displayKey = key; if (key.Equals("文件", StringComparison.CurrentCultureIgnoreCase)) displayKey = "电子文档"; statis.Append("<tr height=\"35px\"><td class=\"TableValue\" style=\"font-size:9pt;text-align:center;border-right:none\" width=\"30px\"><img src=\"icon_search_16px.gif\" width=\"16px\" height=\"16px\" /></td><td class=\"TableValue\" style=\"font-size:9pt;text-align:left;border-left:none\"><a href=\"" + url + "\" >" + displayKey + "</a> (" + sr.Statistics[key].ToString() + ")</td></tr>"); } } url = GetUrl(szWordsAllContains, szExactPhraseContain, szOneOfWordsAtLeastContain, szWordNotInclude, "", 1); statis.Append(GetStatisticDisplay(sr.Statistics,url)); statis.Append("</table>"); if(sr.Records.Count > 0) tdStatis.InnerHtml = statis.ToString(); #endregion #region Page StringBuilder pageBuilder = new StringBuilder(); if (sr.PageNum > 1) { url = GetUrl(szWordsAllContains, szExactPhraseContain, szOneOfWordsAtLeastContain, szWordNotInclude, filter, sr.PageNum - 1); pageBuilder.Append("<a class=\"SmallTitle\" href=\"" + url + "\" >上一页</a> "); } if (sr.TotalPages<=10) { for (int i = 1; i <= sr.TotalPages; i++) { if (i != sr.PageNum) { url = GetUrl(szWordsAllContains, szExactPhraseContain, szOneOfWordsAtLeastContain, szWordNotInclude, filter, i); pageBuilder.Append("<a class=\"SmallTitle\" href=\"" + url + "\" >" + i.ToString() + "</a> "); } else { pageBuilder.Append(sr.PageNum.ToString() + " "); } } } else { int startPage= sr.PageNum>=6 ? sr.PageNum-5 :1 ; int endPage=sr.PageNum+4>sr.TotalPages ? sr.TotalPages : sr.PageNum+4; if(endPage==sr.TotalPages) startPage=endPage-9; if (startPage == 1) endPage = startPage + 9; for (int i = startPage; i <= endPage; i++) { if (i != sr.PageNum) { url = GetUrl(szWordsAllContains, szExactPhraseContain, szOneOfWordsAtLeastContain, szWordNotInclude, filter, i); pageBuilder.Append("<a class=\"SmallTitle\" href=\"" + url + "\" >" + i.ToString() + "</a> "); } else { pageBuilder.Append(sr.PageNum.ToString() + " "); } } } if (sr.PageNum < sr.TotalPages) { url = GetUrl(szWordsAllContains, szExactPhraseContain, szOneOfWordsAtLeastContain, szWordNotInclude, filter, sr.PageNum + 1); pageBuilder.Append("<a class=\"SmallTitle\" href=\"" + url + "\" >下一页</a>"); } tdPageSet.InnerHtml = pageBuilder.ToString(); #endregion } catch (SocketException sep) { Response.Write("搜索服务没有运行!"); Response.Write(sep.StackTrace.ToString()); return; } catch (Exception se) { Response.Write(se.StackTrace.ToString()); return; } }
CallTreeNodeViewModel GetViewModelFromPath(IEnumerable<NodePath> paths, SearchInfo info) { CallTreeNodeViewModel result = null; var parent = list.Roots.FirstOrDefault(i => i.Node.Equals(info.ResultRoot)); foreach (var path in paths) { var items = parent.Children; foreach (var pathId in path.Skip(1)) { foreach (var item in items) { if (item.Node.NameMapping.Id == pathId) { items = item.Children; result = item; break; } } if (result == null) break; } } return result; }
public void TestSearchOneDoc() { DMLogin.ServerName = DMProdEnvironment.Server; DMLogin.Password = TestHelperSecure.MyPassword; // a known document in our library string expectedDocNum = "12387815"; string expectedName = "TEST 2"; var info = new SearchInfo { SearchObject = "STANDARD_S", Criteria = new Dictionary<string, string> { { "DOCNUMBER", expectedDocNum } }, ReturnProperties = new List<string> { "DOCNUMBER", "DOCNAME" } }; var search = new DMSearch() { Dst = DMLogin.Dst, Library = DMLogin.Library }; var result = search.Search(info); Assert.IsNotNull(result); Assert.IsNotNull(result.Rows); Assert.AreEqual(1, result.Rows.Count); Assert.AreEqual(expectedDocNum, result.Rows[0][info.ReturnProperties[0]]); Assert.AreEqual(expectedName, result.Rows[0][info.ReturnProperties[1]]); }