How to search an item properly using Hql in my asp.net project? - asp.net-mvc-3

My query returns searched data but it does'nt search properly
in my table values are
------------------------
Help
------------------------
1 help for abcd
2 help needed before
my Hql query given below
select help from Help help where lower(help.Subject) like lower ('%'" + searchterm + "'%')
when i search for "for" it returns
------------------------
Help
------------------------
1 help for abcd
2 help needed before
I need to return only the first
1. help for abcd
ie: I need to search only the term begins with the search term
Any one please help...

This sounds Like a Word Boundary Problem. Here Is A similar question answered
Search for "whole word match" in MySQL
Sorry, I Have No Idea Why Android Wants To Capitalize All My Words.

Hello frnds i got the solution which works perfectly
at first using the query
select help from Help help
then store the list of help in
var ListofHelps
then
foreach (var item in ListofHelps)
{
if (!string.IsNullOrEmpty(searchterm))
{
var splitsearchterm = Regex.Split(searchterm, #"\s");//split search term
var splittedsubjects = Regex.Split(item.Subject.ToUpper(), #"\s"); //Subject is to be searched
var found = splittedsubjects.Where(x => x.StartsWith(searchterm.ToUpper()));
int datacount = found.Count();
if (splitsearchterm.Count() > 1 && item.Subject.ToUpper().Contains(searchterm.ToUpper()))
{
datacount = 1;
}
if (datacount > 0)
{
Helplist.Add(new HelpViewModel //Helplist is an item in HelpViewModel ie public IEnumerable<MultiSelectList> Taglists { get; set; }
{
Subject = item.Subject,
HelpId = Convert.ToInt32(item.Id),
Content = item.Content
});
}
}
else
{
Helplist.Add(new HelpViewModel
{
Subject = item.Subject,
HelpId = Convert.ToInt32(item.Id),
Content = item.Content
});
}
}
It works for me .Is there any better way to do that

Related

Google AppMaker: Fetch a MAX value

I am not able to fetch a max value from a number field in AppMaker. The field is filled with unique integers from 1 and up. In SQL I would have asked like this:
SET #tKey = (SELECT MAX(ID) FROM GiftCard);
In AppMaker I have done the following (with a bit help from other contributors in this forum) until now, and it returns tKey = "NaN":
var tKey = google.script.run.MaxID();
function MaxID() {
var ID_START_FROM = 11000;
var lock = LockService.getScriptLock();
lock.waitLock(3000);
var query = app.models.GiftCard.newQuery();
query.sorting.ID._descending();
query.limit = 1;
var records = query.run();
var next_id = records.length > 0 ? records[0].ID : ID_START_FROM;
lock.releaseLock();
return next_id;
}
There is also a maxValue() function in AppMaker. However, it seems not to work in that way I use it. If maxvalue() is better to use, please show :-)
It seems that you are looking in direction of auto incremented fields. The right way to achieve it would be using Cloud SQL database. MySQL will give you more flexibility with configuring your ids:
ALTER TABLE GiftCard AUTO_INCREMENT = 11000;
In case you strongly want to stick to Drive Tables you can try to fix your script as follow:
google.script.run
.withSuccessHandler(function(maxId) {
var tKey = maxId;
})
.withFailureHandler(function(error) {
// TODO: handle error
})
.MaxID();
As a side note I would also recommend to set your ID in onBeforeCreate model event as an extra security layer instead of passing it to client and reading back since it can be modified by malicious user.
You can try using Math.max(). Take into consideration the example below:
function getMax() {
var query = app.models.GiftCard.newQuery();
var allRecords = query.run();
allIds = [];
for( var i=0; i<allRecords.length;i++){
allIds.push(allRecords[i].ID);
}
var maxId = Math.max.apply(null, allIds);
return maxId;
}
Hope it helps!
Thank you for examples! The Math.max returned an undefined value. Since this simple case is a "big" issue, I will solve this in another way. This value is meant as a starting value for a sequence only. An SQL base is better yes!

Counting results from a search string MVC 3?

I am using MVC3 and have done a search facility in my controller.I have used the model first approach , what I want to be able to allow the user to search for results that contain the given keyword(s) in the data.
If there are no matches to the search term then display an appropriate message.
If there are matching stories:
Display a message like “7 items match your search criteria: 'XXXXX'”
Any help would be much appreciated , Thanks
would it be something like this but with use of the ViewBag to display a message?.
if (!String.IsNullOrEmpty(SearchString))
News = News.Where(s => s.Headline.Count(SearchString));
}
You need to use string.Contains for partial string matching:
var matchingResults = News.Where(s => s.Headline.Contains(searchString));
int count = matchingResults.Count();
if(count == 0)
{
//no matches
}
else
{
//display message
}

Linq Contains and Distinct

I have the following 3 tables with their fields
Books(Id_Book | Title | Year)
Book_Themes (Id | Id_Book| Id_Theme)
Themes (Id_Theme| Title)
I also have an Giud array with Id_Themes
Guid [] themesArray = new Guid []{new Guid("6236c491-b4ae-4a2f-819e-06a38bf2cf41"), new Guid("06586887-7e3f-4f0a-bb17-40c86bfa76ce")};
I'm trying to get all Books containing any of the Theme_Ids from the themesArray
This is what I have so far which is not working. Not sure how to use Contains in this scnenario.
int index = 1; int size= 10;
var books = (from book in DB.Books
join bookWThemes in DB.Book_Themes
on book.Id_Book equals bookWThemes.Id_Book
where themesArray.Contains(bookWThemes.Id_Theme)
orderby book.Year
select book)
.Skip((index - 1) * page)
.Take(size);
I'm getting an error on themesArray.Contains(bookWThemes.Id_Theme): System.Guid[] does not contain a definition for Contains. Also I'm not sure where to put the Distinct
****UPDATE****
noticed that my Model had Id_Theme as nullable... I changed the DB and didn't reflect the changes on my model. So to answer the question if it's nullable just change the Contains line to themesArray.Contains(bookWThemes.Id_Theme.Value)... and with this change it works.
Thanks for all the help!.
It's strange that your LINQ query is breaking down on .Contains. All three of the forms IEnumerable<> and List<> work for me.
[Test]
public void Test43()
{
var a = new List<Guid>(){new Guid(),new Guid(),new Guid()};
a.Contains(new Guid()); // works okay
var b = (IEnumerable<Guid>)a;
b.Contains<Guid>(new Guid()); // works okay
b.Contains(new Guid()); // works okay
}
For the "distinct" question, put the call here:
select book)
.Distinct() // <--
.Skip((index - 1) * page)
Try casting the Guid[] to List<Guid> and then you can use Contains on it.
where themesArray.ToList().Contains(bookWThemes.Id_Theme)

Sphinx wildcard searching won't work

I have used the following code:
function searchSphinx2($tofind,$jobtype_id,$payper_id,$onetimeBounds)
{
$this->load->library('session');
$this->load->library('sphinxclient');
global $result;
global $functionresult;
$functionresult=array();
$this->sphinxclient->setServer('localhost', 3312);
$this->sphinxclient->SetMatchMode( SPH_MATCH_ANY );
$this->sphinxclient->SetIndexWeights( array("jobs_index_main"=>10, "jobs_index_delta"=>10,"jobs_index_prefix_main"=>1,"jobs_index_prefix_delta"=>1,"jobs_index_infix_main"=>1,"jobs_index_infix_delta"=>1) );
$this->sphinxclient->ResetFilters();
$this->sphinxclient->SetFilter('jobtype_id',$jobtype_id,TRUE);
$this->sphinxclient->SetFilter('payper_id',$payper_id,TRUE);
$this->sphinxclient->SetFilterFloatRange('payamount', $ontimeBounds[0], $ontimeBounds[1], FALSE);
$this->sphinxclient->AddQuery("$tofind", "jobs_index_main;jobs_index_delta");
$this->sphinxclient->AddQuery("*$tofind*", "jobs_index_main_prefix;jobs_index_delta_prefix");
$this->sphinxclient->AddQuery("*$tofind*", "jobs_index_main_infix;jobs_index_delta_infix");
$result = $this->sphinxclient->RunQueries();
In my data base there is a job with title "Intern" However, if I search for "inter" I do not get any results.
The indices in my confi file are set up as follows:
index jobs_index_prefix_main
{
source = jobs_main
path = /var/newsphinx/index/main_prefix
morphology = stem_en
min_stemming_len = 4
min_word_len = 3
min_prefix_len = 3
prefix_fields = title, contactname
enable_star =1
}
Can anyone tell me why I am not getting partial word results?
I've never found Sphinx to return partial matches without using stars. I agree that it's not particularly intuitive (surely if the prefixes are being indexed, there's a match?), but if you want to ensure you always get results, add a star to the end of each word.

LINQ QUery: Take () based upon textbox value

I am creating a gridview that will be populated based upon a linq statement, the sql is as follows:
SELECT TOP 10 IDDesc, UnitUserfield1, UnitUserfield2, ProductPercentage
FROM tblOnlineReportingCOMPLETEWeights
WHERE (MaterialLevel = 'Primary') AND (MaterialText = 'Paper')
ORDER BY ProductPercentage DESC
Now, what I would like to do is let the user specify the Top 10, so essentially it is a "Top x" this being defined in a textbox i.e. they type in 50 into the textbox, the linq query is executed and the gridview displays the top 50.
I understand that using Take is the area I want to look at, is this correct? Is this even possible?!
Any thoughts, muchly appreciated.
PS: apologies for asking thick questions, I am very new to all of this!
You are correct. Take user input and feed it to Take. That'll do.
int howMany = Convert.ToInt32 (HowManyTextBox.Value);
var queryResult = /*.....*/.Take (howMany);
int max = 0;
if (Int.TryParse(TextBox1.Text, out max)
{
var q = (from tbl where ... orderby ... desc).Take(max);
}
Along those lines
Thank you all so much, I went with the following:
{
ORWeightsDataClassesDataContext db = new ORWeightsDataClassesDataContext();
int max = 0;
if (int.TryParse(txtbxHowMany.Text, out max))
{
var queryV = db.tblOnlineReportingCOMPLETEWeights
.Where(x => x.MaterialLevel == "Primary" && x.MaterialText == "Paper")
.OrderByDescending(x => x.ProductPercentage).Take(max);
GridView1.DataSource = queryV;
GridView1.DataBind();
}
}
It works a treat.
Thank so so much, very grateful and now my site is finally coming together...I feel liek celebrating...pub anyone?!

Resources