I am trying to read the stepcount from 365 days back in time from the user and then upload this to a server. But I'm currently stuck at extracting the data, I get the permission from the iOS healthkit correctly, but the return type of my data is just get "[0:] HealthKit.HKSample[]"
public void GetSteps()
{
var healthKitStore = new HKHealthStore();
var stepRateType = HKQuantityType.Create(HKQuantityTypeIdentifier.StepCount);
var sort = new NSSortDescriptor(HKSample.SortIdentifierStartDate, true);
var q = new HKSampleQuery(stepRateType, HKQuery.GetPredicateForSamples(NSDate.Now.AddSeconds(TimeSpan.FromDays(-365).TotalSeconds), NSDate.Now.AddSeconds(TimeSpan.FromDays(1).TotalSeconds), HKQueryOptions.None), 0, new NSSortDescriptor[] { },
new HKSampleQueryResultsHandler((HKSampleQuery query2,HKSample[] results, NSError error2) =>
{
var query = results; //property created within the model to expose later.
Debug.WriteLine(query);
Debug.WriteLine(results);
}));
healthKitStore.ExecuteQuery(q);
}
I think I know why you are getting "[0:] HealthKit.HKSample[]", you are trying to Debug.WriteLine an array of objects. The results variable is an array. Loop through the array instead and extract out the "Quantity", "StartDate", and "EndDate" among other fields that are available:
foreach (var item in results)
{
var sample = (HKQuantitySample) item;
var hkUnit = HKUnit.Count;
var quantity = sample.Quantity.GetDoubleValue(hkUnit);
var startDateTime = sample.StartDate.ToDateTime().ToLocalTime();
var endDateTime = sample.EndDate.ToDateTime().ToLocalTime();
Debug.WriteLine(quantity);
Debug.WriteLine(startDateTime);
Debug.WriteLine(endDateTime);
}
Related
I'm trying to load data from DynamoDB.
I use FilterExpression and KeyExpression.
If I search by simple value on the top level everything works fine.
However, when I try to filter records by nested map values, I get 0 records.
CurrentCase is an object, Assignments is Dictionary, Setup is Enum.
Here is my code:
`Expression filterExpression = new ();
filterExpression.ExpressionAttributeNames["#Setup"] = "CurrentCase.Assignments.Setup";
filterExpression.ExpressionAttributeValues[":userId"] = userId;
filterExpression.ExpressionStatement = "#Setup = :userId";`
I tried another way, didn't help. (WHERE CurrentCase.Assignments['Setup'] = 'Id' works in PartyQL):
`Expression filterExpression = new ();
filterExpression.ExpressionAttributeNames["#Setup"] = "CurrentCase.Assignments['Setup']";
filterExpression.ExpressionAttributeValues[":userId"] = userId;
filterExpression.ExpressionStatement = "#Setup = :userId";`
This is how i call query
var queryOperationConfig = new QueryOperationConfig
{
PaginationToken = paginationToken,
Limit = pageSize,
IndexName = GlobalIndexNames.Cases,
KeyExpression = keyExpression,
FilterExpression = filterExpression
};
Search search = _dbContext.GetTargetTable<CaseEntity>().Query(queryOperationConfig);
List<Document> documents = await search.GetNextSetAsync(cancellationToken);
I expect that this request return all records where CurrentCase.Assignments['Setup'] equals userId
Forgive me, im not a .Net coder, but your issue is this:
filterExpression.ExpressionAttributeNames["#Setup"] = "CurrentCase.Assignments.Setup";
You are essentially setting your var #Setup to a String "CurrentCase.Assignments.Setup"
It should be:
ExpressionAttributeNames = new Dictionary<string, string>
{
{ "#CurrentCase", "CurrentCase" },
{ "#Assignments", "Assignments" },
{ "#Setup", "Setup" }
}
filterExpression.ExpressionStatement = "#CurrentCase.#Assignments#Setup = :userId";`
You may need to restructure the example I gave, but you should get the idea.
I want to get the data from the Azure CosmosDB MongoDB older than yesterday. The property date is string "2022-08-03T13:12:24.455271". The below code returns nothing.
var date = DateTime.Today.AddDays(-1);
var page = 1;
var limit = 10;
var subfilter = new BsonDocument("$expr",
new BsonDocument("$lte",
new BsonArray
{
new BsonDocument("$toDate", "$upload_time"), date
}
)
);
var value = await collection.Find(subfilter).Skip((page - 1) * limit).Limit(limit).ToListAsync();
Using Mongosh I can retrieve the data using this
db.uploads.find({"$expr": {"$lte": [{ "$toDate": "$upload_time" }, ISODate("2022-08-03T00:00:00Z")]}}).skip(0).limit(2)
The count of value above is always zero, means it failed to get the data.
If the upload_time is not string then it will be easily using:
var value = await collection.Find(w => w.upload_time < date).Skip((page - 1) * limit).Limit(limit).ToListAsync();
I am accessing the following Json output from a sports statistics API and want to get the specific value that rests in the away team ID for each game being played. (dates>games>teams>away>team:id). Json show here: https://statsapi.web.nhl.com/api/v1/schedule
I've been successful using jObject.Parse() for much of the rest of my project but this value is buried and my knowledge is limited on how to expand my nest to reach it. Any help would be greatly appreciated.
so far I am trying like so but getting errors stating I am accessing invalid key values.
public List<string> GetAwayTeamsPlayingToday()
{
var URL = new UriBuilder("https://statsapi.web.nhl.com/api/v1/schedule");
var client = new WebClient();
List<string> awayTeamsPlayingToday = new List<string>();
JObject ScheduleData = JObject.Parse(client.DownloadString(URL.ToString()));
string lplayerAwayTeamId = string.Empty;
var dates = ScheduleData["dates"] as JArray;
foreach (JObject date in dates)
{
var games = dates["games"] as JArray;
foreach (JObject game in games)
{
var teams = games["teams"] as JArray;
foreach (JObject team in teams)
{
var away = teams["away"] as JArray;
foreach (JObject tm in away)
{
var awayTeam = away["team"] as JObject;
lplayerAwayTeamId = awayTeam["id"].ToString();
awayTeamsPlayingToday.Add(lplayerAwayTeamId);
}
}
}
}
return awayTeamsPlayingToday;
}
You can do this
var URL = new UriBuilder("https://statsapi.web.nhl.com/api/v1/schedule");
var client = new WebClient();
List<string> awayTeamsPlayingToday = new List<string>();
JObject ScheduleData = JObject.Parse(client.DownloadString(URL.ToString()));
var data = JsonConvert.DeserializeObject<dynamic>(ScheduleData.ToString());
//this sample is for first date, first game
var awayTeamId = data.dates[0].games[0].teams.away.team.id;
//to get each game
foreach (var date in data.dates)
{
foreach (var game in date.games)
{
var id = game.teams.away.team.id;
//your logic
}
}
I have a search method that queries Solr for event items. I need to modify it to only get events where the date has not already passed (i.e. Where(x => x.EventDate.Date >= DateTime.Now.Date), but I'm not sure how to add this because I'm not very familiar with Solr. Here's my search function:
public SearchQueryResults Search(string keywords, int page,int perPage, List<Guid> contentTypeFilters, List<Guid> otherFilters, ISortBuilder<SearchResultItem> sortBuilder)
{
var searchFilters = new List<IPredicateBuilder<SearchResultItem>>()
{
new IsSearchablePredicateBuilder()
};
if (contentTypeFilters.Any())
{
var contentTypePredicateBuilder = new ContentTypePredicateBuilder();
contentTypePredicateBuilder.ContentTypes = contentTypeFilters;
searchFilters.Add(contentTypePredicateBuilder);
}
if (otherFilters.Any())
{
var tagFilterBuilder = new TagsAndPredicateBuilder(otherFilters,_sitecoreContext);
searchFilters.Add(tagFilterBuilder);
}
if (string.IsNullOrWhiteSpace(keywords))
{
keywords = "";
}
SearchRequest searchRequest = new SearchRequest();
var queryParams = new Dictionary<string, string>() { };
queryParams.Add("q", keywords);
searchRequest.QueryParameters = queryParams;
searchRequest.SortBy = "";
searchRequest.SortOrder = "";
SearchQuery<SearchResultItem> queryArguments = new SearchQuery<SearchResultItem>();
queryArguments.FilterBuilders = searchFilters;
queryArguments.Page = page;
queryArguments.PerPage = perPage;
queryArguments.FacetsBuilder = new SearchFacetBuilder<SearchResultItem>();
queryArguments.SearchRequest = searchRequest;
queryArguments.IndexName = _indexName;
if (string.IsNullOrWhiteSpace(keywords))
{
queryArguments.QueryBuilders =new List<IPredicateBuilder<SearchResultItem>>();
}
else
{
queryArguments.QueryBuilders = new[] { new KeywordPredicateBuilder<SearchResultItem>(new[] { keywords }) };
}
queryArguments.SortBuilder = sortBuilder;
try
{
var results = _searchManager.GetResults<SearchResultItem>(queryArguments);
SearchQueryResults queryResults = new SearchQueryResults();
queryResults.ResultItems = results.Results;
queryResults.CurrentPage = page;
queryResults.TotalResults = Int32.Parse(results.TotalResults.ToString());
queryResults.TotalPages = (queryResults.TotalResults + perPage - 1) / perPage; ;
return queryResults;
}
catch (Exception exc)
{
Sitecore.Diagnostics.Log.Error("Error with FilteredSearch, could be a loss of connection to the SOLR server: " + exc.Message, this);
return null;
}
}
and here is how it's being called:
Results = _searchService.Search(searchTerm, CurrentPage - 1, 10, contentTypes, searchFilters,
new GenericSortBuilder<SearchResultItem>(q => q.OrderByDescending(r => r.SearchDate)));
How do I add in date filtering so that it only returns items where the date is in the future?
I would add filter query to the list of existing ones filtering the date field. On the documentation page, I was able to find information about fluent API, which could help here
Query.Field("date").From(DateTime.Now)
I'm not C# developer, that this code could have some mistakes, but I think the main idea is clear what needs to be done.
I am using ebay .Net SDK. Everything is working fine except following requirements:
Using of OutputSelector to boost performance
Unable to use SortingOrder, while showing records.
Total income/amount sold for specified time range i.e. Total amount across all calls of the pagination without looping through pages and aggregating it manually.
Here is the code which I am using:
var apicall = new GetOrdersCall(context);
//apicall.ApiRequest.OutputSelector = new StringCollection(new String[] { "Order.OrderID", "Order.Total" });
apicall.ApiRequest.Pagination = new PaginationType
{
EntriesPerPage = Util.RecordsPerPage(),
PageNumber = int.Parse(Request.Form["pageNumber"])
};
var fltr = new TimeFilter(Convert.ToDateTime(Request.Form["dateFrom"] + "T00:00:00.000Z"), Convert.ToDateTime(Request.Form["dateTo"] + "T23:59:59.999Z"));
var statusCodeType = (OrderStatusCodeType)Enum.Parse(typeof(OrderStatusCodeType), Request.Form["statusCode"]);
var orders = apicall.GetOrders(fltr, TradingRoleCodeType.Seller, statusCodeType);
Please assist me how to use these 3 functionality as well.
After much efforts I got the way for it:
var request = new GetOrdersRequestType
{
//OutputSelector = new StringCollection {"OrderID","Total"},
CreateTimeFrom = Convert.ToDateTime(Request.Form["dateFrom"] + "T00:00:00.000Z"),
CreateTimeTo = Convert.ToDateTime(Request.Form["dateTo"] + "T23:59:59.999Z"),
OrderStatus = (OrderStatusCodeType)Enum.Parse(typeof(OrderStatusCodeType), Request.Form["statusCode"]),
OrderRole = TradingRoleCodeType.Seller,
Pagination = new PaginationType
{
EntriesPerPage = Util.RecordsPerPage(),
PageNumber = int.Parse(Request.Form["pageNumber"])
}
};
var apicall = new GetOrdersCall(context)
{
ApiRequest = request,
OutputSelector =
new string[]
{
"OrderID", "Total", "PaidTime", "eBayPaymentStatus",
"PaymentMethod", "Title", "PageNumber", "PaginationResult.TotalNumberOfPages"
}
};
apicall.Execute();
var orders = apicall.ApiResponse.OrderArray;