Exemple #1
0
        /// Asynchronous submission api method.
        /// Most work is pushed off to an OnConnect callback.
        public void SubmitScoreAsync(string level, Score score, Action <SubmissionResponse, ServerException> callback)
        {
            // Ensure arguments are valid
            if (level == null)
            {
                throw new ArgumentNullException();
            }
            score.Validate();

            // external callback and argument container
            SubmitScoreState state = new SubmitScoreState(level, score, callback);

            // make the async connection with the onconnect callback
            ConnectAsync(new AsyncCallback(SubmitScoreOnConnectCallback), state);
        }
Exemple #2
0
        /// OnConnect callback, the bulk of the work is handled here.
        void SubmitScoreOnConnectCallback(IAsyncResult ar)
        {
            SubmitScoreState state = (SubmitScoreState)ar.AsyncState;

            // the arguments for the external callback
            SubmissionResponse position = new SubmissionResponse();
            ServerException    error    = null;

            // handle being unable to connect
            if (!client.Connected)
            {
                error = new ServerException("Unable to connect");
            }
            else
            {
                try {
                    // form a submission message and send it to the server
                    string request = SubmissionRequest.ToJson(state.level, state.score);
                    WriteLine(request);

                    // get a response from server and convert back to an object
                    string response = ReadLine();
                    position = SubmissionResponse.FromJson(response);
                } catch (ServerException e) {
                    error = e;
                }
            }

            // report back to user
            if (state.callback != null)
            {
                state.callback.Invoke(position, error);
            }

            // note: even if connection failed, clean up is still necessary
            DisconnectAsync(ar);
        }