简体   繁体   中英

C#: IBM-Watson Unity SDK NullReferenceException When Trying To Create A Session Using Watson Assistant V2

I'm trying to run the example in the IBM Watson Unity SDK but I'm getting a NullReferenceException when it tries to create a session.

This is the script given as an example with the SDK with the exception of the modified lines. I added these in because for some weird reason the username and password wasn't being added to credentials. If you have an answer for this I have created a separate question for this issue here

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);
        }
    }
}

The error code thrown:

[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)

EDIT: Noticed I asked the question at a bad time so I decided to edit it to see if it has a better chance of getting answered. Still no progress, can't quite figure out what exactly is null. Any insight would be appreciated.

SDK on the Unity Asset store was deprecated. Had to switch to the one on Github. After making the updates I no longer received the error. There are instances however if you edit the example even slightly, there's a chance to receive the NullReferenceException.

The error is coming from Assistant V2 most likely from not providing an AssistantId. Older versions did not have a null check for AssistantId. The latest version from github should have the null check.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM