Getting error 'Insight.Database.FastExpando' does not contain a definition for 'Set1' - insight.database

The following code is giving the above error, and I cannot figure out why:
var x = _sqlConn.Connection().QueryResults<Results>("MyDb.dbo.get_records", new { id = theId });
int retVal = x.Outputs.Return_Value;
if (retVal == 0) // ...meaning result set was also returned...fine to this point.
{
var list = x.Outputs.Set1; // exception thrown here with above error
var temp = list.FirstOrDefault();
I have been using other features of Insight.Database for a number of years, but have not had to retrieve a SQL RETURN value at the same time as a recordset. The SQL itself works correctly in SSMS, returning a result set and the RETURN value of 0, as expected. This is happening in VS2019, .NET 4 and .NET 4.5.2; Insight.Database 5.2.7 and 5.2.8.
I got this code from the following page:
https://github.com/jonwagner/Insight.Database/wiki/Specifying-Result-Structures
where it shows this:
var results = connection.QueryResults<Beer, Glass>("GetAllBeersAndAllGlasses");
IList<Beer> beers = results.Set1;
which I combined with the following code from here:
https://github.com/jonwagner/Insight.Database/wiki/Output-Parameters
var results = connection.QueryResults<Results>("MyProc", inputParameters);
var p = results.Outputs.p;
That part works. It's accessing .Set1 that is failing, and I am not sure how to track down why.
I do not have experience with the FastExpando class, but Jon promised magic, and I want to believe. Thanks for any help.

I haven’t tried results+dynamic objects in a while…
I think it is because you are doing:
QueryResults<Results> and Results is an Insight type
You probably want:
QueryResults<MyType>
And then you get back a Results<MyType>
Which contains the return val and Set1
If not, post a ticket over on github and we will help you out.

Related

local rest api controller does not receive data from repository function-call

Our VS-2022 development project is Blazor WASM Core-6 with local REST-API for data. Using Postman, my testing is not getting data from the controller call to a repository function -- using breakpoints and local debugging -- as one would expect.
The repository function return statement is return Ok(vehicleTrips);. The IEnumerable vehicleTrips data variable contains the correct four records as expected from the DB fetch.
From the controller the call to the repository function is:
var result = (await motripRepository.GetMOTripsByDateRange((int)eModelType.Vehicle, pVehicleList, pDateFrom, pDateTo)!)!;
The controller function signature is:
[HttpGet("byDateRange/{pVehicleList}/{pDateFrom}/{pDateTo}")]
[ActionName(nameof(GetVehicleMOTripsByDateRange))]
public async Task<ActionResult<IEnumerable<MOTRIP>>> GetVehicleMOTripsByDateRange([FromRoute] string pVehicleList, [FromRoute] string pDateFrom, [FromRoute] string pDateTo) {
This is my problem. The result return value from the repository has a return.Value of null -- NOT four trip records as we should.
Additionally, the VS-Studio's 'local'-debugger shows that there are other properties of return such as .Return and .Return.Value.Count as 4 (four).
My question is "what could be causing this"? All of my other rest-api calls and controller calls with Postman work correctly as one would expect.
Did I select the wrong type of "controller" from Visual-Studio? I am not experienced at all in coding classic MVC web-applications. VS-Blazor offer a number of controller-types. In the past, I "copied" a working controller and "changed the code" for a different "model".
Your assistance is welcome and appreciated. Thanks...John
I found out what actually happened to cause the result.Value is null and had nothing to do with the controller-type -- it was in the interpretation of the return value from the repository function.
I found an SO link Get a Value from ActionResult<object> in a ASP.Net Core API Method that explains how to respond to a ActionResult<objecttype> return value in the reply/answer section with the word "actual" is first defined. You will see this word "actual" in my revised code below.
My revised code is posted here with comments both inside the code section and below the code section. My comment inside the code begins with "<==" with text following until "==>"
// Initialize.
MOTRIP emptyMoTrip = new MOTRIP();
MOTRIP? resultMoTrip = new MOTRIP();
IEnumerable<MOTRIP> allTrips = Enumerable.Empty<MOTRIP>();
int daysPrevious = (int)(pTripType == eTripType.Any ? eDateRangeOffset.Week : eDateRangeOffset.Month);
// convert DateRangeOffset to 'dateonly' values.
DateOnly dtTo = DateOnly.FromDateTime( DateTime.Today);
DateOnly dtFrom = dtTo.AddDays(daysPrevious);
// Fetch the vehicle trips by date-range.
var result = await GetVehicleMOTripsByDateRange(UID_Vehicle.ToString(), dtFrom.ToString(), dtTo.ToString());
if ((result.Result as OkObjectResult) is null) { **<== this is the fix from the SO link.==>**
return StatusCode(204, emptyMoTrip);
}
var statusCode = (result.Result as OkObjectResult)!.StatusCode;
if (statusCode==204) {
return StatusCode(204, emptyMoTrip);
}
**<== this next section allows code to get the result's DATA for further processing.==>**
var actual = (result.Result as OkObjectResult)!.Value as IEnumerable<MOTRIP>;
allTrips = (IEnumerable<MOTRIP>)actual!;
if ((allTrips is not null) && (!allTrips.Any())) {
return StatusCode(204, emptyMoTrip);
}
<== this next section continues with business-logic related to the result-DATA.==>
if (allTrips is not null && allTrips.Any()) {
switch (blah-blah-blah) {
**<== the remainder of business logic is not shown as irrelevant to the "fix".==>**
Please use browser search for "<==" to find my code-comments.
Please use browser search for "actual" and "OkObjectResult" to see the relevant code fix sentences.

Having Difficulty Using MongoDb C# Driver's Sample()

I am trying to get some random items from the database using the Sample() method. I updated to the latest version of the driver and copied the using statements from the linked example. However, something isn't working, and I am hoping it's some simple mistake on my part. All the relevant information is in the image below:
Edit:
Greg, I read the aggregation docs here and the raw db method doc here, but I still don't get it. Last two lines are my attempts, I have never used aggregation before:
var mongoCollection = GetMongoCollection<BsonDocument>(collectionName);
long[] locationIds = new long[] { 1, 2, 3, 4, 5 };
var locationsArray = new BsonArray();
foreach (long l in locationIds) { locationsArray.Add(l); };
FilterDefinition<BsonDocument> sampleFilter = Builders<BsonDocument>.Filter.In("LocationId", locationsArray);
var findSomething = mongoCollection.Find(sampleFilter); //this works, the two attempts below don't.
var aggregateSomething = mongoCollection.Aggregate(sampleFilter).Sample(25);
var aggregateSomething2 = mongoCollection.Aggregate().Match(sampleFilter).Sample(25);
Sample is only available from an aggregation. You need to start with Aggregate, not Find. I believe it's also available in Linq.
UPDATE:
Looks like we don't have a method for it specifically. However, you can use the AppendStage method.
mongoCollection.Aggregate(sampleFilter)
.AppendStage<BsonDocument>("{ $sample: { size: 3 } }");

NHibernate: Can't Select after Skip Take In Certain Scenario

For some reason I am unable to use Select() after a Skip()/Take() unless I do this in a certain way. The following code works and allows me to use result as part of a sub query.
var query = QueryOver.Of<MyType>();
query.Skip(1);
var result = query.Select(myType => myType.Id);
However, if I attempt to create the query on one line as below I can't compile.
var query = QueryOver.Of<MyType>().Skip(1);
var result = query.Select(myType => myType.Id);
It looks like the code in the first results in query being of type QueryOver< MyType, MyType> while the second results in query being of type QueryOver< MyType>.
It also works if written like this.
var query = QueryOver.Of<MyType>().Select(myType => myType.Id).Skip(1);
Any ideas why the second version fails horribly when the first and third versions work? It seems like odd behavior.
You have a typo in the second version...
var query = QueryOver.Of<MyType().Skip(1);
is missing the >
var query = QueryOver.Of<MyType>().Skip(1);
Not sure if thats what you where looking for.

error .match expression results null

I am working on a mail merge script. I have used Logger.log to find out that the error is in the expression that tells match what to find. In my case I am trying to pull all the keys that are inside ${xxxxxxx}. Below is what I have and I need help cleaning it up because at this point it returns null.
var template = "This is an example ${key1} that should pull ${key2} both keys from this text."
var templateVars = template.match(/\$\{\"[^\"]+\"\}/g);
Thanks for any guidance anyone can share on this problem.
-Sean
I am not really familiarized with Google Apps Script, but I think this code in Javascript can help you.
It looks for all the ocurences of ${key} and returns each value inside the ${ }. I think that is what you are looking for.
var template = "This is an example ${key1} that should pull ${key2} both keys from this text.";
var matches = template.match(/\$\{[0-9a-zA-Z]*\}/mg);
console.log(matches);
for ( var i = 0; i < matches.length; i++ ) {
console.log(matches[i].replace(/[\$\{|\}]/gm, ""));
}

Passing query results in a viewbag

This seems like it should be so easy, but I've tried three or four ways to do it (but to no avail).
I'm just trying to put a query result in a viewbag and display it.
I've tried putting a model object list in a ViewBag:
var mesg = from MSG in lemondb.Messages
where MSG.msg == Membership.GetUser().ToString()
select MSG;
ViewBag.messages = MSG;
And then I try to spit it out in a .cshtml:
var message = (List<LemonTrader.Models.Message>)ViewBag.messages; // <--- fails here because it is a string
foreach ( var MSG in message )
{
#Html.Label(MSG.msg)<br />
}
But it says:
Cannot convert type
'System.Data.Entity.Infrastructure.DbQuery'
to
'System.Collections.Generic.List'
So it seems I'm using using the wrong template. How do I spit out a System.Entity.Infrastructure.DbQuery?
I've also tried passing the results through the Viewbag as a list of strings. (Is that a worse way to do it?)
var mesg = from MSG in lemondb.Messages
where MSG.msg == Membership.GetUser().ToString()
select MSG.msg;
ViewBag.messages = mesg;
And spitting it out as a string list:
foreach (var atext in ViewBag.messages as List<string>) { // gets hung up on foreach here (why???)
#Html.Label( atext )
}
And I get this:
Object reference not set to an
instance of an object.
And it points at the "foreach" keyword.
Does that mean there were no messages? Or what?
I wish there was a tutorial showing how to put queryresults in a ViewBag and how to get them out! I've seen tutorials that return an object.ToList() without respect to any kind of "where" mechanism, but no examples to pull out a few, relevant entries and display them.
Try
ViewBag.messages = MSG.ToList();
Also, System.Data.Entity.Infrastructure.DbQuery implements IEnumerable ( http://msdn.microsoft.com/en-us/library/system.data.entity.infrastructure.dbquery(v=vs.103).aspx ) so this should also work:
var message = (IEnumerable<LemonTrader.Models.Message>)ViewBag.messages;