Getting values from Elastic-Stack - elasticsearch

I'll initial get dates from elastic stack.
At first just any data set, just to proof it works.
I set up the connection and than I try to get a data set.
I show you my code and the error message below.
You got any suggestions where to look for the missing values?
Thanks, Frank
string elasticSearchConnectionString = configuration.GetConnectionString("ElasticSearchConnection");
string elasticSearchIndex = configuration.GetValue<string>("ElasticSearchIndex");
Uri uri = new Uri(elasticSearchConnectionString);
ConnectionSettings settings = new ConnectionSettings(uri).DefaultIndex(elasticSearchIndex);
ElasticClient = new ElasticClient(settings);
IGetResponse<_doc> result = ElasticClient.Get<_doc>(1);
Invalid NEST response built from a unsuccessful low level call on GET: /hybif/_doc/1
Audit trail of this API call:
- 1 BadResponse: Node: http://10.211.226.31:9200/ Took: 00:00:00.3149405
OriginalException: Elasticsearch.Net.ElasticsearchClientException: Request failed to execute. Call: Status code 404 from: GET
/hybif/_doc/1
Request:
force it to be set on the response.>
Response:
ConnectionSettings to force it to be set on the response.>
00:00:00.3149405
OriginalException: Elasticsearch.Net.ElasticsearchClientException: Request failed to execute. Call: Status code 404 from: GET /hybif/_doc/1
Request:
Response:

That works now...:
The search at my RecordsRepository.cs:
var result = ElasticClient.Search<_doc>(document =>
document
.Query(q => q
.Match(m => m
.Field(f => f.DataRecordId)
.Query(search)
)
)
);
and the _doc.cs:
public class _doc
{
[JsonProperty("contextName")]
public string ContextName { get; set; }
[JsonProperty("resourceId")]
public string ResourceId { get; set; }
[JsonProperty("componentId")]
public string ComponentId { get; set; }
[JsonProperty("processStepId")]
public string ProcessStepId { get; set; }
[JsonProperty("dataRecordId")]
public long DataRecordId { get; set; }
[JsonProperty("timestamp")]
public object Timestamp { get; set; }
[JsonProperty("value")]
public double Value { get; set; }
}

Related

.net core MVC TryUpdateModelAsync passed expression of expression node type 'NewArrayInit' is invalid

when I use TryUpdateModelAsync method to update Model I give this error, any one have an idea about this
The passed expression of expression node type 'NewArrayInit' is invalid. Only simple member access expressions for model properties are supported.
Code for this issue is as below.
[HttpPost,ActionName("Edit")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> EditLocaton([ModelBinder(typeof(EncryptDataBinder))]int id, IFormCollection formCollection)
{
ModelState.Clear();
LocationModel location = new LocationModel();
try
{
await TryUpdateModelAsync<LocationModel>(location, "", p => new object[] { p.ID, p.Name, p.Code, p.RowVersion });
code for the Location Model
public class LocationModel : BaseEntity
{
[Required]
[StringLength(100)]
[Display(Name = "Location Name")]
public string Name { get; set; }
[Required]
[StringLength(20)]
public string Code { get; set; }
[NotMapped]
public string enID { get; set; }
}
Please help for this issue.
Here's a sample for TryUpdateModelAsync.
var studentToUpdate = await _context.Students.FirstOrDefaultAsync(s => s.ID == id);
if (await TryUpdateModelAsync<Student>(
studentToUpdate,
"",
s => s.FirstMidName, s => s.LastName, s => s.EnrollmentDate))
{
try
...
It updates the studentToUpdate using data provided in the incoming request.
So I'm afraid you can try await TryUpdateModelAsync<LocationModel>(location, "", p => p.enID, p => p.Name, p => p.Code);. In your code snippet, I don't find RowVersion in your LocationModel, not sure about it.

Correct interpretation of SQL request by EF Core

I have a certain table in the database that stores the following objects:
public partial class Invoice
{
public string DocumentNumber { get; set; }
public DateTime? DocumentDate { get; set; }
public string DocumentReference { get; set; }
public string SerialNumber { get; set; }
public string ProductCode { get; set; }
public string Description { get; set; }
public string Certificate { get; set; }
public string Language { get; set; }
public string Email { get; set; }
}
I also have a query that returns me the number of specific elements:
SELECT Count(*)
FROM (
SELECT DocumentNumber,DocumentDate,DocumentReference
FROM vInvoiceSwivelInfoWeb
WHERE Email = 'someemail#gmail.com' AND Language = 'FR'
GROUP BY DocumentNumber,DocumentDate,DocumentReference
) AS T
The answer looks something like this:
How to use EF to make such a request and get a numerical answer?
I tried like this:
_context.Database.ExecuteSqlRawAsync($"..some SQL query..")
but I do not get the expected result.
UPD: Having received the answer about the impossibility of fulfilling this request through EF, the following question reasonably arose: Is it possible to make this request using LINQ?
You can Leverage ADO.NET via the Context.Database property.
Unfortunately, there is no way to get the count from the database using EF Core execute methods if you have a custom query that is not related to your entities.
using (var command = context.Database.GetDbConnection().CreateCommand())
{
command.CommandText = "SELECT Count(*) From Table1";
context.Database.OpenConnection();
using (var result = command.ExecuteReader())
{
// do something with result
}
}
for Updated question
var count = from a in _context.vInvoiceSwivelInfoWeb
where a.Email == "someemail#gmail.com" && a.Language == "FR"
group new { a.DocumentNumber , a.DocumentReference , a.DocumentDate } by a into g
select g.Count()
also, it's important to know which version of EF-Core are you using:
currently, if you are using EF-Core 3 group-by doesn't translate to SQL command so you have to do it on client-side:
check this link :
https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-3.0/breaking-changes#linq-queries-are-no-longer-evaluated-on-the-client
for EF-Core 3.0 - 3.1.1
var count = _context.vInvoiceSwivelInfoWeb
.Where(a => a.Email == "someemail#gmail.com" && a.Language == "FR" ).ToList()
.GroupBy(a => new { a.DocumentNumber ,a.DocumentDate, a.DocumentReference }).Count();

Conversion between IEnumerable EnumerableRowCollection

I have the following code:
var aaData = myapi.GetData().AsEnumerable().Select(x => new {
Id = x["myID"],
Desc = x["myDesc"]
});
Trying to do the following
aaData = aaData.OrderBy((string.Join(",", request.Order
.Select(x => request.Columns[x.Column].Data + " " + x.Dir))));
Getting error:
CS0266 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<>' to 'System.Data.EnumerableRowCollection<>'. An explicit conversion exists (are you missing a cast?)
How to fix this?
GetData returns a DataTable
Request is an object having a property:
public OrderCol[] Order { get; set; }
OrderCol is
public class OrderCol {
public int Column { get; set; }
public string Dir { get; set; }
}
Thanks for your assistance.
The above code works for the case when I get a List<> back instead of DataTable. The error states that a Cast is needed and it seems to be how DataTable.AsEnumerable is set up as a EnumerableRowCollection
Can use a mock datatable to mimic the above
DataTable dt = new DataTable();
dt.clear();
dt.Columns.Add("myID");
dt.Columns.Add("myDesc");
all i needed was to convert to a list and things worked fine

Parse.com > Query Constraints > based on user Pointer

I have a class called AccountData and I would like to return all rows that relate to a particular user. In the class I have a Pointer to the User table which contains their "ObjectId"
I have tried with the following call to the API:
string url = "https://api.parse.com/1/classes/AccountData?" + WebUtility.UrlEncode("where={\"user\":\"fvJ8jPjyjx\"}");
where the fvJ8jPjyjx is the ObjectId of the user I want rows relating to...
The api doesn't throw any errors just returns:
{"results":[]}
I have also tried it using a "User Object" as follows:
public class AccountDataUser
{
public string __type { get; set; }
public string className { get; set; }
public string objectId { get; set; }
}
building the object as follows:
AccountDataUser user = new AccountDataUser();
user.__type = "Pointer";
user.className = "_User";
user.objectId = objectId;
string jsonUser = JsonConvert.SerializeObject(user);
but this throws an api error.
Can anyone help me return the rows relating to a "user" please?
Thanks
UPDATE
Based on Ryans feedback I have reverted to trying to send an object...
This is what is being sent:
GET https://api.parse.com/1/classes/AccountData?where%3D%7B%22user%22%3A%22%7B%22__type%22%3A%22Pointer%22%2C%22className%22%3A%22_User%22%2C%22objectId%22%3A%22fvJ8jPjyjx%22%7D%22%7D HTTP/1.1
Content-Type: application/json
X-Parse-Application-Id: xxxxx
X-Parse-REST-API-Key: xxxxxx
Host: api.parse.com
Connection: Keep-Alive
The url is built with this line of code:
ParseModel.AccountDataUser user = new ParseModel.AccountDataUser();
user.__type = "Pointer";
user.className = "_User";
user.objectId = objectId;
string jsonUser = JsonConvert.SerializeObject(user);
string url = "https://api.parse.com/1/classes/AccountData?" + WebUtility.UrlEncode("where={\"user\":\"" + jsonUser + "\"}"); // this doesn't work
And the error I receive from the API is:
{"code":107,"error":"invalid json: {\"user\":\"{\"__type\":\"Pointer\",\"className\":\"_User\",\"objectId\":\"fvJ8jPjyjx\"}\"}"}
I believe the issue is in building the URL. You're wrapping the JSON in a string and Parse is expecting an object. If you strip the double quote around jsonUser, I bet that'll work.
string url = "https://api.parse.com/1/classes/AccountData?" + WebUtility.UrlEncode("where={\"user\":" + jsonUser + "}");

Linq to NHibernate projection to anon. type results in mystifying cast error

I have an TaxWork entity which is persisted using NHibernate. This entity has the following properties (among others):
public virtual TaxWorkType Type { get; set; } //Kctc.TaxWorkType is an enumeration
public virtual TaxWorkStatus Status { get; set; } //Kctc.TaxWorkStatus is an enumeration
public virtual LegalWorkPriority Priority { get; set; } //Kctc.LegalWorkType is an enumeration
public virtual User Handler { get; set; } //Kctc.BusinessLayer.Entities.User is another entity
public virtual int? CaseNumber { get; set; }
I am using Linq to NHibernate to pull of a subset of the tax work objects as follows (taxWorkRepository.All obviously returns an IQueryable):
foreach (TaxWork taxWork in taxWorkRepository.All.Where(x => x.CaseNumber == _caseNumber).OrderBy(x => x.DateCreated))
{
...
}
This works fine. I want to use projection in order to query only the columns that are required in this case. I am usnig the following code:
foreach (var taxWorkFragment in taxWorkRepository.All.Where(x => x.CaseNumber == _caseNumber).OrderBy(x => x.DateCreated).Select(x => new { Type = x.Type, DateCreated = x.DateCreated, Handler = x.Handler, Status = x.Status, Priority = x.Priority }))
{
...
}
However, I'm getting the following error when trying to create the anonymous type:
Invalid cast from 'Kctc.TaxWorkStatus' to 'Kctc.BusinessLayer.Entities.User'.
Where on earth is it getting the idea that it should be casting a TaxWorkStatus to a User?
Any suggestions whatsoever what might be going wrong?
Try to make like this:
foreach (var taxWorkFragment in taxWorkRepository.All.Where(x => x.CaseNumber == _caseNumber).OrderBy(x => x.DateCreated)
.Select(x => new TaxWork { Type = x.Type, DateCreated = x.DateCreated, Handler = x.Handler, Status = x.Status, Priority = x.Priority }))
{
...
}
It should help

Resources