Multiple Searchterm in umbraco Examine Search - umbraco

I am trying to setup a search in umbraco examine.I have two search fields ,material and manufacturer.when I trying to search with one material and one manufactuere it will give the correct result.but when try to search more than one material or manufacturer it doesn't give the result.here is my code
const string materialSearchFields = "material";
const string manufacturerSearchFields = "manufacturer";
if (!string.IsNullOrEmpty(Request.QueryString["material"]))
{
material = Helper.StripTags(Request.QueryString["material"]);
}
if (!string.IsNullOrEmpty(Request.QueryString["manufacturer"]))
{
manufacturer = Helper.StripTags(Request.QueryString["manufacturer"]);
}
if (!string.IsNullOrEmpty(Request.QueryString["material"]) || !string.IsNullOrEmpty(Request.QueryString["manufacturer"]))
{
var query = userFieldSearchCriteria.Field(materialSearchFields, material).And().Field(manufacturerSearchFields, manufacturer).Compile();
contentResults = contentSearcher.Search(query).ToList();
}
here my search keywors in querystring is material=iron,steel
how can we split this keyword and search done?
Thanks in advance for the help....

You are using the AND operator, in your case I think you are looking for the GROUPEDOR instead?
I was just working in an old project and grabbed this snipet from there (which I've adapted for your needs). I think it's going to help you:
public IEnumerable<DynamicNode> SearchUmbraco(string[] keywords, string currentCulture)
{
// In this case I had some diferent cultures, so this sets the BaseSearchProvider to the given culture parameter. You might not need this, use your default one.
BaseSearchProvider searcher = SetBaseSearchProvider(currentCulture);
var searchCriteria = searcher.CreateSearchCriteria(BooleanOperation.Or);
var groupedQuery = searchCriteria.GroupedOr(new[] {"manufacturer", "material"}, keywords).Compile();
var searchResults = searcher.Search(groupedQuery);
// ... return IEnumerable of dynamic nodes (in this snipet case)
}
I just split(etc) the keywords in an helper and pass them to a string array when I call this method.
Just check this infomation on the umbraco blog: http://umbraco.com/follow-us/blog-archive/2011/9/16/examining-examine.aspx

Related

How does the Dart URI class QueryParameters handle Map values?

According to the documentation, it needs to follows the Form Post rules at: https://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4. When looking at that information it did not give me much to work with in terms of complex objects or maps.
Right now, If I have a list for example: Each item in the list needs to be stringified.
var params = {"list": [1,2,3]};
// needs to be stringed.
params["list"] = params["list"].map((item)=>item.toString()).toList();
Simple. Also all base items need to be a string as well
var params = {"number": 1, "boolean": true};
params = params.forEach((k,v)=> params[k].toString());
But how do we handle maps?
var params = {"map": {"a":1,"b":"foo","c":false,"d":[]}};
// ??
It seems that after testing in my app and in dart pad, you need to make sure everything is strings, so i am trying to come up with a way to effectively cover lists, maps, and maybe more complex objects for encoding.
var params = {};
params["list"] = [1,2,3];
params["number"] = 1;
params["boolean"] = true;
params["map"] = {"a":1,"b":"foo","c":false,"d":[]};
params.forEach((String key, dynamic value){
if(value is List){
params[key] = value.map((v)=>v.toString()).toList();
}else if(value is Map){
// ????
}else{
params[key] = value.toString();
}
//maybe have an additional one for custom classes, but if they are being passed around they should already have their own JSON Parsing implementations.
}
Ideally, the result of this would be passed into:
Uri myUri = new Uri(queryParameters: params);
and right now, while i solved the list issue, it doesn't like receiving maps. Part of me just wanted to stringify the map as a whole, but i wasn't not sure if there was a better way. I know that when someone accidentally stringified the array, it was not giving me: ?id=1&id=2 but instead ?id=%5B1%2C2%5D which was not correct.
I don't think there is any special support for maps. Query parameters itself is a map from string to string or string to list-of-strings.
Everything else need to be brought into this format first before you can pass it as query parameter.
A simple approach would be to JSON encode the map and pass the resulting string as a single query parameter.

Associate specific string to a number in google sheets

I am using a google forms to collect responses which I will then use to score people. Unfortunately some of those responses only make sense in a non numeric form, here is an example:
Q: What is your most common mode of transportation?
Car
Carpool
Public transportation
Bike
Walk
I want to be able to have google sheets automatically convert those string responses into a number, as in Car will be 20, carpool 15 and so on so that I can "grade" them and give them a score. Can this be done through google forms? Or maybe some sort of dictionary function?
Thank you!
Another method, requiring no coding, would be to make a worksheet with the encoding of the options and then use VLOOKUP to translate them.
Yep, this can be done through Google Forms. Have a look at https://developers.google.com/apps-script/reference/forms/duration-item#setPoints(Integer)
Using their code, you could go something like
var formResponses = FormApp.getActiveForm().getResponses();
// Go through each form response
for (var i = 0; i < formResponses.length; i++) {
var response = formResponses[i];
var items = FormApp.getActiveForm().getItems();
// Assume it's the first item
var item = items[0];
var itemResponse = response.getGradableResponseForItem(item);
if (itemResponse != null && itemResponse.getResponse() == 'Car') {
var points = item.asMultipleChoiceItem().getPoints();
itemResponse.setScore(points * 20);
// This saves the grade, but does not submit to Forms yet.
response.withItemGrade(itemResponse);
}
}
// Grades are actually submitted to Forms here.
FormApp.getActiveForm().submitGrades(formResponses);

Dynamic table names in Entity Framework linq

I'm using Entity Framework 6 with ASP.Net MVC 5. When using a database context object, is there a way to use a variable for the table name, without having to manually write the query?
For example:
var tableName = "NameOfTable";
result = context.tableName.Find(...);
I know that particular code won't work, because tableName is not defined in context, but is there a way to achieve the desired effect?
There are some similar questions on this site, but they never really solved the problem and they were for earlier versions of entity framework, so I'm hoping that there is an answer now.
Here's a simple solution using a switch to associate a particular Type to a table. You could also maintain use some sort of Dictionary<string, Type> object.
var tableName = "Table1";
// Get proper return type.
Type returnType;
switch(tableName) {
case "Table1":
returnType = typeof(Table1EntityType);
break;
case "Table2":
returnType = typeof(Table2EntityType);
break;
}
var query = context.Set(returnType);
// Filter against "query" variable below...
var result = query.Where(...);
-or-
var tableName = "Table1";
Dictionary<string, Type> tableTypeDict = new Dictionary<string, Type>()
{
{ "Table1", Table1Type },
{ "Table2", Table2Type }
};
var query = context.Set(tableTypeDict[tableName]);
// Filter against "query" variable below...
var result = query.Where(...);
EDIT: Modified for Entity Framework
EDIT2: Use typeof per #thepirat000 's suggestion
In addition to the helpful answers above, I also want to add this in case it helps someone else.
If you are getting this error on the "Where" clause in Mark's answer:
'DbSet does not contain a definition for 'Where' and no acceptable extension method 'Where' accepting an argument of the type 'DbSet' could be found.
Installing the Nuget Package "System.Linq.Dynamic.Core" made the error disappear for us.
If you need to access the LINQ methods and the column names from the table, you can code something like this:
var tableName = "MyTableName";
var tableClassNameSpace = "MyProject.Models.EntityModels";
using (var dbContext = new MyEntities())
{
var tableClassName = $"{tableClassNameSpace}.{tableName}";
var dynamicTableType = Type.GetType(tableClassName); // Type
var dynamicTable = dbContext.Set(dynamicTableType); // DbSet
var records = dynamicTable
.AsQueryable()
.ToDynamicList()
.OrderBy(d => d.MyColumnName)
.Select(d => new { d.MyColumnName })
.ToList();
// do stuff
}

AS2 - How do you remove part of a string

I want a simple function that can remove part of a string, eg:
var foo="oranges";
trace(removeStrings(foo,'rang'));
I want the above output as 'oes'. Any help will be greatly appreciated.
Thanks in advance
A quick solution for removing substrings is to use split with the string that you want to remove as delimiter and then join the result:
function removeSubString(str, remove):String {
return str.split(remove).join("");
}
Another way to do this is
function removeStrings(originalString, pattern):String
{
return originalString.replace(pattern, "");
}
For more information about Strings in AS3 you can visit:
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/String.html
I should mention that the code above is not going to change your String, so if you need to use the property originalString with the new value you should use:
originalString = removeStrings(originalString, pattern);
The second thing that I should mention is that the replace method will replace the first appearance of the pattern, so if you need to replace every match of the pattern you should do something like
while(originalString.search(pattern) != -1)
{
originalString = removeStrings(originalString, pattern);
}
Hope this will help!
Ivan Marinov
I'm using by long time this snippet, which as the advantage to be available to all string objects on your movie:
String.prototype.replace = function(pattern, replacement) {
return this.split(pattern).join(replacement);
}
can be used in this way:
var str = "hello world";
var newstr = str.replace("world", "abc");
trace(newstr);
as you can see the string class have been extended with the replace method.

ASP.NET MVC 2 - HTML.EditorFor() and Custom EditorTemplates

With MVC 2's addition of the HtmlHelper EditorFor() it is not possible to create strongly typed Display and Editor templates for a given Model object and after fiddling with it I am a bit stumped as to how to pass additional Model data to the editor without losing the strong-typing of the editor control.
Classic Example: Product has Category. ProductEditor has a DropDownList for Category containing the names of all Categories. The ProductEditor is strongly typed to Product and we need to pass in the SelectList of Categories as well as the Product.
With a standard view we would wrap the Model data in a new type and pass that along. With the EditorTemplate we lose some of the standard functionality if we pass in a mixed Model containing more than one object (first thing I noticed was all of the LabelFor/TextBoxFor methods were producing entity names like "Model.Object" rather than just "Object").
Am I doing it wrong or should Html.EditorFor() have an additional ViewDataDictionary/Model parameter?
You can either create a custom ViewModel which has both properties OR you'll need to use ViewData to pass that information in.
I am still learning, but I had a similar problem for which I worked out a solution.
My Category is an enum and I use a template control which examines the enum to determine the contents for the Select tag.
It is used in the view as:
<%= Html.DropDownList
(
"CategoryCode",
MvcApplication1.Utility.EditorTemplates.SelectListForEnum(typeof(WebSite.ViewData.Episode.Procedure.Category), selectedItem)
) %>
The enum for Category is decorated with Description attributes to be used as the text values in the Select items:
public enum Category
{
[Description("Operative")]
Operative=1,
[Description("Non Operative")]
NonOperative=2,
[Description("Therapeutic")]
Therapeutic=3
}
private Category _CategoryCode;
public Category CategoryCode
{
get { return _CategoryCode; }
set { _CategoryCode = value; }
}
The SelectListForEnum constructs the list of select items using the enum definition and the index for the currently selected item, as follows:
public static SelectListItem[] SelectListForEnum(System.Type typeOfEnum, int selectedItem)
{
var enumValues = typeOfEnum.GetEnumValues();
var enumNames = typeOfEnum.GetEnumNames();
var count = enumNames.Length;
var enumDescriptions = new string[count];
int i = 0;
foreach (var item in enumValues)
{
var name = enumNames[i].Trim();
var fieldInfo = item.GetType().GetField(name);
var attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
enumDescriptions[i] = (attributes.Length > 0) ? attributes[0].Description : name;
i++;
}
var list = new SelectListItem[count];
for (int index = 0; index < list.Length; index++)
{
list[index] = new SelectListItem { Value = enumNames[index], Text = enumDescriptions[index], Selected = (index == (selectedItem - 1)) };
}
return list;
}
The end result is a nicely presented DDL.
Hope this helps. Any comments about better ways to do this will be greatly appreciated.
Try using ViewData.ModelMetadata this contains all of your class Annotations.
Excellent article http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-4-custom-object-templates.html

Resources