Why can I only destructure anonymous types? - elastic-stack

I am trying to set up an ASP.NET Core 3.1 Web API to test the elk stack using Serilog v2.9 and Serilog.Sinks.Elasticsearch v8.0.1. This is all new to me and I'm just trying to figure things out. I seem to have everything working and can log simple things all day long and see them in both ES and Kibana. Trouble is I can't seem to destructure anything except anonymous types. To illustrate:
var data = new
{
SampleData = "Hello World!"
};
_logger.LogInformation("Destructured anonymous object: {#data}", data);
Produces the expected result. A nice shiny log entry with the object "data" serialized perfectly. Whereas:
var test = new TestClass
{
Guid = Guid.NewGuid(),
Timestamp = DateTime.UtcNow,
Title = "Testing this serialization!"
};
_logger.LogInformation("Destructred discrete type. {#test}", test);
Produces nothing at all. No exception, no entry in ElasticSearch. Nothing. TestClass is a simple class with only those 3 properties, all of which should serialize just fine. I can't figure this out. Here is my LoggerConfiguration:
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.Enrich.WithExceptionDetails()
.WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri(elasticUri))
{
AutoRegisterTemplate = true,
AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv6,
CustomFormatter = new ExceptionAsObjectJsonFormatter(renderMessage: true)
})
.CreateLogger();
What am I missing? Do I have to like, produce a property map or something to destructre non-anonymous objects? Is .Net Core 3.1 too new? I'm at a loss. Every example I've seen online says this should be working.

I finally figured this out after banging my head against the problem for a few more hours. My problem is that I was using the plain old Serilog NuGet Package instead of Serilog.AspNetCore. Once I installed the latter it began working as expected.
Welp. I hope this might help anyone else in my position who is following along with the otherwise excellent guide here: https://www.humankode.com/asp-net-core/logging-with-elasticsearch-kibana-asp-net-core-and-docker

Related

Why does calling AutoFake.Provide() wipe out fakes already configured with A.CallTo()?

Why does calling fake.Provide<T>() wipe out fakes already configured with A.CallTo()? Is this a bug?
I'm trying to understand a problem I've run into with Autofac.Extras.FakeItEasy (aka AutoFake). I have a partial solution, but I don't understand why my original code doesn't work. The original code is complicated, so I've spent some time simplifying it for the purposes of this question.
Why does this test fail? (working DotNetFiddle)
public interface IStringService { string GetString(); }
public static void ACallTo_before_Provide()
{
using (var fake = new AutoFake())
{
A.CallTo(() => fake.Resolve<IStringService>().GetString())
.Returns("Test string");
fake.Provide(new StringBuilder());
var stringService = fake.Resolve<IStringService>();
string result = stringService.GetString();
// FAILS. The result should be "Test string",
// but instead it's an empty string.
Console.WriteLine($"ACallTo_before_Provide(): result = \"{result}\"");
}
}
If I swap the order of the calls to fake.Provide<T>() and A.CallTo(), it works:
public static void Provide_before_ACallTo()
{
// Same code as above, but with the calls to
// fake.Provide<T>() and A.CallTo() swapped
using (var fake = new AutoFake())
{
fake.Provide(new StringBuilder());
A.CallTo(() => fake.Resolve<IStringService>().GetString())
.Returns("Test string");
var stringService = fake.Resolve<IStringService>();
string result = stringService.GetString();
// SUCCESS. The result is "Test string" as expected
Console.WriteLine($"Provide_before_ACallTo(): result = \"{result}\"");
}
}
I know what is happening, sort of, but I'm not sure if it's intentional behavior or if it's a bug.
What is happening is, the call to fake.Provide<T>() is causing anything configured with A.CallTo() to be lost. As long as I always call A.CallTo() after fake.Provide<T>(), everything works fine.
But I don't understand why this should be.
I can't find anything in the documentation stating that A.CallTo() cannot be called before Provide<T>().
Likewise, I can't find anything suggesting Provide<T>() cannot be used with A.CallTo().
It seems the order in which you configure unrelated dependencies shouldn't matter.
Is this a bug? Or is this the expected behavior? If this is the expected behavior, can someone explain why it works like this?
It isn't that the Fake's configuration is being changed. In the first test, Resolve is returning different Fakes each time it's called. (Check them for reference equality; I did.)
Provide creates a new scope and pushes it on a stack. The topmost scope is used by Resolve when it finds an object to return. I think this is why you're getting different Fakes in ACallTo_before_Provide.
Is this a bug? Or is this the expected behavior? If this is the expected behavior, can someone explain why it works like this?
It's not clear to me. I'm not an Autofac user, and don't understand why an additional scope is introduced by Provide. The stacked scope behaviour was introduced in PR 18. Perhaps the author can explain why.
In the meantime, if possible, I'd Provide all you need to before Resolveing, if you can manage it.

Breeze: cannot execute _executeQueryCore until metadataStore is populated

I was using Breeze v1.1.2 that came with the Hot Towel template which has now been extended to form my project. I made the mistake of updating the NuGet package to the current 1.3.3 (I never learn). Anyway, all was well, and now not so much!
I followed the instructions in the release notes and other docs to change my BreezeWebApiConfig file to:
[assembly: WebActivator.PreApplicationStartMethod(
typeof(BreezeWebApiConfig), "RegisterBreezePreStart")]
namespace MyApp.App_Start {
public static class BreezeWebApiConfig {
public static void RegisterBreezePreStart() {
GlobalConfiguration.Configuration.Routes.MapHttpRoute(
name: "BreezeApi",
routeTemplate: "breeze/{controller}/{action}"
);}}}
And the config.js file (which provides the serviceName to the EntityManager constructor) to:
var remoteServiceName = 'breeze/breeze'; // NEW version
//var remoteServiceName = 'api/breeze'; // OLD version
And my BreezeController if you're interested:
[BreezeController]
public class BreezeController : ApiController
{
readonly EFContextProvider<MyDbContext> _contextProvider =
new EFContextProvider<MyDbContext>();
[HttpGet]
public string Metadata()
{
return _contextProvider.Metadata();
}
[HttpGet]
public IQueryable<SomeItem> SomeItems()
{
// Do stuff here...
}
}
Now I get the "cannot execute _executeQueryCore until metadataStore is populated" error.
What am I missing here?
EDIT:
I perhaps left out the part you needed... Above in the SomeItems() method, the stuff that actually gets done is a call to the GetMeSomeData() method in the MyDBContext class. This method makes the following call to a stored procedure to get the data.
public virtual ObjectResult<SomeItem> GetMeSomeData(string inParam)
{
var p = new object[] { new SqlParameter("#inParam", inParam) };
var retVal = ((IObjectContextAdapter)this).ObjectContext.ExecuteStoreQuery<SomeItem>("exec GetData #SN", p);
return retVal;
}
Now given my limited understanding, the call to Metadata() is not failing, but I don't think it has any idea what the entity model is when coming back, even though somewhere along the line, it should figure that out from the entity model I do have (i.e. SomeItem)? The return string from Metadata() doesn't have any information about the entity. Is there a way to make it aware? Or am I just completely off in left field playing with the daisies?
Hard to say based on this report. Let's see if Breeze is right.
Open the browser debugging tools and look at the network traffic. Do you see an attempt to get metadata from the server before you get that error? If so, did it succeed? Or 404? Or 500? What was the error?
I'm betting it didn't even try. If it didn't, the usual reason is that you tried some Breeze operation before your first query ... and you didn't ask for metadata explicitly either. Did you try to create an entity? That requires metadata.
The point is, you've got to track down the Breeze operation that precipitates the error. Sure everything should just work. The world should be rainbows and unicorns. When it isn't, we heave a sigh, break out the debugger, and start with the information that the error gave us.
And for the rest of you out there ... upgrading to a new Breeze version is a good thing.
Happy coding everyone.
Follow-up to your update
Breeze doesn't know how you get your data on the back-end. If the query result has a recognizable entity in it, Breeze will cache that. It's still up to you in the query callback to ensure that what you deliver to the caller is something meaningful.
You say that you're server-side metadata method doesn't have any idea what SomeItem is? Then it's not much use to the client. If it returns a null string, Breeze may treat that as "no metadata at all" in which case you should be getting the "cannot execute _executeQueryCore until metadataStore is populated" error message. Btw, did you check the network traffic to determine what your server actually returned in response to the metadata request (or if there was such a request)?
There are many ways to create Metadata on the server. The easiest is to use EF ... at least as a modeling tool at design time. What's in that MyDbContext of yours? Why isn't SomeItem in there?
You also can create metadata on the client if you don't want to generate it from the server. You do have to tell the Breeze client that you've made that choice. Much of this is explained in the documentation "Metadata Format".
I get the feeling that you're kind of winging it. You want to stray from the happy path ... and that's cool. But most of us need to learn to walk before we run.

Phonegap and Nova Data Framework -

I am learning PhoneGap for an app project and need to use the database for certain aspects, I am trying out the Nova Data framework,
https://cordova.codeplex.com/wikipage?title=How%20to%20use%20nova.data
I am trying to use my code to put together a test entity, but I am getting a db error telling me there is a missing table. The documentation does not specify that the database should be created beforehand, but I am starting to think that may be the case. Has anyone out there used the Nova framework in a project? I just need a little guidance.
Here is my code I am using to kick off the DB Context:
var DataContext = function () {
nova.data.DbContext.call(this, "HealthDb", "1.0", "Health DB", 1000000);
this.Temperatures = new nova.data.Repository(this, Temperature, "Temperatures");
};
DataContext.prototype = new nova.data.DbContext();
DataContext.constructor = DataContext;
And my entity (Temperature) :
var Temperature = function () {
nova.data.Entity.call(this);
this.Value = 101;
};
Temperature.prototype = new nova.data.Entity();
Temperature.constructor = Temperature;
It is creating an empty database with the proper name, just no tables! I am grateful for any assistance!
Thanks for using our library. I have made the html5 sqlite as a standalone library. Please get it from github.
A live demo link is also available there. And the documentation is more complete. The lib itself has also been updated and a few bugs fixed.
Thanks,
Leo
Turns out I was trying to start up the dbcontext before I defined my entity classes....
Changed the order of my js files and it works.

QBO Queries and SpecifyOperatorOption

I'm trying to query QBO for, among other entities, Accounts, and am running into a couple of issues. I'm using the .Net Dev Kit v 2.1.10.0 (I used NuGet to update to the latest version) and when I use the following technique:
Intuit.Ipp.Data.Qbo.AccountQuery cquery = new Intuit.Ipp.Data.Qbo.AccountQuery();
IEnumerable<Intuit.Ipp.Data.Qbo.Account> qboAccounts = cquery.ExecuteQuery<Intuit.Ipp.Data.Qbo.Account>(context);
(i.e. just create a new AccountQuery of the appropriate type and call ExecuteQuery) I get an error. It seems that the request XML is not created properly, I just see one line in the XML file. I then looked at the online docs and tried to emulate the code there:
Intuit.Ipp.Data.Qbo.AccountQuery cquery = new Intuit.Ipp.Data.Qbo.AccountQuery();
cquery.CreateTime = DateTime.Now.Date.AddDays(-20);
cquery.SpecifyOperatorOption(Intuit.Ipp.Data.Qbo.FilterProperty.CreateTime,
Intuit.Ipp.Data.Qbo.FilterOperatorType.AFTER);
cquery.CreateTime = DateTime.Now.Date;
cquery.SpecifyOperatorOption(Intuit.Ipp.Data.Qbo.FilterProperty.CreateTime,
Intuit.Ipp.Data.Qbo.FilterOperatorType.BEFORE);
// Specify a Request validator
Intuit.Ipp.Data.Qbo.AccountQuery cquery = new Intuit.Ipp.Data.Qbo.AccountQuery();
IEnumerable<Intuit.Ipp.Data.Qbo.Account> qboAccounts = cquery.ExecuteQuery<Intuit.Ipp.Data.Qbo.Account>(context);
unfortunately, VS 2010 insists that AccountQuery doesn't contain a definition for SpecifyOperatorOption and there is no extension method by that name. So I'm stuck.
Any ideas how to resolve this would be appreciated.

XML serialization errors when trying to serialize Entity Framework objects

I have entities that I am getting via Entity Framework. I'm using Code-First so they're POCOs. When I try to XML Serialize them using XmlSerializer, I get the following error:
The type
System.Data.Entity.DynamicProxies.Song_C59F4614EED1B7373D79AAB4E7263036C9CF6543274A9D62A9D8494FB01F2127
was not expected. Use the XmlInclude
or SoapInclude attribute to specify
types that are not known statically.
Anybody got any ideas on how to get around this (short of creating a whole new object)?
Just saying POCO doesn't really help (especially in this case since it looks like you're using proxies). Proxies come in handy in a lot of cases but make things like serialization more difficult since the actual object being serialized is not really your object but an instance of a proxy.
This blog post should give you your answer.
http://blogs.msdn.com/b/adonet/archive/2010/01/05/poco-proxies-part-2-serializing-poco-proxies.aspx
Sorry, I know I'm coming at this a bit late (a couple YEARS late), but if you don't need the proxy objects for lazy loading, you can do this:
Configuration.ProxyCreationEnabled = false;
in your Context. Worked like a charm for me. Shiv Kumar actually gives better insight into why, but this at least will get you back to work (again, assuming you don't need the proxies).
Another way that works independent of the database configuration is by doing a deep clone of your object(s).
I use Automapper (https://www.nuget.org/packages/AutoMapper/) for this in my code-first EF project. Here is some sample code that exports a list of an EF objects called 'IonPair':
public bool ExportIonPairs(List<IonPair> ionPairList, string filePath)
{
Mapper.CreateMap<IonPair, IonPair>(); //creates the mapping
var clonedList = Mapper.Map<List<IonPair>>(ionPairList); // deep-clones the list. EF's 'DynamicProxies' are automatically ignored.
var ionPairCollection = new IonPairCollection { IonPairs = clonedList };
var serializer = new XmlSerializer(typeof(IonPairCollection));
try
{
using (var writer = new StreamWriter(filePath))
{
serializer.Serialize(writer, ionPairCollection);
}
}
catch (Exception exception)
{
string message = string.Format(
"Trying to export to the file '{0}' but there was an error. Details: {1}",
filePath, exception.Message);
throw new IOException(message, exception);
}
return true;
}