Botstate.SetConversationData - Unexpected character encountered while parsing value - sms

I am trying to save conversation data via state client and I am getting inconsistent results between the emulator and the sms channels. Testing my bot app via emulator allows me to SetConversationData and GetConversationData fine, but as soon as I try it on sms with service url: https://sms.botframework.com/ I get the following error:
"exceptionMessage": "Unable to deserialize the response.",
"exceptionType": "Microsoft.Rest.SerializationException",
"stackTrace": " at Microsoft.Bot.Connector.BotState.d__9.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.Bot.Connector.BotStateExtensions.d__9.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.Bot.Connector.BotStateExtensions.SetConversationData(IBotState operations, String channelId, String conversationId, BotData botData)\r\n at OutboundTestApp.Controllers.OutboundController.Post(OutboundConversationData`1 outboundData)",
"innerException": {
"message": "An error has occurred.",
"exceptionMessage": "Unexpected character encountered while parsing value: T. Path '', line 0, position 0.",
"exceptionType": "Newtonsoft.Json.JsonReaderException",
"stackTrace": " at Newtonsoft.Json.JsonTextReader.ParseValue()\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)\r\n at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)\r\n at Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject[T](String json, JsonSerializerSettings settings)\r\n at Microsoft.Bot.Connector.BotState.d__9.MoveNext()"
Here is my code to set the data where the channelId is "sms", conversationId is a valid id and the data is just a simple POCO class:
var stateClient = new StateClient(new Uri(serviceUrl), account);
stateClient.BotState.SetConversationData(outboundData.ChannelId, conversationResponse.Id, new BotData(data: outboundData.Data));
Should I be using SetPrivateConversationDataWithHttpMessagesAsync and pass in the content type and set my botdata to a json string? I feel the state client is assuming json is being passed somewhere, but the object it is deserializing is actually not json.

The problem is that the serviceUrl was set incorrectly when creating the state client. The baseUri should be https://state.botframework.com.

Related

Error occurs when try to implement virtual entity in MS CRM - An OData error occurred

I am trying to implement Virtual Entity in CRM Online V9.1.0.5220. I have created custom ODATA services below are the screenshots -
I have created Bank virtual entity in CRM, when I am trying to call the virtual entity I am getting following error 'Entity could not be retrieved from data source. Please try again or contact your system administrator.'
When I am trying to call the virtual entity from browser as /api/data/v9.1/geo_banks, I am getting below error -
{
"error": {
"code": "0x80050263",
"message": "An OData error occurred.",
"innererror": {
"message": "An OData error occurred.",
"type": "System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]",
"stacktrace": " at Microsoft.Crm.Extensibility.OrganizationSdkServiceInternal.RetrieveMultiple(QueryBase query, InvocationContext invocationContext, CallerOriginToken callerOriginToken, WebServiceType serviceType, Boolean checkAdminMode, Guid appModuleId, Dictionary`2 optionalParameters)\r\n at Microsoft.Crm.Extensibility.OData.CrmODataExecutionContext.RetrieveMultiple(QueryBase query)\r\n at Microsoft.Crm.Extensibility.OData.CrmODataServiceDataProvider.RetrieveEdmEntityCollection(CrmODataExecutionContext context, String entityCollectionName, String castedEntityName, ODataQueryOptions queryOptions)\r\n at Microsoft.Crm.Extensibility.OData.EntityController.<>c__DisplayClass35_0.<GetEntitySetInternal>b__1()\r\n at Microsoft.PowerApps.CoreFramework.ActivityLoggerExtensions.Execute(ILogger logger, EventId eventId, ActivityType activityType, Action action, IEnumerable`1 additionalCustomProperties)\r\n at Microsoft.Xrm.Telemetry.XrmTelemetryExtensions.Execute(ILogger logger, XrmTelemetryActivityType activityType, Action action)\r\n at Microsoft.Crm.Extensibility.OData.EntityController.GetEntitySetInternal(String entitySetName, String castedEntityName, CrmODataExecutionContext context, CrmEdmEntityObjectCollection crmEdmEntityObjectCollection, ODataQueryOptions queryOptions)\r\n at Microsoft.Crm.Extensibility.OData.EntityController.GetEntitySetImplementation(String entitySetName)\r\n at Microsoft.PowerApps.CoreFramework.ActivityLoggerExtensions.Execute[TResult](ILogger logger, EventId eventId, ActivityType activityType, Func`1 func, IEnumerable`1 additionalCustomProperties)\r\n at Microsoft.Xrm.Telemetry.XrmTelemetryExtensions.Execute[TResult](ILogger logger, XrmTelemetryActivityType activityType, Func`1 func)\r\n at lambda_method(Closure , Object , Object[] )\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"
}
}
}
I have tried to consume https://services.odata.org/V4/OData/OData.svc/ ODATA service and it is working as expected.
I know the issue is with the service but couldn't figure out the exact reason as both the services are similar.

JsonResult Response from WebAPI for Elasticsearch NEST query

I have created WEBAPI methods, to search ES using NEST. The search with ES is working as expected. The issue that I have is when I try to return the Json(response) using POSTMAN, it throws this exception:
{
"Message": "An error has occurred.",
"ExceptionMessage": "If you use a custom contract resolver be sure to subclass from ElasticContractResolver",
"ExceptionType": "System.Exception",
"StackTrace": " at Nest.JsonExtensions.GetConnectionSettings(JsonSerializer
serializer)\r\n at
Nest.VerbatimDictionaryKeysJsonConverter2.WriteJson(JsonWriter
writer, Object value, JsonSerializer serializer)\r\n at
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeConvertable(JsonWriter
writer, JsonConverter converter, Object value, JsonContract contract,
JsonContainerContract collectionContract, JsonProperty
containerProperty)\r\n at
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter
writer, Object value, JsonContract valueContract, JsonProperty member,
JsonContainerContract containerContract, JsonProperty
containerProperty)\r\n at
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter
writer, Object value, JsonObjectContract contract, JsonProperty
member, JsonContainerContract collectionContract, JsonProperty
containerProperty)\r\n at
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter
writer, Object value, JsonContract valueContract, JsonProperty member,
JsonContainerContract containerContract, JsonProperty
containerProperty)\r\n at
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter
jsonWriter, Object value, Type objectType)\r\n at
Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter
jsonWriter, Object value, Type objectType)\r\n at
System.Web.Http.Results.JsonResult1.Serialize()\r\n at
System.Web.Http.Results.JsonResult1.Execute()\r\n at
System.Web.Http.Results.JsonResult1.ExecuteAsync(CancellationToken
cancellationToken)\r\n at
System.Web.Http.Controllers.ApiControllerActionInvoker.d__0.MoveNext()\r\n---
End of stack trace from previous location where exception was thrown
---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task)\r\n at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task)\r\n at
System.Web.Http.Controllers.ActionFilterResult.d__2.MoveNext()\r\n---
End of stack trace from previous location where exception was thrown
---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task)\r\n at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task)\r\n at
System.Web.Http.Controllers.AuthenticationFilterResult.d__0.MoveNext()\r\n---
End of stack trace from previous location where exception was thrown
---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task)\r\n at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task)\r\n at
System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()"
}
This is my WEB API method
[System.Web.Http.Route("SearchElastic")]
[System.Web.Http.HttpPost]
public JsonResult<ISearchResponse<T>> SearchElastic([FromBody] ElasticSearchRequest esRequest)
{
var searchResponse = EsClient.Search<T>(
"...NEST query..."
));
return Json(searchResponse);
}
//<T> is a custom C# class.
I am using Elasticsearch/NEST 5.x.
The error message hints at what the problem is
{ "Message": "An error has occurred.", "ExceptionMessage": "If you use
a custom contract resolver be sure to subclass from
ElasticContractResolver", "ExceptionType": "System.Exception",
"StackTrace": " at ...
and it relates to the line
return Json(searchResponse);
the configuration for the Json serializer used by Web API does not know how to handle serializing certain types from NEST because some of those types need ElasticContractResolver to be serialized correctly.
There are a few ways to solve this, but the two most straightforward are:
Configure the Json Serializer used by Web API with ElasticContractResolver as the IContractResolver on the JsonSerializerSettings. The disadvantage here is that all of your types that you're serializing to json will be going through NEST's resolver
Avoid the deserialization/re-serialization loop from Elasticsearch -> deserialized by NEST -> reserialized by Web API altogether by using the low level client to return a string or byte array from Elasticsearch. I would recommend this approach if you are not doing any introspection on searchResponse. If you do need to inspect searchResponse, you can always deserialize the string or byte array to SearchResponse<T> as a separate step.
This is one of the reasons that the direct dependency on Json.NET has been removed in NEST 6.x

Updating stageid of a Dynamics CRM entity using the OData API resulting in Invalid Cast exception

I am trying to update the stageid of the Business process Workflow(BPF) enabled entity in attempt to move the next stage using the Odata api.
Below is my HTTP request details
[organization]/api/data/v8.1/MyEntity(0df630c1-3e1e-e811-810f-3863bb35ed38)
Method :- Patch
Body :-
{"stageid#odata.bind":"/processstages(0e603558-a5e2-176b-6c18-3b498377ab12)","traversedpath":"4625784d-7813-4e07-aef5-a7e3f231219f,0e603558-a5e2-176b-6c18-3b498377ab12"}
But, my request fails with invalid cast exception.
{
"error":{
"code":"","message":"System.InvalidCastException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #E6D73AE1","innererror":{
"message":"System.InvalidCastException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #E6D73AE1","type":"System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]","stacktrace":" at Microsoft.Crm.Extensibility.OrganizationSdkServiceInternal.Update(Entity entity, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType, Boolean checkAdminMode, Boolean checkForOptimisticConcurrency, Dictionary`2 optionalParameters)\r\n at Microsoft.Crm.Extensibility.OData.CrmODataExecutionContext.Update(Entity entity, UpdateOption updateOption)\r\n at Microsoft.Crm.Extensibility.OData.CrmODataServiceDataProvider.UpdateEdmEntity(CrmODataExecutionContext context, String edmEntityName, String entityKeyValue, EdmEntityObject entityObject)\r\n at Microsoft.Crm.Extensibility.OData.EntityController.PatchEntity(String entityName, String key, EdmEntityObject entityDelta)\r\n at lambda_method(Closure , Object , Object[] )\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"
}
}
}
Any help on what i might be doing wrong here? I usually use the #odata.bind for the lookups, but stageid seems to be of type Unique identifier. how do i update a unique identifier?
Also, it would be really helpful to know how can one debug or know more details about this administrator reference numbers.
P.S:- I know updating the stageid can be achieved using the CRM SDK's, but i din't find any help doing the same with the odata API.
Techically stageid is just a guid and not a lookup. Try to update your entity using following payload:
{"stageid":"0e603558-a5e2-176b-6c18-3b498377ab12"}

How can i get message from telegram channel into my bot?

I'm using Telegeram.bot for develop simple telegram bot on .net
I added my bot(administrator) to public channel and i want to get message from channel ans resend again to bot users
but I have problem, here is my code
#region Properties
private Api bot;
string botToken = "Bot Token";
#endregion
#region Constructor
/// <summary>
/// Basic constructor for the api controller
/// </summary>
public WebhookController()
{
bot = new Api(botToken);
}
#endregion
public async Task<IHttpActionResult> Post(Update update)
{
var text = update.Message.Text;
var chatType = update.Message.Chat.Type;
if (chatType == ChatType.Channel)
{
// Send Text message to users that previusly we gathered their telegram id and saved them in our DB
// ******Problem is here******
}
else if (chatType == ChatType.Private)
{
if (text != null && text.Contains("/start") || text.Contains("start"))
{
await bot.SendTextMessage(chatId: update.Message.Chat.Id, text: "START");
}
}
else
{
await bot.SendTextMessage(chatId: update.Message.Chat.Id, text: "ERROR!!!");
}
return Ok();
}
public string Get()
{
return "Yes Its Work";
}
But I got 500 Internal Server Error
"Message": "An error has occurred.",
"ExceptionMessage": "Object reference not set to an instance of an object.",
"ExceptionType": "System.NullReferenceException",
"StackTrace": " at CodeBlock.Bot.Engine.Controllers.webhookController.<Post>d__11.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Threading.Tasks.TaskHelpersExtensions.<CastToObject>d__3`1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.AuthenticationFilterResult.<ExecuteAsync>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"

Windows HttpClient response header invalid character

I'm using HttpClient postAsync method for posting and retriving json. It's working like a charm.
But if server return "Ö" character in response header's any field, it throws below exception.
System.ArgumentException ---> System.ArgumentException: [net_WebHeaderInvalidControlChars]
Arguments:
Debugging resource strings are unavailable. Often the key and arguments provide sufficient information to diagnose the problem. See http://go.microsoft.com/fwlink/?linkid=106663&Version=4.7.60408.0&File=System.Net.dll&Key=net_WebHeaderInvalidControlChars
Parameter name: name
at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClasse.<EndGetResponse>b__d(Object sendState)
at System.Net.Browser.AsyncHelper.<>c__DisplayClass1.<BeginOnUI>b__0(Object sendState)
--- End of inner exception stack trace ---
at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.Http.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
HTTP Header are ASCII only. See RFC: https://www.rfc-editor.org/rfc/rfc2616
Umlaute in the Header are just a protocol Violation and will throw an exception.

Resources