Value cannot be null. Parameter name: key - linq

I am using NEST to get some aggregations to work, but what I always get is "Value cannot be null.Parameter name: key"
I updated the query
Could you please help me.
Code:
var agg = esclient.Search<Artifact>(s => s.Aggregations(ag => ag
.Filter("refineSearch", fi => fi.Filter(fl => fl.Bool(b => b
.Should(sh => sh.Terms("multimediaReferenceList.mimeType", input.Filters.Media)
&& sh.Terms("physicalLocations.level1", input.Filters.Location)
&& sh.Terms("objectCategory", input.Filters.Type)
&& sh.Range(r => r.GreaterOrEquals(input.Years[0]).OnField(of => of.MinYear))
&& sh.Range(ra => ra.LowerOrEquals(input.Years[1]).OnField(od => od.MaxYear)))))
.Aggregations(aa => aa
.Terms("type", att => att.Field("objectCategory"))
.Terms("media", att => att.Field("multimediaReferenceList.mimeType"))
.Terms("location", att => att.Field("physicalLocations.level1"))))));
Stack Trace:
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add) at Nest.Resolvers.Converters.Aggregations.AggregationConverter.GetNestedAggregations(JsonReader reader, JsonSerializer serializer)
at Nest.Resolvers.Converters.Aggregations.AggregationConverter.GetSingleBucketAggregation(JsonReader reader, JsonSerializer serializer)
at Nest.Resolvers.Converters.Aggregations.AggregationConverter.ReadAggregation(JsonReader reader, JsonSerializer serializer)
at Nest.Resolvers.Converters.Aggregations.AggregationConverter.ReadJson(JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.DeserializeConvertable(JsonConverter converter, JsonReader reader, Type objectType, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateDictionary(IDictionary dictionary, JsonReader reader, JsonDictionaryContract contract, JsonProperty containerProperty, String id)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.SetPropertyValue(JsonProperty property, JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, Object target)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
at Nest.NestSerializer.DeserializeUsingSettings[T](Stream stream, JsonSerializerSettings settings)
at Nest.NestSerializer.Deserialize[T](Stream stream)
at Nest.NestSerializer.DeserializeInternal[T](Stream stream, JsonConverter converter)
at Nest.ElasticClient.FieldsSearchDeserializer[T,TResult](IElasticsearchResponse response, Stream stream, ISearchRequest d)
at Nest.ElasticClient.<>c__DisplayClass1f9`2.<CreateSearchDeserializer>b__1f8(IElasticsearchResponse r, Stream s)
at Elasticsearch.Net.Connection.RequestHandlers.RequestHandler.StreamToTypedResponse[T](ElasticsearchResponse`1 streamResponse, ITransportRequestState requestState, Byte[] readBytes)
at Elasticsearch.Net.Connection.RequestHandlers.RequestHandler.ReturnTypedResponse[T](TransportRequestState`1 requestState, ElasticsearchResponse`1 streamResponse, ElasticsearchServerError& error)
at Elasticsearch.Net.Connection.RequestHandlers.RequestHandler.CoordinateRequest[T](TransportRequestState`1 requestState, Int32 maxRetries, Int32 retried, Boolean& aliveResponse)
at Elasticsearch.Net.Connection.RequestHandlers.RequestHandler.DoRequest[T](TransportRequestState`1 requestState)
at Elasticsearch.Net.Connection.RequestHandlers.RequestHandler.Request[T](TransportRequestState`1 requestState, Object data)
at Elasticsearch.Net.Connection.Transport.DoRequest[T](String method, String path, Object data, IRequestParameters requestParameters)
at Elasticsearch.Net.ElasticsearchClient.Search[T](Object body, Func`2 requestParameters)
at Nest.ElasticClient.Search[T,TResult](Func`2 searchSelector)
at THF.CMS.Api.SearchManager.GetSearchResults(SearchRequest input) in c:\inetpub\wwwroot\SearchManager.cs:line 71

You tried searching something in a Dictionary using null for the key, i.e.:
Dictionary<DataType, AlsoDataType> dict = new Dictionary<DataType, AlsoDataType>();
DataType key = null;
Console.WriteLine(dict[key].ToString()); // <-------- key is null

Related

Masstransit Deserialization Issue With Encryption enabled in Amazon SQS

Object deserialization is working without encryption in both RabbitMQ and Amazon SQS in Masstransit and also Object deserialization working fine in case of encryption enabled with RabbitMQ, But getting deserialization error in case of encryption enabled with Amazon SQS.
Getting below error while deserialization :
System.Runtime.Serialization.SerializationException: An exception occurred while deserializing the message envelope
---> System.ArgumentOutOfRangeException: Unexpected BsonType value: 38 (Parameter 'type')
at Newtonsoft.Json.Bson.BsonDataReader.ReadType(BsonType type)
at Newtonsoft.Json.Bson.BsonDataReader.ReadNormal()
at Newtonsoft.Json.Bson.BsonDataReader.Read()
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.DeserializeConvertable(JsonConverter converter, JsonReader reader, Type objectType, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
at MassTransit.Serialization.EncryptedMessageDeserializerV2.Deserialize(MessageBody body, Headers headers, Uri destinationAddress) in /_/src/MassTransit.Newtonsoft/Serialization/EncryptedMessageDeserializerV2.cs:line 47
--- End of inner exception stack trace ---
at MassTransit.Serialization.EncryptedMessageDeserializerV2.Deserialize(MessageBody body, Headers headers, Uri destinationAddress) in /_/src/MassTransit.Newtonsoft/Serialization/EncryptedMessageDeserializerV2.cs:line 62
at MassTransit.Serialization.EncryptedMessageDeserializerV2.Deserialize(ReceiveContext receiveContext) in /_/src/MassTransit.Newtonsoft/Serialization/EncryptedMessageDeserializerV2.cs:line 36
at MassTransit.Middleware.DeserializeFilter.Send(ReceiveContext context, IPipe`1 next) in /_/src/MassTransit/Middleware/DeserializeFilter.cs:line 36
at MassTransit.Middleware.RescueFilter`2.MassTransit.IFilter<TContext>.Send(TContext context, IPipe`1 next) in /_/src/MassTransit/Middleware/RescueFilter.cs:line 43
Below Are Amazon SQS Configuration :
public class Program
{
public static async Task Main(string[] args)
{
await Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddMassTransit(x =>
{
x.AddConsumers(typeof(SampleCommandConsumer).Assembly);
x.UsingAmazonSqs(
(context, sqsConfig) =>
{
sqsConfig.Host(
Environment.GetEnvironmentVariable("AWS_DEFAULT_REGION"),
h =>
{
var accessKey = Environment.GetEnvironmentVariable("AWS_ACCESS_KEY_ID");
h.AccessKey(accessKey);
var env = Environment.GetEnvironmentVariable("AWS_ENV_PREFIX");
h.Scope(env, true);
var secret = Environment.GetEnvironmentVariable("AWS_SECRET_ACCESS_KEY");
var serviceUrl = Environment.GetEnvironmentVariable("AWS_SQS_URL");
if (!string.IsNullOrEmpty(secret))
{
h.SecretKey(secret);
}
if (!string.IsNullOrEmpty(serviceUrl))
{
h.Config(new AmazonSQSConfig { ServiceURL = serviceUrl });
}
});
byte[] key = { 156, 62, 75, 207, 47, 62, 42, 73, 53, 164, 114, 49, 46, 226, 164, 1, 79, 225, 65, 193, 59, 192, 72, 27, 234, 87, 17, 44, 46, 207, 137, 1 };
sqsConfig.UseJsonSerializer();
sqsConfig.UseJsonDeserializer();
sqsConfig.UseEncryption(key);
var prefix = $"{Environment.GetEnvironmentVariable("ENVIRONMENT")}_{Environment.GetEnvironmentVariable("SERVICE_ACCOUNT_CLIENT_ID")}";
sqsConfig.ConfigureEndpoints(
context,
new KebabCaseEndpointNameFormatter(prefix, false)
);
}
);
});
services.AddHostedService<Publisher>();
})
.Build()
.RunAsync();
}
}
Publish Contract:
public class SampleCommand
{
/// <summary>
/// The correlation id events published as a result of processing this command must include.
/// </summary>
public Guid CorrelationId { get; init; }
/// <summary>
/// The identifer of the Sender that is to be authorized to use the listed message features.
/// </summary>
public long SenderId { get; set; }
}
Consumer:
public class SampleCommandConsumer : IConsumer<SampleCommand>
{
readonly IBus bus;
/// <summary>
/// Initializes a new instance of the <see cref="MessageDeliveredConsumer" /> class.
/// </summary>
public SampleCommandConsumer(IBus bus)
{
this.bus = bus;
}
public async Task Consume(ConsumeContext<SampleCommand> context)
{
await context.Publish(new SampleEvent()
{
CorrelationId = context.CorrelationId.Value,
});
}
}
configured Amazon SQS as per masstransit documentation, but didn't workout
Amazon SQS doesn't allow binary messages, neither does SNS. You should enable encryption at the queue level in SQS if you want message encryption.
You can configure queue encryption using a configuration callback:
x.AddConfigureEndpointCallback((_,cfg) =>
{
if (cfg is IAmazonSqsReceiveEndpointConfigurator sqs)
sqs.QueueAttributes.Add(QueueAttributeName.KmsMasterKeyId, "arn of key");
});

Sorting in elastic Search by Location and getting error while location lat and long is not coming

I have tried with the below code full fill my location sorting requirements in elastic search, when location is coming then it's working fine, but when location lat and long is not coming then my Nest c# code giving me the Exception
.Sort(s = >s.Ascending(fs = >fs.current_stage).Field(gh = >{
var query = new SortFieldDescriptor < CarSearchRequest > ();
if (searchAjaxRequest.sortingFilter != null) {
if (searchAjaxRequest.sortingFilter == "titleasc") {
query = gh.Field(tt = >tt.model).Order(SortOrder.Ascending);
}
else if (searchAjaxRequest.sortingFilter == "titledsc") {
query = gh.Field(tt = >tt.model).Order(SortOrder.Descending);
}
else if (searchAjaxRequest.sortingFilter == "priceasc") {
query = gh.Field(tt = >tt.price).Order(SortOrder.Ascending);
}
else if (searchAjaxRequest.sortingFilter == "Pricedsc") {
query = gh.Field(tt = >tt.price).Order(SortOrder.Descending);
}
else if (searchAjaxRequest.sortingFilter == "Kmasc") {
query = gh.Field(tt = >tt.kmRun).Order(SortOrder.Ascending);
}
else if (searchAjaxRequest.sortingFilter == "kmdsc") {
query = gh.Field(tt = >tt.kmRun).Order(SortOrder.Descending);
}
else if (searchAjaxRequest.sortingFilter == "introductiondateasc") {
query = gh.Field(tt = >tt.mfYear).Order(SortOrder.Ascending);
}
else if (searchAjaxRequest.sortingFilter == "introductiondatedesc") {
query = gh.Field(tt = >tt.mfYear).Order(SortOrder.Descending);
}
return query;
}
else if (searchAjaxRequest.category != null) {
if (searchAjaxRequest.category == "recentViewed") {
query = gh.Field(tt = >tt.createdDate).Order(SortOrder.Descending);
}
else if (searchAjaxRequest.category == "topRated") {
query = gh.Field(tt = >tt.overallRating).Order(SortOrder.Descending);
}
return query;
}
return query;
}).GeoDistance(g = >{
var locatioSorting = new SortGeoDistanceDescriptor < CarSearchRequest > ();
if (searchAjaxRequest.location != null) {
locatioSorting = g.Field(ab = >ab.location).Order(SortOrder.Ascending).Unit(DistanceUnit.Kilometers).Mode(SortMode.Min).Points(new GeoLocation(searchAjaxRequest.location.lat, searchAjaxRequest.location.lon));
}
return locatioSorting;
})));
Exception which is coming after null handle in my code.
System.NullReferenceException: Object reference not set to an instance of an object.
at Nest.FieldResolver.Resolve(Field field)
at Nest.SortJsonConverter.<>c__DisplayClass6_1.<WriteJson>b__0(JsonWriter w)
at Nest.ReserializeJsonConverter`2.Reserialize(JsonWriter writer, Object value, JsonSerializer serializer, Action`1 inlineWriter)
at Nest.SortJsonConverter.WriteJson(JsonWriter writer, Object value, JsonSerializer serializer)
at Elastic.Internal.JsonNet.Serialization.JsonSerializerInternalWriter.SerializeConvertable(JsonWriter writer, JsonConverter converter, Object value, JsonContract contract, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Elastic.Internal.JsonNet.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Elastic.Internal.JsonNet.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Elastic.Internal.JsonNet.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)
at Elastic.Internal.JsonNet.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)
at Nest.InternalSerializer.Serialize[T](T data, Stream writableStream, SerializationFormatting formatting)
at Elasticsearch.Net.SerializableData`1.Write(Stream writableStream, IConnectionConfigurationValues settings)
at Elasticsearch.Net.HttpWebRequestConnection.Request[TResponse](RequestData requestData)
at Elasticsearch.Net.RequestPipeline.CallElasticsearch[TResponse](RequestData requestData)
at Elasticsearch.Net.Transport`1.Request[TResponse](HttpMethod method, String path, PostData data, IRequestParameters requestParameters)
# Inner Exception: Object reference not set to an instance of an object.
System.NullReferenceException: Object reference not set to an instance of an object.
at Nest.FieldResolver.Resolve(Field field)
at Nest.SortJsonConverter.<>c__DisplayClass6_1.<WriteJson>b__0(JsonWriter w)
at Nest.ReserializeJsonConverter`2.Reserialize(JsonWriter writer, Object value, JsonSerializer serializer, Action`1 inlineWriter)
at Nest.SortJsonConverter.WriteJson(JsonWriter writer, Object value, JsonSerializer serializer)
at Elastic.Internal.JsonNet.Serialization.JsonSerializerInternalWriter.SerializeConvertable(JsonWriter writer, JsonConverter converter, Object value, JsonContract contract, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Elastic.Internal.JsonNet.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Elastic.Internal.JsonNet.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Elastic.Internal.JsonNet.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)
at Elastic.Internal.JsonNet.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)
at Nest.InternalSerializer.Serialize[T](T data, Stream writableStream, SerializationFormatting formatting)
at Elasticsearch.Net.SerializableData`1.Write(Stream writableStream, IConnectionConfigurationValues settings)
at Elasticsearch.Net.HttpWebRequestConnection.Request[TResponse](RequestData requestData)
at Elasticsearch.Net.RequestPipeline.CallElasticsearch[TResponse](RequestData requestData)
at Elasticsearch.Net.Transport`1.Request[TResponse](HttpMethod method, String path, PostData data, IRequestParameters requestParameters)
# Exception:
Elasticsearch.Net.UnexpectedElasticsearchClientException: Object reference not set to an instance of an object. ---> System.NullReferenceException: Object reference not set to an instance of an object.
at Nest.FieldResolver.Resolve(Field field)
at Nest.SortJsonConverter.<>c__DisplayClass6_1.<WriteJson>b__0(JsonWriter w)
at Nest.ReserializeJsonConverter`2.Reserialize(JsonWriter writer, Object value, JsonSerializer serializer, Action`1 inlineWriter)
at Nest.SortJsonConverter.WriteJson(JsonWriter writer, Object value, JsonSerializer serializer)
at Elastic.Internal.JsonNet.Serialization.JsonSerializerInternalWriter.SerializeConvertable(JsonWriter writer, JsonConverter converter, Object value, JsonContract contract, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Elastic.Internal.JsonNet.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Elastic.Internal.JsonNet.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Elastic.Internal.JsonNet.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)
at Elastic.Internal.JsonNet.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)
at Nest.InternalSerializer.Serialize[T](T data, Stream writableStream, SerializationFormatting formatting)
at Elasticsearch.Net.SerializableData`1.Write(Stream writableStream, IConnectionConfigurationValues settings)
at Elasticsearch.Net.HttpWebRequestConnection.Request[TResponse](RequestData requestData)
at Elasticsearch.Net.RequestPipeline.CallElasticsearch[TResponse](RequestData requestData)
at Elasticsearch.Net.Transport`1.Request[TResponse](HttpMethod method, String path, PostData data, IRequestParameters requestParameters)
--- End of inner exception stack trace ---

RegionInfo serializing in ElasticSearch

It seems that the RegionInfo object has kinda been forgotten in terms of serialization. CultureInfo works great and is serialized to and from a string. When attempting to throw in a RegionInfo object, I get a mess of all the properties of RegionInfo that can't be deserialized because there is no constructor that takes all those properties in reverse. I would love to just serialize and deserialize the RegionInfos as strings, like CultureInfo, but can't quite figure that out.
My attempt:
I created a regioninfo converter
public class RegionInfoConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, ((RegionInfo)value).Name);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var token = JToken.Load(reader);
return new RegionInfo(token.ToObject<string>());
}
public override bool CanConvert(Type objectType)
{
return typeof(RegionInfo) == objectType;
}
}
I stuffed that into the ConnectionSettings:
var connectionSettings = new ConnectionSettings(pool,
(builtin, settings) => new JsonNetSerializer(
builtin,
settings,
contractJsonConverters: new JsonConverter[] { new RegionInfoConverter() })
);
but I get the error: object mapping for [region] tried to parse field [region] as object, but found a concrete value
That sounds like one of my serializer pieces is wrong, but I don't feel like I quite understand enough to figure out which part it is. Thanks.
I think the issue here may be that Elasticsearch has initially inferred an object datatype mapping for RegionInfo from a document to be indexed, and is now being passed a string value for RegionInfo. You may need to delete the index and create again, mapping the RegionInfo property as a keyword datatype.
Here's a working example
private static void Main()
{
var defaultIndex = "my_index";
var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
var settings = new ConnectionSettings(pool, (b, s) =>
new JsonNetSerializer(b, s, contractJsonConverters: new JsonConverter[] { new RegionInfoConverter() })
)
.DefaultIndex(defaultIndex);
var client = new ElasticClient(settings);
if (client.IndexExists(defaultIndex).Exists)
client.DeleteIndex(defaultIndex);
var createIndexResponse = client.CreateIndex(defaultIndex, c => c
.Settings(s => s
.NumberOfShards(1)
.NumberOfReplicas(0)
)
.Mappings(m => m
.Map<MyEntity>(mm => mm
.AutoMap()
.Properties(p => p
.Keyword(k => k
.Name(n => n.RegionInfo)
)
)
)
)
);
var indexResponse = client.Index(new MyEntity
{
RegionInfo = RegionInfo.CurrentRegion
}, i => i.Refresh(Refresh.WaitFor));
}
public class MyEntity
{
public RegionInfo RegionInfo { get; set; }
}
public class RegionInfoConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value == null)
{
writer.WriteNull();
return;
}
writer.WriteValue(((RegionInfo)value).Name);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
if (reader.TokenType != JsonToken.String)
throw new JsonSerializationException($"Cannot deserialize {nameof(RegionInfo)} from {reader.TokenType}");
return new RegionInfo((string)reader.Value);
}
public override bool CanConvert(Type objectType)
{
return typeof(RegionInfo) == objectType;
}
}
The index request sends the following JSON
{
"regionInfo": "AU"
}

How to create a custom POST controller method for a DTO class?

I created a DTO class that is not mapped to any SQL table in the model:
public class FooDTO
{
public int Id { get; set; }
public string Name { get; set; }
}
I created an entity set of this type in the model:
public override IEdmModel GetModel()
{
var builder = new ODataConventionModelBuilder();
builder.EntitySet<FooDTO>("FooDTOs");
// ...
}
And created a custom controller:
public class FooDTOsController : ODataController
{
private IDatasourceFactory datasourceFactory;
public FooDTOsController(IDatasourceFactory datasourceFactory)
{
this.datasourceFactory = datasourceFactory;
}
// The GET is working great.
public IHttpActionResult Get()
{
var db = (MyModel)this.datasourceFactory;
IQueryable<FooDTO> foos = db.Set<Foo>().Select(
t => new FooDTO()
{
Id = t.Id,
Name = "blah blah blah"
});
return Ok(foos);
}
// I am not getting here.
[HttpPost]
public IHttpActionResult Post(FooDTO entity)
{
System.Diagnostics.Debug.WriteLine("YEAH!");
return Ok(entity);
}
}
But the Post method is not being executed. I have tried many ways to define the POST method, but I cannot find one that works.
Posting some data into my controller, results in the following error:
Cannot create an abstract class.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated
in the code.
Exception Details: System.MissingMethodException: Cannot create an abstract class.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception
stack trace below.
Stack Trace:
[MissingMethodException: Cannot create an abstract class.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +138
System.Activator.CreateInstance(Type type, Boolean nonPublic) +105
System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, StackCrawlMark& stackMark) +1528
System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) +191
System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture) +27
System.Web.HttpRuntime.CreateNonPublicInstance(Type type, Object[] args) +82
System.Web.Configuration.HandlerFactoryCache..ctor(String type) +58
System.Web.HttpApplication.GetFactory(String type) +104
System.Web.MaterializeHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +262
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +137
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.114.0
UPDATE: I am using the following PowerShell script to test the POST method:
$body = #{
Id = 1;
Name = "Blah blah blah";
} | ConvertTo-Json -Compress
$response = Invoke-WebRequest `
-Method POST `
-Uri "https://localhost/MyModel/FooDTOs/" `
-ContentType "application/json" `
-Body $body

Error in SqlMembershipProvider.GetPasswordWithFormat

I have the following error in my asp.net login page:
Unable to cast object of type 'System.Int32' to type 'System.String'
with stack trace:
at System.Data.SqlClient.SqlBuffer.get_String()
at System.Web.Security.SqlMembershipProvider.GetPasswordWithFormat(String username, Boolean updateLastLoginActivityDate, Int32& status, String& password, Int32& passwordFormat, String& passwordSalt, Int32& failedPasswordAttemptCount, Int32& failedPasswordAnswerAttemptCount, Boolean& isApproved, DateTime& lastLoginDate, DateTime& lastActivityDate)
at System.Web.Security.SqlMembershipProvider.CheckPassword(String username, String password, Boolean updateLastLoginActivityDate, Boolean failIfNotApproved, String& salt, Int32& passwordFormat)
at System.Web.Security.SqlMembershipProvider.ValidateUser(String username, String password)
at System.Web.UI.WebControls.Login.AuthenticateUsingMembershipProvider(AuthenticateEventArgs e)
at System.Web.UI.WebControls.Login.AttemptLogin()
at System.Web.UI.WebControls.Login.OnBubbleEvent(Object source, EventArgs e)
at System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)
at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
The error is not occured every time.
Any ideas?

Resources