botframework-sdk icon indicating copy to clipboard operation
botframework-sdk copied to clipboard

StateClient Exception

Open wiltodelta opened this issue 10 years ago • 17 comments

My code:

            var stateClient = new StateClient(
                new Uri(loginSession.ServiceUrl),
                _microsoftAppId,
                _microsoftAppPassword);

            BotData userData = await stateClient.BotState.GetUserDataAsync(
                loginSession.ChannelId, loginSession.UserId);

            userData.SetProperty("AccessToken", tokenResponseModel.AccessToken);
            userData.SetProperty("UserId", tokenResponseModel.UserId);

            await stateClient.BotState.SetUserDataAsync(
                loginSession.ChannelId, loginSession.UserId, userData);

Exception:

[JsonReaderException: Unexpected character encountered while parsing value: T. Path '', line 0, position 0.] Newtonsoft.Json.JsonTextReader.ParseValue() +1025 Newtonsoft.Json.JsonTextReader.Read() +103 Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter) +74 Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent) +451 Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType) +210 Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType) +13 Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject(String json, JsonSerializerSettings settings) +312 Microsoft.Bot.Connector.d__5.MoveNext() in C:\Projects\GitHub\BotBuilder-NuGet3.1.0\CSharp\Library\Microsoft.Bot.Connector\StateAPI\BotState.cs:186

I can't use IDialogContext to changing UserData, because code executing in different context.

wiltodelta avatar Aug 17 '16 12:08 wiltodelta

Can you tell me about the original thrown exception?

https://github.com/Microsoft/BotBuilder/blob/master/CSharp/Library/Microsoft.Bot.Connector/StateAPI/BotState.cs#L186

willportnoy avatar Aug 17 '16 17:08 willportnoy

@willportnoy The exception thrown here BotData userData = await stateClient.BotState.GetUserDataAsync(loginSession.ChannelId, loginSession.UserId); with message "Unable to deserialize the response.".

I double checked all parameters.

wiltodelta avatar Aug 17 '16 18:08 wiltodelta

@willportnoy And checked at different channels (Telegram, Facebook, Web Chat).

wiltodelta avatar Aug 17 '16 18:08 wiltodelta

@willportnoy Full Stack Trace:

[JsonReaderException: Unexpected character encountered while parsing value: T. Path '', line 0, position 0.] Newtonsoft.Json.JsonTextReader.ParseValue() +1025 Newtonsoft.Json.JsonTextReader.Read() +103 Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter) +74 Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent) +451 Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType) +210 Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType) +13 Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject(String json, JsonSerializerSettings settings) +312 Microsoft.Bot.Connector.d__5.MoveNext() in C:\Projects\GitHub\BotBuilder-NuGet3.1.0\CSharp\Library\Microsoft.Bot.Connector\StateAPI\BotState.cs:186

[RestException: Unable to deserialize the response.] Microsoft.Bot.Connector.d__5.MoveNext() in C:\Projects\GitHub\BotBuilder-NuGet3.1.0\CSharp\Library\Microsoft.Bot.Connector\StateAPI\BotState.cs:190 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58 Microsoft.Bot.Connector.d__1.MoveNext() in C:\Projects\GitHub\BotBuilder-NuGet3.1.0\CSharp\Library\Microsoft.Bot.Connector\StateAPI\BotStateExtensions.cs:53 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58 System.Runtime.CompilerServices.TaskAwaiter1.GetResult() +28 Abbyy.Contento.Bot.Web.Controllers.Mvc.<SsoCallback>d__10.MoveNext() in C:\Projects\Findo\backend\Abbyy.Contento.Bot.Web\Controllers\Mvc\AuthorizationController.cs:83 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58 System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult) +97 System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeAsynchronousActionMethod>b__36(IAsyncResult asyncResult) +17 System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32 System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +50 System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +225 System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +10 System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34 System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +26 System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100 System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27 System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +29 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49 System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36 System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +22 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49 System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26 System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10 System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +29 System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9 System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar) +129

wiltodelta avatar Aug 17 '16 18:08 wiltodelta

I also use ConnectorClient with same parameters and it works fine!

            var connectorClient = new ConnectorClient(
                new Uri(loginSession.ServiceUrl),
                _microsoftAppId,
                _microsoftAppPassword);

            IMessageActivity message = Activity.CreateMessageActivity();

            message.From = new ChannelAccount
            {
                Id = loginSession.BotId,
                Name = loginSession.BotName
            };

            message.Recipient = new ChannelAccount
            {
                Id = loginSession.UserId
            };

            message.Conversation = new ConversationAccount
            {
                Id = loginSession.ConversationId
            };

            message.Text = "TODO";

            await connectorClient.Conversations.SendToConversationAsync((Activity) message);

wiltodelta avatar Aug 17 '16 18:08 wiltodelta

It's really critical issue for us.

wiltodelta avatar Aug 17 '16 20:08 wiltodelta

I suspect the state service is returning something that can't be parsed by the json reader.

Are you trying to save a lot of state? If so, there may be an earlier error you could just avoid.

If you use fiddler or the debugger, can you see the body of the http response returned by the state service, that apparently can't be parsed by the json reader?

willportnoy avatar Aug 17 '16 22:08 willportnoy

@willportnoy Yes, can't be parsed and returned http status 500, it's not success response.

I save 2 values (12 bytes, 16 bytes) in state, but exception thrown when executing GetUserDataAsync.

I use Azure App Service to host bot app, I can't see body of request/response via fiddler.

wiltodelta avatar Aug 17 '16 23:08 wiltodelta

curl -v -XGET -H 'Authorization: Bearer ACCESS_TOKEN_HIDDEN' -H 'User-Agent: Microsoft.Bot.Connector.StateClient/3.1.0.0' -H "Content-type: application/json" 'https://webchat.botframework.com/v3/botstate/webchat/users/JaNtkMidx4P'
*   Trying 40.121.91.199...
* Connected to webchat.botframework.com (40.121.91.199) port 443 (#0)
* TLS 1.2 connection using TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384
* Server certificate: *.botframework.com
* Server certificate: Microsoft IT SSL SHA2
* Server certificate: Baltimore CyberTrust Root
> GET /v3/botstate/webchat/users/JaNtkMidx4P HTTP/1.1
> Host: webchat.botframework.com
> Accept: */*
> Authorization: Bearer ACCESS_TOKEN_HIDDEN
> User-Agent: Microsoft.Bot.Connector.StateClient/3.1.0.0
> Content-type: application/json
>
< HTTP/1.1 500 Internal Server Error
< Cache-Control: private
< Content-Length: 75
< Content-Type: text/html
< Server: Microsoft-IIS/8.0
< X-Powered-By: ASP.NET
< Strict-Transport-Security: max-age=31536000
< Set-Cookie: ARRAffinity=24bc3facd6e5b4f0d66d9006b97f0eee028109c691fcceba8f9012e8e8d94017;Path=/;Domain=webchat.botframework.com
< Date: Thu, 18 Aug 2016 00:18:48 GMT
<
* Connection #0 to host webchat.botframework.com left intact
The page cannot be displayed because an internal server error has occurred.%

wiltodelta avatar Aug 17 '16 23:08 wiltodelta

May be @msft-shahins can help?

wiltodelta avatar Aug 18 '16 00:08 wiltodelta

I registered and tried another bot, problem doesn't depend on this.

wiltodelta avatar Aug 18 '16 00:08 wiltodelta

@wiltodelta can you do a direct call to GetUserData for State API using postman or curl and see what is the returned results by the service for that specific user? I guess the saved data for that user is not a valid JSON and causes the exception to be thrown.

msft-shahins avatar Aug 18 '16 01:08 msft-shahins

@willportnoy, @msft-shahins BaseUri for StateClient is https://state.botframework.com.

ConnectorClient and StateClient have similar parameters in constructor:

        /// <summary>
        /// Create a new instance of the StateClient class
        /// </summary>
        /// <param name="baseUri">Base URI for the Connector service</param>
        /// <param name="microsoftAppId">Optional. Your Microsoft app id. If null, this setting is read from settings["MicrosoftAppId"]</param>
        /// <param name="microsoftAppPassword">Optional. Your Microsoft app password. If null, this setting is read from settings["MicrosoftAppPassword"]</param>
        /// <param name="handlers">Optional. The delegating handlers to add to the http client pipeline.</param>
        public StateClient(Uri baseUri, string microsoftAppId = null, string microsoftAppPassword = null, params DelegatingHandler[] handlers)
            : this(baseUri, new MicrosoftAppCredentials(microsoftAppId, microsoftAppPassword), handlers: handlers)
        {
        }
        /// <summary>
        /// Create a new instance of the ConnectorClient class
        /// </summary>
        /// <param name="baseUri">Base URI for the Connector service</param>
        /// <param name="microsoftAppId">Optional. Your Microsoft app id. If null, this setting is read from settings["MicrosoftAppId"]</param>
        /// <param name="microsoftAppPassword">Optional. Your Microsoft app password. If null, this setting is read from settings["MicrosoftAppPassword"]</param>
        /// <param name="handlers">Optional. The delegating handlers to add to the http client pipeline.</param>
        public ConnectorClient(Uri baseUri, string microsoftAppId = null, string microsoftAppPassword = null, params DelegatingHandler[] handlers)
            : this(baseUri, new MicrosoftAppCredentials(microsoftAppId, microsoftAppPassword), handlers: handlers)
        {
        }

wiltodelta avatar Aug 18 '16 01:08 wiltodelta

@wiltodelta does changing the URL solve your issue?

willportnoy avatar Aug 18 '16 02:08 willportnoy

@willportnoy Yes.

wiltodelta avatar Aug 18 '16 06:08 wiltodelta

so glad I found this - saved me hours with the same issue

karlbarber avatar Nov 17 '16 17:11 karlbarber

thanks for the help guys. this saved me more time as well.

arthurtina724 avatar Apr 04 '17 22:04 arthurtina724