コード例 #1
0
ファイル: ConvergeGame.cs プロジェクト: ssammi/wobspring2015
    public void ProcessConvergePriorAttemptCount(NetworkResponse response)
    {
        ResponseConvergePriorAttemptCount args = response as ResponseConvergePriorAttemptCount;

        new_ecosystem_id         = args.ecosystem_id;
        attemptCount             = args.count;
        priorHintIdList          = new List <int>();
        isResetSliderInitialized = false;

        //once count of attempts has been received, send requests for individual attempt's data
        for (int attemptOffset = 0; attemptOffset < attemptCount; attemptOffset++)
        {
            NetworkManager.Send(
                ConvergePriorAttemptProtocol.Prepare(player_id, new_ecosystem_id, attemptOffset),
                ProcessConvergePriorAttempt
                );
            //Debug.Log ("Send RequestConvergePriorAttempt");
        }

        UpdateEcosystemIds();

        //if no prior attempts found create new curAttempt based on default config
        //of curr ecosystem
        if (attemptCount == 0)
        {
            FinalizeLoadPriorAttempts();
        }
    }
コード例 #2
0
            public void ContextSetup()
            {
                var masterModel  = new MasterModel();
                var server1      = masterModel.CreateCruiseServer(x => x.Url = "http://www.example.com/1");
                var server2      = masterModel.CreateCruiseServer(x => x.Url = "http://www.example.com/2");
                var ccReaderData = new Projects {
                    Items = new[] { new ProjectsProject(), new ProjectsProject() }
                };
                var mappedData = new CcProjectCollectionViewModel
                {
                    Items = new[] { new CcProjectViewModel {
                                        Name = "Homer Wuz Here"
                                    } }
                };

                var ccReaderResponse =
                    NetworkResponse.Success(ccReaderData);

                var statusProvider = S <ISystemStatusProvider>();

                statusProvider.Stub(x => x.GetSystemStatus()).Return(masterModel);

                var ccReader = S <ICcReader>();

                ccReader.Stub(x => x.GetStatus("http://www.example.com/1")).Return(ccReaderResponse);

                var mapper = S <IMapper>();

                mapper.Stub(x => x.Map <Projects, CcProjectCollectionViewModel>(ccReaderData)).Return(mappedData);

                var provider = new CruiseProjectModelProvider(ccReader, mapper, statusProvider);

                _result = provider.GetProjects(server1.Id);
            }
コード例 #3
0
ファイル: DatabaseControl.cs プロジェクト: ignatisD/firefps
    public IEnumerator storeDataRequest(string _email, string _password, Player _player)
    {
        // Create a form object
        WWWForm form = new WWWForm();

        form.AddField("email", _email);
        form.AddField("password", _password);
        form.AddField("userdata", _player.userdata);
        form.AddField("action", "store");

        // Create a download object
        WWW returned = new WWW(account_api, form);

        // Wait until the download is done
        yield return(returned);

        if (!string.IsNullOrEmpty(returned.error))
        {
            Debug.Log("Error downloading: " + returned.error);
            yield break;
        }
        // Debug.Log(returned.text);
        NetworkResponse             response = JsonUtility.FromJson <NetworkResponse>(returned.text);
        Dictionary <string, string> results  = response.ToDictionary();

        if (results["success"] != "true")
        {
            Debug.Log(results["errors"]);
        }
    }
コード例 #4
0
    public void ProcessUpdateTime(NetworkResponse response)
    {
        ResponseUpdateTime args = response as ResponseUpdateTime;

        currentTime = (args.day - 1) * Constants.MONTH_DURATION / 30;
        scale       = args.rate;
    }
コード例 #5
0
 public void readSocket()
 {
     if (!socketReady)
     {
         return;
     }
     if (theStream != null && theStream.DataAvailable)
     {
         byte[] buffer = new byte[2];
         theStream.Read(buffer, 0, 2);
         short bufferSize = BitConverter.ToInt16(buffer, 0);
         buffer = new byte[bufferSize];
         theStream.Read(buffer, 0, bufferSize);
         MemoryStream    dataStream  = new MemoryStream(buffer);
         short           response_id = DataReader.ReadShort(dataStream);
         NetworkResponse response    = NetworkResponseTable.get(response_id);
         if (response != null)
         {
             response.dataStream = dataStream;
             response.parse();
             ExtendedEventArgs args = response.process();
             if (args != null)
             {
                 MessageQueue msgQueue = mainObject.GetComponent <MessageQueue>();
                 msgQueue.AddMessage(args.event_id, args);
             }
         }
     }
 }
コード例 #6
0
ファイル: Chat.cs プロジェクト: hunvil/ConvergeGame_Client
    public void ProcessMessage(NetworkResponse response)
    {
        ResponseMessage args = response as ResponseMessage;
        string message = "";

        if (args.status == 0) {
            message = "";

            if (args.type == 0) {
                if (args.username.Equals(GameState.player.name)) {
                    return;
                }

                message += "[" + args.username + "] says: ";
            } else if (args.type == 2) {
                message += "Whisper from [" + args.username + "]: ";
            }

            message += args.message;
            SetMessage(message);
        } else if (args.status == 1) {
            message = "Whisper failed.";
            SetMessage(message);
        }
    }
コード例 #7
0
    public void ProcessDealCard(NetworkResponse response)
    {
        ResponseDealCard args = response as ResponseDealCard;

        Debug.Log("DealCard status" + args.status);
        // TODO:
        //dealDummyCard(1);
    }
コード例 #8
0
ファイル: iApp.cs プロジェクト: Zebra/iFactr-Android
 /// <summary>
 /// Posts the specified network response.
 /// </summary>
 /// <param name="networkResponse">The network response to post.</param>
 public static void PostNetworkResponse(NetworkResponse networkResponse)
 {
     if (networkResponse == null)
     {
         return;
     }
     TargetFactory.HandleNetworkResponse(networkResponse);
 }
コード例 #9
0
    public void ProcessPrediction(NetworkResponse response)
    {
        ResponsePrediction args = response as ResponsePrediction;

        if (args.status == 0) {
            results = args.results;
        }
    }
コード例 #10
0
    public void ProcessLogout(NetworkResponse response)
    {
        ResponseLogout args = response as ResponseLogout;

        //act on logout regardless of response
        Application.Quit();
        Game.SwitchScene("Login");
    }
コード例 #11
0
        public NetworkResponse invokeTransaction(JObject action, List <byte[]> privatekeys, bool preExec)
        {
            Core.Transaction tx = Core.TransactionBuilder.MakeInvokeTransaction(action);
            sign(tx, privatekeys);
            NetworkResponse result = send(tx.toHexString(), preExec);

            return(result);
        }
コード例 #12
0
        /// <inheritdoc />
        public async Task CreateAsync(CancellationToken ct = default)
        {
            var id = await this.client.CreateAsync(this.configuration, ct)
                     .ConfigureAwait(false);

            this.network = await this.client.ByIdAsync(id, ct)
                           .ConfigureAwait(false);
        }
コード例 #13
0
            public void ContextSetup()
            {
                var masterModel = new MasterModel();

                _project1 = masterModel.CreateProject(); //1
                _project2 = masterModel.CreateProject(); //2

                var server1 = masterModel.CreateCruiseServer(x =>
                {
                    x.Url  = "http://www.example.com/1";
                    x.Name = "1";
                });
                var server2 = masterModel.CreateCruiseServer(x =>
                {
                    x.Url  = "http://www.example.com/2";
                    x.Name = "2";
                });

                var statusProvider = S <ISystemStatusProvider>();

                statusProvider.Stub(x => x.GetSystemStatus())
                .Return(masterModel);

                var cruiseProjectProvider = S <ICruiseProjectModelProvider>();
                var projectResponse1      = NetworkResponse.Success(new CcProjectCollectionViewModel
                {
                    Items = new[] { new CcProjectViewModel {
                                        Name = "1.1"
                                    }, new CcProjectViewModel {
                                        Name = "1.2"
                                    } }
                });
                var projectResponse2 = NetworkResponse.Success(new CcProjectCollectionViewModel
                {
                    Items = new[] { new CcProjectViewModel {
                                        Name = "2.1"
                                    }, new CcProjectViewModel {
                                        Name = "2.2"
                                    } }
                });

                cruiseProjectProvider.Stub(x => x.GetProjects(server1.Id)).Return(projectResponse1);
                cruiseProjectProvider.Stub(x => x.GetProjects(server2.Id)).Return(projectResponse2);

                var mapper = new StubMapper()
                             .StubResult(new[]
                {
                    new EditProjectCruiseServerViewModel {
                        Url = "Mapped 1", Id = server1.Id
                    },
                    new EditProjectCruiseServerViewModel {
                        Url = "Mapped 2", Id = server2.Id
                    }
                });
                var provider = new AdminViewModelProvider(statusProvider, mapper, cruiseProjectProvider);

                _result = provider.GetEditProjectViewModel(null);
            }
コード例 #14
0
ファイル: GameState.cs プロジェクト: ssammi/wobspring2015
    public void ProcessEcosystem(NetworkResponse response)
    {
        ResponseEcosystem args = response as ResponseEcosystem;

        if (args.status == 0)
        {
            GameState.ecosystem = args.ecosystem;
        }
    }
コード例 #15
0
    public List <NetworkResponse> Read(int numPackets = 20)
    {
        List <NetworkResponse> responses = new List <NetworkResponse>();

        while (theStream.DataAvailable && responses.Count < numPackets)
        {
            byte[] buffer = new byte[2];
            theStream.Read(buffer, 0, 2);
            short bufferSize = BitConverter.ToInt16(buffer, 0);

            buffer = new byte[bufferSize];
            //to allow for network latency, check number of bytes read and continue reading
            //until expected data is received
            int bytesRead = 0;
            int counter   = 0;
            do
            {
                bytesRead += theStream.Read(buffer, bytesRead, bufferSize - bytesRead);
                counter++;
            }while(bytesRead < bufferSize);
            MemoryStream dataStream = new MemoryStream(buffer);

            short protocol_id = DataReader.ReadShort(dataStream);
            Type  pType       = NetworkProtocolTable.Get(protocol_id);
            if (counter > 1)
            {
                Debug.Log(string.Format(
                              "Note, network latency issue identified, wait count = {0}, protocol ID = {1}",
                              counter,
                              protocol_id
                              ));
            }
            //output packet-level info to screen for debugging purposes
            //DebugPacket (buffer, true, false);

            if (pType == null)
            {
                Debug.LogError("Invalid Response No. " + protocol_id + " [" + "Unknown" + "]");
            }
            else
            {
                try {
                    NetworkResponse args = pType.GetMethod("Parse").Invoke(null, new object[] { dataStream }) as NetworkResponse;

                    if (args != null)
                    {
                        responses.Add(args);
                    }
                } catch (Exception ex) {
                    Debug.LogError("Failed Response No. " + protocol_id + " [" + pType.ToString() + "]");
                    Debug.LogException(ex);
                }
            }
        }

        return(responses);
    }
コード例 #16
0
        /// <summary>
        /// Queries by Name
        /// </summary>
        private void GetByName()
        {
            NetworkResponse networkResponse =
                RecoveryServicesClient.GetAzureSiteRecoveryNetwork(
                    Utilities.GetValueFromArmId(this.Server.ID, ARMResourceTypeConstants.ReplicationFabrics),
                    this.Name);

            this.WriteNetwork(networkResponse.Network);
        }
コード例 #17
0
        public void CompleteRequest(TimedObject <NetworkRequest> request, NetworkResponse response)
        {
            lock (timedRequestManager.timedObjects)
            {
                timedRequestManager.FinishTimedObject(request);
            }

            request.obj.ExecuteResponseHandlers(response);
        }
コード例 #18
0
        protected override void ProcessResponse(NetworkResponse networkResponse)
        {
            var response = networkResponse as CommandNetworkResponse;

            if (Command != null && Command is IHandlesResponse responseHandler)
            {
                responseHandler.Handle(response.Content);
            }
        }
コード例 #19
0
    // transfer fund to another address, signed by privatekey
    public static void transfer()
    {
        NetworkResponse result = OntSDK.transfer("ONG", from, to, 5, payer, 20000, 500, new List <byte[]>()
        {
            Helper.HexString2Bytes(privatekey)
        }, true);

        Console.WriteLine(result.JobjectResponse);
    }
コード例 #20
0
    public void ProcessPrediction(NetworkResponse response)
    {
        ResponsePrediction args = response as ResponsePrediction;

        if (args.status == 0)
        {
            results = args.results;
        }
    }
コード例 #21
0
        //preExec = true, for check this transaction
        public NetworkResponse transfer(string name, string from, string to, long value, string payer, uint gasLimit, uint gasPrice, List <byte[]> privatekeys, bool preExec)
        {
            Core.Transaction tx = Core.TransactionBuilder.MakeTransferTransaction(name, from, to, value, payer, gasLimit, gasPrice);
            sign(tx, privatekeys);

            NetworkResponse result = send(tx.toHexString(), preExec);

            return(result);
        }
コード例 #22
0
        /// <summary>
        /// Queries by Name
        /// </summary>
        private void GetByName()
        {
            NetworkResponse networkResponse =
                RecoveryServicesClient.GetAzureSiteRecoveryNetwork(
                    this.Fabric.Name,
                    this.Name);

            this.WriteNetwork(networkResponse.Network);
        }
コード例 #23
0
ファイル: CacheIndex.cs プロジェクト: BenButzer/iFactr-Data
        /// <summary>
        /// Gets the name of the file.
        /// </summary>
        /// <param name="cacheIndexItem">The cache index item.</param>
        /// <param name="networkResponse">The network response.</param>
        /// <returns></returns>
        public string GetFileName(CacheIndexItem cacheIndexItem, out NetworkResponse networkResponse)
        {
            NetworkResourceArguments args = new NetworkResourceArguments()
            {
                Headers = Device.RequestInjectionHeaders
            };

            return(GetFileName(cacheIndexItem, args, out networkResponse));
        }
コード例 #24
0
ファイル: Program.cs プロジェクト: naib864/Remake-Core
        public async static Task HandleParsed(ValidateEventCommand parsed)
        {
            Api api = new Api();

            api.SetToken(parsed.Token);

            NetworkResponse <GameEventResponse> gameEvents = await api.GetGameEvents(Int32.Parse(parsed.GameId));

            Console.WriteLine("Done");
        }
コード例 #25
0
    // Updates player's credits
    public void ProcessEndGame(NetworkResponse response)
    {
        ResponsePlayGame args = response as ResponsePlayGame;

        if (args.status == 1)
        {
            GameState.player.credits = args.creditDiff;
            Debug.Log(args.creditDiff);
        }
    }
コード例 #26
0
    public void ProcessMatchInit(NetworkResponse response)
    {
        ResponseMatchInit args = response as ResponseMatchInit;

        if (args.status == 0)
        {
            GameState.matchID = args.matchID;
            Debug.Log("MatchID set to: " + args.matchID);
        }
    }
コード例 #27
0
    public void ProcessHeartbeat(NetworkResponse response)
    {
        if (!lostConnection) {
            Debug.LogWarning ("Lost connection!");

            gameObject.AddComponent ("ConnectionLostGUI");

            lostConnection = true;
        }
    }
コード例 #28
0
    // DH change
    public void MCProcessMatchInit(NetworkResponse response)
    {
        ResponseMCMatchInit args = response as ResponseMCMatchInit;

        if (args.status == 0)
        {
            Debug.Log("MC MatchID set to: " + args.matchID + " Player id is: " + GameState.player.GetID());
            Game.SwitchScene("MultiConverge");
        }
    }
コード例 #29
0
    // Updates player's credits
    public void ProcessEndGame(NetworkResponse response)
    {
        ResponsePlayGame args = response as ResponsePlayGame;

        if (args.status == 1) {

            GameState.player.credits = args.creditDiff;
            Debug.Log (args.creditDiff);
        }
    }
コード例 #30
0
ファイル: Login.cs プロジェクト: dkushner/wobspring2015
    public void ProcessPlayerSelect(NetworkResponse response)
    {
        ResponsePlayerSelect args = response as ResponsePlayerSelect;

        if (args.status == 0)
        {
            GameState.player = args.player;
            Game.SwitchScene("Converge");             //"World");
        }
    }
コード例 #31
0
    public void OnQuitRoomResult(NetworkResponse response)
    {
        this.enableRRButton = true;
        this.enableCWButton = true;
        this.waiting = false;

        RoomManager.getInstance().removePlayer(GameState.account.account_id);
        if (quiting) {
            Destroy (this);
        }
    }
コード例 #32
0
ファイル: Login.cs プロジェクト: ssammi/wobspring2015
    public void ProcessPlayerSelect(NetworkResponse response)
    {
        ResponsePlayerSelect args = response as ResponsePlayerSelect;

        if (args.status == 0)
        {
            GameState.player = args.player;
            //Game.SwitchScene("Converge"); //"World");
            Application.LoadLevel("ClashSplash");
        }
    }
コード例 #33
0
        public static string GetUserCustomTag([NotNull] string steamId)
        {
            NetworkResponse response = SendClientRequest($"GETCUSTOMTAG {steamId} Plugin");

            if (response != null && !string.IsNullOrEmpty(response.content))
            {
                return(response.content);
            }

            return(null);
        }
コード例 #34
0
        public void OnClientResponse(ClientController controller, NetworkResponse response)
        {
            Debug($"Response ({response.id}): \"{response.content}\"");

            TimedObject <NetworkRequest> request = controller.GetRequest(response.id);

            if (request != null)
            {
                controller.CompleteRequest(request, response);
            }
        }
コード例 #35
0
    public void ProcessHeartbeat(NetworkResponse response)
    {
        if (!lostConnection)
        {
            Debug.LogWarning("Lost connection!");

            gameObject.AddComponent <ConnectionLostGUI>();

            lostConnection = true;
        }
    }
コード例 #36
0
    public void ProcessWorld(NetworkResponse response)
    {
        ResponseWorld args = response as ResponseWorld;

        if (args.status == 0) {
            GameState.world = args.world;

            SwitchToTileSelect(1);

            LoadComponents();
        }
    }
コード例 #37
0
    public void ProcessPlayGame(NetworkResponse response)
    {
        ResponsePlayGame args = response as ResponsePlayGame;

        if (args.status == 1) {
            GameState.player.credits -= 10;
            Destroy (this);
            Game.SwitchScene ("DontEatMe");
        } else {
            Debug.Log ("Not enough credits");
        }
    }
コード例 #38
0
 public override Response ParseNetworkResponse(NetworkResponse response)
 {
     lock (sDecodeLock)
     {
         try
         {
             return DoParse(response);
         }
         catch (Java.Lang.OutOfMemoryError e)
         {
             VolleyLog.E("Caught OOM for {0} byte image,url={1}", response.Data.Length, Url);
             return Response.Error(new ParseError(e));
         }
     }
 }
コード例 #39
0
    public void OnPairResult(NetworkResponse response)
    {
        ResponsePair args = response as ResponsePair;
        int userID = GameState.account.account_id;

        if (args.status == 0) {
            Debug.Log("All players are ready to play [room id=" + args.id + "]");
            this.room_id = args.id;

            this.enableRRButton = true;
            this.enableCWButton = true;

            var room = RoomManager.getInstance().getRoom(args.id);
            if (!room.containsPlayer(userID)) {
                room.addPlayer(userID);
            }

            // switch scene
            if (args.gameID == Constants.MINIGAME_RUNNING_RHINO) {
                RR.RRConnectionManager cManager = RR.RRConnectionManager.getInstance();
                cManager.Send (RR_RequestRaceInit ());

                Game.SwitchScene ("RRReadyScene");
            } else if (args.gameID == Constants.MINIGAME_CARDS_OF_WILD) {
                CW.GameManager.matchID = args.id;
                CW.NetworkManager.Send (CW.MatchInitProtocol.Prepare
                                        (GameState.player.GetID(), args.id),
                                        ProcessMatchInit);
            }
        } else {
            Debug.Log("New room allocated [room id=" + args.id + "]");
            var room = RoomManager.getInstance().addRoom(args.id, args.gameID);
            room.host = GameState.player.GetName();
            room.addPlayer(userID);

            this.enableRRButton = false;
            this.enableCWButton = false;
            this.waiting = true;
        }
    }
コード例 #40
0
ファイル: Login.cs プロジェクト: hunvil/ConvergeGame_Client
    public void ProcessLogin(NetworkResponse response)
    {
        ResponseLogin args = response as ResponseLogin;

        if (args.status == 0) {
            GameState.account = args.account;

            NetworkManager.Send(
                TopListProtocol.Prepare(),
                ProcessTopList
                );
            NetworkManager.Send(
                PlayerSelectProtocol.Prepare(0),
                ProcessPlayerSelect
                );
            CW.NetworkManager.Send(
                CW.PlayerSelectProtocol.Prepare(0),
                CW_ProcessPlayerSelect
                );
        } else {
            Debug.Log ("login failed, server message = " + args.status);
            //mainObject.GetComponent<Main>().CreateMessageBox("Login Failed");
        }
    }
コード例 #41
0
        public NetworkResponse Fetch( string uri, string filename, Dictionary<string, string> headers )
        {
            #if SILVERLIGHT || MONO
            throw new NotSupportedException("FetcherSynch is not supported in Silverlight");
            #else
            NetworkResponse networkResponse = new NetworkResponse()
            {
                URI = uri,
                Verb = "GET"
            };

            DateTime dtMetric = DateTime.UtcNow;

            Stream stream = null;
            StreamReader reader = null;
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            try
            {
                request = (HttpWebRequest) WebRequest.Create( uri );
                request.Method = "GET";
                request.AutomaticDecompression = DecompressionMethods.Deflate;

                //// If required by the server, set the credentials.
                //request.Credentials = CredentialCache.DefaultCredentials;

                // To-Do: Refactor this central storage of header values to inject into an abstract network object.
                if ( headers != null && headers.Count() > 0 )
                {
                    foreach ( string key in headers.Keys )
                    {
                        request.Headers[key] = headers[key];
                    }
                }

                #region Get Response state from Response stream

                response = (HttpWebResponse) request.GetResponse();

                networkResponse.StatusCode = response.StatusCode;

                switch ( response.StatusCode )
                {
                    case HttpStatusCode.OK:
                    case HttpStatusCode.Created:
                    case HttpStatusCode.Accepted:
                        break;
                    case HttpStatusCode.NoContent:
                        networkResponse.Expiration = DateTime.UtcNow;
                        networkResponse.Message = String.Format( "No Content returned: Result {0} for {1}", response.StatusCode, uri );
                        MXDevice.Log.Warn( networkResponse.Message );
                        break;
                    default:
                        networkResponse.Expiration = DateTime.UtcNow;
                        networkResponse.Message = String.Format( "{0} failed. Received HTTP {1} for {2}", request.Method, response.StatusCode, uri );
                        MXDevice.Log.Error( networkResponse.Message );
                        return networkResponse;
                }

                // extract response into bytes and string.
                WebResponse webResponse = NetworkUtils.ExtractResponse( response, filename );
                networkResponse.ResponseBytes = webResponse.ResponseBytes;
                networkResponse.ResponseString = webResponse.ResponseString;

                MXDevice.Log.Debug( string.Format( "Fetch Completed: Uri: {0} Time: {1} milliseconds  Size: {2} ", uri, DateTime.UtcNow.Subtract( dtMetric ).TotalMilliseconds, ( networkResponse.ResponseBytes != null ? networkResponse.ResponseBytes.Length : -1 ) ) );

                #endregion

                networkResponse.Expiration = response.Headers["Expires"].TryParseDateTimeUtc();
            }
            catch ( WebException ex )
            {
                ex.Data.Add( "Uri", networkResponse.URI );
                ex.Data.Add( "Verb", networkResponse.Verb );

                networkResponse.Message = string.Format( "Call to {0} had a Webexception. {1}   Status: {2}   Desc: {3}", networkResponse.URI, ex.Message, ex.Status, ( (HttpWebResponse) ex.Response ).StatusDescription );

                networkResponse.StatusCode = ( (HttpWebResponse) ex.Response ).StatusCode;
                ex.Data.Add( "StatusCode", networkResponse.StatusCode );
                ex.Data.Add( "StatusDescription", ( (HttpWebResponse) ex.Response ).StatusDescription );

                networkResponse.Exception = ex;
                networkResponse.Expiration = DateTime.UtcNow;

                MXDevice.Log.Error( networkResponse.Message );
                MXDevice.Log.Error( ex );
            }
            catch ( Exception ex )
            {
                ex.Data.Add( "Uri", networkResponse.URI );
                ex.Data.Add( "Verb", networkResponse.Verb );

                networkResponse.Message = string.Format( "Call to {0} had an Exception. {1}", networkResponse.URI, ex.Message );
                networkResponse.Exception = ex;
                networkResponse.StatusCode = (HttpStatusCode) ( -1 );
                networkResponse.Expiration = DateTime.UtcNow;

                MXDevice.Log.Error( networkResponse.Message );
                MXDevice.Log.Error( ex );
            }
            finally
            {
                // Cleanup the streams and the response.
                if ( reader != null )
                    reader.Close();
                if ( stream != null )
                    stream.Close();
                if ( response != null )
                    response.Close();
            }

            return networkResponse;

            #endif
        }
コード例 #42
0
        public NetworkResponse PostBytes( string uri, byte[] postBytes, string contentType, string verb, Dictionary<string, string> headers )
        {
            #if !SILVERLIGHT && !MONO

            // Create the request obj
            HttpWebRequest request = (HttpWebRequest) WebRequest.Create( uri );

            // Set values for the request back
            request.Method = verb;  // "POST";
            request.ContentType = contentType;
            request.ContentLength = postBytes.Length;
            request.AutomaticDecompression = DecompressionMethods.Deflate;

            NetworkResponse networkResponse = new NetworkResponse()
            {
                URI = request.RequestUri.AbsoluteUri,
                Verb = verb
            };
            DateTime dtMetric = DateTime.UtcNow;

            Stream postStream = null;

            HttpWebResponse response = null;
            Stream streamResponse = null;
            StreamReader streamRead = null;
            try
            {
                #region Send Post object to Request stream

                // To-Do: Refactor this central storage of header values to inject into an abstract network object.
                if ( headers != null && headers.Count() > 0 )
                {
                    foreach ( string key in headers.Keys )
                    {
                        request.Headers[key] = headers[key];
                    }
                }

                postStream = request.GetRequestStream();
                postStream.Write( postBytes, 0, postBytes.Length );
                postStream.Close();

                #endregion

                #region Get Response state from Response stream

                response = (HttpWebResponse) request.GetResponse();

                networkResponse.StatusCode = response.StatusCode;

                switch ( response.StatusCode )
                {
                    case HttpStatusCode.OK:
                    case HttpStatusCode.Created:
                    case HttpStatusCode.Accepted:
                        break;
                    case HttpStatusCode.NoContent:
                        networkResponse.Expiration = DateTime.UtcNow;
                        networkResponse.Message = String.Format( "No Content returned: Result {0} for {1}", response.StatusCode, uri );
                        MXDevice.Log.Warn( networkResponse.Message );
                        break;
                    default:
                        networkResponse.Expiration = DateTime.UtcNow;
                        networkResponse.Message = String.Format( "{0} failed. Received HTTP {1} for {2}", request.Method, response.StatusCode, uri );
                        MXDevice.Log.Error( networkResponse.Message );
                        return networkResponse;
                }

                // extract response into bytes and string.
                WebResponse webResponse = NetworkUtils.ExtractResponse( response );
                networkResponse.ResponseBytes = webResponse.ResponseBytes;
                networkResponse.ResponseString = webResponse.ResponseString;

                MXDevice.Log.Debug( string.Format( "PostBytes Completed: Uri: {0} Time: {1} milliseconds  Size: {2} ", uri, DateTime.UtcNow.Subtract( dtMetric ).TotalMilliseconds, ( networkResponse.ResponseBytes != null ? networkResponse.ResponseBytes.Length : -1 ) ) );

                // set expiration values
                networkResponse.Expiration = response.Headers["Expires"].TryParseDateTimeUtc();

                #endregion

            }
            catch ( WebException ex )
            {
                ex.Data.Add( "ResponseStatusCode", ex.Status );
                ex.Data.Add( "Uri", request.RequestUri );
                ex.Data.Add( "Verb", request.Method );

                MXDevice.Log.Error( string.Format( "Call to {0} had a Webexception. {1}  Status: {2}", request.RequestUri, ex.Message, ex.Status ) );
                MXDevice.Log.Error( ex );

                networkResponse.ResponseBytes = null;
                networkResponse.ResponseString = null;
                networkResponse.Expiration = DateTime.MinValue.ToUniversalTime();

                networkResponse.StatusCode = ( (HttpWebResponse) ex.Response ).StatusCode;
                ex.Data.Add( "StatusCode", networkResponse.StatusCode );
                ex.Data.Add( "StatusDescription", ( (HttpWebResponse) ex.Response ).StatusDescription );

                networkResponse.Message = ex.Message;
                networkResponse.Exception = ex;

            }
            catch ( Exception ex )
            {
                ex.Data.Add( "Uri", request.RequestUri );
                ex.Data.Add( "Verb", request.Method );

                networkResponse.ResponseBytes = null;
                networkResponse.ResponseString = null;
                networkResponse.Expiration = DateTime.MinValue.ToUniversalTime();
                networkResponse.StatusCode = (HttpStatusCode) ( -1 );
                networkResponse.Message = ex.Message;
                networkResponse.Exception = ex;
            }
            finally
            {
                // Close the stream object
                if ( streamResponse != null )
                    streamResponse.Close();

                if ( streamRead != null )
                    streamRead.Close();

                // Release the HttpWebResponse
                if ( response != null )
                    response.Close();
            }

            return networkResponse;
            #else
                   throw new NotSupportedException("PosterSynch is not supported in Silverlight");
            #endif
        }
コード例 #43
0
ファイル: Clock.cs プロジェクト: hunvil/ConvergeGame_Client
 public void ProcessUpdateTime(NetworkResponse response)
 {
     ResponseUpdateTime args = response as ResponseUpdateTime;
     currentTime = (args.day - 1) * Constants.MONTH_DURATION / 30;
     scale = args.rate;
 }
コード例 #44
0
 public void ProcessConvergeEcosystems(NetworkResponse response)
 {
     ResponseConvergeEcosystems args = response as ResponseConvergeEcosystems;
     ecosystemList = args.ecosystemList;
 }
コード例 #45
0
ファイル: Login.cs プロジェクト: hunvil/ConvergeGame_Client
    public void ProcessPlayerSelect(NetworkResponse response)
    {
        ResponsePlayerSelect args = response as ResponsePlayerSelect;

        if (args.status == 0) {
            isActive = false;
            GameState.player = args.player;
            playerRank = PlayerIsTop(user_id);
        }
    }
コード例 #46
0
        public NetworkResponse PostBytes( string uri, byte[] postBytes, string contentType, string verb, Dictionary<string, string> headers )
        {
            PostNetworkResponse = new NetworkResponse();
            RequestParameters requestParameters = new RequestParameters()
            {
                PostBytes = postBytes,
                Uri = uri,
                Headers = headers,
                ContentType = contentType,
                Verb = verb
            };
            DateTime dtMetric = DateTime.UtcNow;

            // set callback and error handler
            OnComplete += new PostRequestEventHandler( PostRequest_OnComplete );
            OnError += new PostRequestErrorHandler( PostRequest_OnError );

            System.Threading.ThreadPool.QueueUserWorkItem( parameters =>
            {
                try
                {
                    RequestAsynch( parameters );
                }
                //catch ( Exception e )
                //{
                //    // You could react or save the exception to an 'outside' variable 
                //    // threadExc = e;    
                //}
                finally
                {
                    autoEvent.Set(); // if you're firing and not forgetting ;)    
                }
            }, requestParameters );

            // WaitOne returns true if autoEvent were signaled (i.e. process completed before timeout expired)
            // WaitOne returns false it the timeout expired before the process completed.
            if ( !autoEvent.WaitOne( DefaultTimeout ) )
            {
                //throw TimeoutException( "Waited ages for a thread to come in." );
                string message = "PosterAsynch call to RequestAsynch timed out. uri " + requestParameters.Uri;
                MXDevice.Log.Error( message );

                MXDevice.Log.Debug( string.Format( "PosterAsynch timed out: Uri: {0} Time: {1} milliseconds ", uri, DateTime.UtcNow.Subtract( dtMetric ).TotalMilliseconds ) );

                NetworkResponse networkResponse = new NetworkResponse()
                {
                    Message = message,
                    URI = requestParameters.Uri,
                    StatusCode = HttpStatusCode.RequestTimeout,
                    ResponseString = string.Empty,
                    Expiration = DateTime.MinValue.ToUniversalTime(),
                };

                MXDevice.PostNetworkResponse( networkResponse );
                return networkResponse;
            }

            //if ( threadExc != null )
            //{
            //    throw threadExc;
            //}
            MXDevice.Log.Debug( string.Format( "PosterAsynch Completed: Uri: {0} Time: {1} milliseconds  Size: {2} ", uri, DateTime.UtcNow.Subtract( dtMetric ).TotalMilliseconds, ( PostNetworkResponse.ResponseBytes != null ? PostNetworkResponse.ResponseBytes.Length : -1 ) ) );

            return PostNetworkResponse;
        }
コード例 #47
0
        private Response DoParse(NetworkResponse response)
        {
            byte[] data = response.Data;
            BitmapFactory.Options decodeOption = new BitmapFactory.Options();
            Bitmap bitmap = null;
            if (mMaxWidth == 0 && mMaxHeight == 0)
            {
                decodeOption.InPreferredConfig = mDecodeConfig;
                bitmap = BitmapFactory.DecodeByteArray(data, 0, data.Length, decodeOption);
            }
            else
            {
                decodeOption.InJustDecodeBounds = true;
                BitmapFactory.DecodeByteArray(data, 0, data.Length, decodeOption);
                int actualWidth = decodeOption.OutWidth;
                int actualHeight = decodeOption.OutHeight;

                int desiredWidth = GetResizedDimension(mMaxWidth, mMaxHeight, actualWidth, actualHeight, mScaleType);
                int desiredHeight = GetResizedDimension(mMaxHeight, mMaxWidth, actualHeight, actualWidth, mScaleType);

                decodeOption.InJustDecodeBounds = false;
                decodeOption.InSampleSize = FindBestSampleSize(actualWidth, actualHeight, desiredWidth, desiredHeight);
                Bitmap tempBitmap = BitmapFactory.DecodeByteArray(data, 0, data.Length, decodeOption);

                if (tempBitmap != null && (tempBitmap.Width > desiredWidth || tempBitmap.Height > desiredHeight))
                {
                    bitmap = Bitmap.CreateScaledBitmap(tempBitmap, desiredWidth, desiredHeight, true);
                    tempBitmap.Recycle();
                }
                else
                {
                    bitmap = tempBitmap;
                }
            }

            if (bitmap == null)
            {
                return Response.Error(new ParseError(response));
            }
            else
            {
                return Response.Success(bitmap, HttpHeaderParser.ParseCacheHeaders(response));
            }
        }
コード例 #48
0
    public void ProcessConvergeNewAttempt(NetworkResponse response)
    {
        ConvergeAttempt attempt;
        ResponseConvergeNewAttempt args = response as ResponseConvergeNewAttempt;
        attempt = args.attempt;

        //if the submission resulted in a valid attempt, add to attempt list and reinitialize
        //currAttempt for next attempt.  Otherwise, keep current attempt
        if (attempt != null && attempt.attempt_id != Constants.ID_NOT_SET) {
            currAttempt.attempt_id = attempt.attempt_id;
            currAttempt.SetCSV (attempt.csv_string);
            attemptList.Add (currAttempt);
            attemptCount = attemptList.Count;

            //calculate score and send back to server.
            CSVObject target = ecosystemList[ecosystem_idx].csv_target_object;
            int score = currAttempt.csv_object.CalculateScore (target);
            NetworkManager.Send (
                ConvergeNewAttemptScoreProtocol.Prepare (
                player_id,
                ecosystem_id,
                attempt.attempt_id,
                score
                ),
                ProcessConvergeNewAttemptScore
                );

            //update pertinent variables with new data
            if (currAttempt.hint_id != Constants.ID_NOT_SET) {
                priorHintIdList.Add (currAttempt.hint_id);
            }
            //need to recalc reset slider config due to additional attempt
            isResetSliderInitialized = false;

            if (barGraph != null) {
                barGraph.InputToCSVObject (currAttempt.csv_string, manager);
            }

            currAttempt = new ConvergeAttempt (
                player_id,
                ecosystem_id,
                attempt.attempt_id + 1,
                allowHintsMaster,
                Constants.ID_NOT_SET,
                attempt.config,
                null
                //manager
            );

            FinalizeAttemptUpdate (attemptCount - 1, false);
        } else {
            Debug.LogError ("Submission of new attempt failed to produce results.");
            SetIsProcessing (false);
        }
    }
コード例 #49
0
    public void ProcessConvergePriorAttempt(NetworkResponse response)
    {
        ResponseConvergePriorAttempt args = response as ResponseConvergePriorAttempt;
        ConvergeAttempt attempt = args.attempt;

        //add new attempt to list if response includes an attempt
        if (attempt.attempt_id == Constants.ID_NOT_SET) {
            Debug.LogError ("attempt_id not valid in ProcessConvergePriorAttempt");
        } else {
            attemptList.Add (attempt);
            if (attempt.hint_id != Constants.ID_NOT_SET) {
                priorHintIdList.Add (attempt.hint_id);
            }
        }

        //Once all attempts have been processed, finalize.
        if (attemptList.Count == attemptCount) {
            FinalizeLoadPriorAttempts ();
        }
    }
コード例 #50
0
    public void ProcessUpdateEcoScore(NetworkResponse response)
    {
        ResponseUpdateEnvScore args = response as ResponseUpdateEnvScore;

        SetScore(args.score);
    }
コード例 #51
0
    public void ProcessConvergePriorAttemptCount(NetworkResponse response)
    {
        ResponseConvergePriorAttemptCount args = response as ResponseConvergePriorAttemptCount;
        new_ecosystem_id = args.ecosystem_id;
        attemptCount = args.count;
        priorHintIdList = new List<int>();
        isResetSliderInitialized = false;

        //once count of attempts has been received, send requests for individual attempt's data
        for (int attemptOffset = 0; attemptOffset < attemptCount; attemptOffset++) {
            NetworkManager.Send (
                ConvergePriorAttemptProtocol.Prepare (player_id, new_ecosystem_id, attemptOffset),
                ProcessConvergePriorAttempt
            );
            //Debug.Log ("Send RequestConvergePriorAttempt");
        }

        UpdateEcosystemIds ();

        //if no prior attempts found create new curAttempt based on default config
        //of curr ecosystem
        if (attemptCount == 0) {
            FinalizeLoadPriorAttempts ();
        }
    }
コード例 #52
0
ファイル: Login.cs プロジェクト: hunvil/ConvergeGame_Client
 public void ProcessTopList(NetworkResponse response)
 {
     ResponseTopList args = response as ResponseTopList;
     //client team -- use this data for the toplist functionality
     topPlayers = new string[3];
     topPlayers [0] = args.name1;
     topPlayers [1] = args.name2;
     topPlayers [2] = args.name3;
     Debug.Log ("rank 1 player: " + args.name1 + " with " + args.score1 + " points.");
     Debug.Log ("rank 2 player: " + args.name2 + " with " + args.score2 + " points.");
     Debug.Log ("rank 3 player: " + args.name3 + " with " + args.score3 + " points.");
 }
コード例 #53
0
ファイル: Map.cs プロジェクト: hunvil/ConvergeGame_Client
    public void ProcessZoneUpdate(NetworkResponse response)
    {
        ResponseZoneUpdate args = response as ResponseZoneUpdate;

        if (args.status == 0) {
        //			Debug.Log("update tile");
        //			var tile = (GameObject)zoneList[args.tile_id];
        //
        //			var oldOwner = tile.GetComponent<Zone>().player_id;
        //			Debug.Log("Old Owner: " + oldOwner);
        //			tile.GetComponent<Zone>().player_id = args.owner_id;
        //			var ownerID = tile.GetComponent<Zone>().player_id;
        //			Debug.Log("New Owner: " + ownerID);
        //			if (oldOwner == 0 )
        //			{
        //				GameObject tileOwnershipGameObject = GameObject.Instantiate(owned_tile) as GameObject;
        //				tileOwnershipGameObject.SetActive(true);
        //				tileOwnershipGameObject.transform.position = tile.transform.position;
        //				tileOwnershipGameObject.transform.parent = tile.transform;
        //				tileOwnershipGameObject.renderer.material = colorMats[playerList[ownerID].color - 1];
        //			}
        }
    }
コード例 #54
0
    //    void OnGUI() {
    //        windowRect = GUILayout.Window((int) Constants.GUI_ID.World_Menu, windowRect, MakeWindow, "World Menu");
    //        
    //        windowRect.x = (Screen.width - windowRect.width) / 2;
    //        windowRect.y = (Screen.height - windowRect.height) / 2;
    //    }
    //    
    //    void MakeWindow(int id) {
    //        avatarRect = new Rect(20, 30, 80, 80);
    //        GUI.Box(avatarRect, "");
    ////		GUI.DrawTexture(avatarRect, avatar);
    //        
    //        List<WorldData> wListSorted = new List<WorldData>(worldList.Values);
    //        
    //        Rect wListBox = new Rect(20, 120, 180, 30);
    //        GUI.Box(wListBox, "");
    //
    //        scrollViewVector = GUI.BeginScrollView(wListBox, scrollViewVector, new Rect(0, 0, wListBox.width - 16, wListBox.height * wListSorted.Count), false, true);
    //            for (int i = 0; i < wListSorted.Count; i++) {
    //                if (wListSorted[i] == worldSelected) {
    //                    GUI.backgroundColor = Color.black;
    //                }
    //
    //                if (GUI.Button(new Rect(0, i * 30, wListBox.width - 16, wListBox.height), wListSorted[i].name)) {
    //                    worldSelected = wListSorted[i];
    //                }
    //
    //                GUI.backgroundColor = Color.white;
    //            }
    //        GUI.EndScrollView();
    //        
    //        GUIStyle style = new GUIStyle();
    //
    //        if (avatarSelected != null) {
    //            style.alignment = TextAnchor.UpperLeft;
    //            style.normal.textColor = Color.white;
    //    
    //            GUI.Label(new Rect(115, 40, 100, 100), name, style);
    //            GUI.Label(new Rect(115, 60, 100, 100), "Level " + avatarSelected.level, style);
    //            
    //            style = new GUIStyle();
    //            style.alignment = TextAnchor.UpperRight;
    //            style.normal.textColor = Color.white;
    //            
    ////			GUI.Label(new Rect(170, 60, 100, 100), avatarSelected.coins + " Coins", style);
    //            
    //            style = new GUIStyle();
    //            style.alignment = TextAnchor.UpperCenter;
    //            style.normal.textColor = Color.white;
    //            
    //            GUI.Label(new Rect(140, 80, 100, 100), "Last Played on " + last_logout.Split(' ')[0], style);
    //        }
    //
    //        if (worldSelected != null) {
    //            style = new GUIStyle();
    //            style.alignment = TextAnchor.UpperLeft;
    //            style.normal.textColor = Color.white;
    //            
    //            GUI.Label(new Rect(20, 160, 100, 100), "Type " + (worldSelected.type + 1), style);
    //            GUI.Label(new Rect(20, 180, 100, 100), "Played " + (worldSelected.play_time / 3600).ToString() + ":" + (worldSelected.play_time % 3600 / 60).ToString().PadLeft(2, '0'), style);
    //    
    //            style = new GUIStyle();
    //            style.alignment = TextAnchor.UpperRight;
    //            style.normal.textColor = Color.white;
    //            
    //            GUI.Label(new Rect(100, 160, 100, 100), "Credits: " + worldSelected.credits, style);
    //            GUI.Label(new Rect(100, 180, 100, 100), "Score: " + worldSelected.score, style);
    //        }
    //
    //        GUILayout.Space(190);
    //
    //        for (int i = 0; i < 3; i++) {
    //            buttonRectList[i] = new Rect(windowRect.width - 85, 120 + i * 30, 75, 25);
    //        }
    //        
    //        if (GUI.Button(buttonRectList[0], "Join")) {
    //            Join();
    //        }
    //        
    //        if (GUI.Button(buttonRectList[1], "Create")) {
    //            Create();
    //        }
    //        
    //        if (GUI.Button(buttonRectList[2], "Delete")) {
    //            Delete();
    //        }
    //    }
    //    
    //    public void SetAvatarImage(string avatar_id) {
    //    }
    //    
    //    public void Create() {
    ////			RequestWorldMenuAction request = new RequestWorldMenuAction();
    ////			request.CreateAction(0, "", 1, "Savanna", 1, "");
    ////			
    ////			cManager.Send(request);
    ////			messageBox = mainObject.GetComponent<Main>().CreateMessageBox("Creating World...");
    //        
    //        // Get Default Species
    //        NetworkManager.Send(
    //            SpeciesActionProtocol.Prepare(0, 0),
    //            ProcessSpeciesAction
    //        );
    //    }
    //    
    //    public void Join() {
    //        ConnectionManager cManager = mainObject.GetComponent<ConnectionManager>();
    //        
    //        if (cManager) {
    ////			RequestWorldMenuAction request = new RequestWorldMenuAction();
    ////			request.JoinAction(worldSelected.world_id);
    ////			
    ////			cManager.Send(request);
    ////			messageBox = mainObject.GetComponent<Main>().CreateMessageBox("Joining World...");
    //        }
    //    }
    //
    //    public void Delete() {
    //        ConnectionManager cManager = mainObject.GetComponent<ConnectionManager>();
    //        
    //        if (cManager) {
    ////			RequestWorldMenuAction request = new RequestWorldMenuAction();
    ////			request.DeleteAction(worldSelected.world_id);
    ////			
    ////			cManager.Send(request);
    ////			messageBox = mainObject.GetComponent<Main>().CreateMessageBox("Deleting World...");
    //        }
    //    }
    //
    //    public void SwitchToLogin() {
    //        Destroy(this);
    //        GameObject.Find("LoginObject").GetComponent<Login>().Show();
    //    }
    //
    //    public void ResponseWorldMenuAction(NetworkResponse response) {
    ////		ResponseWorldMenuActionresponse args = response as ResponseWorldMenuActionresponse;
    ////
    ////		switch (args.action) {
    ////			case 1: // Create
    ////				if (args.status == 0) {
    ////					WorldData world = new WorldData(args.world_id);
    ////					world.name = args.name;
    ////					world.credits = args.credits;
    ////					world.month = args.month;
    ////		
    ////					worldList.Add(args.world_id, world);
    ////				}
    ////				break;
    ////			case 2: // Join
    ////				if (args.status == 0) {
    ////					WorldData world = new WorldData(args.world_id);
    ////					world.name = args.name;
    ////					world.credits = args.credits;
    ////					world.month = args.month;
    ////	
    ////					GameState.world = world;
    ////					Application.LoadLevel("World");//World
    ////				}
    ////				break;
    ////			case 3: // Delete
    ////				worldList.Remove(args.world_id);
    ////
    ////				if (worldList.Count > 0) {
    ////					worldSelected = new List<WorldData>(worldList.Values)[0];
    ////				}
    ////				break;
    ////			default:
    ////				break;
    ////		}
    //    }
    public void ProcessSpeciesAction(NetworkResponse response)
    {
        ResponseSpeciesAction args = response as ResponseSpeciesAction;

        if (args.action == 0) {
            Dictionary<int, int> speciesList = new Dictionary<int, int>();

            foreach (string item in args.selectionList.Split(',')) {
                string[] pair = item.Split(':');
                int species_id = int.Parse(pair[0]);
                int biomass = int.Parse(pair[1]);

                speciesList.Add(species_id, biomass);
                Debug.Log(species_id + " " + biomass);
            }

            NetworkManager.Send(
                SpeciesActionProtocol.Prepare(1, speciesList),
                ProcessSpeciesAction
            );
        }
    }
コード例 #55
0
 public void ProcessClient(NetworkResponse response)
 {
     ResponseClient args = response as ResponseClient;
     Constants.SESSION_ID = args.session_id;
 }
コード例 #56
0
    public void ProcessConvergeHintCount(NetworkResponse response)
    {
        ResponseConvergeHintCount args = response as ResponseConvergeHintCount;
        hintCount = args.count;

        //once count of hints has been received, send requests for individual hint's data
        for (int hintOffset = 0; hintOffset < hintCount; hintOffset++) {
            NetworkManager.Send (
                ConvergeHintProtocol.Prepare (hintOffset),
                ProcessConvergeHint
                );
            //Debug.Log ("Send RequestConvergeHint");
        }
    }
コード例 #57
0
    public void ProcessConvergeHint(NetworkResponse response)
    {
        ResponseConvergeHint args = response as ResponseConvergeHint;
        ConvergeHint hint = args.hint;

        if (hint == null) {
            Debug.LogError ("Returned hint not valid in ProcessConvergeHint");
        } else {
            hintDict.Add (hint.hintId, hint.text);
            //Debug.Log ("adding hint: " + hint.text);
        }
    }
コード例 #58
0
        /// <summary>
        /// Synchronous Wrapper method around FetchAsynch() method
        /// </summary>
        /// <param name="cacheIndex"></param>
        /// <param name="cacheIndexItem"></param>
        public NetworkResponse Fetch( string uri, string filename, Dictionary<string, string> headers )
        {
            PostNetworkResponse = new NetworkResponse();
            FetchParameters fetchParameters = new FetchParameters()
            {
                Uri = uri,
                Headers = headers,
                FileName = filename
            };

            DateTime dtMetric = DateTime.UtcNow;

            // set callback and error handler
            OnDownloadComplete += new NetworkingEventHandler( FetcherAsynch_OnDownloadComplete );
            OnError += new NetworkingErrorHandler( FetcherAsynch_OnError );

            System.Threading.ThreadPool.QueueUserWorkItem( parameters =>
            {
                try
                {
                    FetchAsynch( parameters );
                }
                //catch ( Exception e )
                //{
                //    // You could react or save the exception to an 'outside' variable 
                //    // threadExc = e;    
                //}
                finally
                {
                    autoEvent.Set(); // if you're firing and not forgetting ;)    
                }
            }, fetchParameters );

            // WaitOne returns true if autoEvent were signaled (i.e. process completed before timeout expired)
            // WaitOne returns false it the timeout expired before the process completed.
            if ( !autoEvent.WaitOne( DefaultTimeout ) )
            {
                string message = "FetcherAsynch call to FetchAsynch timed out. uri " + fetchParameters.Uri;
                MXDevice.Log.Error( message );

                MXDevice.Log.Debug( string.Format( "FetchAsynch timed out: Uri: {0} Time: {1} milliseconds ", uri, DateTime.UtcNow.Subtract( dtMetric ).TotalMilliseconds ) );

                NetworkResponse networkResponse = new NetworkResponse()
                {
                    Message = message,
                    URI = fetchParameters.Uri,
                    StatusCode = HttpStatusCode.RequestTimeout,
                    ResponseString = string.Empty,
                    Expiration = DateTime.MinValue.ToUniversalTime(),
                };

                MXDevice.PostNetworkResponse( networkResponse );
                return networkResponse;
            }

            //if ( threadExc != null )
            //{
            //    throw threadExc;
            //}

            MXDevice.Log.Debug( string.Format( "FetchAsynch Completed: Uri: {0} Time: {1} milliseconds  Size: {2} ", uri, DateTime.UtcNow.Subtract( dtMetric ).TotalMilliseconds, ( PostNetworkResponse.ResponseBytes != null ? PostNetworkResponse.ResponseBytes.Length : -1 ) ) );


            return PostNetworkResponse;
        }
コード例 #59
0
 public void ProcessConvergeNewAttemptScore(NetworkResponse response)
 {
     ResponseConvergeNewAttemptScore args = response as ResponseConvergeNewAttemptScore;
     int status = args.status;
     //Debug.Log ("Processed ReponseConvergeNewAttemptScore, status = " + status);
 }
コード例 #60
0
 public void ProcessLogout(NetworkResponse response)
 {
     ResponseLogout args = response as ResponseLogout;
     //act on logout regardless of response
     Application.Quit ();
     Game.SwitchScene ("Login");
 }