示例#1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DownloadNotification"/> class.
 /// </summary>
 /// <param name="ctx">
 /// The ctx.
 /// </param>
 /// <param name="applicationLabel">
 /// The application label.
 /// </param>
 internal DownloadNotification(Context ctx, string applicationLabel)
 {
     this.clientState         = DownloaderState.Unknown;
     this.context             = ctx;
     this.label               = applicationLabel;
     this.notificationManager =
         this.context.GetSystemService(Context.NotificationService).JavaCast <NotificationManager>();
     this.notification        = new Notification();
     this.currentNotification = this.notification;
 }
示例#2
0
 private int FindIndexByStatus(DownloaderState state)
 {
     for (int i = 0; i < dgvDownload.Rows.Count; i++)
     {
         if ((DownloaderState)dgvDownload.Rows[i].Cells[5].Tag == state)
         {
             return(i);
         }
     }
     return(-1);
 }
        protected override void Establish_context()
        {
            base.Establish_context();
            if (File.Exists(BinaryStateSerializer.STATE_FILE_NAME))
            {
                File.Delete(BinaryStateSerializer.STATE_FILE_NAME);
            }

            createdByDefaultState            = BinaryStateSerializer.CurrentState;
            createdByDefaultState.CurrentUri = uriInStateToSave;
        }
示例#4
0
        public static bool IsWaitingForCellApproval(this DownloaderState newState)
        {
            bool showCellMessage = false;

            switch (newState)
            {
            case DownloaderState.PausedNeedCellularPermission:
            case DownloaderState.PausedWifiDisabledNeedCellularPermission:
                showCellMessage = true;
                break;
            }
            return(showCellMessage);
        }
示例#5
0
        public DownloaderState GetDownloadStateById(int id)
        {
            DownloaderState state = DownloaderState.UnknowDownload;

            Execute(() =>
            {
                Downloader downloader = GetDownloaderById(id);
                if (downloader != null)
                {
                    state = downloader.State;
                }
            });
            return(state);
        }
示例#6
0
        public static bool IsIndeterminate(this DownloaderState newState)
        {
            bool indeterminate = false;

            switch (newState)
            {
            case DownloaderState.Idle:
            case DownloaderState.Connecting:
            case DownloaderState.FetchingUrl:
                indeterminate = true;
                break;
            }
            return(indeterminate);
        }
示例#7
0
        public static bool IsPaused(this DownloaderState newState)
        {
            bool paused = true;

            switch (newState)
            {
            case DownloaderState.Idle:
            case DownloaderState.Connecting:
            case DownloaderState.FetchingUrl:
            case DownloaderState.Downloading:
                paused = false;
                break;
            }
            return(paused);
        }
示例#8
0
        public void OnDownloadStateChanged(DownloaderState newState)
        {
            if (this.downloaderState != newState)
            {
                this.downloaderState     = newState;
                this.statusTextView.Text = Helpers.GetDownloaderStringFromState(newState);
            }

            if (newState != DownloaderState.Completed)
            {
                this.dashboardView.Visibility   = newState.CanShowProgress() ? ViewStates.Visible : ViewStates.Gone;
                this.useCellDataView.Visibility = newState.IsWaitingForCellApproval() ? ViewStates.Visible : ViewStates.Gone;
                this.progressBar.Indeterminate  = newState.IsIndeterminate();
                this.UpdatePauseButton(newState.IsPaused());
            }
        }
示例#9
0
        public static bool CanShowProgress(this DownloaderState newState)
        {
            bool showDashboard = true;

            switch (newState)
            {
            case DownloaderState.Failed:
            case DownloaderState.FailedCanceled:
            case DownloaderState.FailedFetchingUrl:
            case DownloaderState.FailedUnlicensed:
            case DownloaderState.PausedNeedCellularPermission:
            case DownloaderState.PausedWifiDisabledNeedCellularPermission:
                showDashboard = false;
                break;
            }
            return(showDashboard);
        }
示例#10
0
        public void OnDownloadStateChanged(DownloaderState newState)
        {
            if (this.downloaderState != newState)
            {
                this.downloaderState = newState;

                RunOnUiThread(() => { _progressDialog.SetMessage(GetDownloaderStringFromState(newState)); });
            }

            if (newState != DownloaderState.Completed)
            {
                _progressDialog.Indeterminate = newState.IsIndeterminate();
            }
            else
            {
                _progressDialog.SetMessage(GetString(Resource.String.apkDown_completed));
                CheckDownloadedFile();
            }
        }
示例#11
0
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            DownloaderState ds = ((DownloaderState)value);
            string          currentStateDescribe = string.Empty;

            switch (ds)
            {
            case DownloaderState.NeedToPrepare:
            case DownloaderState.WaitingForReconnect:
            case DownloaderState.Preparing:
            case DownloaderState.Prepared:
            case DownloaderState.Pausing:
            case DownloaderState.Paused:
            case DownloaderState.Working: currentStateDescribe = "移除"; break;

            case DownloaderState.Ended:
            case DownloaderState.EndedWithError: currentStateDescribe = "删除"; break;
            }
            return(currentStateDescribe);
        }
示例#12
0
 private void ControlDownloadFiles()
 {
     foreach (KeyValuePair <int, DownloadFile_v1 <TKey> > value in _downloadFiles)
     {
         DownloadFile_v1 <TKey> downloadFile = value.Value;
         // downloadFile.state == DownloadState.DownloadStarted
         //if (downloadFile.state == DownloadState.WaitToDownload)
         //{
         DownloaderState state = _downloadClient.GetDownloadStateById(downloadFile.downloadId);
         if (state == DownloaderState.NeedToPrepare)
         {
             if (_downloadClient.GetDownloadRetryCountById(downloadFile.downloadId) == _downloadClient.GetMaxRetryCount())
             {
                 downloadFile.state = DownloadState.DownloadFailed;
                 EndDownloadFile(downloadFile);
             }
         }
         //}
     }
 }
示例#13
0
        private void btnDownload_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < dgvDownload.SelectedRows.Count; i++)
            {
                DataGridViewRow row = dgvDownload.SelectedRows[i];

                DownloaderState state = (DownloaderState)row.Cells[5].Tag;

                // queuing
                if (state != DownloaderState.Downloading && state != DownloaderState.Ended)
                {
                    SetStatus(row.Index, DownloaderState.Queuing);
                }
            }

            if (!isDownloading)
            {
                DoDownload();
            }
        }
示例#14
0
        private void ControlDownloadFiles()
        {
            foreach (int downloadId in _currentDownloadFiles.Keys.ToArray())
            {
                DownloadLinkRef downloadLinkRef = _currentDownloadFiles[downloadId];
                DownloaderState state           = _downloadClient.GetDownloadStateById(downloadLinkRef.DownloadId);
                if (state == DownloaderState.NeedToPrepare)
                {
                    if (_downloadClient.GetDownloadRetryCountById(downloadLinkRef.DownloadId) == _downloadClient.GetMaxRetryCount())
                    {
                        QueueDownloadFile downloadFile = GetQueueDownloadFile(downloadLinkRef.QueueDownloadFileId);
                        downloadFile.Modified = true;
                        DownloadFilePartLink filePartLink = GetDownloadFilePartLink(downloadLinkRef);

                        downloadFile.UncompleteDownload = true;
                        DownloadItemLink itemLink = GetDownloadItemLink(downloadLinkRef);
                        itemLink.UncompleteDownload = true;
                        filePartLink.State          = DownloadState.DownloadFailed;

                        EndDownloadFilePart(downloadId);
                    }
                }
            }
        }
示例#15
0
        /**
         * Download overview data.
         * @see WebDownload()
         * @see LocalDownload()
         */

        public void GetOverview()
        {
            if (_gotLocal)
            {
                SettingsManager.Instance.ContinueUpdate = false;
                SettingsManager.Instance.ErrorPosition  = ErrorPosition.Overview;
                bool finishedDownloadOK = false;

                // Download overview via HTTP or HTTPS.
                if (LocalInformation.UpdateServerUrl.Contains(Strings.SEARCHSTRING_HTTP) ||
                    LocalInformation.UpdateServerUrl.Contains(Strings.SEARCHSTRING_HTTPS))
                {
                    // Instantiate new downloader.
                    Downloader      overviewdownloader = new Downloader();
                    DownloaderState state = WebDownload(
                        overviewdownloader,
                        new StringBuilder().Append(LocalInformation.UpdateServerUrl).Append(Strings.FILE_OVERVIEW).ToString(),
                        new StringBuilder().Append(Strings.FOLDER_UPDATE_INFORMATION)
                        .Append(Path.DirectorySeparatorChar)
                        .Append(Strings.FILE_OVERVIEW)
                        .ToString()
                        );
                    while (!overviewdownloader.DownloadFinished)
                    {
                        Thread.Sleep(100);
                        Application.DoEvents();
                    }
                    if (overviewdownloader.ErrorMessage != null)
                    {
                        if (SettingsManager.Instance.UseGUI)
                        {
                            MessageBox.Show(overviewdownloader.ErrorMessage);
                        }
                    }
                    else
                    {
                        finishedDownloadOK = true;
                    }

                    // Download overview from LAN or local device.
                }
                else if (LocalInformation.UpdateServerUrl.StartsWith(Strings.STARTSTRING_LAN) ||
                         LocalInformation.UpdateServerUrl.Contains(Strings.SEARCHSTRING_LOCAL))
                {
                    // use network or local path to get information
                    Downloader      overviewdownloader = new Downloader();
                    DownloaderState state = overviewdownloader.Download(
                        new StringBuilder().Append(LocalInformation.UpdateServerUrl)
                        .Append(Path.DirectorySeparatorChar)
                        .Append(Strings.FILE_OVERVIEW)
                        .ToString(),
                        new StringBuilder().Append(Strings.FOLDER_UPDATE_INFORMATION)
                        .Append(Path.DirectorySeparatorChar)
                        .Append(Strings.FILE_OVERVIEW)
                        .ToString(),
                        null,
                        null);
                    if (overviewdownloader.ErrorMessage != null)
                    {
                        if (SettingsManager.Instance.UseGUI)
                        {
                            MessageBox.Show(overviewdownloader.ErrorMessage);
                        }
                    }
                    else
                    {
                        finishedDownloadOK = true;
                    }
                }

                // Try to deserialize overview data if download finished successfully.
                // Else return from GetOverview().
                if (finishedDownloadOK)
                {
                    try {
                        _overview = DeSerializer.Deserializer <Overview>(
                            new StringBuilder().Append(Strings.FOLDER_UPDATE_INFORMATION)
                            .Append(Path.DirectorySeparatorChar)
                            .Append(Strings.FILE_OVERVIEW)
                            .ToString());
                    } catch {
                        return;
                    }
                }

                // Continues update if version information found in overview.
                if (_overview != null)
                {
                    if (_overview.Versions.Count > 0)
                    {
                        _gotOverview = true;
                        SettingsManager.Instance.ContinueUpdate = true;
                    }
                }
            }
        }
示例#16
0
        /**
         * Get detailed remote version information.
         * Recursivly get all remote version information from newest avaiable down to current version.
         * Depends on applies to value in version information.
         * @param version newest version number
         */

        public void GetVersions(string version)
        {
            // If fetching local and overview informations finished successfully continue with update.
            if (_gotLocal && _gotOverview)
            {
                SettingsManager.Instance.ContinueUpdate = false;
                SettingsManager.Instance.ErrorPosition  = ErrorPosition.Remoteinformation;

                // Check if temporary folder for version exists. If not, create it.
                if (Directory.Exists(Path.GetFullPath(
                                         new StringBuilder().Append(Strings.FOLDER_UPDATE_INFORMATION)
                                         .Append(Path.DirectorySeparatorChar)
                                         .Append(version)
                                         .ToString())))
                {
                }
                else
                {
                    Directory.CreateDirectory(Path.GetFullPath(
                                                  new StringBuilder().Append(Strings.FOLDER_UPDATE_INFORMATION)
                                                  .Append(Path.DirectorySeparatorChar)
                                                  .Append(version)
                                                  .ToString()));
                }

                bool finishedDownloadOK = false;

                // Download via HTTP or HTTPS.
                if (LocalInformation.UpdateServerUrl.Contains(Strings.SEARCHSTRING_HTTP) ||
                    LocalInformation.UpdateServerUrl.Contains(Strings.SEARCHSTRING_HTTPS))
                {
                    Downloader      overviewdownloader = new Downloader();
                    DownloaderState state = WebDownload(overviewdownloader,
                                                        new StringBuilder()
                                                        .Append(LocalInformation.UpdateServerUrl)
                                                        .Append(Path.DirectorySeparatorChar)
                                                        .Append(version)
                                                        .Append(Path.DirectorySeparatorChar)
                                                        .Append(Strings.FILE_VERSION_INFORMATION)
                                                        .ToString(),
                                                        new StringBuilder()
                                                        .Append(Strings.FOLDER_UPDATE_INFORMATION)
                                                        .Append(Path.DirectorySeparatorChar)
                                                        .Append(version)
                                                        .Append(Path.DirectorySeparatorChar)
                                                        .Append(Strings.FILE_VERSION_INFORMATION)
                                                        .ToString());
                    while (!overviewdownloader.DownloadFinished)
                    {
                        Thread.Sleep(100);
                        Application.DoEvents();
                    }

                    if (overviewdownloader.ErrorMessage != null)
                    {
                        MessageBox.Show(overviewdownloader.ErrorMessage);
                    }
                    else
                    {
                        finishedDownloadOK = true;
                    }

                    // Download from LAN or local device.
                }
                else if (LocalInformation.UpdateServerUrl.StartsWith(Strings.STARTSTRING_LAN) ||
                         LocalInformation.UpdateServerUrl.Contains(Strings.SEARCHSTRING_LOCAL))
                {
                    // use network or local path to get information
                    Downloader      overviewdownloader = new Downloader();
                    DownloaderState state = overviewdownloader.Download(
                        new StringBuilder()
                        .Append(LocalInformation.UpdateServerUrl)
                        .Append(Path.DirectorySeparatorChar)
                        .Append(version)
                        .Append(Path.DirectorySeparatorChar)
                        .Append(Strings.FILE_VERSION_INFORMATION)
                        .ToString(),
                        new StringBuilder()
                        .Append(Strings.FOLDER_UPDATE_INFORMATION)
                        .Append(Path.DirectorySeparatorChar)
                        .Append(version)
                        .Append(Path.DirectorySeparatorChar)
                        .Append(Strings.FILE_VERSION_INFORMATION)
                        .ToString(),
                        null,
                        null);
                    while (!overviewdownloader.DownloadFinished)
                    {
                        Thread.Sleep(100);
                        Application.DoEvents();
                    }

                    if (overviewdownloader.ErrorMessage != null)
                    {
                        MessageBox.Show(overviewdownloader.ErrorMessage);
                    }
                    else
                    {
                        finishedDownloadOK = true;
                    }
                }

                // If download finished try to deserialize information.
                if (finishedDownloadOK)
                {
                    try {
                        _remoteVersions.Add(DeSerializer.Deserializer <VersionInformation>(
                                                new StringBuilder()
                                                .Append(Strings.FOLDER_UPDATE_INFORMATION)
                                                .Append(Path.DirectorySeparatorChar)
                                                .Append(version)
                                                .Append(Path.DirectorySeparatorChar)
                                                .Append(Strings.FILE_VERSION_INFORMATION)
                                                .ToString()));
                        SettingsManager.Instance.ContinueUpdate = true;
                    } catch {
                        return;
                    }
                }

                // Check if last downloaded version matches local installation. If not, get next previous version.
                if (_remoteVersions[_remoteVersions.Count - 1].AppliesToVersion.ToString() == _localInformation.CurrentVersion.ToString() ||
                    !SettingsManager.Instance.ContinueUpdate)
                {
                }
                else
                {
                    GetVersions(_remoteVersions[_remoteVersions.Count - 1].AppliesToVersion.ToString());
                }
            }
        }
示例#17
0
 /// <summary>
 /// Converts download states that are returned by the
 /// <see cref="IDownloaderClient.OnDownloadStateChanged"/> callback into usable strings.
 /// This is useful if using the state strings built into the library to display user messages.
 /// </summary>
 /// <param name="context">
 /// The context to use when reading resources.
 /// </param>
 /// <param name="state">
 /// A string representing one of the STATE_* constant values from <see cref="IDownloaderClient"/>.
 /// </param>
 /// <returns>
 /// A string id that corresponds to the state message.
 /// </returns>
 public static string GetDownloaderStringFromState(Context context, DownloaderState state)
 {
     return(context.GetString(GetDownloaderStringFromState(state)));
 }
示例#18
0
        /// <summary>
        ///     Downloads a file to a given path
        /// </summary>
        /// <param name="url">Url of the file to download</param>
        /// <param name="destination">Download to</param>
        /// <param name="user">(opt) Username for https access</param>
        /// <param name="pwd">(opt) Passwort for https access</param>
        /// <param name="proxyurl">(opt) Url of proxyserver</param>
        /// <param name="proxyuser">(opt) User for proxyserver</param>
        /// <param name="proxypwd">(opt) Passwort for proxyserver</param>
        /// <returns></returns>

        /**
         * Download.
         * Downloads a file to a given path.
         * @param url Url of the file to download
         * @param destination Download destination path
         * @param user (opt) Username for https access
         * @param pwd (opt) Passwort for https access
         * @param proxyurl (opt) Url of proxyserver
         * @param proxyuser (opt) User for proxyserver
         * @param proxyppwd (opt) Passwort for proxyserver
         * @see CheckWriteAccess
         * @return downloader state
         */
        public DownloaderState Download(string url, string destination, string user, string pwd, string proxyurl, string proxyuser,
                                        string proxypwd, string proxyport)
        {
            // try to check if destination folder exists and is writeable
            // if it does not exist create new folder from given destination
            _destination = Path.GetFullPath(@destination);

            // Check write access of destination directory.
            DownloaderState resultAccessChecker = CheckWriteAccess();

            if (resultAccessChecker == DownloaderState.ErrorDestinationNotAccessible)
            {
                return(resultAccessChecker);
            }

            // Check url.
            if (url.StartsWith(Strings.STARTSTRING_HTTPS))
            {
                _useHttps = true;
            }
            else
            {
                _useHttps = false;
            }

            // Check proxy given.
            if (proxyurl != null && proxyurl != "")
            {
                _useProxy = true;
            }
            else
            {
                _useProxy = false;
            }

            // Get new web client.
            WebClient client = new WebClient();

            // Generate fake zertificate for https.
            if (_useHttps)
            {
                client.Credentials = new NetworkCredential(user, pwd);

                ServicePointManager.ServerCertificateValidationCallback += delegate {
                    return(true);
                };
            }
            // Generate new proxy.
            if (_useProxy)
            {
                if (_useHttps)
                {
                    client.Proxy = new WebProxy(proxyurl, Convert.ToInt32(proxyport));
                    if (proxyuser != null && proxypwd != null)
                    {
                        client.Proxy.Credentials = new NetworkCredential(proxyuser, proxypwd);
                    }
                }
                else
                {
                    client.Proxy = new WebProxy(proxyurl, true);
                }
            }

            // Start download.
            try {
                client.DownloadProgressChanged += client_DownloadProgressChanged;
                client.DownloadFileCompleted   += client_DownloadFileCompleted;
                client.DownloadFileAsync(new Uri(url), destination);
            } catch (Exception ex) {
                _errorMessage = "Http/Https: " + ex.Message;
                return(DownloaderState.ErrorDownloadFailed);
            }

            return(DownloaderState.Running);
        }
 /// <summary>
 /// The on download state changed.
 /// </summary>
 /// <param name="newState">
 /// The new state.
 /// </param>
 public void OnDownloadStateChanged(DownloaderState newState)
 {
     using (var p = new Bundle(1))
     {
         p.PutInt(ClientMessageParameters.NewState, (int)newState);
         this.SendMessage(ClientMessages.DownloadStateChanged, p);
     }
 }
示例#20
0
        // execute in thread
        private void ManageEndDownloadFiles()
        {
            foreach (KeyValuePair <int, DownloadFile_v1 <TKey> > value in _downloadFiles)
            {
                DownloadFile_v1 <TKey> downloadFile = value.Value;
                if (downloadFile.state == DownloadState.DownloadStarted)
                {
                    DownloaderState state = _downloadClient.GetDownloadStateById(downloadFile.downloadId);
                    if (state == DownloaderState.Ended || state == DownloaderState.EndedWithError)
                    {
                        if (state == DownloaderState.Ended)
                        {
                            downloadFile.state = DownloadState.DownloadCompleted;
                        }
                        else
                        {
                            downloadFile.state = DownloadState.DownloadFailed;
                        }
                        EndDownloadFile(downloadFile);
                        //DownloadedFile_v1<TKey> downloadedFile = new DownloadedFile_v1<TKey>
                        //{
                        //    key = downloadFile.key,
                        //    downloadLinks = downloadFile.downloadLinks,
                        //    downloadLink = downloadFile.downloadLink,
                        //    file = downloadFile.file,
                        //    state = downloadFile.state,
                        //    requestTime = downloadFile.requestTime,
                        //    startDownloadTime = downloadFile.startDownloadTime,
                        //    endDownloadTime = DateTime.Now,
                        //    downloadDuration = DateTime.Now - downloadFile.startDownloadTime
                        //};
                        //string downloadedPath = _downloadClient.GetDownloadLocalFileById(downloadFile.downloadId);
                        //string downloadDirectory = zPath.GetDirectoryName(downloadFile.file);
                        ////if (_trace)
                        ////{
                        ////    pb.Trace.WriteLine("ManageEndDownloadFiles()                      : downloadFile.file : \"{0}\"", downloadFile.file);
                        ////    pb.Trace.WriteLine("ManageEndDownloadFiles()                      : _downloadClient.GetDownloadLocalFileById() : \"{0}\"", downloadedPath);
                        ////}
                        //downloadedFile.downloadedFile = zpath.PathSetDirectory(downloadedPath, downloadDirectory);
                        //downloadedFile.id = _mongoDownloadedFileManager.GetNewId();

                        //_mongoDownloadedFileManager.Save(downloadedFile.id, downloadedFile);
                        //_mongoQueueDownloadFileManager.Remove(downloadFile.id);
                        //_downloadClient.RemoveDownloadById(downloadFile.downloadId);

                        //// _uncompressFile
                        //if (_uncompressManager != null && CompressManager.IsCompressFile(downloadedPath))
                        //{
                        //    TaskManager.AddTask(new Task
                        //    {
                        //        name = "Uncompress download file",
                        //        task = () =>
                        //            {
                        //                UncompressFile(downloadedPath, downloadedFile, downloadDirectory);
                        //                _mongoDownloadedFileManager.Save(downloadedFile.id, downloadedFile);
                        //            }
                        //    });
                        //    if (_onDownloaded != null)
                        //        TaskManager.AddTask(new Task { name = "onDownloaded", task = () => _onDownloaded(downloadedFile) });
                        //}
                        //else if (_onDownloaded != null)
                        //    _onDownloaded(downloadedFile);

                        //DownloadFile<TKey> downloadFile2;
                        //if (!_downloadFiles.TryRemove(downloadFile.id, out downloadFile2))
                        //    pb.Trace.WriteLine("error unable to remove downloadFile with id {0} from ConcurrentDictionary _downloadFiles (DownloadManager<TKey>.ManageEndDownloadFiles())", downloadFile.id);
                        //continue;
                    }
                }
            }
        }
示例#21
0
        /// <summary>
        /// Converts download states that are returned by the
        /// <see cref="IDownloaderClient.OnDownloadStateChanged"/> callback into usable strings.
        /// This is useful if using the state strings built into the library to display user messages.
        /// </summary>
        /// <param name="state">
        /// One of the STATE_* constants from <see cref="IDownloaderClient"/>.
        /// </param>
        /// <returns>
        /// A string message tht corresponds to the state.
        /// </returns>
        public static string GetDownloaderStringFromState(DownloaderState state)
        {
            switch (state)
            {
            case DownloaderState.Idle:
                return("Waiting for download to start");

            case DownloaderState.FetchingUrl:
                return("Looking for resources to download");

            case DownloaderState.Connecting:
                return("Connecting to the download server");

            case DownloaderState.Downloading:
                return("Downloading resources");

            case DownloaderState.Completed:
                return("Download finished");

            case DownloaderState.PausedNetworkUnavailable:
                return("Download paused because no network is available");

            case DownloaderState.PausedByRequest:
                return("Download paused");

            case DownloaderState.PausedWifiDisabled:
            case DownloaderState.PausedWifiDisabledNeedCellularPermission:
                return("Download paused because wifi is disabled");

            case DownloaderState.PausedNeedWifi:
            case DownloaderState.PausedNeedCellularPermission:
                return("Download paused because wifi is unavailable");

            case DownloaderState.PausedRoaming:
                return("Download paused because you are roaming");

            case DownloaderState.PausedNetworkSetupFailure:
                return("Download paused. Test a website in browser");

            case DownloaderState.PausedSdCardUnavailable:
                return("Download paused because the external storage is unavailable");

            case DownloaderState.FailedUnlicensed:
                return("Download failed because you may not have purchased this app");

            case DownloaderState.FailedFetchingUrl:
                return("Download failed because the resources could not be found");

            case DownloaderState.FailedSdCardFull:
                return("Download failed because the external storage is full");

            case DownloaderState.Failed:
                return("Download failed");

            case DownloaderState.FailedCanceled:
                return("Download cancelled");

            default:
                return("Starting...");
            }
        }
        /// <summary>
        /// The on download state changed.
        /// </summary>
        /// <param name="newState">
        /// The new state.
        /// </param>
        public void OnDownloadStateChanged(DownloaderState newState)
        {
            if (null != this.clientProxy)
            {
                this.clientProxy.OnDownloadStateChanged(newState);
            }

            if (newState != this.clientState)
            {
                this.clientState = newState;
                if (newState == DownloaderState.Idle || null == this.PendingIntent)
                {
                    return;
                }

                int stringDownload;
                int iconResource;
                bool ongoingEvent;

                // get the new title string and paused text
                switch (newState)
                {
                    case DownloaderState.Downloading:
                        iconResource = Android.Resource.Drawable.StatSysDownload;
                        stringDownload = Helpers.GetDownloaderStringFromState(newState);
                        ongoingEvent = true;
                        break;

                    case DownloaderState.FetchingUrl:
                    case DownloaderState.Connecting:
                        iconResource = Android.Resource.Drawable.StatSysDownloadDone;
                        stringDownload = Helpers.GetDownloaderStringFromState(newState);
                        ongoingEvent = true;
                        break;

                    case DownloaderState.Completed:
                    case DownloaderState.PausedByRequest:
                        iconResource = Android.Resource.Drawable.StatSysDownloadDone;
                        stringDownload = Helpers.GetDownloaderStringFromState(newState);
                        ongoingEvent = false;
                        break;

                    case DownloaderState.Failed:
                    case DownloaderState.FailedCanceled:
                    case DownloaderState.FailedFetchingUrl:
                    case DownloaderState.FailedSdCardFull:
                    case DownloaderState.FailedUnlicensed:
                        iconResource = Android.Resource.Drawable.StatSysWarning;
                        stringDownload = Helpers.GetDownloaderStringFromState(newState);
                        ongoingEvent = false;
                        break;

                    default:
                        iconResource = Android.Resource.Drawable.StatSysWarning;
                        stringDownload = Helpers.GetDownloaderStringFromState(newState);
                        ongoingEvent = true;
                        break;
                }

                this.currentText = context.GetString(stringDownload);
                this.currentTitle = this.label;

                    this.currentNotification.TickerText = new String(this.label + ": " + this.currentText);
                    this.currentNotification.Icon = iconResource;
                    this.currentNotification.SetLatestEventInfo(this.context, this.currentTitle, this.currentText, this.PendingIntent);
                    if (ongoingEvent)
                    {
                        this.currentNotification.Flags |= NotificationFlags.OngoingEvent;
                    }
                    else
                    {
                        this.currentNotification.Flags &= ~NotificationFlags.OngoingEvent;
                        this.currentNotification.Flags |= NotificationFlags.AutoCancel;
                    }

                    this.notificationManager.Notify(NotificationId, this.currentNotification);
                }
        }
示例#23
0
        // Token: 0x06000105 RID: 261 RVA: 0x00005B78 File Offset: 0x00003D78
        public bool IsWorking()
        {
            DownloaderState downloaderState = this.State;

            return(downloaderState == DownloaderState.Preparing || downloaderState == DownloaderState.WaitingForReconnect || downloaderState == DownloaderState.Working);
        }
示例#24
0
 // Token: 0x0600010D RID: 269 RVA: 0x00005C6E File Offset: 0x00003E6E
 private void SetState(DownloaderState value)
 {
     this.state = value;
     this.OnStateChanged();
 }
 /// <summary>
 /// Converts download states that are returned by the
 /// <see cref="IDownloaderClient.OnDownloadStateChanged"/> callback into usable strings.
 /// This is useful if using the state strings built into the library to display user messages.
 /// </summary>
 /// <param name="state">
 /// One of the STATE_* constants from <see cref="IDownloaderClient"/>.
 /// </param>
 /// <returns>
 /// A string message tht corresponds to the state.
 /// </returns>
 public static string GetDownloaderStringFromState(DownloaderState state)
 {
     switch (state)
     {
         case DownloaderState.Idle:
             return "Waiting for download to start";
         case DownloaderState.FetchingUrl:
             return "Looking for resources to download";
         case DownloaderState.Connecting:
             return "Connecting to the download server";
         case DownloaderState.Downloading:
             return "Downloading resources";
         case DownloaderState.Completed:
             return "Download finished";
         case DownloaderState.PausedNetworkUnavailable:
             return "Download paused because no network is available";
         case DownloaderState.PausedByRequest:
             return "Download paused";
         case DownloaderState.PausedWifiDisabled:
         case DownloaderState.PausedWifiDisabledNeedCellularPermission:
             return "Download paused because wifi is disabled";
         case DownloaderState.PausedNeedWifi:
         case DownloaderState.PausedNeedCellularPermission:
             return "Download paused because wifi is unavailable";
         case DownloaderState.PausedRoaming:
             return "Download paused because you are roaming";
         case DownloaderState.PausedNetworkSetupFailure:
             return "Download paused. Test a website in browser";
         case DownloaderState.PausedSdCardUnavailable:
             return "Download paused because the external storage is unavailable";
         case DownloaderState.FailedUnlicensed:
             return "Download failed because you may not have purchased this app";
         case DownloaderState.FailedFetchingUrl:
             return "Download failed because the resources could not be found";
         case DownloaderState.FailedSdCardFull:
             return "Download failed because the external storage is full";
         case DownloaderState.Failed:
             return "Download failed";
         case DownloaderState.FailedCanceled:
             return "Download cancelled";
         default:
             return "Starting...";
     }
 }
示例#26
0
        public string CopyFileToLocal(string version, UpdateFile file)
        {
            // Build remote path.
            string remotePath = new StringBuilder()
                                .Append(VersionsManager.Instance.LocalInformation.UpdateServerUrl)
                                .Append(Path.DirectorySeparatorChar)
                                .Append(version)
                                .Append(Path.DirectorySeparatorChar)
                                .Append(file.DestinationFolder)
                                .Append(Path.DirectorySeparatorChar)
                                .Append(file.Name)
                                .ToString();
            // Build local path.
            string localPath = new StringBuilder()
                               .Append(SettingsManager.Instance.BasePath)
                               .Append(Path.DirectorySeparatorChar)
                               .Append(Strings.FOLDER_UPDATE_INFORMATION)
                               .Append(Path.DirectorySeparatorChar)
                               .Append(Strings.FOLDER_TEMP_DOWNLOAD)
                               .Append(Path.DirectorySeparatorChar)
                               .Append(file.Name)
                               .ToString();
            // Get new downloader.
            Downloader downloader = new Downloader();

            ReportMessage(
                new StringBuilder().Append(Strings.MESSAGE_DOWNLOADING_TBC)
                .Append(remotePath)
                .Append(" -> ")
                .Append(localPath)
                .ToString());

            DownloaderState dlState = DownloaderState.OK;

            // switch download based on protocoll and/or location and load file.
            if (remotePath.Contains(Strings.SEARCHSTRING_HTTP) || remotePath.Contains(Strings.SEARCHSTRING_HTTPS))
            {
                dlState = downloader.Download(
                    remotePath,
                    localPath,
                    VersionsManager.Instance.LocalInformation.ServerUser.Name,
                    VersionsManager.Instance.LocalInformation.ServerUser.Pwd,
                    VersionsManager.Instance.LocalInformation.Proxy.Url,
                    VersionsManager.Instance.LocalInformation.Proxy.ProxyUser.Name,
                    VersionsManager.Instance.LocalInformation.Proxy.ProxyUser.Pwd,
                    VersionsManager.Instance.LocalInformation.Proxy.HttpsPort);
            }
            else if (remotePath.StartsWith(Strings.STARTSTRING_LAN) || remotePath.Contains(Strings.SEARCHSTRING_LOCAL))
            {
                dlState = downloader.Download(
                    remotePath,
                    localPath,
                    VersionsManager.Instance.LocalInformation.ServerUser.Name,
                    VersionsManager.Instance.LocalInformation.ServerUser.Pwd);
            }
            while (!downloader.DownloadFinished && dlState == DownloaderState.Running)
            {
                Thread.Sleep(200);
                Application.DoEvents();
                ReportProgress(downloader.PercentFinished);
            }
            if (dlState == DownloaderState.ErrorDestinationNotAccessible || dlState == DownloaderState.ErrorDownloadFailed)
            {
                ReportMessage(Strings.MESSAGE_DOWNLOAD_FAILED);
                return("0");
            }
            ReportMessage(Strings.MESSAGE_DOWNLOAD_FINISHED);
            return(localPath);
        }
示例#27
0
        /// <summary>
        /// Converts download states that are returned by the
        /// <see cref="IDownloaderClient.OnDownloadStateChanged"/> callback into usable string IDs.
        /// This is useful if using the state strings built into the library to display user messages.
        /// </summary>
        /// <param name="state">
        /// One of the STATE_* constants from <see cref="IDownloaderClient"/>.
        /// </param>
        /// <returns>
        /// A string ID that corresponds to the state message.
        /// </returns>
        public static int GetDownloaderStringFromState(DownloaderState state)
        {
            switch (state)
            {
            case DownloaderState.Idle:
                return(Resource.String.state_idle);

            case DownloaderState.FetchingUrl:
                return(Resource.String.state_fetching_url);

            case DownloaderState.Connecting:
                return(Resource.String.state_connecting);

            case DownloaderState.Downloading:
                return(Resource.String.state_downloading);

            case DownloaderState.Completed:
                return(Resource.String.state_completed);

            case DownloaderState.PausedNetworkUnavailable:
                return(Resource.String.state_paused_network_unavailable);

            case DownloaderState.PausedByRequest:
                return(Resource.String.state_paused_by_request);

            case DownloaderState.PausedWifiDisabled:
            case DownloaderState.PausedWifiDisabledNeedCellularPermission:
                return(Resource.String.state_paused_wifi_disabled);

            case DownloaderState.PausedNeedWifi:
            case DownloaderState.PausedNeedCellularPermission:
                return(Resource.String.state_paused_wifi_unavailable);

            case DownloaderState.PausedRoaming:
                return(Resource.String.state_paused_roaming);

            case DownloaderState.PausedNetworkSetupFailure:
                return(Resource.String.state_paused_network_setup_failure);

            case DownloaderState.PausedSdCardUnavailable:
                return(Resource.String.state_paused_sdcard_unavailable);

            case DownloaderState.FailedUnlicensed:
                return(Resource.String.state_failed_unlicensed);

            case DownloaderState.FailedFetchingUrl:
                return(Resource.String.state_failed_fetching_url);

            case DownloaderState.FailedSdCardFull:
                return(Resource.String.state_failed_sdcard_full);

            case DownloaderState.Failed:
                return(Resource.String.state_failed);

            case DownloaderState.FailedCanceled:
                return(Resource.String.state_failed_cancelled);

            default:
                return(Resource.String.state_unknown);
            }
        }
        public void OnDownloadStateChanged(DownloaderState newState)
        {
            if (this.downloaderState != newState)
            {
                this.downloaderState = newState;
                this.statusTextView.Text = this.GetString(Helpers.GetDownloaderStringFromState(newState));
            }

            if (newState != DownloaderState.Completed)
            {
                this.dashboardView.Visibility = newState.CanShowProgress() ? ViewStates.Visible : ViewStates.Gone;
                this.useCellDataView.Visibility = newState.IsWaitingForCellApproval() ? ViewStates.Visible : ViewStates.Gone;
                this.progressBar.Indeterminate = newState.IsIndeterminate();
                this.UpdatePauseButton(newState.IsPaused());
            }
        }
示例#29
0
 private int FindIndexByStatus(DownloaderState state)
 {
     for (int i = 0; i < dgvDownload.Rows.Count; i++)
     {
         if ((DownloaderState)dgvDownload.Rows[i].Cells[5].Tag == state)
         {
             return i;
         }
     }
     return -1;
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="DownloadNotification"/> class.
        /// </summary>
        /// <param name="ctx">
        /// The ctx.
        /// </param>
        /// <param name="applicationLabel">
        /// The application label.
        /// </param>
        internal DownloadNotification(Context ctx, string applicationLabel)
        {
            this.clientState = DownloaderState.Unknown;
            this.context = ctx;
            this.label = applicationLabel;
            this.notificationManager =
                this.context.GetSystemService(Context.NotificationService).JavaCast<NotificationManager>();
            this.notification = new Notification();
			this.customNotification = CustomNotificationFactory.CreateCustomNotification();
            this.currentNotification = this.notification;
        }
示例#31
0
 /// <summary>
 /// Конструктор.
 /// </summary>
 /// <param name="value">Новое значение загрузчика.</param>
 public StateChangedEventArgs(DownloaderState value)
 {
     this.Value = value;
 }
        /// <summary>
        /// The on download state changed.
        /// </summary>
        /// <param name="newState">
        /// The new state.
        /// </param>
        public void OnDownloadStateChanged(DownloaderState newState)
        {
            if (null != this.clientProxy)
            {
                this.clientProxy.OnDownloadStateChanged(newState);
            }

            if (newState != this.clientState)
            {
                this.clientState = newState;
                if (newState == DownloaderState.Idle || null == this.PendingIntent)
                {
                    return;
                }

                int  stringDownload;
                int  iconResource;
                bool ongoingEvent;

                // get the new title string and paused text
                switch (newState)
                {
                case DownloaderState.Downloading:
                    iconResource   = Android.Resource.Drawable.StatSysDownload;
                    stringDownload = Helpers.GetDownloaderStringFromState(newState);
                    ongoingEvent   = true;
                    break;

                case DownloaderState.FetchingUrl:
                case DownloaderState.Connecting:
                    iconResource   = Android.Resource.Drawable.StatSysDownloadDone;
                    stringDownload = Helpers.GetDownloaderStringFromState(newState);
                    ongoingEvent   = true;
                    break;

                case DownloaderState.Completed:
                case DownloaderState.PausedByRequest:
                    iconResource   = Android.Resource.Drawable.StatSysDownloadDone;
                    stringDownload = Helpers.GetDownloaderStringFromState(newState);
                    ongoingEvent   = false;
                    break;

                case DownloaderState.Failed:
                case DownloaderState.FailedCanceled:
                case DownloaderState.FailedFetchingUrl:
                case DownloaderState.FailedSdCardFull:
                case DownloaderState.FailedUnlicensed:
                    iconResource   = Android.Resource.Drawable.StatSysWarning;
                    stringDownload = Helpers.GetDownloaderStringFromState(newState);
                    ongoingEvent   = false;
                    break;

                default:
                    iconResource   = Android.Resource.Drawable.StatSysWarning;
                    stringDownload = Helpers.GetDownloaderStringFromState(newState);
                    ongoingEvent   = true;
                    break;
                }

                this.currentText  = context.GetString(stringDownload);
                this.currentTitle = this.label;

                this.currentNotification.TickerText = new String(this.label + ": " + this.currentText);
                this.currentNotification.Icon       = iconResource;
                this.currentNotification.SetLatestEventInfo(this.context, this.currentTitle, this.currentText, this.PendingIntent);
                if (ongoingEvent)
                {
                    this.currentNotification.Flags |= NotificationFlags.OngoingEvent;
                }
                else
                {
                    this.currentNotification.Flags &= ~NotificationFlags.OngoingEvent;
                    this.currentNotification.Flags |= NotificationFlags.AutoCancel;
                }

                this.notificationManager.Notify(NotificationId, this.currentNotification);
            }
        }
        /// <summary>
        /// The download state should trigger changes in the UI.
        /// It may be useful to show the state as being indeterminate at times.  
        /// </summary>
        /// <param name="newState">
        /// The new state.
        /// </param>
        public void OnDownloadStateChanged(DownloaderState newState)
        {
            Debug.WriteLine("newState: " + newState);

            if (this.downloaderState != newState)
            {
                this.downloaderState = newState;
                this.statusTextView.Text = Helpers.GetDownloaderStringFromState(newState);
            }

            bool showDashboard = true;
            bool showCellMessage = false;
            bool paused = false;
            bool indeterminate = true;
            switch (newState)
            {
                case DownloaderState.Idle:
                case DownloaderState.Connecting:
                case DownloaderState.FetchingUrl:
                    break;
                case DownloaderState.Downloading:
                    indeterminate = false;
                    break;
                case DownloaderState.Failed:
                case DownloaderState.FailedCanceled:
                case DownloaderState.FailedFetchingUrl:
                case DownloaderState.FailedUnlicensed:
                    paused = true;
                    showDashboard = false;
                    indeterminate = false;
                    break;
                case DownloaderState.PausedNeedCellularPermission:
                case DownloaderState.PausedWifiDisabledNeedCellularPermission:
                    showDashboard = false;
                    paused = true;
                    indeterminate = false;
                    showCellMessage = true;
                    break;
                case DownloaderState.PausedByRequest:
                    paused = true;
                    indeterminate = false;
                    break;
                case DownloaderState.PausedRoaming:
                case DownloaderState.PausedSdCardUnavailable:
                    paused = true;
                    indeterminate = false;
                    break;
                default:
                    paused = true;
                    break;
            }

            if (newState != DownloaderState.Completed)
            {
                this.dashboardView.Visibility = showDashboard ? ViewStates.Visible : ViewStates.Gone;
                this.useCellDataView.Visibility = showCellMessage ? ViewStates.Visible : ViewStates.Gone;
                this.progressBar.Indeterminate = indeterminate;
                this.UpdatePauseButton(paused);
            }
            else
            {
                this.ValidateExpansionFiles();
            }
        }
	    /// <summary>
        /// Converts download states that are returned by the
        /// <see cref="IDownloaderClient.OnDownloadStateChanged"/> callback into usable string IDs.
        /// This is useful if using the state strings built into the library to display user messages.
        /// </summary>
        /// <param name="state">
        /// One of the STATE_* constants from <see cref="IDownloaderClient"/>.
        /// </param>
        /// <returns>
        /// A string ID that corresponds to the state message.
        /// </returns>
        public static int GetDownloaderStringFromState(DownloaderState state)
        {
            switch (state)
            {
                case DownloaderState.Idle:
                    return Resource.String.state_idle;
                case DownloaderState.FetchingUrl:
					return Resource.String.state_fetching_url;
                case DownloaderState.Connecting:
					return Resource.String.state_connecting;
                case DownloaderState.Downloading:
					return Resource.String.state_downloading;
                case DownloaderState.Completed:
					return Resource.String.state_completed;
                case DownloaderState.PausedNetworkUnavailable:
					return Resource.String.state_paused_network_unavailable;
                case DownloaderState.PausedByRequest:
					return Resource.String.state_paused_by_request;
                case DownloaderState.PausedWifiDisabled:
                case DownloaderState.PausedWifiDisabledNeedCellularPermission:
					return Resource.String.state_paused_wifi_disabled;
                case DownloaderState.PausedNeedWifi:
                case DownloaderState.PausedNeedCellularPermission:
					return Resource.String.state_paused_wifi_unavailable;
                case DownloaderState.PausedRoaming:
					return Resource.String.state_paused_roaming;
                case DownloaderState.PausedNetworkSetupFailure:
					return Resource.String.state_paused_network_setup_failure;
                case DownloaderState.PausedSdCardUnavailable:
					return Resource.String.state_paused_sdcard_unavailable;
                case DownloaderState.FailedUnlicensed:
					return Resource.String.state_failed_unlicensed;
                case DownloaderState.FailedFetchingUrl:
					return Resource.String.state_failed_fetching_url;
                case DownloaderState.FailedSdCardFull:
					return Resource.String.state_failed_sdcard_full;
                case DownloaderState.Failed:
					return Resource.String.state_failed;
                case DownloaderState.FailedCanceled:
					return Resource.String.state_failed_cancelled;
                default:
					return Resource.String.state_unknown;
            }
        }
示例#35
0
        private void DoGetAssemblyPackages(object callState)
        {
            var arguments     = (object[])callState;
            var asyncResult   = (Threading.AsyncResult <AssemblyPackageContainer>)arguments[0];
            var assemblyParts = (IEnumerable <AssemblyPart>)arguments[1];
            AssemblyPackageContainer packageContainer = null;

            try
            {
                assemblyParts = assemblyParts.Distinct(AssemblyPartEqualityComparer.Instance);
                var result = new List <IAssemblyPackage>();
                var assemblyPartsPackage = GetAssemblyPackagesFromCache(assemblyParts);
                var assemblyParts2       = new List <AssemblyPart>();
                foreach (var package in assemblyPartsPackage.GroupBy(f => f.Item2))
                {
                    if (package.Key != null)
                    {
                        result.Add(package.Key.Package);
                    }
                    else
                    {
                        assemblyParts2.AddRange(package.Select(f => f.Item1));
                    }
                }
                if (assemblyParts2.Count == 0)
                {
                    packageContainer = new AssemblyPackageContainer(result);
                }
                else
                {
                    if (_assemblyFilesDirectories.Length > 0)
                    {
                        var container = GetAssemblyPackageFromLocal(assemblyParts2);
                        if (container != null)
                        {
                            result.AddRange(container);
                        }
                    }
                    else if (_downloader != null)
                    {
                        DownloaderState state = null;
                        lock (_downloaderLock)
                        {
                            var start = DateTime.Now.AddSeconds(60);
                            while (_downloader.IsBusy && start > DateTime.Now)
                            {
                                System.Threading.Thread.Sleep(200);
                            }
                            if (!_downloader.IsBusy)
                            {
                                _downloader.Add(new AssemblyPackage(assemblyParts2));
                                state = new DownloaderState(this, result, asyncResult);
                                _downloader.DownloadCompleted += Downloader_DownloadCompleted;
                                _downloader.RunAsync(state);
                            }
                        }
                        return;
                    }
                    packageContainer = new AssemblyPackageContainer(result.Distinct());
                }
            }
            catch (Exception ex3)
            {
                asyncResult.HandleException(ex3, false);
                return;
            }
            asyncResult.Complete(packageContainer, false);
        }
        private void SetState(DownloaderState value)
        {
            state = value;

            OnStateChanged();
        }
        private void SetState(DownloaderState value)
        {
            state = value;

            OnStateChanged();
        }
 /// <summary>
 /// Method to be called when all the requested photos have been downloaded.
 /// </summary>
 /// <remarks>This method directly calls OnFinished event invoker, so it should be 
 /// always BeginInvoke'd.</remarks>
 private void Done()
 {
     try
     {
         DisposeAsyncState(); //it should be already disposed
         Program.StatusSink.EndOperation();
         state = DownloaderState.Idle;
     }
     finally
     {
         OnFinished(); //this should get called _ALWAYS_...
     }
 }
示例#39
0
 private void SetState(DownloaderState value)
 {
     state = value;
 }
示例#40
0
        /// <summary>
        /// The download state should trigger changes in the UI.
        /// It may be useful to show the state as being indeterminate at times.
        /// </summary>
        /// <param name="newState">
        /// The new state.
        /// </param>
        public void OnDownloadStateChanged(DownloaderState newState)
        {
            Debug.WriteLine("newState: " + newState);

            if (this.downloaderState != newState)
            {
                this.downloaderState     = newState;
                this.statusTextView.Text = Helpers.GetDownloaderStringFromState(newState);
            }

            bool showDashboard   = true;
            bool showCellMessage = false;
            bool paused          = false;
            bool indeterminate   = true;

            switch (newState)
            {
            case DownloaderState.Idle:
            case DownloaderState.Connecting:
            case DownloaderState.FetchingUrl:
                break;

            case DownloaderState.Downloading:
                indeterminate = false;
                break;

            case DownloaderState.Failed:
            case DownloaderState.FailedCanceled:
            case DownloaderState.FailedFetchingUrl:
            case DownloaderState.FailedUnlicensed:
                paused        = true;
                showDashboard = false;
                indeterminate = false;
                break;

            case DownloaderState.PausedNeedCellularPermission:
            case DownloaderState.PausedWifiDisabledNeedCellularPermission:
                showDashboard   = false;
                paused          = true;
                indeterminate   = false;
                showCellMessage = true;
                break;

            case DownloaderState.PausedByRequest:
                paused        = true;
                indeterminate = false;
                break;

            case DownloaderState.PausedRoaming:
            case DownloaderState.PausedSdCardUnavailable:
                paused        = true;
                indeterminate = false;
                break;

            default:
                paused = true;
                break;
            }

            if (newState != DownloaderState.Completed)
            {
                this.dashboardView.Visibility   = showDashboard ? ViewStates.Visible : ViewStates.Gone;
                this.useCellDataView.Visibility = showCellMessage ? ViewStates.Visible : ViewStates.Gone;
                this.progressBar.Indeterminate  = indeterminate;
                this.UpdatePauseButton(paused);
            }
            else
            {
                this.ValidateExpansionFiles();
            }
        }
        /// <summary>
        /// Async callback for Request.BeginGetResponse().
        /// </summary>
        /// <param name="ar">Async result.</param>
        private void GetResponseCallback(IAsyncResult ar)
        {
            if (ar == null)
                return;
            if (asyncState == null)
                return;

            try
            {
                asyncState.Response = asyncState.Request.EndGetResponse(ar);
                if (asyncState.Response != null)
                {
                    asyncState.ResponseStream = asyncState.Response.GetResponseStream();
                    asyncState.ResponseStream.BeginRead(asyncState.Buffer, 0, asyncState.Buffer.Length,
                        new AsyncCallback(ResponseReadCallback), null);
                    state = DownloaderState.Downloading;
                }
            }
            catch (WebException ex)
            {
                if (abort)
                    HandleAsyncAbort();
                else
                    HandleDownloadException(ex);
            }
            catch (Exception ex)
            {
                HandleDownloadException(ex);
            }
        }
        /// <summary>
        /// Starts the downloading.
        /// </summary>
        public void BeginDownload()
        {
            if (state != DownloaderState.Idle)
                return;
            abort = false;

            if (photos.Count == 0)
            {
                //nothing to be done here and no work has started yet
                //as we haven't even started yet, there is no need to call Done() here
                //just invoke Finished event, it should get called always
                MethodInvoker async = () => OnFinished();
                async.BeginInvoke(null, null);
            }
            else
                try
                {
                    state = DownloaderState.Started;
                    Program.StatusSink.BeginOperation(0, photos.Count, string.Empty);
                    if (!abort)
                    {
                        MethodInvoker async = () => BeginDownloadNextPhoto();
                        async.BeginInvoke(null, null);
                    }
                    else
                    {
                        MethodInvoker async = () => Done();
                        async.BeginInvoke(null, null);
                    }
                }
                catch (Exception ex)
                {
                    state = DownloaderState.Idle;
                    currentPhoto = -1;
                    Program.PromptSink.Error(ex.Message);
                }
        }
 /// <summary>
 /// Initializes a new instance of Downloader.
 /// </summary>
 public Downloader()
 {
     currentPhoto = -1;
     photos = new List<Photo>();
     state = DownloaderState.Idle;
 }
        /// <summary>
        /// Starts downloading of the next photo int the queue.
        /// </summary>
        /// <remarks>This method should be treated as an extension to BeginDownloadPhoto()
        /// that just automatically fills in the photoIndex parameter and thus, it should be
        /// always called asynchronously.</remarks>
        private void BeginDownloadNextPhoto()
        {
            if (photos.Count == 0)
                return;

            if (currentPhoto == photos.Count - 1)
            {
                //this was the last photo, we're done
                currentPhoto = -1;
                MethodInvoker async = () => Done();
                async.BeginInvoke(null, null);
            }
            else if (currentPhoto >= -1 && currentPhoto <= photos.Count - 1)
            {
                //-1 is valid here as the photos must contain at least one item
                state = DownloaderState.PreparingRequest;
                currentPhoto++;
                Program.StatusSink.SetStatusText(string.Format(
                    Properties.Resources.Status_DownloadingFile,
                    Path.GetFileName(photos[currentPhoto].SourceURL)
                    ));
                Program.StatusSink.SetProgressBarPos(currentPhoto);
                BeginDownloadPhoto(currentPhoto);
            }
            else
                throw new InvalidOperationException("Invalid currentPhoto value.");
        }
        /// <summary>
        /// Starts download of a single photo.
        /// </summary>
        /// <param name="photoIndex">Index of the photo to be downloaded.</param>
        /// <remarks>This method should be called always asynchronously, with the exception of 
        /// BeginDownloadNextPhoto().</remarks>
        /// <seealso cref="LH.Apps.RajceDownloader.Engine.Downloader"/>
        private void BeginDownloadPhoto(int photoIndex)
        {
            if (photoIndex < 0 || photoIndex > photos.Count - 1)
                return;

            if (asyncState != null)
                asyncState.Dispose();

            asyncState = new AsyncState();
            asyncState.Photo = photos[photoIndex];
            try
            {
                string fileName = Path.GetFullPath(asyncState.Photo.TargetPath);
                if (File.Exists(fileName))
                {
                    //TODO: workaround for a directory with that name...
                    DialogResult dr = Program.PromptSink.Question(
                        string.Format(
                            Properties.Resources.Downloader_FileExists,
                            Path.GetFileName(fileName)
                            ),
                        MessageBoxButtons.YesNoCancel
                        );
                    switch (dr)
                    {
                        case DialogResult.Yes:
                            //just continue
                            break;

                        case DialogResult.No:
                            fileName = Utils.GetUniqueFileName(fileName);
                            break;

                        case DialogResult.Cancel:
                            //cancel this round
                            asyncState.Dispose();
                            asyncState = null;

                            MethodInvoker async = () => BeginDownloadNextPhoto();
                            async.BeginInvoke(null, null);
                            return;
                    }
                }

                asyncState.FileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None);
                asyncState.Request = WebRequest.Create(asyncState.Photo.SourceURL);
                if (!abort)
                {
                    asyncState.Request.BeginGetResponse(new AsyncCallback(GetResponseCallback), null);
                    state = DownloaderState.RequestSent;
                }
                else
                    HandleAsyncAbort();
            }
            catch (Exception ex)
            {
                HandleDownloadException(ex);
            }
        }
示例#46
0
        private void SetStatus(int rowIndex, DownloaderState state)
        {
            string status;
            switch (state)
            {
                case DownloaderState.Queuing:
                    status = "Queuing";
                    break;
                case DownloaderState.Downloading:
                    status = "Downloading";
                    break;
                case DownloaderState.Stopped:
                    status = "Stopped";
                    break;
                case DownloaderState.Ended:
                    status = "Done";
                    break;
                case DownloaderState.EndedWithError:
                    status = "Error";
                    break;
                default:
                    status = "Not started";
                    break;
            }

            dgvDownload.Rows[rowIndex].Cells[5].Value = status;
            dgvDownload.Rows[rowIndex].Cells[5].Tag = state;
        }
	    /// <summary>
	    /// Converts download states that are returned by the
	    /// <see cref="IDownloaderClient.OnDownloadStateChanged"/> callback into usable strings.
	    /// This is useful if using the state strings built into the library to display user messages.
	    /// </summary>
	    /// <param name="context">
	    /// The context to use when reading resources.
	    /// </param>
	    /// <param name="state">
	    /// A string representing one of the STATE_* constant values from <see cref="IDownloaderClient"/>.
	    /// </param>
	    /// <returns>
	    /// A string id that corresponds to the state message.
	    /// </returns>
	    public static string GetDownloaderStringFromState(Context context, DownloaderState state)
	    {
		    return context.GetString(GetDownloaderStringFromState(state));
	    }