How to sort when also using a where clause - database

I am currently pulling a list from a database, using the following code. The list is retrieved using a WHERE condition, however the list is returned unsorted. This is in the controller.
How can I modify this code so that the returned list is sorted alphabetically?
if (!string.IsNullOrEmpty(TargetYear))
{
ViewBag.HSID = new SelectList(db.Hotspots.Where(g => g.HSID.Contains(TargetYear)).ToList(), "ID", "HSID");
}
On several other fields I have used the following method to order, but I'm not sure how, or if I can combine this with the where clause above. The key piece is ".OrderBy(e=>e.FIELD), however this is precisely the piece I'm not sure how to integrate with the query.
ViewBag.LocalityCode = new SelectList(db.Localities.OrderBy(e=>e.LOCALITY1), "LOC_CODE", "LOCALITY1");
Other helpful bits of info:
ASP.Net MVC5
Microsoft SQL 2012

if (!string.IsNullOrEmpty(TargetYear))
{
var data =
db.Hotspots
.Where(g => g.HSID.Contains(TargetYear))
.OrderBy(e=>e.HSID)
.ToList();
ViewBag.HSID = new SelectList(data,"ID", "HSID");
}

Related

DotNet Core Azure Search SDK - filtering results

We are trying to implement Filter functionality into Azure (Cognitive) Search. I was hoping to find some nice SDK methods that hide all the ugly parts, but so far the only example I found looks like this (source):
SearchParameters parameters = new SearchParameters()
{
Filter = String.Format("groupIds/any(p:search.in(p, '{0}'))", string.Join(",", groups.Select(g => g.ToString()))),
Select = new[] { "application essays" }
};
I was wondering, whether I am missing some docs. Or maybe it is on the roadmap?
Check out our new Azure.Search.Documents SDK we released last month. It does have OData filter helps as you can find here:
int stars = 4;
SearchOptions options = new SearchOptions
{
// Filter to only Rating greater than or equal our preference
Filter = SearchFilter.Create($"Rating ge {stars}"),
Size = 5, // Take only 5 results
OrderBy = { "Rating desc" } // Sort by Rating from high to low
};
It'll escape string parameters correctly. The OData $filter syntax still requires raw input, but the type helpers in the formattable string should make your situation easier: you don't have to worry about escaping values yourself.

Create database seeder with same random value in a table row with Laravel database seeder

I am trying to create a table and populate the table with the following fields with the help of database seeder:
option a
option b
option c
option d
correct option
First four fields will be assigned random word, and the last field 'correct option' will contain any one of the first four.
I could not find any solution to do it with Laravel database seeder. Can anyone help?
Something like this?
use faker random element function in your factory or seeder.
$optionA = $faker->word;
$optionB = $faker->word;
$optionC = $faker->word;
$optionD = $faker->word;
return [
'option_a' => $optionA,
'option_b' => $optionB,
'option_c' => $optionC,
'option_d' => $optionD,
'correct_option' => $faker->randomElement([$optionA,$optionB,$optionC,$optionD]),
];
Create a factory and use Faker to generate the random words you're after
This sounds like an ideal use case for JSON columns (both for questions and answers). For instance, you might decide to have multiple valid answers to a single multiple choice question.
In your migration:
// create_questions_table.php
...
$table->json('choices')->default(new Expression('(JSON_ARRAY())'));
$table->json('answer')->default(new Expression('(JSON_ARRAY())'));
From https://laravel.com/docs/7.x/migrations#column-modifiers:
Using an Expression instance will prevent wrapping the value in quotes and allow you to use database specific functions. One situation where this is particularly useful is when you need to assign default values to JSON columns.
Then create a factory:
// QuestionFactory.php
$factory->define(Location::class, function (Faker $faker) {
$choices = $faker->words(4);
$answer = [ $choices[rand(1,4)] ];
return [
'choices' => $choices,
'answer' => $answer,
];
});
Using the Faker library included in Laravel, we can pick 4 words and randomly assign one of them to be the answer.

IDistributedCache Removing keys

I've recently started using the sql version of IDistributedCache on a dotnet core web api.
How would you remove/invalidate a set of keys for say a specific user?
I.e: I structured the keys to follow this convention:
/users/{userId}/Key1
/users/{userId}/Key2
/users/{userId}/Section/Key3
I cannot find any method to remove all keys starting with: /users/{userId}
How do you remove more than one item from the IDistributedCache at a time?
Removing via SQL statement is not a good solution because the webapp process performs some kind of lock. For example, I had to manually stop after three minutes and half the following simple query Delete from SqlSession with only two records.
So I ended up this way: I retrieve data with a simple query like
Select Id from SqlSession where Id like 'MyIdGroup%'
or with Entity framework
var cacheElementsToDelete = await _dbContext.SQLSessions
.Where(a => a.Id.StartsWith("MyIdGroup"))
.ToListAsync();
Then I use the method of the IDistributedCache to remove each item
foreach (var item in cacheElementsToDelete)
{
await _cache.RemoveAsync(item.Id);
}

Visualforce RemoteObjectModels Query filtering using "OR"

I am using in visualforce page of Salesforce.com. For demo purposes, I have used the following code snippet from the example docs shown in
http://docs.releasenotes.salesforce.com/en-us/spring14/release-notes/rn_vf_remote_objects.htm
In my code snippet i have a 'Where' clause in which i am trying to filter using 3 fields. My requirement is that the records must match the criteria A or criteria B or criteria C.
Code Example
<apex:page >
<!-- Remote Objects definition to set accessible sObjects and fields -->
<apex:remoteObjects >
<apex:remoteObjectModel name="Group_Donor__c" jsShorthand="Groupdonor"
fields="Name,Id">
<apex:remoteObjectField name="State__c" jsShorthand="State"/>
<apex:remoteObjectField name="Org_Phone__c" jsShorthand="Phone"/>
<apex:remoteObjectField name="Billing_Type__c" jsShorthand="billingtype"/>
</apex:remoteObjectModel>
</apex:remoteObjects>
<!-- JavaScript to make Remote Objects calls -->
<script>
var fetchWarehouses = function(){
// Create a new Remote Object
var wh = new SObjectModel.Groupdonor();
// Use the Remote Object to query for 10 warehouse records
wh.retrieve({
where: {
or: {
Name : {like:"%Helloworld%"}, // Error
State: {like:"%chennai%"},
//Phone: {like:"%098765432344%"},
billingtype: {like:"%Credit Card%"}
}
},
limit: 10 ,
}, function(err, records, event){
if(err) {
alert(err.message);
}
else {
var ul = document.getElementById("warehousesList");
records.forEach(function(record) {
// Build the text for a warehouse line item
var whText = record.get("Name");
whText += " -- ";
whText += record.get("Phone");
whText += " -- ";
whText += record.get("billingtype");
// Add the line item to the warehouses list
var li = document.createElement("li");
li.appendChild(document.createTextNode(whText));
ul.appendChild(li);
});
}
});
};
</script>
<h1>Retrieve Group Donors via Remote Objects</h1>
<p>Warehouses:</p>
<ul id="warehousesList">
</ul>
<button onclick="fetchWarehouses()">Retrieve Group Donors</button>
</apex:page>
When i execute this code i get the following error.
Error Message :
Invalid criteria specified for retreival. ValidationError [code=11, message=Data does not match any schemas from "oneOf" path=/where, schemaKey=null]
This issue occurs only during the following conditions.
When i use Standard field like Name in the OR condition. ( Even 2 or 1 filter)
When i use more than 3 Custom fields in the OR condition ( More than 2 Query filter)
But when i use just any 2 custom fields mentioned in the RemoteObjectModel as filters, i get the expected results.
Kindly let me know what am i missing here. If i have use more than 2 filters in or condition, how do i achieve it ? is the usage of 'OR' proper in the remote-objects?. And has anyone come across this issue. if so kindly provide me some pointers.
Thanks in advance.
I've been doing some looking and there's some bad news and some good news.
First, it's a (obscure)known limitation that you can't have more than 2 predicates for AND and OR queries - Docs here
However, you seem to have discovered another bug in that an Standard Field (Name, Id) seems to not work when used with a custom one. My workaround was to redefine ALL fields, even standard ones like this:
<apex:remoteObjectModel name="Group_Donor__c" jsShorthand="GroupDonor">
<apex:remoteObjectField name="Name" jsShorthand="NameJS"/>
<apex:remoteObjectField name="State__c" jsShorthand="State"/>
<apex:remoteObjectField name="Org_Phone__c" jsShorthand="Phone"/>
<!--.... etc-->
At least you'll be able to query standard fields this way.
As an ultimate work around, you'll probably have to retrieve two lists of records and use JavaScript to create your ultimate OR list.
Good luck!

How do I build this complex database query in CakePHP 3.0?

This is my database design, or at least the tables that are relevant to this question.
I want to build a query that returns a single page (find will be based on the path attribute), with the associated container, with its associated child-containers in threaded form and all of those containers should individually have their associated blocks with them (preferably in the right order sorted by the index column from the blocks_pages table).
Can anybody give me a clue how to wrap that all up with the query-builder? Or if that is not possible, then is it possible to do it using the new map/reduce feature, since the after-find function has been removed?
In case it helps, this will be the visualized result, if you just ignore the magenta Article-box for a moment.
Try this
$pagesTable
->find()
->where(['path' => $myPath])
->contain([
'Containers.ChildContainers' => function($q) {
return $q->formatResults(function($results) {
return $results->map(function($container) {
$container->nested = $container->source()
->find('children', ['for' => $container->id])
->find('threaded')
->contain(['Blocks']);
return $container;
});
});
},
'Containers.ChildContainers.Blocks'
])

Resources