Esempio n. 1
0
        /// <summary>
        /// Read some data from the HTTP response stream, handling I/O errors.
        /// </summary>
        /// <param name="state">
        /// </param>
        /// <param name="innerState">
        /// </param>
        /// <param name="data">
        /// data buffer to use to read data
        /// </param>
        /// <param name="entityStream">
        /// entityStream stream for reading the HTTP response entity
        /// </param>
        /// <returns>
        /// the number of bytes actually read or -1 if the end of the stream has been reached
        /// </returns>
        private int ReadFromResponse(State state, InnerState innerState, byte[] data, Stream entityStream)
        {
            try
            {
                return(entityStream.Read(data, 0, data.Length));
            }
            catch (IOException ex)
            {
                this.LogNetworkState();
                this.downloadInfo.CurrentBytes = innerState.BytesSoFar;
                DownloadsDatabase.UpdateDownload(this.downloadInfo);

                string message;
                ExpansionDownloadStatus finalStatus;
                if (CannotResume(innerState))
                {
                    finalStatus = ExpansionDownloadStatus.CannotResume;
                    message     =
                        string.Format("while reading response: {0}, can't resume interrupted download with no ETag", ex);
                }
                else
                {
                    finalStatus = this.GetFinalStatusForHttpError(state);
                    message     = string.Format("while reading response: {0}", ex);
                }

                throw new StopRequestException(finalStatus, message, ex);
            }
        }
Esempio n. 2
0
        public AbstractActivatedState(Connection connection, ConnectionParameter param, TcpClient tcpControlConnection)
        {
            innerState                = InnerState.ACTIVE;
            this.connection           = connection;
            this.param                = param;
            this.tcpControlConnection = tcpControlConnection;
            this.stream               = tcpControlConnection.GetStream();
            this.mouse                = new MouseExecutor(connection.HeightClientMonitor, connection.WidthClientMonitor);
            this.keyboard             = new KeyboardExecutor();
            this.clipboard            = null;

            controlConnectionListener = new BackgroundWorker();
            controlConnectionListener.WorkerSupportsCancellation = true;
            controlConnectionListener.WorkerReportsProgress      = true;
            controlConnectionListener.DoWork             += controlConnectionListener_DoWork;
            controlConnectionListener.RunWorkerCompleted += controlConnectionListener_RunWorkerCompleted;
            controlConnectionListener.ProgressChanged    += controlConnectionListener_ProgressChanged;
            controlConnectionListener.RunWorkerAsync();

            clipboardWorker = new BackgroundWorker();
            clipboardWorker.WorkerSupportsCancellation = true;
            clipboardWorker.WorkerReportsProgress      = true;
            clipboardWorker.DoWork             += clipboardWorker_DoWork;
            clipboardWorker.RunWorkerCompleted += clipboardWorker_RunWorkerCompleted;
            clipboardWorker.ProgressChanged    += clipboardWorker_ProgressChanged;

            ListeningForMouse();
        }
Esempio n. 3
0
        /// <summary>
        /// Fully execute a single download request - setup and send the request,
        /// handle the response, and transfer the data to the destination file.
        /// </summary>
        /// <param name="state">
        /// The state.
        /// </param>
        /// <param name="request">
        /// The request.
        /// </param>
        private void ExecuteDownload(State state, HttpWebRequest request)
        {
            var innerState = new InnerState();
            var data       = new byte[DownloaderService.BufferSize];

            this.CheckPausedOrCanceled();

            this.SetupDestinationFile(state, innerState);
            AddRequestHeaders(innerState, request);

            // check just before sending the request to avoid using an invalid connection at all
            this.CheckConnectivity();

            this.downloadNotification.OnDownloadStateChanged(DownloaderState.Connecting);
            HttpWebResponse response = this.SendRequest(state, request);

            this.HandleExceptionalStatus(state, innerState, response);

            Debug.WriteLine("DownloadThread : received response for {0}", this.downloadInfo.Uri);

            this.ProcessResponseHeaders(state, innerState, response);
            Stream entityStream = this.OpenResponseEntity(state, response);

            this.downloadNotification.OnDownloadStateChanged(DownloaderState.Downloading);
            this.TransferData(state, innerState, data, entityStream);
        }
Esempio n. 4
0
        /// <summary>
        /// Check the HTTP response status and handle anything unusual (e.g. not 200/206).
        /// </summary>
        /// <param name="state">
        /// The state.
        /// </param>
        /// <param name="innerState">
        /// The inner State.
        /// </param>
        /// <param name="response">
        /// The response.
        /// </param>
        private void HandleExceptionalStatus(State state, InnerState innerState, HttpWebResponse response)
        {
            HttpStatusCode statusCode = response.StatusCode;

            if (statusCode == HttpStatusCode.ServiceUnavailable &&
                this.downloadInfo.FailedCount < DownloaderService.MaximumRetries)
            {
                HandleServiceUnavailable(state, response);
            }

            switch (statusCode)
            {
            case HttpStatusCode.TemporaryRedirect:
            case HttpStatusCode.SeeOther:
            case HttpStatusCode.Found:
            case HttpStatusCode.Moved:
                this.HandleRedirect(state, response, statusCode);
                break;
            }

            HttpStatusCode expectedStatus = innerState.ContinuingDownload
                                                ? HttpStatusCode.PartialContent
                                                : HttpStatusCode.OK;

            if (statusCode != expectedStatus)
            {
                HandleOtherStatus(innerState, statusCode);
            }
            else
            {
                // no longer redirected
                state.RedirectCount = 0;
            }
        }
        public AbstractActivatedState(Connection connection, ConnectionParameter param, TcpClient tcpControlConnection)
        {
            innerState = InnerState.ACTIVE;
            this.connection = connection;
            this.param = param;
            this.tcpControlConnection = tcpControlConnection;
            this.stream = tcpControlConnection.GetStream();
            this.mouse = new MouseExecutor(connection.HeightClientMonitor, connection.WidthClientMonitor);
            this.keyboard = new KeyboardExecutor();
            this.clipboard = null;

            controlConnectionListener = new BackgroundWorker();
            controlConnectionListener.WorkerSupportsCancellation = true;
            controlConnectionListener.WorkerReportsProgress = true;
            controlConnectionListener.DoWork += controlConnectionListener_DoWork;
            controlConnectionListener.RunWorkerCompleted += controlConnectionListener_RunWorkerCompleted;
            controlConnectionListener.ProgressChanged += controlConnectionListener_ProgressChanged;
            controlConnectionListener.RunWorkerAsync();

            clipboardWorker = new BackgroundWorker();
            clipboardWorker.WorkerSupportsCancellation = true;
            clipboardWorker.WorkerReportsProgress = true;
            clipboardWorker.DoWork += clipboardWorker_DoWork;
            clipboardWorker.RunWorkerCompleted += clipboardWorker_RunWorkerCompleted;
            clipboardWorker.ProgressChanged += clipboardWorker_ProgressChanged;

            ListeningForMouse();
        }
Esempio n. 6
0
        /// <summary>
        /// Called when we've reached the end of the HTTP response stream, to update the database and
        /// check for consistency.
        /// </summary>
        /// <param name="state">
        /// The state.
        /// </param>
        /// <param name="innerState">
        /// The inner State.
        /// </param>
        private void HandleEndOfStream(State state, InnerState innerState)
        {
            Debug.WriteLine("HandleEndOfStream");

            this.downloadInfo.CurrentBytes = innerState.BytesSoFar;

            //// this should always be set from the market
            // if (innerState.HeaderContentLength == null)
            // {
            // downloadInfo.TotalBytes = innerState.BytesSoFar;
            // }
            DownloadsDatabase.UpdateDownload(this.downloadInfo);

            bool lengthMismatched = innerState.HeaderContentLength != null &&
                                    innerState.BytesSoFar != int.Parse(innerState.HeaderContentLength);

            if (lengthMismatched)
            {
                string message;
                ExpansionDownloadStatus finalStatus;
                if (CannotResume(innerState))
                {
                    finalStatus = ExpansionDownloadStatus.CannotResume;
                    message     = "mismatched content length";
                }
                else
                {
                    finalStatus = this.GetFinalStatusForHttpError(state);
                    message     = "closed socket before end of file";
                }

                throw new StopRequestException(finalStatus, message);
            }
        }
Esempio n. 7
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (State != global::Google.Cloud.Dataproc.V1.ClusterOperationStatus.Types.State.Unknown)
            {
                hash ^= State.GetHashCode();
            }
            if (InnerState.Length != 0)
            {
                hash ^= InnerState.GetHashCode();
            }
            if (Details.Length != 0)
            {
                hash ^= Details.GetHashCode();
            }
            if (stateStartTime_ != null)
            {
                hash ^= StateStartTime.GetHashCode();
            }
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
Esempio n. 8
0
    public override void on_start(InnerState state)
    {
        anim = GetComponent <Animator>();

        state.set(InnerState.Emotion.Hungry, 0.0f);
        state.set(InnerState.Emotion.NotHungry, 1.0f);
    }
Esempio n. 9
0
 public override void InnerRestart()
 {
     base.InnerRestart();
     toy             = null;
     collectionPoint = null;
     state           = InnerState.Setup;
 }
Esempio n. 10
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (State != 0)
            {
                hash ^= State.GetHashCode();
            }
            if (InnerState.Length != 0)
            {
                hash ^= InnerState.GetHashCode();
            }
            if (Details.Length != 0)
            {
                hash ^= Details.GetHashCode();
            }
            if (stateStartTime_ != null)
            {
                hash ^= StateStartTime.GetHashCode();
            }
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
Esempio n. 11
0
 void controlConnectionListener_ProgressChanged(object sender, ProgressChangedEventArgs e)
 {
     try
     {
         WriteMessage(stream, (byte[])e.UserState, 0, COMMAND_LENGHT);
     }
     catch (NetworkException)
     {
         Trace.TraceError("NetworkException in controlConnectionListener_ProgressChanged().");
         innerState = InnerState.STOP_BY_NETWORK_ERROR;
         controlConnectionListener.CancelAsync();
     }
     catch (SocketException se)
     {
         Trace.TraceError("SocketException in controlConnectionListener_ProgressChanged(). Stack trace:\n{0}\nSocket error:{1}\n", se.StackTrace, se.SocketErrorCode);
         innerState = InnerState.STOP_BY_ERROR;
         controlConnectionListener.CancelAsync();
     }
     catch (IOException ioe)
     {
         Trace.TraceError("IOException in controlConnectionListener_ProgressChanged(). Stack trace:\n{0}\n", ioe.StackTrace);
         innerState = InnerState.STOP_BY_ERROR;
         controlConnectionListener.CancelAsync();
     }
 }
Esempio n. 12
0
        private void mouseWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (innerState == InnerState.STOP_BY_ERROR || innerState == InnerState.STOP_BY_NETWORK_ERROR || innerState == InnerState.STOP_BY_CONTROLLER)
            {
                return;
            }

            if (e.Result != null)
            {
                string result = e.Result as string;
                switch (result)
                {
                case NETWORK_ERROR_RESULT:
                    innerState = InnerState.STOP_BY_NETWORK_ERROR;
                    if (controlConnectionListener.IsBusy)
                    {
                        controlConnectionListener.CancelAsync();
                    }
                    break;

                case CLIENT_ERROR_RESULT:
                    innerState = InnerState.STOP_BY_ERROR;
                    if (controlConnectionListener.IsBusy)
                    {
                        controlConnectionListener.CancelAsync();
                    }
                    break;
                }
            }
        }
Esempio n. 13
0
 void clipboardWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
 {
     try
     {
         //invio il messaggio di ack
         WriteMessage(stream, TipoComandoBytes.ACTIVE_CLIPBOARD_ACK, 0, TipoComandoBytes.ACTIVE_CLIPBOARD_ACK.Length);
     }
     catch (IOException ioe)
     {
         Trace.TraceError("IOException in clipboardWorker_ProgressChanged(). Stack trace:\n{0}\n", ioe.StackTrace);
         innerState = InnerState.STOP_BY_ERROR;
         if (controlConnectionListener.IsBusy)
         {
             controlConnectionListener.CancelAsync();
         }
     }
     catch (SocketException se)
     {
         Trace.TraceError("SocketException in clipboardWorker_ProgressChanged(). Stack trace:\n{0}\nSocket error:{1}\n", se.StackTrace, se.SocketErrorCode);
         innerState = InnerState.STOP_BY_ERROR;
         if (controlConnectionListener.IsBusy)
         {
             controlConnectionListener.CancelAsync();
         }
     }
     catch (NetworkException)
     {
         Trace.TraceError("NetworkException in clipboardWorker_ProgressChanged().");
         innerState = InnerState.STOP_BY_NETWORK_ERROR;
         if (controlConnectionListener.IsBusy)
         {
             controlConnectionListener.CancelAsync();
         }
     }
 }
Esempio n. 14
0
        /// <summary>
        /// Report download progress through the database if necessary.
        /// </summary>
        /// <param name="innerState">
        /// The inner State.
        /// </param>
        private void ReportProgress(InnerState innerState)
        {
            long now = PolicyExtensions.GetCurrentMilliseconds();

            if (innerState.BytesSoFar - innerState.BytesNotified > DownloaderService.MinimumProgressStep &&
                now - innerState.TimeLastNotification > DownloaderService.MinimumProgressTime)
            {
                // we store progress updates to the database here
                this.downloadInfo.CurrentBytes = innerState.BytesSoFar;
                DownloadsDatabase.UpdateDownloadCurrentBytes(this.downloadInfo);

                innerState.BytesNotified        = innerState.BytesSoFar;
                innerState.TimeLastNotification = now;

                long totalBytesSoFar = innerState.BytesThisSession + this.downloaderService.BytesSoFar;

                Debug.WriteLine(
                    "DownloadThread : downloaded {0} out of {1}",
                    this.downloadInfo.CurrentBytes,
                    this.downloadInfo.TotalBytes);
                Debug.WriteLine(
                    "DownloadThread :      total {0} out of {1}", totalBytesSoFar, this.downloaderService.TotalLength);

                this.downloaderService.NotifyUpdateBytes(totalBytesSoFar);
            }
        }
Esempio n. 15
0
        void controlConnectionListener_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            try
            {
                switch (e.ProgressPercentage)
                {
                case 0:
                    WriteMessage(stream, (byte[])e.UserState, 0, COMMAND_LENGHT);
                    break;

                case 100:
                    bool isRemoteCopy = (bool)e.UserState;
                    ListeningForClipboard(isRemoteCopy);
                    break;
                }
            }
            catch (NetworkException)
            {
                Trace.TraceError("NetworkException in controlConnectionListener_ProgressChanged().");
                innerState = InnerState.STOP_BY_NETWORK_ERROR;
                controlConnectionListener.CancelAsync();
            }
            catch (SocketException se)
            {
                Trace.TraceError("SocketException in controlConnectionListener_ProgressChanged(). Stack trace:\n{0}\nSocket error:{1}\n", se.StackTrace, se.SocketErrorCode);
                innerState = InnerState.STOP_BY_ERROR;
                controlConnectionListener.CancelAsync();
            }
            catch (IOException ioe)
            {
                Trace.TraceError("IOException in controlConnectionListener_ProgressChanged(). Stack trace:\n{0}\n", ioe.StackTrace);
                innerState = InnerState.STOP_BY_ERROR;
                controlConnectionListener.CancelAsync();
            }
        }
Esempio n. 16
0
        /// <summary>
        /// Prepare the destination file to receive data.
        /// If the file already exists, we'll set up appropriately for resumption.
        /// </summary>
        /// <param name="state">
        /// </param>
        /// <param name="innerState">
        /// </param>
        private void SetupDestinationFile(State state, InnerState innerState)
        {
            if (state.Filename != null)
            {
                // only true if we've already run a thread for this download
                if (!Helpers.IsFilenameValid(state.Filename))
                {
                    // this should never happen
                    throw new StopRequestException(
                              ExpansionDownloadStatus.FileError, "found invalid internal destination filename");
                }

                // We're resuming a download that got interrupted
                if (File.Exists(state.Filename))
                {
                    long fileLength = new FileInfo(state.Filename).Length;
                    if (fileLength == 0)
                    {
                        // The download hadn't actually started, we can restart from scratch
                        File.Delete(state.Filename);
                        state.Filename = null;
                    }
                    else if (this.downloadInfo.ETag == null)
                    {
                        // This should've been caught upon failure
                        File.Delete(state.Filename);
                        throw new StopRequestException(
                                  ExpansionDownloadStatus.CannotResume, "Trying to resume a download that can't be resumed");
                    }
                    else
                    {
                        // All right, we'll be able to resume this download
                        try
                        {
                            state.Stream = new FileStream(state.Filename, FileMode.Append);
                        }
                        catch (FileNotFoundException exc)
                        {
                            throw new StopRequestException(
                                      ExpansionDownloadStatus.FileError, "while opening destination for resuming: " + exc, exc);
                        }

                        innerState.BytesSoFar = (int)fileLength;
                        if (this.downloadInfo.TotalBytes != -1)
                        {
                            innerState.HeaderContentLength = this.downloadInfo.TotalBytes.ToString();
                        }

                        innerState.HeaderETag         = this.downloadInfo.ETag;
                        innerState.ContinuingDownload = true;
                    }
                }
            }

            if (state.Stream != null)
            {
                CloseDestination(state);
            }
        }
Esempio n. 17
0
    public void Interact(RaycastHit hit)
    {
        switch (state)
        {
        case InnerState.Placing:

            // If it can not be placed simply break
            if (canPlace == false)
            {
                break;
            }

            // otherwise set the state to the next state and save the MousePosition for the rotation
            state = InnerState.Rotating;
            rotateAroundMosPos = Input.mousePosition;

            break;

        case InnerState.Rotating:

            // If the building can not be placed then simply break
            if (canPlace == false)
            {
                break;
            }

            // Add it to the town. If there are not enough resources then delete the building
            Town town = TownDict.Instance.Towns[0];     // TODO: Replace if multiple towns are allowed
            if (town.Supplies.AdjustAmount(Cost) == false)
            {
                UIManager.Instance.DisplayEvent(ToyEvent.NotEnoughResources);
                DeSelect();
                return;
            }
            town.AddBuilding(building);

            // Set the state to the placed state
            state = InnerState.Placed;

            // Deselect the building from the camera controller
            if (CameraController.Instance.DeSelect(this) == false)
            {
                DeSelect();
            }

            // Reenable all colliders
            for (int i = 0; i < colliders.Count; i++)
            {
                colliders[i].enabled = true;
            }

            buildingsSelectable = GetComponent <IBuildingsSelectable>();
            SetOutlineColor(0);

            building.OnBuildingPlaced();

            break;
        }
    }
Esempio n. 18
0
 public LibraryController(ILibraryView view)
 {
     this.state = InnerState.INITIAL;
     binding = new WS2007HttpBinding(new HttpTransportBindingConfig(new Uri("http://" + IP_ADDRESS + "/LibraryWS/Service.svc")));
     View = view;
     View.Controller = this;
     View.ShowLoginPage();
 }
Esempio n. 19
0
        public bool Invalid(TValidationResult result, string reason, string?debugMessage = null)
        {
            Result       = result;
            RejectReason = reason;
            DebugMessage = debugMessage;
            _mode        = InnerState.Invalid;

            return(false);
        }
Esempio n. 20
0
 private void Clear()
 {
     mInnerState          = InnerState.Idle;
     mGetVersionInfoEvent = null;
     mReqResult           = null;
     UrlList         = null;
     mCurReqUrlIndex = DefaultUrlsReqIndex;
     mCurRequest     = null;
 }
Esempio n. 21
0
        public bool Error(string reason)
        {
            if (_mode == InnerState.Valid)
            {
                RejectReason = reason;
            }

            _mode = InnerState.Error;

            return(false);
        }
Esempio n. 22
0
    public override void on_update(AnimalShelter shelter, InnerState state)
    {
        state.change(InnerState.Emotion.Lonely, 0.01f * Time.deltaTime);
        state.change(InnerState.Emotion.Loved, -0.01f * Time.deltaTime);

        refresh_emotion(state);

        if (state.get(InnerState.Emotion.Lonely) > 0.8f)
        {
            shelter.kill(this);
        }
    }
Esempio n. 23
0
 public void Stop()
 {
     try
     {
         innerState = InnerState.STOP_BY_USER;
         WriteMessage(stream, TipoComandoBytes.CLOSE_CONNECTION, 0, TipoComandoBytes.CLOSE_CONNECTION.Length);
         controlConnectionListener.CancelAsync();
     }
     catch (Exception e)
     {      /*non devo fare nulla perché sto chiudendo*/
         Trace.TraceError("Exception in Stop(). Stack trace:\n{0}\n", e.StackTrace);
     }
 }
Esempio n. 24
0
 private void Update()
 {
     if (this._outerState == OuterState.Glow)
     {
         float t = this._timer / 0.2f;
         this._mpb_flagFader.LerpAlpha(t);
         this._mpb_outerFader.LerpAlpha(t);
         if (this._timer > 0.2f)
         {
             this._outerState = OuterState.Idle;
         }
     }
     else if (this._outerState == OuterState.Idle)
     {
     }
     if (this._innerState == InnerState.Hide)
     {
         if (this._timer > this._config.InnerStartDelay)
         {
             this._innerState = InnerState.Inflate;
         }
     }
     else if (this._innerState == InnerState.Inflate)
     {
         float time = (this._timer - this._config.InnerStartDelay) / this._config.InnerInflateDuration;
         if (time > 1f)
         {
             this.innerHint.localScale = (Vector3)(Vector3.one * this._innerMaxScale);
             this._innerState          = InnerState.FadeOut;
         }
         else
         {
             this._mpb_flagFader.LerpAlpha(this.outerFadeCurve.Evaluate(time));
             this._mpb_outerFader.LerpAlpha(this.outerFadeCurve.Evaluate(time));
             this.innerHint.localScale = (Vector3)(Vector3.one * Mathf.Lerp(this._innerMinScale, this._innerMaxScale, this.inflateCurve.Evaluate(time)));
         }
     }
     else if (this._innerState == InnerState.FadeOut)
     {
         float num3 = ((this._timer - this._config.InnerStartDelay) - this._config.InnerInflateDuration) / this.fadeOutTime;
         if (num3 > 1f)
         {
             base.SetDestroy();
         }
         else
         {
             this._mpb_innerFader.LerpAlpha(this.fadeOutCurve.Evaluate(num3));
         }
     }
     this._timer += Time.deltaTime * this._owner.TimeScale;
 }
Esempio n. 25
0
    protected override void InnerAwake()
    {
        // Deactivate all colliders
        colliders = new List <Collider>();
        transform.GetComponentsInChildren(false, colliders);
        for (int i = 0; i < colliders.Count; i++)
        {
            colliders[i].enabled = false;
        }

        building = GetComponent <Building>();
        state    = InnerState.Placing;
        canPlace = false;
    }
Esempio n. 26
0
        /// <summary>
        /// Add headers for this download to the HTTP request to allow for resume.
        /// </summary>
        /// <param name="innerState">
        /// The inner State.
        /// </param>
        /// <param name="request">
        /// The request.
        /// </param>
        private static void AddRequestHeaders(InnerState innerState, HttpWebRequest request)
        {
            if (innerState.ContinuingDownload)
            {
                if (innerState.HeaderETag != null)
                {
                    request.Headers.Add("If-Match", innerState.HeaderETag);
                }

                request.AddRange(innerState.BytesSoFar);
            }

            // request.SendChunked = true;
        }
Esempio n. 27
0
        /// <summary>
        /// Read HTTP response headers and take appropriate action, including setting up the destination
        /// file and updating the database.
        /// </summary>
        /// <param name="state">
        /// </param>
        /// <param name="innerState">
        /// </param>
        /// <param name="response">
        /// </param>
        private void ProcessResponseHeaders(State state, InnerState innerState, HttpWebResponse response)
        {
            if (!innerState.ContinuingDownload)
            {
                this.ReadResponseHeaders(innerState, response);

                try
                {
                    state.Filename = this.downloaderService.GenerateSaveFile(
                        this.downloadInfo.FileName, this.downloadInfo.TotalBytes);
                }
                catch (DownloaderService.GenerateSaveFileError exc)
                {
                    throw new StopRequestException(exc.Status, exc.Message);
                }

                try
                {
                    if (!File.Exists(state.Filename))
                    {
                        // make sure the directory exists
                        string path = Helpers.GetSaveFilePath(this.downloaderService);

                        if (!string.IsNullOrWhiteSpace(path))
                        {
                            Directory.CreateDirectory(path);
                        }

                        state.Stream = new FileStream(state.Filename, FileMode.Create);
                    }
                    else
                    {
                        state.Stream = new FileStream(state.Filename, FileMode.Open);
                    }
                }
                catch (Exception ex)
                {
                    throw new StopRequestException(
                              ExpansionDownloadStatus.FileError, string.Format("while opening destination file: {0}", ex), ex);
                }

                Debug.WriteLine("DownloadThread : writing {0} to {1}", this.downloadInfo.Uri, state.Filename);

                this.UpdateDatabaseFromHeaders(innerState);

                // check connectivity again now that we know the total size
                this.CheckConnectivity();
            }
        }
Esempio n. 28
0
 private void WaitingForRequestToHttpServer()
 {
     if (Time.realtimeSinceStartup - mStartTime > mReqInternal)
     {
         mInnerState = InnerState.RequestAgain;
         s_mLogger.Info("Request again!");
     }
     else
     {
         if (!CheckCurrentUrlValid())
         {
             mInnerState = InnerState.RequestFailure;
         }
     }
 }
Esempio n. 29
0
    public override void on_update(AnimalShelter shelter, InnerState state)
    {
        become_hungry(state);

        if (state.get(InnerState.Emotion.Hungry) > 0.9f) // Replace lonely with hunger
        {
            if (try_eat_neighbour(shelter, state))
            {
                state.set(InnerState.Emotion.Hungry, 0.0f);
                state.set(InnerState.Emotion.NotHungry, 1.0f);
            }
        }

        refresh_emotion(state);
    }
Esempio n. 30
0
    private void refresh_emotion(InnerState state, bool forced = false)
    {
        var sorted  = state.get_emotions_sorted_by_intensity();
        var current = sorted.GetEnumerator();

        prev = emotion;
        if (current.MoveNext())
        {
            emotion = current.Current.Value;
            bool changed = prev != emotion;
            if (changed || forced)
            {
                set_animation(emotion);
            }
        }
    }
Esempio n. 31
0
        public void ReqGetVersion(LighthouseConfig.Server serverData, string appVersion, string lighthouseId, string channel, FileServerType fromTo, Action <GetVersionResponseInfo> getVersionResponseInfoAction)
        {
            Clear();
            UrlList    = new string[serverData.FallbackUrlList.Count + 1];
            UrlList[0] = serverData.Url;
            serverData.FallbackUrlList.ForCall((x, index) => { UrlList[index + 1] = x; });

            s_mLogger.Debug($"[appVersion : {appVersion}] [lighthouseId : {lighthouseId}] [channel : {channel}] [fromTo : {fromTo}] .");

            mAppVersion          = appVersion;
            mChannel             = channel;
            mGetVersionInfoEvent = getVersionResponseInfoAction;

            mCurRequest              = new EntryPointRequest();
            mCurRequest.AppVersion   = appVersion;
            mCurRequest.LighthouseId = lighthouseId;
            mCurRequest.From         = (fromTo == FileServerType.CDN) ? EntryPointFromType.Cdn : EntryPointFromType.Oss;

            mInnerState = InnerState.StartRequest;
        }
Esempio n. 32
0
        public AgentStepMessage Step(Action action)
        {
            if (_agent == null)
            {
                return(null);
            }
            switch (action)
            {
            case Action.Up:
                MoveUp();
                break;

            case Action.Down:
                MoveDown();
                break;

            case Action.Left:
                MoveLeft();
                break;

            case Action.Right:
                MoveRight();
                break;

            default:
                break;
            }
            _currMoveSteps += 1;
            InnerState       state = GetCurrentState();
            AgentStepMessage msg   = new AgentStepMessage
            {
                Reward = state.reward,
                IsDone = state.isDone
            };

            TotalReward  += msg.Reward;
            _prevAgentPos = _agent.transform.position;
            ClearColliderObj(state.colliderObj);
            return(msg);
        }
 /// <summary>
 /// The cannot resume.
 /// </summary>
 /// <param name="innerState">
 /// The inner state.
 /// </param>
 /// <returns>
 /// True if the download cannot resume, otherwise false
 /// </returns>
 private static bool CannotResume(InnerState innerState)
 {
     return innerState.BytesSoFar > 0 && innerState.HeaderETag == null;
 }
        /// <summary>
        /// Read HTTP response headers and take appropriate action, including setting up the destination
        /// file and updating the database.
        /// </summary>
        /// <param name="state">
        /// </param>
        /// <param name="innerState">
        /// </param>
        /// <param name="response">
        /// </param>
        private void ProcessResponseHeaders(State state, InnerState innerState, HttpWebResponse response)
        {
            if (!innerState.ContinuingDownload)
            {
                this.ReadResponseHeaders(innerState, response);

                try
                {
                    state.Filename = this.downloaderService.GenerateSaveFile(
                        this.downloadInfo.FileName, this.downloadInfo.TotalBytes);
                }
                catch (DownloaderService.GenerateSaveFileError exc)
                {
                    throw new StopRequestException(exc.Status, exc.Message);
                }

                try
                {
                    if (!File.Exists(state.Filename))
                    {
                        // make sure the directory exists
                        string path = Helpers.GetSaveFilePath(this.downloaderService);

                        if (!string.IsNullOrWhiteSpace(path))
                        {
                            Directory.CreateDirectory(path);
                        }

                        state.Stream = new FileStream(state.Filename, FileMode.Create);
                    }
                    else
                    {
                        state.Stream = new FileStream(state.Filename, FileMode.Open);
                    }
                }
                catch (Exception ex)
                {
                    throw new StopRequestException(
                        ExpansionDownloadStatus.FileError, string.Format("while opening destination file: {0}", ex), ex);
                }

                Debug.WriteLine("DownloadThread : writing {0} to {1}", this.downloadInfo.Uri, state.Filename);

                this.UpdateDatabaseFromHeaders(innerState);

                // check connectivity again now that we know the total size
                this.CheckConnectivity();
            }
        }
        /// <summary>
        /// Transfer as much data as possible from the HTTP response to the destination file.
        /// </summary>
        /// <param name="state">
        /// </param>
        /// <param name="innerState">
        /// </param>
        /// <param name="data">
        /// buffer to use to read data
        /// </param>
        /// <param name="entityStream">
        /// stream for reading the HTTP response entity
        /// </param>
        private void TransferData(State state, InnerState innerState, byte[] data, Stream entityStream)
        {
            int bytesRead;

            do
            {
                bytesRead = this.ReadFromResponse(state, innerState, data, entityStream);

                if (bytesRead != 0)
                {
                    state.GotData = true;
                    WriteDataToDestination(state, data, bytesRead);
                    innerState.BytesSoFar += bytesRead;
                    innerState.BytesThisSession += bytesRead;
                    this.ReportProgress(innerState);

                    this.CheckPausedOrCanceled();
                }
            }
            while (bytesRead != 0);

            // success, end of stream already reached
            this.HandleEndOfStream(state, innerState);
        }
        /// <summary>
        /// Add headers for this download to the HTTP request to allow for resume.
        /// </summary>
        /// <param name="innerState">
        /// The inner State.
        /// </param>
        /// <param name="request">
        /// The request.
        /// </param>
        private static void AddRequestHeaders(InnerState innerState, HttpWebRequest request)
        {
            if (innerState.ContinuingDownload)
            {
                if (innerState.HeaderETag != null)
                {
                    request.Headers.Add("If-Match", innerState.HeaderETag);
                }

                request.AddRange(innerState.BytesSoFar);
            }

            // request.SendChunked = true;
        }
Esempio n. 37
0
        public void Login(string id)
        {
            if (state != InnerState.INITIAL) throw new InvalidOperationException("The user is already logged in!");
            IServiceClientProxy proxy = null;
            try
            {
                //using (IServiceClientProxy proxy = new IServiceClientProxy(binding, new ProtocolVersion11()))
                //{
                 proxy = new IServiceClientProxy(binding, new ProtocolVersion11());

                //login request to the WS
                LogIn loginRequest = new LogIn() { card_number = id };
                LogInResponse response = proxy.LogIn(loginRequest);
                if (response.LogInResult.FirstName == null)
                {
                    //show a message and return in the login page
                    Action action = () => { View.ShowLoginPage(); };
                    View.ShowMessageWithButton(UNREGISTERED_USER_MSG, action);
                    return;
                }
                //set the the logged user and show the welcome page
                LibraryModelSingleton.Instance.User = response.LogInResult;
                state = InnerState.WELCOME;
                View.ShowWelcomePage();
                //}
            }
            catch (Exception)
            {
                //show a message and then returns in the login page
                state = InnerState.INITIAL;
                View.ShowMessageWithButton(ERROR_MSG, () => { View.ShowLoginPage(); });
            }
            finally
            {
             //  if (proxy != null) { proxy.Dispose(); }
            }
        }
Esempio n. 38
0
 public void BorrowBook()
 {
     try
     {   //show a loading message
         View.ShowLoading();
         using (IServiceClientProxy proxy = new IServiceClientProxy(binding, new ProtocolVersion11()))
         {
             //execute the borrow request
             int bookId = LibraryModelSingleton.Instance.Book.ID;
             int userId = LibraryModelSingleton.Instance.User.ID;
             Borrow borrowRequest = new Borrow() { bookID = bookId, userID = userId };
             BorrowResponse response = proxy.Borrow(borrowRequest);
             //show positive a message if the result is valid otherwise a negative message
             //and return in the welcome page
             state = InnerState.WELCOME;
             string msg = (response.BorrowResult.StartDate.Equals(DateTime.MinValue)) ? BORROW_FAILED_MSG : OPERATION_COMPLETED_MSG;
             View.ShowMessageWithButton(msg, () => { View.ShowWelcomePage(); });
         }
     }
     //show a message and then returns in the login page
     catch (Exception) { View.ShowMessageWithButton(ERROR_MSG, () => { this.Logout(); }); }
 }
 void clipboardWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
 {
     try
     {
         //invio il messaggio di ack
         WriteMessage(stream, TipoComandoBytes.ACTIVE_CLIPBOARD_ACK, 0, TipoComandoBytes.ACTIVE_CLIPBOARD_ACK.Length);
     }
     catch (IOException ioe)
     {
         Trace.TraceError("IOException in clipboardWorker_ProgressChanged(). Stack trace:\n{0}\n", ioe.StackTrace);
         innerState = InnerState.STOP_BY_ERROR;
         if (controlConnectionListener.IsBusy) { controlConnectionListener.CancelAsync(); }
     }
     catch (SocketException se)
     {
         Trace.TraceError("SocketException in clipboardWorker_ProgressChanged(). Stack trace:\n{0}\nSocket error:{1}\n", se.StackTrace, se.SocketErrorCode);
         innerState = InnerState.STOP_BY_ERROR;
         if (controlConnectionListener.IsBusy) { controlConnectionListener.CancelAsync(); }
     }
     catch (NetworkException)
     {
         Trace.TraceError("NetworkException in clipboardWorker_ProgressChanged().");
         innerState = InnerState.STOP_BY_NETWORK_ERROR;
         if (controlConnectionListener.IsBusy) { controlConnectionListener.CancelAsync(); }
     }
 }
Esempio n. 40
0
 public void StartReturnTransaction()
 {
     if (state != InnerState.WELCOME) throw new InvalidOperationException("The user is not in the Welcome Page!");
     //show the camera page
     state = InnerState.RETURNING;
     View.ShowCamera();
 }
        /// <summary>
        /// Called when we've reached the end of the HTTP response stream, to update the database and
        /// check for consistency.
        /// </summary>
        /// <param name="state">
        /// The state.
        /// </param>
        /// <param name="innerState">
        /// The inner State.
        /// </param>
        private void HandleEndOfStream(State state, InnerState innerState)
        {
            Debug.WriteLine("HandleEndOfStream");

            this.downloadInfo.CurrentBytes = innerState.BytesSoFar;

            //// this should always be set from the market
            // if (innerState.HeaderContentLength == null)
            // {
            // downloadInfo.TotalBytes = innerState.BytesSoFar;
            // }
            DownloadsDatabase.UpdateDownload(this.downloadInfo);

            bool lengthMismatched = innerState.HeaderContentLength != null
                                    && innerState.BytesSoFar != int.Parse(innerState.HeaderContentLength);
            if (lengthMismatched)
            {
                string message;
                ExpansionDownloadStatus finalStatus;
                if (CannotResume(innerState))
                {
                    finalStatus = ExpansionDownloadStatus.CannotResume;
                    message = "mismatched content length";
                }
                else
                {
                    finalStatus = this.GetFinalStatusForHttpError(state);
                    message = "closed socket before end of file";
                }

                throw new StopRequestException(finalStatus, message);
            }
        }
Esempio n. 42
0
 public void StartLoanTransaction()
 {
     if (state != InnerState.WELCOME) throw new InvalidOperationException("The user is not in the Welcome Page!");
     //change the inner state and show the camera page
     state = InnerState.BORROWING;
     View.ShowCamera();
 }
Esempio n. 43
0
        public void RecognizeBarcode(Bitmap bitmap)
        {
            if (state != InnerState.BORROWING && state != InnerState.RETURNING) { throw new InvalidOperationException("The user is in an invalid state!"); }

            if (bitmap == null)
            {
                //invalid request, show in the welcome page
                View.ShowWelcomePage();
                return;
            }

            try
            {
                short port = 0;
                //show a loading message
                View.ShowLoading();
                //call the web service to send the picture
                using (IServiceClientProxy proxy = new IServiceClientProxy(binding, new ProtocolVersion11()))
                {
                    SendBarcodeImage sendImageRequest = new SendBarcodeImage();
                    SendBarcodeImageResponse response = proxy.SendBarcodeImage(sendImageRequest);
                    port = response.SendBarcodeImageResult;

                    //send the image
                    string code = SendImage(port, GHI.Utilities.Bitmaps.ConvertToFile(bitmap));
                    if (code == null)
                    {
                        //the bar code was not recognized
                        //show the camera page
                        View.ShowMessageWithButton(CODE_NOT_RECOGNIZED_MSG, () => { View.ShowCamera(); });
                        return;
                    }

                    //get book info
                    GetBookInformationsResponse bookInfoResponse = proxy.GetBookInformations(new GetBookInformations() { barcode = code });
                    if (bookInfoResponse.GetBookInformationsResult.ISBN == null)
                    {
                        //the book is not in the WS database
                        View.ShowMessageWithButton(INVALID_BARCODE_MSG, () => { View.ShowCamera(); });
                        return;
                    }

                    LibraryModelSingleton.Instance.Book = bookInfoResponse.GetBookInformationsResult;
                    if (state == InnerState.BORROWING)
                    {
                        //show the book information
                        View.ShowBooKForLoan();
                    }
                    else if (state == InnerState.RETURNING)
                    {
                        //call the ws in order to get the loan information
                        GetLoanState loanStateRequest = new GetLoanState();
                        loanStateRequest.bookID = bookInfoResponse.GetBookInformationsResult.ID;
                        loanStateRequest.userID = LibraryModelSingleton.Instance.User.ID;
                        loanStateRequest.returned = false;
                        GetLoanStateResponse loanStateResponse = proxy.GetLoanState(loanStateRequest);
                        if (loanStateResponse.GetLoanStateResult.LoanStateCompositeType.Length == 0)
                        {
                            //the book was not borrowed by the user
                            View.ShowMessageWithButton(INVALID_BARCODE_MSG, () => { View.ShowWelcomePage(); });
                        }
                        else
                        {
                            //show the book information
                            LibraryModelSingleton.Instance.StartDate = loanStateResponse.GetLoanStateResult.LoanStateCompositeType[0].LoanStartDate;
                            LibraryModelSingleton.Instance.DueDate = loanStateResponse.GetLoanStateResult.LoanStateCompositeType[0].LoanExpirationDate;
                            View.ShowBooKForReturning();
                        }
                    }
                }
            }
            catch (Exception)
            { //show a message and then returns in the login page
                state = InnerState.INITIAL;
                View.ShowMessageWithButton(ERROR_MSG, () => { this.Logout(); });
            }
        }
Esempio n. 44
0
 public void Logout()
 {
     //log out and show the login page
     state = InnerState.INITIAL;
     LibraryModelSingleton.Instance.Logout();
     View.ShowLoginPage();
 }
 void controlConnectionListener_ProgressChanged(object sender, ProgressChangedEventArgs e)
 {
     try
     {
         switch (e.ProgressPercentage)
         {
             case 0:
                 WriteMessage(stream, (byte[])e.UserState, 0, COMMAND_LENGHT);
                 break;
             case 100:
                 bool isRemoteCopy = (bool)e.UserState;
                 ListeningForClipboard(isRemoteCopy);
                 break;
         }
     }
     catch (NetworkException)
     {
         Trace.TraceError("NetworkException in controlConnectionListener_ProgressChanged().");
         innerState = InnerState.STOP_BY_NETWORK_ERROR;
         controlConnectionListener.CancelAsync();
     }
     catch (SocketException se)
     {
         Trace.TraceError("SocketException in controlConnectionListener_ProgressChanged(). Stack trace:\n{0}\nSocket error:{1}\n", se.StackTrace, se.SocketErrorCode);
         innerState = InnerState.STOP_BY_ERROR;
         controlConnectionListener.CancelAsync();
     }
     catch (IOException ioe)
     {
         Trace.TraceError("IOException in controlConnectionListener_ProgressChanged(). Stack trace:\n{0}\n", ioe.StackTrace);
         innerState = InnerState.STOP_BY_ERROR;
         controlConnectionListener.CancelAsync();
     }
 }
Esempio n. 46
0
 public void CancelCameraTransaction()
 {
     if (state != InnerState.BORROWING && state != InnerState.RETURNING) { throw new InvalidOperationException("The user is in an invalid state!"); }
     //change the inner state and show the camera page
     state = InnerState.WELCOME;
     View.ShowWelcomePage();
 }
        void controlConnectionListener_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //Interrompo gli altri thread
            StopMouseListening();
            StopClipboardListening();
            ClientErrorEventArgs args = null;
            switch (innerState)
            {
                case InnerState.STOP_BY_NETWORK_ERROR:
                    connection.State = null;
                    args = new ClientErrorEventArgs() { ErrorCode = ClientErrorEventArgs.NETWORK_ERROR };
                    connection.ClientErrorMessageReceived(args);
                    if (tcpControlConnection != null)
                    {
                        stream.Close();
                        tcpControlConnection.Close();
                    }
                    connection.CloseConnectionMessageRecived();
                    return;

                case InnerState.STOP_BY_ERROR:
                    connection.State = null;
                    args = new ClientErrorEventArgs() { ErrorCode = ClientErrorEventArgs.CLIENT_ERROR };
                    connection.ClientErrorMessageReceived(args);
                    if (tcpControlConnection != null)
                    {
                        stream.Close();
                        tcpControlConnection.Close();
                    }
                    connection.CloseConnectionMessageRecived();
                    return;

                case InnerState.STOP_BY_USER:
                    connection.State = null;
                    if (tcpControlConnection != null)
                    {
                        stream.Close();
                        tcpControlConnection.Close();
                    }
                    connection.CloseConnectionMessageRecived();
                    return;
            }

            if (e.Error == null && e.Result != null)
            {
                string result = (string)e.Result;
                switch (result)
                {
                    case DEACTIVE_RESULT:
                        //cambio lo stato in connesso 
                        innerState = InnerState.STOP_BY_CONTROLLER;
                        connection.State = NextState(State.CONNECTED);
                        connection.ConnectClientMessageRecived(null, 0, 0);
                        forceButtonUp();
                        break;
                    case CLOSE_RESULT:
                        //passo allo stato disconnected
                        innerState = InnerState.STOP_BY_CONTROLLER;
                        connection.State = NextState(State.DISCONNECTED);
                        connection.DisconnectClientMessageRecived();
                        forceButtonUp();
                        if (tcpControlConnection != null)
                        {
                            stream.Close();
                            tcpControlConnection.Close();
                        }
                        break;

                    case EXTERNAL_CLOSE_RESULT:
                        
                        try
                        {
                            if (stream != null) { WriteMessage(stream, TipoComandoBytes.CLOSE_CONNECTION, 0, COMMAND_LENGHT); }
                        }
                        catch (Exception ex)
                        {
                            Trace.TraceError("Exception in controlConnectionListener_RunWorkerComplited(). Stack trace:\n{0}\n", ex.StackTrace);
                            if (!(ex is NetworkException || ex is IOException || ex is SocketException)) { throw; }
                        }
                        finally
                        {
                            if (tcpControlConnection != null)
                            {
                                stream.Close();
                                tcpControlConnection.Close();
                            }
                            connection.CloseConnectionMessageRecived();
                        }
                        break;

                    case NETWORK_ERROR_RESULT:
                        innerState = InnerState.STOP_BY_NETWORK_ERROR;
                        connection.State = null;
                        args = new ClientErrorEventArgs() { ErrorCode = ClientErrorEventArgs.NETWORK_ERROR };
                        connection.ClientErrorMessageReceived(args);
                        if (tcpControlConnection != null)
                        {
                            stream.Close();
                            tcpControlConnection.Close();
                        }
                        connection.CloseConnectionMessageRecived();
                        break;

                    case CLIENT_ERROR_RESULT:
                        innerState = InnerState.STOP_BY_ERROR;
                        connection.State = null;
                        args = new ClientErrorEventArgs() { ErrorCode = ClientErrorEventArgs.CLIENT_ERROR };
                        connection.ClientErrorMessageReceived(args);
                        if (tcpControlConnection != null)
                        {
                            stream.Close();
                            tcpControlConnection.Close();
                        }
                        connection.CloseConnectionMessageRecived();
                        break;

                    case GENERIC_ERROR_RESULT:
                        innerState = InnerState.STOP_BY_ERROR;
                        connection.State = null;
                        args = new ClientErrorEventArgs() { ErrorCode = ClientErrorEventArgs.GENERIC_ERROR };
                        connection.ClientErrorMessageReceived(args);
                        if (tcpControlConnection != null)
                        {
                            stream.Close();
                            tcpControlConnection.Close();
                        }
                        connection.CloseConnectionMessageRecived();
                        break;
                }
            }
        }
 public void Stop()
 {
     try
     {
         innerState = InnerState.STOP_BY_USER;
         WriteMessage(stream, TipoComandoBytes.CLOSE_CONNECTION, 0, TipoComandoBytes.CLOSE_CONNECTION.Length);
         controlConnectionListener.CancelAsync();
     }
     catch (Exception ex)
     {
         /*non devo fare nulla perché sto chiudendo*/
         Trace.TraceError("Exception in controlConnectionListener_DoWork(). Stack trace:\n{0}\n", ex.StackTrace);
     }
 }
        void clipboardWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            tcpClipboardConnection = null;
            if (innerState == InnerState.STOP_BY_ERROR || innerState == InnerState.STOP_BY_NETWORK_ERROR) { return; }
            if (e.Result != null)
            {
                string result = e.Result as string;
                switch (result)
                {
                    case NETWORK_ERROR_RESULT:
                        innerState = InnerState.STOP_BY_NETWORK_ERROR;
                        if (controlConnectionListener.IsBusy) { controlConnectionListener.CancelAsync(); }
                        break;
                    case CLIENT_ERROR_RESULT:
                        innerState = InnerState.STOP_BY_ERROR;
                        if (controlConnectionListener.IsBusy) { controlConnectionListener.CancelAsync(); }
                        break;
                    case REMOTE_PASTE_EXECUTED:
                        //imposto la Clipboard di sistema
                        clipboard.CopyOnClipboard();
                        break;
                    case TRANSFER_CANCELLED:
                        //In questo caso non devo fare nulla perché il trasferimento è stato annullato
                        break;
                }
            }


        }
        /// <summary>
        /// Check the HTTP response status and handle anything unusual (e.g. not 200/206).
        /// </summary>
        /// <param name="state">
        /// The state.
        /// </param>
        /// <param name="innerState">
        /// The inner State.
        /// </param>
        /// <param name="response">
        /// The response.
        /// </param>
        private void HandleExceptionalStatus(State state, InnerState innerState, HttpWebResponse response)
        {
            HttpStatusCode statusCode = response.StatusCode;
            if (statusCode == HttpStatusCode.ServiceUnavailable
                && this.downloadInfo.FailedCount < DownloaderService.MaximumRetries)
            {
                HandleServiceUnavailable(state, response);
            }

            switch (statusCode)
            {
                case HttpStatusCode.TemporaryRedirect:
                case HttpStatusCode.SeeOther:
                case HttpStatusCode.Found:
                case HttpStatusCode.Moved:
                    this.HandleRedirect(state, response, statusCode);
                    break;
            }

            HttpStatusCode expectedStatus = innerState.ContinuingDownload
                                                ? HttpStatusCode.PartialContent
                                                : HttpStatusCode.OK;
            if (statusCode != expectedStatus)
            {
                HandleOtherStatus(innerState, statusCode);
            }
            else
            {
                // no longer redirected
                state.RedirectCount = 0;
            }
        }
        private void mouseWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (innerState == InnerState.STOP_BY_ERROR || innerState == InnerState.STOP_BY_NETWORK_ERROR || innerState == InnerState.STOP_BY_CONTROLLER)
            { return; }

            if (e.Result != null)
            {
                string result = e.Result as string;
                switch (result)
                {
                    case NETWORK_ERROR_RESULT:
                        innerState = InnerState.STOP_BY_NETWORK_ERROR;
                        if (controlConnectionListener.IsBusy) { controlConnectionListener.CancelAsync(); }
                        break;

                    case CLIENT_ERROR_RESULT:
                        innerState = InnerState.STOP_BY_ERROR;
                        if (controlConnectionListener.IsBusy) { controlConnectionListener.CancelAsync(); }
                        break;
                }
            }
        }
Esempio n. 52
0
 public void CancelReturnTransaction()
 {
     //show the welcome page
     state = InnerState.WELCOME;
     View.ShowWelcomePage();
 }
 /// <summary>
 /// Update necessary database fields based on values of HTTP response headers that have been read.
 /// </summary>
 /// <param name="innerState">
 /// The inner State.
 /// </param>
 private void UpdateDatabaseFromHeaders(InnerState innerState)
 {
     this.downloadInfo.ETag = innerState.HeaderETag;
     DownloadsDatabase.UpdateDownload(this.downloadInfo);
 }
        /// <summary>
        /// Fully execute a single download request - setup and send the request,
        /// handle the response, and transfer the data to the destination file.
        /// </summary>
        /// <param name="state">
        /// The state.
        /// </param>
        /// <param name="request">
        /// The request.
        /// </param>
        private void ExecuteDownload(State state, HttpWebRequest request)
        {
            var innerState = new InnerState();
            var data = new byte[DownloaderService.BufferSize];

            this.CheckPausedOrCanceled();

            this.SetupDestinationFile(state, innerState);
            AddRequestHeaders(innerState, request);

            // check just before sending the request to avoid using an invalid connection at all
            this.CheckConnectivity();

            this.downloadNotification.OnDownloadStateChanged(DownloaderState.Connecting);
            HttpWebResponse response = this.SendRequest(state, request);
            this.HandleExceptionalStatus(state, innerState, response);

            Debug.WriteLine("DownloadThread : received response for {0}", this.downloadInfo.Uri);

            this.ProcessResponseHeaders(state, innerState, response);
            Stream entityStream = this.OpenResponseEntity(state, response);
            this.downloadNotification.OnDownloadStateChanged(DownloaderState.Downloading);
            this.TransferData(state, innerState, data, entityStream);
        }
        /// <summary>
        /// Report download progress through the database if necessary.
        /// </summary>
        /// <param name="innerState">
        /// The inner State.
        /// </param>
        private void ReportProgress(InnerState innerState)
        {
            long now = PolicyExtensions.GetCurrentMilliseconds();
            if (innerState.BytesSoFar - innerState.BytesNotified > DownloaderService.MinimumProgressStep
                && now - innerState.TimeLastNotification > DownloaderService.MinimumProgressTime)
            {
                // we store progress updates to the database here
                this.downloadInfo.CurrentBytes = innerState.BytesSoFar;
                DownloadsDatabase.UpdateDownloadCurrentBytes(this.downloadInfo);

                innerState.BytesNotified = innerState.BytesSoFar;
                innerState.TimeLastNotification = now;

                long totalBytesSoFar = innerState.BytesThisSession + this.downloaderService.BytesSoFar;

                Debug.WriteLine(
                    "DownloadThread : downloaded {0} out of {1}", 
                    this.downloadInfo.CurrentBytes, 
                    this.downloadInfo.TotalBytes);
                Debug.WriteLine(
                    "DownloadThread :      total {0} out of {1}", totalBytesSoFar, this.downloaderService.TotalLength);

                this.downloaderService.NotifyUpdateBytes(totalBytesSoFar);
            }
        }
        /// <summary>
        /// Handle a status that we don't know how to deal with properly.
        /// </summary>
        /// <param name="innerState">
        /// The inner State.
        /// </param>
        /// <param name="statusCode">
        /// The status Code.
        /// </param>
        private static void HandleOtherStatus(InnerState innerState, HttpStatusCode statusCode)
        {
            ExpansionDownloadStatus finalStatus;
            var downloadStatus = (ExpansionDownloadStatus)statusCode;

            if (downloadStatus.IsError())
            {
                finalStatus = downloadStatus;
            }
            else if (downloadStatus.IsRedirect())
            {
                finalStatus = ExpansionDownloadStatus.UnhandledRedirect;
            }
            else if (innerState.ContinuingDownload && downloadStatus == ExpansionDownloadStatus.Success)
            {
                finalStatus = ExpansionDownloadStatus.CannotResume;
            }
            else
            {
                finalStatus = ExpansionDownloadStatus.UnhandledHttpCode;
            }

            throw new StopRequestException(finalStatus, "http error " + statusCode);
        }
        /// <summary>
        /// Prepare the destination file to receive data. 
        /// If the file already exists, we'll set up appropriately for resumption.
        /// </summary>
        /// <param name="state">
        /// </param>
        /// <param name="innerState">
        /// </param>
        private void SetupDestinationFile(State state, InnerState innerState)
        {
            if (state.Filename != null)
            {
                // only true if we've already run a thread for this download
                if (!Helpers.IsFilenameValid(state.Filename))
                {
                    // this should never happen
                    throw new StopRequestException(
                        ExpansionDownloadStatus.FileError, "found invalid internal destination filename");
                }

                // We're resuming a download that got interrupted
                if (File.Exists(state.Filename))
                {
                    long fileLength = new FileInfo(state.Filename).Length;
                    if (fileLength == 0)
                    {
                        // The download hadn't actually started, we can restart from scratch
                        File.Delete(state.Filename);
                        state.Filename = null;
                    }
                    else if (this.downloadInfo.ETag == null)
                    {
                        // This should've been caught upon failure
                        File.Delete(state.Filename);
                        throw new StopRequestException(
                            ExpansionDownloadStatus.CannotResume, "Trying to resume a download that can't be resumed");
                    }
                    else
                    {
                        // All right, we'll be able to resume this download
                        try
                        {
                            state.Stream = new FileStream(state.Filename, FileMode.Append);
                        }
                        catch (FileNotFoundException exc)
                        {
                            throw new StopRequestException(
                                ExpansionDownloadStatus.FileError, "while opening destination for resuming: " + exc, exc);
                        }

                        innerState.BytesSoFar = (int)fileLength;
                        if (this.downloadInfo.TotalBytes != -1)
                        {
                            innerState.HeaderContentLength = this.downloadInfo.TotalBytes.ToString();
                        }

                        innerState.HeaderETag = this.downloadInfo.ETag;
                        innerState.ContinuingDownload = true;
                    }
                }
            }

            if (state.Stream != null)
            {
                CloseDestination(state);
            }
        }
        /// <summary>
        /// Read headers from the HTTP response and store them into local state.
        /// </summary>
        /// <param name="innerState">
        /// The inner State.
        /// </param>
        /// <param name="response">
        /// The response.
        /// </param>
        private void ReadResponseHeaders(InnerState innerState, HttpWebResponse response)
        {
            string header = response.GetResponseHeader("Content-Disposition");
            if (header != null)
            {
                innerState.HeaderContentDisposition = header;
            }

            header = response.GetResponseHeader("Content-Location");
            if (header != null)
            {
                innerState.HeaderContentLocation = header;
            }

            header = response.GetResponseHeader("ETag");
            if (header != null)
            {
                innerState.HeaderETag = header;
            }

            header = response.GetResponseHeader("Content-Type");
            if (header != null && header != "application/vnd.android.obb")
            {
                throw new StopRequestException(
                    ExpansionDownloadStatus.FileDeliveredIncorrectly, "file delivered with incorrect Mime type");
            }

            string headerTransferEncoding = response.GetResponseHeader("Transfer-Encoding");

            // todo - there seems to be no similar thing in .NET
            // if (!string.IsNullOrEmpty(headerTransferEncoding))
            // {
            header = response.GetResponseHeader("Content-Length");
            if (header != null)
            {
                innerState.HeaderContentLength = header;

                // this is always set from Market
                long contentLength = long.Parse(innerState.HeaderContentLength);
                if (contentLength != -1 && contentLength != this.downloadInfo.TotalBytes)
                {
                    // we're most likely on a bad wifi connection -- we should probably
                    // also look at the mime type --- but the size mismatch is enough
                    // to tell us that something is wrong here
                    Debug.WriteLine("LVLDL Incorrect file size delivered.");
                }
            }

            // }
            // else
            // {
            // // Ignore content-length with transfer-encoding - 2616 4.4 3
            // System.Diagnostics.Debug.WriteLine("DownloadThread : ignoring content-length because of xfer-encoding");
            // }
            Debug.WriteLine("DownloadThread : Content-Disposition: " + innerState.HeaderContentDisposition);
            Debug.WriteLine("DownloadThread : Content-Length: " + innerState.HeaderContentLength);
            Debug.WriteLine("DownloadThread : Content-Location: " + innerState.HeaderContentLocation);
            Debug.WriteLine("DownloadThread : ETag: " + innerState.HeaderETag);
            Debug.WriteLine("DownloadThread : Transfer-Encoding: " + headerTransferEncoding);

            bool noSizeInfo = innerState.HeaderContentLength == null
                              &&
                              (headerTransferEncoding == null
                               || !"chunked".Equals(headerTransferEncoding, StringComparison.OrdinalIgnoreCase));
            if (noSizeInfo)
            {
                throw new StopRequestException(ExpansionDownloadStatus.HttpDataError, "can't know size of download, giving up");
            }
        }
Esempio n. 59
0
        /// <summary>
        /// Allows the game component to update itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        public override void Update(GameTime gameTime)
        {
            // TODO: Add your update code here
            //Make the state fade in and out, removing after certain amount of time
            switch (state)
            {
                case InnerState.Appearing:
                    if (alpha >= 254.0f)
                        state = InnerState.Showing;
                    alpha += (float)gameTime.ElapsedGameTime.TotalMilliseconds * 0.1f;
                    break;
                case InnerState.Showing:
                    if (time > 3000)
                        state = InnerState.Fading;
                    time += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
                    break;
                case InnerState.Fading:
                    if (alpha <= 1.0f)
                        Manager.StateManager.RemoveState(this);
                    alpha -= (float)gameTime.ElapsedGameTime.TotalMilliseconds * 0.1f;
                    break;
            }

            alpha = MathHelper.Clamp(alpha, 0.0f, 255.0f);
            base.Update(gameTime);
        }
        /// <summary>
        /// Read some data from the HTTP response stream, handling I/O errors.
        /// </summary>
        /// <param name="state">
        /// </param>
        /// <param name="innerState">
        /// </param>
        /// <param name="data">
        /// data buffer to use to read data
        /// </param>
        /// <param name="entityStream">
        /// entityStream stream for reading the HTTP response entity
        /// </param>
        /// <returns>
        /// the number of bytes actually read or -1 if the end of the stream has been reached
        /// </returns>
        private int ReadFromResponse(State state, InnerState innerState, byte[] data, Stream entityStream)
        {
            try
            {
                return entityStream.Read(data, 0, data.Length);
            }
            catch (IOException ex)
            {
                this.LogNetworkState();
                this.downloadInfo.CurrentBytes = innerState.BytesSoFar;
                DownloadsDatabase.UpdateDownload(this.downloadInfo);

                string message;
                ExpansionDownloadStatus finalStatus;
                if (CannotResume(innerState))
                {
                    finalStatus = ExpansionDownloadStatus.CannotResume;
                    message =
                        string.Format("while reading response: {0}, can't resume interrupted download with no ETag", ex);
                }
                else
                {
                    finalStatus = this.GetFinalStatusForHttpError(state);
                    message = string.Format("while reading response: {0}", ex);
                }

                throw new StopRequestException(finalStatus, message, ex);
            }
        }