C #: IBM-Watson Unity SDK NullReferenceException при попытке создать сеанс с помощью Watson Assistant V2 - PullRequest
0 голосов
/ 27 января 2019

Я пытаюсь запустить пример в IBM Watson Unity SDK, но я получаю исключение NullReferenceException при попытке создать сеанс.

Это сценарий, приведенный в качестве примера с SDK сисключение измененных строк.Я добавил их, потому что по какой-то странной причине имя пользователя и пароль не были добавлены в учетные данные.Если у вас есть ответ на этот вопрос, я создал отдельный вопрос для этой проблемы здесь

using System.Collections;
using System.Collections.Generic;
using IBM.Watson.DeveloperCloud.Connection;
using IBM.Watson.DeveloperCloud.Logging;
using IBM.Watson.DeveloperCloud.Utilities;
using IBM.WatsonDeveloperCloud.Assistant.v2;
using UnityEngine;

namespace IBM.Watson.DeveloperCloud.Services.Assistant.v2
{
    public class ExampleAssistantV2 : MonoBehaviour
    {
        #region PLEASE SET THESE VARIABLES IN THE INSPECTOR
        [Space(10)]
        [Tooltip("The service URL (optional). This defaults to \"https://gateway.watsonplatform.net/assistant/api\"")]
        [SerializeField]
        private string _serviceUrl;
        [Tooltip("The assistantId to run the example.")]
        [SerializeField]
        private string _assistantId;
        [Tooltip("The version date with which you would like to use the service in the form YYYY-MM-DD.")]
        [SerializeField]
        private string _versionDate;
        [Header("CF Authentication")]
        [Tooltip("The authentication username.")]
        [SerializeField]
        private string _username;
        [Tooltip("The authentication password.")]
        [SerializeField]
        private string _password;
        [Header("IAM Authentication")]
        [Tooltip("The IAM apikey.")]
        [SerializeField]
        private string _iamApikey;
        [Tooltip("The IAM url used to authenticate the apikey (optional). This defaults to \"https://iam.bluemix.net/identity/token\".")]
        [SerializeField]
        private string _iamUrl;
        #endregion

        private Assistant _service;

        private bool _createSessionTested = false;
        private bool _messageTested = false;
        private bool _deleteSessionTested = false;
        private string _sessionId;

        private void Start()
        {
            LogSystem.InstallDefaultReactors();
            Runnable.Run(CreateService());
        }

        private IEnumerator CreateService()
        {
            //  Create credential and instantiate service
            Credentials credentials = null;
            if (!string.IsNullOrEmpty(_username) && !string.IsNullOrEmpty(_password))
            {
                //  Authenticate using username and password
                credentials = new Credentials(_username, _password, _serviceUrl);
                credentials.Username = _username; //Modified
                credentials.Password = _password; //Modified
                credentials.Url = _serviceUrl; //Modified
            }
            else if (!string.IsNullOrEmpty(_iamApikey))
            {
                //  Authenticate using iamApikey
                TokenOptions tokenOptions = new TokenOptions()
                {
                    IamApiKey = _iamApikey,
                    IamUrl = _iamUrl
                };

                credentials = new Credentials(tokenOptions, _serviceUrl);

                //  Wait for tokendata
                while (!credentials.HasIamTokenData())
                    yield return null;
            }
            else
            {
                throw new WatsonException("Please provide either username and password or IAM apikey to authenticate the service.");
            }

            _service = new Assistant(credentials);
            _service.VersionDate = _versionDate;

            Runnable.Run(Examples());
        }

        private IEnumerator Examples()
        {
            Log.Debug("ExampleAssistantV2.Examples()", "Attempting to CreateSession");
            _service.CreateSession(OnCreateSession, OnFail, _assistantId);

            while (!_createSessionTested)
            {
                yield return null;
            }

            Log.Debug("ExampleAssistantV2.Examples()", "Attempting to Message");
            _service.Message(OnMessage, OnFail, _assistantId, _sessionId);

            while (!_messageTested)
            {
                yield return null;
            }

            Log.Debug("ExampleAssistantV2.Examples()", "Attempting to DeleteSession");
            _service.DeleteSession(OnDeleteSession, OnFail, _assistantId, _sessionId);

            while (!_deleteSessionTested)
            {
                yield return null;
            }

            Log.Debug("ExampleAssistantV2.Examples()", "Assistant examples complete.");
        }

        private void OnDeleteSession(object response, Dictionary<string, object> customData)
        {
            Log.Debug("ExampleAssistantV2.OnDeleteSession()", "Session deleted.");
            _createSessionTested = true;
        }

        private void OnMessage(MessageResponse response, Dictionary<string, object> customData)
        {
            _messageTested = true;
        }

        private void OnCreateSession(SessionResponse response, Dictionary<string, object> customData)
        {
            Log.Debug("ExampleAssistantV2.OnCreateSession()", "Session: {0}", response.SessionId);
            _sessionId = response.SessionId;
            _createSessionTested = true;
        }

        private void OnFail(RESTConnector.Error error, Dictionary<string, object> customData)
        {
            Log.Debug("ExampleAssistantV2.OnFail()", "Call failed: {0}: {1}", error.ErrorCode, error.ErrorMessage);
        }
    }
}

Сгенерирован код ошибки:

[01/27/2019 09:33:18][Unity][CRITICAL] Unity Exception NullReferenceException: Object reference not set to an instance of an object : IBM.Watson.DeveloperCloud.Services.Assistant.v2.ExampleAssistantV2.OnFail (IBM.Watson.DeveloperCloud.Connection.Error error, System.Collections.Generic.Dictionary`2 customData) (at Assets/Watson/Examples/ServiceExamples/Scripts/ExampleAssistantV2.cs:157)
IBM.Watson.DeveloperCloud.Services.Assistant.v2.Assistant.OnCreateSessionResponse (IBM.Watson.DeveloperCloud.Connection.Request req, IBM.Watson.DeveloperCloud.Connection.Response resp) (at Assets/Watson/Scripts/Services/Assistant/v2/Assistant.cs:208)
IBM.Watson.DeveloperCloud.Connection.RESTConnector+<ProcessRequestQueue>c__Iterator0.MoveNext () (at Assets/Watson/Scripts/Connection/RESTConnector.cs:581)
IBM.Watson.DeveloperCloud.Utilities.Runnable+Routine.MoveNext () (at Assets/Watson/Scripts/Utilities/Runnable.cs:131)
UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)

UnityEngine.Debug:LogError(Object)
IBM.Watson.DeveloperCloud.Debug.DebugReactor:ProcessLog(LogRecord) (at Assets/Watson/Scripts/Debug/DebugReactor.cs:60)
IBM.Watson.DeveloperCloud.Logging.LogSystem:ProcessLog(LogRecord) (at Assets/Watson/Scripts/Logging/Logger.cs:206)
IBM.Watson.DeveloperCloud.Logging.Log:Critical(String, String, Object[]) (at Assets/Watson/Scripts/Logging/Logger.cs:294)
IBM.Watson.DeveloperCloud.Logging.LogSystem:UnityLogCallback(String, String, LogType) (at Assets/Watson/Scripts/Logging/Logger.cs:167)
UnityEngine.Application:CallLogCallback(String, String, LogType, Boolean)

NullReferenceException: Object reference not set to an instance of an object
IBM.Watson.DeveloperCloud.Services.Assistant.v2.ExampleAssistantV2.OnFail (IBM.Watson.DeveloperCloud.Connection.Error error, System.Collections.Generic.Dictionary`2 customData) (at Assets/Watson/Examples/ServiceExamples/Scripts/ExampleAssistantV2.cs:157)
IBM.Watson.DeveloperCloud.Services.Assistant.v2.Assistant.OnCreateSessionResponse (IBM.Watson.DeveloperCloud.Connection.Request req, IBM.Watson.DeveloperCloud.Connection.Response resp) (at Assets/Watson/Scripts/Services/Assistant/v2/Assistant.cs:208)
IBM.Watson.DeveloperCloud.Connection.RESTConnector+<ProcessRequestQueue>c__Iterator0.MoveNext () (at Assets/Watson/Scripts/Connection/RESTConnector.cs:581)
IBM.Watson.DeveloperCloud.Utilities.Runnable+Routine.MoveNext () (at Assets/Watson/Scripts/Utilities/Runnable.cs:131)
UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)

РЕДАКТИРОВАТЬ: Заметил Iзадал вопрос в неподходящее время, поэтому я решил отредактировать его, чтобы увидеть, есть ли у него больше шансов получить ответ.По-прежнему нет прогресса, не могу понять, что именно является нулевым.Любое понимание будет оценено.

Ответы [ 2 ]

0 голосов
/ 28 января 2019

Ошибка исходит от Assistant V2, скорее всего из-за отсутствия AssistantId. В старых версиях не было нулевой проверки AssistantId. Последняя версия от github должна иметь нулевую проверку.

0 голосов
/ 28 января 2019

SDK в хранилище активов Unity устарел. Пришлось переключиться на тот на Github. После внесения обновлений я больше не получил ошибку. Однако есть случаи, если вы хотя бы немного отредактируете пример, есть шанс получить исключение NullReferenceException.

...