NEST mapping group - nest

I'm beginning with NEST and I want to group my properties.
namespace Prototype.Logs
{
[ElasticType(Name = "msglogs")]
internal class Msg : BaseLog
{
[ElasticProperty(Name = "exception")]
public string BaseException { get; set; }
public string InnerException { get; set; }
I want to map groups like for instance
"exception" : {
"baseexception" : "blablabla() : blabla",
"innerexception" : "blablabla() : blabla",
},
Instead I get a flat document :
"baseexception" : "blablabla() : blabla",
"innerexception" : "blablabla() : blabla",
I tried to search on the NEST doc but I did not find anything.
Thank you very much

Your exception object should be broken out into it's own class and mapped as an inner or nested object of Msg.
Something like this:
class MyExceptionClass
{
[ElasticProperty(Name = "baseexception")]
public string BaseException { get; set; }
[ElasticProperty(Name = "innerexception")]
public string InnerException { get; set; }
}
...and then in your Msg class:
[ElasticType(Name = "msglogs")]
internal class Msg : BaseLog
{
[ElasticProperty(Name = "exception")]
public MyExceptionClass Exception { get; set; }
}

Related

How to use Patch method in minimal api application?

I am trying to use patch method in my minimal api application this is my code :
Car class
public class Car
{
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "producent")]
public Producent Producent { get; set; }
[JsonProperty(PropertyName = "age")]
public int Age { get; set; }
[JsonProperty(PropertyName = "yearCreated")]
public int YearCreated { get; set; }
[JsonProperty(PropertyName = "engine")]
public Engine Engine { get; set; }
public Car()
{
Id= Guid.NewGuid().ToString();
YearCreated = DateTime.Now.Year - Age;
}
}
ICarService:
public interface ICarService
{
Task<IEnumerable<Car>> GetAll();
Task<Car> GetById(string id,string partitionKey);
Task Create(Car car);
Task<bool> Update(Car car);
Task<Car> UpdatePatchAsync(string id, string partitionKey,List<PatchOperation> patchOperations);
Task<bool> Delete(string id,string partitionKey);
}
patch method in service
public async Task<Car> UpdatePatchAsync(string id, string partitionKey, List<PatchOperation> patchOperations)
{
var result = await _container.PatchItemAsync<Car>(id, new PartitionKey(partitionKey),
patchOperations:patchOperations );
return result;
}
my requests:
[HttpPatch]
public static async Task<IResult> Patch(ICarService service,string id,string partitionKey,
[FromBody]List<PatchOperation> operations)
{
var updatedCar = await service.UpdatePatchAsync(id,partitionKey,operations);
if (updatedCar == null)
{
return Results.NotFound();
}
return Results.Ok(updatedCar);
}
app.MapMethods("/cars/patch/{id}/{partitionKey}", new string[] { "PATCH" }, CarRequests.Patch);
I use cosmosDb database and when i code like this:
{
"op": "replace",
"path": "age",
"value": 22
}
i get the error
System.NotSupportedException: Deserialization of types without a parameterless constructor, a singular parameterized constructor, or a parameterized constructor annotated with 'JsonConstructorAttribute' is not supported. Type 'Microsoft.Azure.Cosmos.PatchOperation'. Path: $[0] | LineNumber: 3 | BytePositionInLine: 3.
---> System.NotSupportedException: Deserialization of types without a parameterless constructor, a singular parameterized constructor, or a parameterized constructor annotated with 'JsonConstructorAttribute' is not supported. Type 'Microsoft.Azure.Cosmos.PatchOperation'.
The problem is you are using [FromBody]List<PatchOperation> operations.
This is making ASP.NET attempt to deserialize a JSON raw string into PatchOperation, which when we look at our source code, has no parameterless constructor: https://github.com/Azure/azure-cosmos-dotnet-v3/blob/master/Microsoft.Azure.Cosmos/src/Patch/PatchOperation.cs, it is an abstract class.
The way it is meant to be used is through PatchOperation.XXXX, like PatchOperation.Add, you cannot use it to deserialize into it. You could have your own MyPatchOperation<Car> that has the exposed properties for deserialization, and then simply have a method in that class that based on which properties are populated, calls PatchOperation<Car>.Add (or whatever operation).
Not the full code but:
public class MyPatchOperation
{
[JsonProperty(PropertyName = "op")]
public string Operation { get; set; }
[JsonProperty(PropertyName = "path")]
public string Path { get; set; }
[JsonProperty(PropertyName = "value")]
public string Value { get; set; }
public PatchOperation<Car> ToPatchOperation()
{
switch (this.Operation)
{
case "replace":
return PatchOperation<Car>.Replace(this.Path, this.Value);
/* other operations */
}
}
}

How to deserialize Graphql Response

Hi I have a graphql Response after Mutating
{{
"carCreate": {
"car": {
"id": "TestId"
}
}
}}
I want to Desealize it I am using The following Code
var graphQlClient = new GraphQLHttpClient(AppConfig.GraphQlUrl, new NewtonsoftJsonSerializer());
I have tried to resolve with the following code
var response = await graphQlClient.SendMutationAsync<CarCreate>(request);
My Created Model is :
public class Car
{
public string Id { get; set; }
}
public class CarCreate
{
public Car Car { get; set; }
}
Your class should be something like this,
// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class Car
{
public string id { get; set; }
}
public class CarCreate
{
public Car car { get; set; }
}
public class Root
{
public CarCreate carCreate { get; set; }
}

Can not implement discriminated union and serialize it

Hello i am trying to create a hierarchy of classes using a discriminated unionand it seems i can't serialize them.I keep getting this error :
Newtonsoft.Json.JsonSerializationException: 'Self referencing loop detected for property 'AsRun' with type 'MsgPattern.Message+Run'. Path ''.'
Base class
[Serializable]
public abstract partial class Message {
public enum Type {
WALK = 0,
RUN = 1
}
protected abstract Type Discriminator { get; }
public Type Kind => this.Discriminator;
internal static Message Create(string data) {
var message = JsonConvert.DeserializeObject<Message>(data);
switch (message.Kind) {
case Type.RUN:message= message.AsRun;break;
case Type.WALK:message= message.AsWalk;break;
}
return message;
}
[JsonIgnore]
public bool IsWalk => this.Kind==Type.Walk;
[JsonIgnore]
public bool IsRun => this.Kind==Type.Run;
[JsonIgnore]
public Message.Walk AsWalk => this as Message.Walk;
[JsonIgnore]
public Message.Run AsRun => this as Message.Run;
}
Dervived
partial class Message {
public class Run : Message {
protected override Type Discriminator => Type.RUN;
public string Location { get; set; }
public int Speed { get; set; }
}
}
partial class Message {
public class Walk : Message {
protected override Type Discriminator => Type.WALK;
public int Gait { get; set; }
public bool IsJogging { get; set; }
}
}
Usage
class Program {
static void Main(string[] args) {
Message.Run run = new Message.Run { Location = "asa", Speed = 33 };
string data = JsonConvert.SerializeObject(run);
Message msg=Message.Create(data);
}
}
I will get these type of messages via json and i want to be able to do actions based on their type. I do not understand why i can't serialize them .
P.S I know it's a self-referencing loop but I need those As[something] and Is[Something] fields.

How to resolve an error with WCF data contract -Message = "There was an error while trying to serialize parameter

I have two data contracts of same contents in two different namespaces. i have copied one datacontract to another and
passed to a particular method. but it is giving the below error and throwing exception. it is not going into that method.
Please let me know any ideas /suggestions on how to resolve this.Appreciate your help:
Exception errror:
{"Type 'System.Collections.Generic.List`1[[GlobalWcfServiceLib.TopicDetailsInfo, GlobalWcfContracts, Version=1.2.2.0, Culture=neutral,
PublicKeyToken=17c64733a9775004]]' with data contract name 'ArrayOfTopicDetailsInfo:http://CName.GlobalService/11.1/2010/11'
is not expected. Consider using a DataContractResolver or add any types not known statically to the list of
known types - for example, by using the KnownTypeAttribute attribute or by
adding them to the list of known types passed to DataContractSerializer."}
Message = "There was an error while trying to serialize parameter
http://CName.SharedServices.DBServiceLib:subscriptionDataContract.
The InnerException message was 'Type 'System.Collections.Generic.List`1
[[GlobalWcfServiceLib.TopicDetailsInfo,
GlobalWcfContra...
//////
Here is my scenario : i am copying the data from dc to new data contract as below. after copying , when i am executing the createsubscriptions method i am getting the above mentioned error. i have given the details of data contract and error attached to this question. please refer to that as well.
Method1(SubscriptionDataContracts dc)
{
SubscriptionDataContract subscriptionDataContract = new SubscriptionDataContract();
List<SubscriptionTopicInfo> topicsInfo = dc.TopicList;
List<SubscriptionTopic> newTopicsList = new List<SubscriptionTopic>();
subscriptionDataContract.ExtensionData = dc.ExtensionData;
subscriptionDataContract.UserID = dc.UserID;
for (int i = 0; i < topicsInfo.Count; i++)
{
SubscriptionTopic topic = new SubscriptionTopic();
topic.DBHandle = topicsInfo[i].DBHandle;
topic.Topic = topicsInfo[i].Topic;
topic.Target = topicsInfo[i].Target;
newTopicsList.Add(topic);
}
subscriptionDataContract.TopicList = newTopicsList;
CreateSubscriptions(subscriptionDataContract); //getting the above mentioned error in another dll after going into this method
}
////////////////////////////////
//My data contract
[DataContract(Name = "TopicDetailsInfo", Namespace = "http://CName.GlobalService")]
[Serializable]
public class TopicDetailsInfo
{
protected object topic;
protected object baseObjectType;
[DataMember]
public object BaseObjectType
{
get
{
return baseObjectType;
}
set
{
baseObjectType = value;
}
}
[DataMember]
public object TopicID
{
get
{
return topic;
}
set
{
topic = value;
}
}
static public TopicDetailsInfo CreateTopic<T, mT>(IComparable<T> objectType, IComparable<mT> objectID)
{
var topicDetails = new TopicDetailsInfo();
topicDetails.BaseObjectType = objectType;
topicDetails.TopicID = objectID;
return topicDetails;
}
}
[DataContract(Name = "SubscriptionTopicInfo", Namespace = "http://CName.GlobalService")]
[KnownType(typeof(List<TopicDetailsInfo>))]
[Serializable]
public class SubscriptionTopicInfo
{
private object topic;
private object target;
private object creator;
[DataMember]
public object Topic
{
get
{
return topic;
}
set
{
topic = value;
}
}
[DataMember]
public object Target
{
get
{
return target;
}
set
{
target = value;
}
}
[DataMember]
public object DBHandle
{
get
{
return creator;
}
set
{
creator = value;
}
}
static public SubscriptionTopicInfo CreateSubscriptions<T, mT, nT>(IList<TopicDetailsInfo> topic, IComparable<mT> target, IComparable<nT> handle)
{
var subscriptionTopic = new SubscriptionTopicInfo();
subscriptionTopic.Target = target;
subscriptionTopic.Topic = topic;
subscriptionTopic.DBHandle = handle;
return subscriptionTopic;
}
}
[DataContract(Name = "SubscriptionData", Namespace = "http://CName.GlobalService")]
[KnownType(typeof(List<SubscriptionTopicInfo>))]
[Serializable]
public class SubscriptionDataContracts : IExtensibleDataObject
{
private ExtensionDataObject extensionDataObjectValue;
[DataMember]
public string UserID
{
get;
set;
}
[DataMember]
public string ProjectID
{
get;
set;
}
[DataMember]
public string FromDiscipline
{
get;
set;
}
[DataMember]
public string ModuleID
{
get;
set;
}
[DataMember]
public string SessionID
{
get;
set;
}
[DataMember]
public List<SubscriptionTopicInfo> TopicList
{
get;
set;
}
public ExtensionDataObject ExtensionData
{
get
{
return extensionDataObjectValue;
}
set
{
extensionDataObjectValue = value;
}
}
}

How to convert XAML File to objects

I have a xaml file that needs to convert into objects, Is there anyone done this before?
using (var stream = File.OpenRead(filename)) {
var yourObj = XamlReader.Load(stream);
}
//Configuration Class
namespace SKAT.Postfordeler.Shared.DataTypes
{
[Serializable]
public class PostFordelerConfiguration
{
private readonly ReceiverAddressList _receiverAddresses;
private readonly DocumentTypeList _documentTypes;
public PostFordelerConfiguration()
{
_receiverAddresses = new ReceiverAddressList();// I don't want to implement like this.
_documentTypes = new DocumentTypeList(); //// I don't want to implement like this.
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public ReceiverAddressList ReceiverAddresses
{
get { return _receiverAddresses; }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public DocumentTypeList DocumentTypes { get {return _documentTypes;} }
public static PostFordelerConfiguration Load(string location)
{
return (PostFordelerConfiguration)XamlReader.Load(new XmlTextReader(location));
}
}
}
//Document Entity
namespace SKAT.Postfordeler.Shared.DataTypes
{
[Serializable]
public class DocumentType
{
public String Id { get; set; }
}
}
//Document List
namespace SKAT.Postfordeler.Shared.DataTypes
{
[Serializable]
public class DocumentTypeList : List<DocumentType>{ }
}
//ReceiverAddress Entities
namespace SKAT.Postfordeler.Shared.DataTypes
{
[Serializable]
public class ReceiverAddress
{
public String Id { get; set; }
public String Routable { get; set; }
public String Description { get; set; }
}
}
//ReceiverAddress List
namespace SKAT.Postfordeler.Shared.DataTypes
{
[Serializable]
public class ReceiverAddressList : List<ReceiverAddress>{ }
}
// Load XAML file and Convert into objects
SKAT.Postfordeler.Shared.DataTypes.PostFordelerConfiguration loader =
Postfordeler.Shared.DataTypes.PostFordelerConfiguration.Load(
#"D:\projects\skatpostfordeler\SKAT.Postfordeler.Client.UI\PostfordelerConfiguration.xaml");