Query with date range - asp.net

I have the following query;
foreach (Item sourceChild in source.Axes.GetDescendants()
.OrderBy(x => x["date-optional-1"])
.ThenBy(x => x["date-optional-2"])
.Reverse())
{..}
date-optional-1 and 2 are, as the name states, optional, and therefore not guaranteed to be filed.
But if they are, no 1 takes precedence over 2.
I need to add, that if no 1 is filed, then I only need the items from today and forward (it is an event date). How would i go about this in a Where()?

foreach (Item sourceChild in source.Axes.GetDescendants()
.Where(x => DateUtil.ParseDateTime(x["date-optional-1"], DateTime.MaxValue) >= DateTime.UtcNow.Date)
.OrderBy(x => x["date-optional-1"])
.ThenBy(x => x["date-optional-2"])
.Reverse())
{..}
DateUtil.ParseDateTime converts the string value of the 'date-optional-1' field into a DateTime.
Sitecore stores dates in UTC so we compare that DateTime value with DateTime.UtcNow.Date. This includes only items with a 'date-optional-1' value >= today in the result set.
DateTime.MaxValue is passed as the second parameter to DateUtil.ParseDateTime so that items with no 'date-optional-1' value are included in the result set.

Related

How to fetch past 30 days data from dynamo db

I want to fetch the past 30 days data from dynamo db. I can only able to fetch only one id at a time. How can i get all the data of 30 days from dynamo db.
$sevenDaysAgo = date('Y-m-d H:i:s', strtotime('30 days'));
echo $response = $dynamodb->query([ 'TableName' => 'notifications',
'KeyConditionExpression' => 'id = :id and date_time >= :datess', 'ExpressionAttributeValues' => [ ':id' => ['S' => '350'],
':datess' => ['S' => $sevenDaysAgo] ],
'ProjectionExpression' => 'id', 'ConsistentRead' => true ]);
You could use the new TTL feature, Streams, and Lambda to maintain a sliding 30 day window of data in a new table called sliding. Steps:
Create a new table called sliding with the same schema as your base table. This table should have TTL enabled on an attribute named myttl.
Enable your original table's DynamoDB Stream with both old and new images.
Attach a lambda function to your original table's Stream. This lambda would write all item creations/updates/deletions from the base table to the sliding table.
It seems like each item might already contain a timestamp. Scan your original table and add a N attribute called myttl equal to timestamp+30 days in epoch time, if the item's timestamp was in the last 30 days.
The result of steps 1-4 will be a table sliding that contains an eventually consistent view of the last 30 days worth of data.

Is there a way to select a columns from a joined table without explicitly listing all columns?

I'm trying to use JoinSqlBuilder to select a data from one of the joined tables, and can't find a way to do that unless I list all columns from that table. Hopefully I'm missing something and it actually can be done.
This is approximately what I have:
var sql = new JoinSqlBuilder<Product, Product>()
.Join<Product, Customer>(src => src.Id, dst => dst.Id)
.Where<Customer>(x => x.Id == Id);
and I want to select everything from a product table. The query above throws an exception complaining about column name collisions, so its clearly does a select from both tables.
Edit: In the end I want to have this sql (never mind the design, its not a real thing):
select
p.* //<-- This is the piece that I'm struggling with
from product p inner join customer c on p.id on c.productId
where blah;
Looks like OrmLite want me to explicitly list all columns I want to return, which I want to avoid.
Note: I'm using 3.9.71 of servicestack. I've not looked at the 4.0 implementation yet.
I think you have a FK relationship problem with your join. Assuming that a product has a customer FK named (CustID), it'd look like this. Additionally, you'd need a POCO to represent the result set, if you are returning a "combination" of the results. I don't think you'll want to return both "ID" columns, and instead return a FK column.
return _factory.Run<ProductCustomer>(conn=>
{
var jn = new JoinSqlBuilder<Product, Customer>();
jn = jn.Join<Product, Customer>(srcProd => srcProd.CustId,
dstCust => dstCust.Id, // set up join Customer.id -> Product.CustId
p => new { p.Id, p.OtherField}, // product table fields returned
c => new { c.Name, c.AddressId}, // customer fields returned
null, //where clause on the product table
cust=>cust.Id = customerId // where clause on the customer table
);
var sql = jn.ToSQL();
return conn.FirstOrDefault<ProductCustomer>(sql);
}
Hope this helps.
Edit: After your Edit, try this:
// set up join Customer.id -> c.ProductId
jn = jn.Join<Product, Customer>(srcProd => srcProd.Id, dstCust => dstCust.productId)
.Where<Customer>(c=>c.Id == custIdParameter);
var sql = jn.ToSql();
You can add a ".Where" again for the
Where<Product>(p=>p.id == foo);
if you need to add more product with your BLAH. This should get you close.
Have you tried the SelectAll extension method?
var sql = new JoinSqlBuilder<Product, Product>()
.Join<Product, Customer>(src => src.Id, dst => dst.Id)
.SelectAll<Product>()
.Where<Customer>(x => x.Id == Id);

Date comparision using Linq

I have a DateTime type column named "CreatedDate" in my sql table, and am passing the value for this column by using "DateTime.Now" from my asp.net application....
The datas in my CreatedDate column are,
CreatedDate
-----------
2012-05-07 18:56:17.487
2012-05-07 18:56:28.443
2012-05-07 19:21:24.497
2012-05-14 15:22:04.587
I need to get the datas with this CreatedDate.
in my entity framework I tried the condition like
DataAccess.Entities dataEntities = new DataAccess.Entities();
DataAccess.Employee employee = dataEntities.Employees
.First(e => e.CreatedDate == DateTime.Today);
like this, I have data for this date(2012-05-14) , but the mininutes part differes (the DateTime.Today gives '2012-05-14 12:00:000' like this) here, and it shows error like, sequence contains no element....
How can I compare the 'Date' alone in Linq.....can anyone help me here,,,
Use the Date Property on the DateTime object
CreatedDate.Date==DateTime.Today
So your code will be
DataAccess.Employee employee=dataEntities.
Employees.First(e=>e.CreatedDate.Date==DateTime.Today);
Date Property returns the Date Component of the DateTime object and the time value set to 12:00:00 midnight (00:00:00).
Try this:
DataAccess.Employee employee =
dataEntities.Employees.First(e=>e.CreatedDate.Date==DateTime.Today)
I just declared two variable like
DateTime date1=DateTime.Now.Date;
DateTime date2=DateTime.Now.Date.AddDays(1);
and in the condition I used these variables like
DataAccess.Employee employee = dataEntities.Employees
.First(e => e.CreatedDate >= date1
&& e.CreatedDate < date2);
its working....

How to query the number of view counts for a post in Wordpress JetPack?

I use JetPack stats to follow the stats for my blog. I would like to extract the top 10 most-viewed posts for a given period (e.g. last month).
I used the WordPress stats plugin API before which worked nicely, but after upgrade to JetPack this doesn't work anymore.
Is there an API which allows me to query the number of view counts for a post?
Inside the Database
This option is recorded in the database and is used by the Dashboard widget:
get_option( 'stats_cache' );
It returns an array like this:
array(
['7375996b7a989f95a6ed03ca7c899b1f'] => array(
[1353440532] => array(
[0] => array(
['post_id'] => 0
['post_title'] => 'Home page'
['post_permalink'] => 'http://www.example.com/'
['views'] => 1132
)
[1] => array(
['post_id'] => 4784
['post_title'] => 'Hello World!'
['post_permalink'] =>
['views'] => 493
)
/* till item [9] */
Querying WordPress.com
It is possible to call the following Jetpack function:
if( function_exists( 'stats_get_csv' ) ) {
$top_posts = stats_get_csv( 'postviews', 'period=month&limit=30' );
}
Which returns:
array(
[0] => array(
['post_id'] => 0
['post_title'] => 'Home page'
['post_permalink'] => 'http://www.example.com/'
['views'] => 6806
)
[1] => array(
['post_id'] => 8005
['post_title'] => 'Hello World!'
['post_permalink'] =>
['views'] => 1845
)
/* till item [29] */
Function get_stats_csv
/plugins/jetpack/modules/stats.php
The function get_stats_csv calls http://stats.wordpress.com/csv.php. If we visit this address, we get this response:
Error: api_key is a required parameter.
Required parameters: api_key, blog_id or blog_uri.
Optional parameters: table, post_id, end, days, limit, summarize.
Parameters:
api_key String A secret unique to your WordPress.com user account.
blog_id Integer The number that identifies your blog.
Find it in other stats URLs.
blog_uri String The full URL to the root directory of your blog.
Including the full path.
table String One of views, postviews, referrers, referrers_grouped,
searchterms, clicks, videoplays.
post_id Integer For use with postviews table.
end String The last day of the desired time frame.
Format is 'Y-m-d' (e.g. 2007-05-01)
and default is UTC date.
days Integer The length of the desired time frame.
Default is 30. "-1" means unlimited.
period String For use with views table and the 'days' parameter.
The desired time period grouping. 'week' or 'month'
Use 'days' as the number of results to return
(e.g. '&period=week&days=12' to return 12 weeks)
limit Integer The maximum number of records to return.
Default is 100. "-1" means unlimited.
If days is -1, limit is capped at 500.
summarize Flag If present, summarizes all matching records.
format String The format the data is returned in,
'csv', 'xml' or 'json'.
Default is 'csv'.
Non-working query example:
?api_key=123456789abc&blog_id=155&table=referrers&days=30&limit=-1&summarize
Result format is csv with one row per line and column names in first row.
Strings containing double quotes, commas, or "\n" are enclosed in double-quotes.
Double-qoutes in strings are escaped by inserting another double-quote.
Example: "pet food" recipe
Becomes: """pet food"" recipe"
Developers, please cache the results for at least 180 seconds.

Possible to convert result of Drupal db_query to PHP array?

In Drupal, I can execute a SQL as follows:
$query_object = db_query("SELECT * FROM {nodes}");
If I know the query returns only a single result (so only 1 row and 1 column), I can directly fetch it with:
$result = db_result($query_object);
If I got multiple results, I need to loop through them with something like:
$rows[] = array();
while (($row = db_fetch_object($query_object) != FALSE) {
$rows[] = $row;
}
I'm wondering if there is an easier way to do that? Is there a way that I can transfer all results into an array with a single statement? Or isn't that working, because db_result returns a cursor-like object, where you can only fetch a single row each time?
Not in Drupal 6.
In Drupal 7, there are fetch methods that can help to avoid loops like that. From http://drupal.org/node/310072:
<?php
// Retrieve all records into an indexed array of stdClass objects.
$result->fetchAll();
// Retrieve all records into an associative array keyed by the field in the result specified.
$result->fetchAllAssoc($field);
// Retrieve a 2-column result set as an associative array of field 1 => field 2.
$result->fetchAllKeyed();
// You can also specify which two fields to use by specifying the column numbers for each field
$result->fetchAllKeyed(0,2); // would be field 0 => field 2
$result->fetchAllKeyed(1,0); // would be field 1 => field 0
// Retrieve a 1-column result set as one single array.
$result->fetchCol();
// Column number can be specified otherwise defaults to first column
$result->fetchCol($column_index);
?>
In Drupal 7, you can also use:
db_query('QUERY')->fetchAll(PDO::FETCH_ASSOC);
I do always something like this ( just a simple exemple) :
$query = db_query("SELECT nid
FROM {from}
WHERE blallala
",
$tab_arg
);
if ($query->rowCount() == 0) {
$output=t('no result')
} else
{
foreach($query as $result)
{
$tab_res[]=$result;
}
foreach($tab_res as $res)
{
$output.=$res->nid;
}
}
One can also use db_fetch_array($result), where $result =db_query($queryString). As explained from the Drupal documentation:
[It returns] ...an associative array representing the next row of the result, or
FALSE. The keys of this object are the names of the table fields
selected by the query, and the values are the field values for this
result row.

Categories

Resources