Ejemplo n.º 1
0
        private void HandleError(Exception e, int operationCode)
        {
            if (operationCode != CurrentOperationCode || State == DownloadState.Error)
            {
                return;
            }

            lock (threadLock)
            {
                if (operationCode != CurrentOperationCode || State == DownloadState.Error)
                {
                    return;
                }

                if (State == DownloadState.Downloading && retryCount < MaximumRetries)
                {//自动重试,不烦用户
                    retryCount++;
                    AutoRefresh();
                    return;
                }
                else
                {
                    State = DownloadState.Error;
                    DisposeThreads();
                }
            }
            //上面的else执行后没有return,会执行这里
            DownloadError?.Invoke(e);
        }
Ejemplo n.º 2
0
        public void DownloadAndInstallPackage(
			ReportInstallProgress reportProgress,
			DownloadComplete downloadComplete,
			DownloadError downloadError,
			VerificationError verificationError,
			IsCancelled isCancelled
		)
        {
            string downloadPath = PrepareDownloadFilePath (FileUtil.GetUniqueTempPathInProject (), config.Filename);

            new Detail.AsyncTaskRunnerBuilder<byte[]> ().Do ((object[] args) => {
                return Net.Validator.MakeRequest (() => {
                    return API.V1.DownloadFile (config.PackageUrl, (progress) => reportProgress(progress), () => { return isCancelled (); });
                });
            }).OnError ((System.Exception e) => {
                downloadError(e);
                return Detail.AsyncTaskRunner<byte[]>.ErrorRecovery.Nothing;
            }).OnCompletion ((byte[] downloadedBytes) => {
                if (downloadedBytes.Length == 0) {
                    return;
                }
                try {
                    System.IO.File.WriteAllBytes (downloadPath, downloadedBytes);
                    string signatureUrl = SignatureUrlFromPackageUrl (config.PackageUrl);

                    VerifySignature (signatureUrl, downloadedBytes, verificationError, downloadError, isCancelled, () => {
                        downloadComplete (downloadPath);
                        InstallPackage (downloadPath);
                    });
                } catch (IOException e) {
                    downloadError (e as Exception);
                }
            }).Run ();
        }
Ejemplo n.º 3
0
        private static void VerifySignature(
            string signatureUrl,
            byte[] fileToVerify,
            VerificationError verificationError,
            DownloadError downloadError,
            IsCancelled isCancelled,
            Action onSuccess
            )
        {
            new Detail.AsyncTaskRunnerBuilder <byte[]> ().Do((object[] args) => {
                return(Net.Validator.MakeRequest(() => {
                    return API.V1.DownloadFile(signatureUrl, (progress) => {}, () => { return isCancelled(); });
                }));
            }).OnError((System.Exception e) => {
                downloadError(e);
                return(Detail.AsyncTaskRunner <byte[]> .ErrorRecovery.Nothing);
            }).OnCompletion((byte[] signature) => {
                if (SignatureMatches(signature, fileToVerify) == VerificationStatus.Success)
                {
                    onSuccess();
                    return;
                }

                verificationError();
            }).Run();
        }
Ejemplo n.º 4
0
        public void DownloadAndInstallPackage(
            ReportInstallProgress reportProgress,
            DownloadComplete downloadComplete,
            DownloadError downloadError,
            VerificationError verificationError,
            IsCancelled isCancelled
            )
        {
            string downloadPath = PrepareDownloadFilePath(FileUtil.GetUniqueTempPathInProject(), config.Filename);

            new Detail.AsyncTaskRunnerBuilder <byte[]> ().Do((object[] args) => {
                return(Net.Validator.MakeRequest(() => {
                    return API.V1.DownloadFile(config.PackageUrl, (progress) => reportProgress(progress), () => { return isCancelled(); });
                }));
            }).OnError((System.Exception e) => {
                downloadError(e);
                return(Detail.AsyncTaskRunner <byte[]> .ErrorRecovery.Nothing);
            }).OnCompletion((byte[] downloadedBytes) => {
                if (downloadedBytes.Length == 0)
                {
                    return;
                }
                try {
                    System.IO.File.WriteAllBytes(downloadPath, downloadedBytes);
                    string signatureUrl = SignatureUrlFromPackageUrl(config.PackageUrl);

                    VerifySignature(signatureUrl, downloadedBytes, verificationError, downloadError, isCancelled, () => {
                        downloadComplete(downloadPath);
                        InstallPackage(downloadPath);
                    });
                } catch (IOException e) {
                    downloadError(e as Exception);
                }
            }).Run();
        }
Ejemplo n.º 5
0
        public static async Task DownloadS3ObjectAsync(string downloadDir, string objectKey)
        {
            try
            {
                var settings     = SettingsManager.GetSettings();
                var downloadInfo = new DownloadObjectInfo {
                    DownloadDirectory = downloadDir, ObjectKey = objectKey
                };
                AmazonS3Client client = new AmazonS3Client(
                    settings.AWSAccessKeyID,
                    settings.AWSSecretAccessKey,
                    RegionEndpoint.GetBySystemName(settings.AWSS3Region.SystemName));

                var request = new GetObjectRequest {
                    BucketName = settings.AWSS3Bucket, Key = objectKey
                };
                var response = await client.GetObjectAsync(request);
                await SaveObjectAsync(response, downloadInfo);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                DownloadError?.Invoke("Error during download");
                throw ex;
            }
        }
Ejemplo n.º 6
0
        private void HandleError(Exception e, int operationCode)
        {
            lock (threadLock)
            {
                if (operationCode != CurrentOperationCode || State == DownloadState.Error)
                {
                    return;
                }

                if (State == DownloadState.Downloading && retryCount < MaximumRetries)
                {//自动重试,不烦用户
                    retryCount++;
                    Debug.WriteLine("正在进行第" + retryCount + "次重试...");
                    AutoRefresh();
                    return;
                }
                else
                {
                    State = DownloadState.Error;
                    DisposeThreads();
                }
            }
            //上面的else执行后没有return,会执行这里(事件回调内含Async不应在lock块中?)
            DownloadError?.Invoke(e);
        }
Ejemplo n.º 7
0
 protected void EgvDownloadError_RowCommand(object sender, CommandEventArgs e)
 {
     if (e.CommandName == "Deleted")
     {
         DownloadError.Delete(e.CommandArgument.ToString());
     }
 }
Ejemplo n.º 8
0
        public static void ProcessArchiveModel()
        {
            var model = GetArchiveModel();

            if (model != null)
            {
                foreach (var m in model)
                {
                    if (m.ArchiveTopicFilePath != null)
                    {
                        var topicFile = GetArchiveTopicFileName(m.ArchiveId);
                        var topic     = GetExistingTopic(topicFile);
                        if (topic != null)
                        {
                            try
                            {
                                var result = ProcessQueue(topic);
                                //if (result == GlacierResult.Completed)
                                //    DownloadSuccess?.Invoke($"Glacier archive was downloaded to {topic.GetOutputFile()}");
                            }
                            catch (Exception ex)
                            {
                                DownloadError?.Invoke("An error occurred processing a Glacier job. " + ex.Message);
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// 下载完成事件的回调函数
        /// </summary>
        private async void Client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            if (sender != client)
            {
                return;
            }
            try
            {
                string      path = StorageTools.Settings.DownloadFolderPath;
                StorageFile file = await StorageFile.GetFileFromPathAsync(Message.TempFilePath);

                await file.MoveAsync(await StorageFolder.GetFolderFromPathAsync(StorageTools.Settings.DownloadFolderPath), Message.FileName + Message.Extention, NameCollisionOption.GenerateUniqueName);

                //播放一个通知
                Toasts.ToastManager.ShowDownloadCompleteToastAsync(Strings.AppResources.GetString("DownloadCompleted"), Message.FileName + ": " +
                                                                   Converters.StringConverter.GetPrintSize(_prog_.CurrentValue), file.Path);
                //触发事件
                DownloadComplete?.Invoke(Message);
            }
            catch (Exception ex)
            {
                //若用户把下载文件夹设置在奇怪的地方,这里会导致无法访问,触发异常
                Debug.WriteLine(ex.ToString());
                DownloadError?.Invoke(ex);
            }
        }
 private void OnDownloadError(string errorType)
 {
     DownloadError?.Invoke(this, new DoanlodErrorArgs
     {
         Tag       = TagName,
         ErrorType = errorType
     });
 }
Ejemplo n.º 11
0
 private void OnDownloadError(string message)
 {
     if (DownloadStatus != DownloadStatus.Cancelled)
     {
         DownloadStatus = DownloadStatus.Error;
     }
     DownloadError?.Invoke(this, new DownloadErrorEventArgs(message));
 }
Ejemplo n.º 12
0
 protected void EBtnClear_Click(object sender, EventArgs e)
 {
     if (DownloadError.Clear())
     {
         BasePage.ResponseRedirect("DownloadErrorManage.aspx");
     }
     else
     {
         AdminPage.WriteErrMsg("清空下载地址错误信息失败!");
     }
 }
Ejemplo n.º 13
0
        //private bool unzipPackedFile(DownloadTask task)
        //{
        //    bool isSuccess = true;

        //    int index = task.storagePath.LastIndexOf("/");
        //    string unzipDir = Path.GetDirectoryName(task.storagePath);
        //    DirectoryInfo info = new DirectoryInfo(unzipDir);
        //    if (!info.Exists)
        //    {
        //        info.Create();
        //    }

        //    try
        //    {
        //        using (ZipInputStream s = new ZipInputStream(File.OpenRead(task.storagePath)))
        //        {
        //            ZipEntry theEntry;
        //            while ((theEntry = s.GetNextEntry()) != null)
        //            {
        //                string directoryName = Path.GetDirectoryName(theEntry.FileName);
        //                string fileName = Path.GetFileName(theEntry.FileName);
        //                string filePath = Path.Combine(unzipDir, theEntry.FileName);
        //                DirectoryInfo dirInfo = new DirectoryInfo(Path.Combine(unzipDir, directoryName));
        //                if (!dirInfo.Exists)
        //                {
        //                    dirInfo.Create();
        //                }

        //                if (File.Exists(filePath))
        //                {
        //                    File.Delete(filePath);
        //                }

        //                if (fileName != String.Empty)
        //                {
        //                    using (FileStream streamWriter = File.Create(filePath))
        //                    {
        //                        int size = 2048;
        //                        byte[] data = new byte[2048];
        //                        while (true)
        //                        {
        //                            size = s.Read(data, 0, data.Length);
        //                            if (size > 0)
        //                            {
        //                                streamWriter.Write(data, 0, size);
        //                            }
        //                            else
        //                            {
        //                                break;
        //                            }
        //                        }
        //                    }
        //                }
        //            }

        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        if (ex.Message.Contains("Disk full"))
        //        {
        //            task.errorCode = DownloadError.DiskFull;
        //        }
        //        else
        //        {
        //            task.errorCode = DownloadError.Unknown;
        //        }
        //        task.status = DownloadStatus.Fail;
        //        isSuccess = false;
        //    }
        //    return isSuccess;
        //}

        private void NotifyResult(DownloadTask task, DownloadStatus status, DownloadError error = DownloadError.Unknown)
        {
            task.status    = status;
            task.errorCode = error;
//			if (status == DownloadStatus.Complete) {
            lock (_finishedTasks) {
                _finishedTasks.Enqueue(task);
            }
//			}
            _currentTask = null;
        }
Ejemplo n.º 14
0
        /* Methode zum synchronen Download einer Datei */
        public void DownloadSync(string url, Stream destStream, int blockSize,
                                 DownloadProgress downloadProgress, DownloadEnd downloadEnd,
                                 DownloadError downloadError)
        {
            // Download-Objekt erzeugen und initialisieren
            Download download = new Download(url, destStream, blockSize,
                                             downloadProgress, downloadEnd, downloadError);

            // Download synchron starten
            download.PerformDownload();
        }
Ejemplo n.º 15
0
 /* Konstruktor */
 public Download(string url, Stream destStream, int blockSize,
                 DownloadProgress downloadProgress, DownloadEnd downloadEnd,
                 DownloadError downloadError)
 {
     this.Url              = url;
     this.BlockSize        = blockSize;
     this.DownloadProgress = downloadProgress;
     this.DownloadEnd      = downloadEnd;
     this.DestStream       = destStream;
     this.DownloadError    = downloadError;
 }
Ejemplo n.º 16
0
 /* Konstruktor */
 public Download(string url, Stream destStream, int blockSize,
     DownloadProgress downloadProgress, DownloadEnd downloadEnd,
     DownloadError downloadError)
 {
     this.Url = url;
     this.BlockSize = blockSize;
     this.DownloadProgress = downloadProgress;
     this.DownloadEnd  = downloadEnd;
     this.DestStream = destStream;
     this.DownloadError = downloadError ;
 }
Ejemplo n.º 17
0
        /* Methode zum synchronen Download einer Datei */
        public void DownloadSync(string url, Stream destStream, int blockSize,
            DownloadProgress downloadProgress, DownloadEnd downloadEnd,
            DownloadError downloadError)
        {
            // Download-Objekt erzeugen und initialisieren
            Download download = new Download(url, destStream, blockSize,
                downloadProgress, downloadEnd, downloadError);

            // Download synchron starten
            download.PerformDownload();
        }
Ejemplo n.º 18
0
        /* Methode zum asynchronen Download einer Datei */
        public void DownloadAsync(string url, Stream destStream, int blockSize, 
            DownloadProgress downloadProgress, DownloadEnd downloadEnd,
            DownloadError downloadError)
        {
            // Download-Objekt erzeugen und initialisieren
            Download download = new Download(url, destStream, blockSize,
                downloadProgress, downloadEnd, downloadError);

            // Thread für den Download starten
            Thread downloadThread = new Thread(new ThreadStart(download.PerformDownload));
            downloadThread.Start();
        }
Ejemplo n.º 19
0
        /* Methode zum asynchronen Download einer Datei */
        public void DownloadAsync(string url, Stream destStream, int blockSize,
                                  DownloadProgress downloadProgress, DownloadEnd downloadEnd,
                                  DownloadError downloadError)
        {
            // Download-Objekt erzeugen und initialisieren
            Download download = new Download(url, destStream, blockSize,
                                             downloadProgress, downloadEnd, downloadError);

            // Thread für den Download starten
            Thread downloadThread = new Thread(new ThreadStart(download.PerformDownload));

            downloadThread.Start();
        }
Ejemplo n.º 20
0
        protected override bool OnError(DownloadError error)
        {
            if (_errorCount == 0)
            {
                Log.InfoFormat("Failed download, Url = {0}, Message = {1}", Url, error.Message);
            }
            else
            {
                Log.InfoFormat("Retry failed download, Url = {0}, Message = {1}", Url, error.Message);
            }

            _errorCount++;
            return(_errorCount < RetryCount);
        }
Ejemplo n.º 21
0
        public object Download()
        {
            object bytes = new byte[0];

            while (true)
            {
                try
                {
                    OnBeforeDownload();
                    bytes = Wire.Download();

                    OnSuccess();
                    break;
                }
                catch (WebException ex)
                {
                    var error = new DownloadError {
                        Status = ex.Status, Message = ex.Message
                    };
                    var response = ex.Response as HttpWebResponse; //this can be null
                    if (response != null)
                    {
                        error.HttpStatus = response.StatusCode;
                    }

                    if (!OnError(error))
                    {
                        break;
                    }

                    //Forbidden
                    //NotFound

                    //if (ex.Status == WebExceptionStatus.ConnectFailure) //if we cannot even contact the web server we give up.
                    //  break;
                }
                catch (Exception e)
                {
                    var error = new DownloadError {
                        Message = e.Message
                    };
                    if (!OnError(error))
                    {
                        break;
                    }
                }
            }

            return(bytes);
        }
        protected override bool OnError(DownloadError error)
        {
            Log.InfoFormat("Download error, Proxy={0}, Url = {1}, Message = {2}", _selectorCopy.Current, Wire.Url, error.Message);

            bool tryAgain = true;
            _error.Push(new AttemptPair() { Proxy = _selectorCopy.Current, Error = error });

            if (_error.Count >= _selectorCopy.ProxyCount) //We went through all the proxies and they all had an error. We give up.
            {
                _error.Clear();
                tryAgain = false;
            }

            return tryAgain;
        }
Ejemplo n.º 23
0
 private void StartDisposeTemporaryFile()
 {
     Task.Run(async() =>
     {
         try
         {
             StorageFile temp = await StorageFile.GetFileFromPathAsync(Message.TempFilePath);
             await temp.DeleteAsync();
         }
         catch (Exception e)
         {
             DownloadError?.Invoke(e);
         }
     });
 }
Ejemplo n.º 24
0
        internal static void ThrowException(int errorCode, string errorMessage = null, string paramName = null)
        {
            DownloadError err = (DownloadError)errorCode;
            string        message;

            if (String.IsNullOrEmpty(errorMessage))
            {
                message = err.ToString();
            }
            else
            {
                message = errorMessage;
            }
            switch ((DownloadError)errorCode)
            {
            case DownloadError.InvalidParameter:
            case DownloadError.InvalidUrl:
            case DownloadError.InvalidDestination:
            case DownloadError.InvalidNetworkType: throw new ArgumentException(message, paramName);

            case DownloadError.OutOfMemory:
            case DownloadError.NetworkUnreachable:
            case DownloadError.ConnectionTimedOut:
            case DownloadError.NoSpace:
            case DownloadError.InvalidState:
            case DownloadError.ConnectionFailed:
            case DownloadError.TooManyDownloads:
            case DownloadError.QueueFull:
            case DownloadError.AlreadyCompleted:
            case DownloadError.FileAlreadyExists:
            case DownloadError.CannotResume:
            case DownloadError.FieldNotFound:
            case DownloadError.TooManyRedirects:
            case DownloadError.UnhandledHttpCode:
            case DownloadError.RequestTimeout:
            case DownloadError.ResponseTimeout:
            case DownloadError.SystemDown:
            case DownloadError.IdNotFound:
            case DownloadError.NoData:
            case DownloadError.IoError: throw new InvalidOperationException(message);

            case DownloadError.NotSupported: throw new NotSupportedException(message);

            case DownloadError.PermissionDenied: throw new UnauthorizedAccessException(message);
            }
        }
Ejemplo n.º 25
0
        private async void HandleDownloadAsync(DownloadOperation operation, bool start = true)
        {
            var tokenSource = new CancellationTokenSource();
            var callback    = new Progress <DownloadOperation>(OnDownloadProgressChanged);

            _downloads.Add(operation);
            _cts.Add(operation.Guid, tokenSource);

            OnDownloadProgressChanged(operation);

            try
            {
                if (start)
                {
                    await operation.StartAsync().AsTask(tokenSource.Token, callback);
                }
                else
                {
                    await operation.AttachAsync().AsTask(tokenSource.Token, callback);
                }
            }
            catch (OperationCanceledException) { }
            catch (Exception ex)
            {
                DownloadError?.Invoke(this, new TransferOperationErrorEventArgs(
                                          operation.Guid,
                                          GetOperationNameFromFileName(operation.ResultFile.Name),
                                          GetContentTypeFromExtension(operation.ResultFile.FileType),
                                          ex));
            }

            OnDownloadProgressChanged(operation);
            if (operation.Progress.Status == BackgroundTransferStatus.Canceled ||
                operation.Progress.Status == BackgroundTransferStatus.Error)
            {
                await operation.ResultFile.DeleteAsync(StorageDeleteOption.PermanentDelete);
            }

            _cts.Remove(operation.Guid);
            _downloads.Remove(operation);

            if (_downloads.Count == 0)
            {
                DownloadsCompleted?.Invoke(this, EventArgs.Empty);
            }
        }
Ejemplo n.º 26
0
        protected void EBtnDelete_Click(object sender, EventArgs e)
        {
            StringBuilder selectList = new StringBuilder("");

            selectList = this.EgvDownloadError.SelectList;
            if (selectList.Length == 0)
            {
                AdminPage.WriteErrMsg("对不起,您还没选择要删除的下载报错信息!");
            }
            else if (DownloadError.Delete(selectList.ToString()))
            {
                AdminPage.WriteSuccessMsg("删除下载报错信息成功!", "DownloadErrorManage.aspx");
            }
            else
            {
                AdminPage.WriteErrMsg("删除下载地址错误信息失败!");
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// 下载完成事件的回调函数
        /// </summary>
        private async void Client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            if (sender != client)
            {
                return;
            }
            try
            {
                StorageFile file = await StorageFile.GetFileFromPathAsync(Message.TempFilePath);

                StorageFolder folder = await StorageManager.TryGetFolderAsync(Message.FolderToken);

                if (folder == null)
                {
                    folder = await StorageManager.TryGetFolderAsync(Settings.DownloadsFolderToken);

                    Message.FolderToken = Settings.DownloadsFolderToken;
                    if (folder == null)
                    {
                        folder = ApplicationData.Current.LocalCacheFolder;
                        Message.FolderToken = StorageApplicationPermissions.FutureAccessList
                                              .Add(ApplicationData.Current.LocalCacheFolder);
                    }
                    Toasts.ToastManager.ShowSimpleToast(Strings.AppResources.GetString("DownloadFolderPathIllegal"),
                                                        Strings.AppResources.GetString("DownloadFolderPathIllegalMessage"));
                }

                await file.MoveAsync(folder, Message.FileName + Message.Extention, NameCollisionOption.GenerateUniqueName);

                Message.DownloadSize = (long)(await file.GetBasicPropertiesAsync()).Size;

                Message.IsDone = true;

                //触发事件
                State = DownloadState.Done;
                DownloadComplete?.Invoke(Message);
            }
            catch (Exception ex)
            {
                //若用户把下载文件夹设置在奇怪的地方,这里会导致无法访问,触发异常
                Debug.WriteLine(ex.ToString());
                DownloadError?.Invoke(ex);
            }
        }
Ejemplo n.º 28
0
        protected override bool OnError(DownloadError error)
        {
            Log.InfoFormat("Download error, Proxy={0}, Url = {1}, Message = {2}", _selectorCopy.Current, Url, error.Message);

            bool tryAgain = true;

            _error.Push(new AttemptPair()
            {
                Proxy = _selectorCopy.Current, Error = error
            });

            if (_error.Count >= _selectorCopy.ProxyCount) //We went through all the proxies and they all had an error. We give up.
            {
                _error.Clear();
                tryAgain = false;
            }

            return(tryAgain);
        }
Ejemplo n.º 29
0
        public byte[] Download()
        {
            byte[] bytes = new byte[0];

            while (true)
            {
                try
                {
                    OnBeforeDownload();
                    bytes = Wire.Download();

                    OnSuccess();
                    break;
                }
                catch (WebException ex)
                {
                    var error = new DownloadError { Status = ex.Status, Message = ex.Message };
                    var response = ex.Response as HttpWebResponse; //this can be null
                    if(response != null)
                        error.HttpStatus = response.StatusCode;

                    if (!OnError(error))
                        break;

                    //Forbidden
                    //NotFound

                    //if (ex.Status == WebExceptionStatus.ConnectFailure) //if we cannot even contact the web server we give up.
                    //  break;
                }
                catch(Exception e)
                {
                    var error = new DownloadError { Message = e.Message };
                    if (!OnError(error))
                        break;
                }
            }

            return bytes;
        }
Ejemplo n.º 30
0
        public static GlacierResult ProcessQueue(Topic topic)
        {
            // Check for notifications on topic and process any message
            try
            {
                var settings = SettingsManager.GetSettings();
                using (var client = new AmazonGlacierClient(
                           settings.AWSAccessKeyID,
                           settings.AWSSecretAccessKey,
                           RegionEndpoint.GetBySystemName(settings.AWSS3Region.SystemName)))
                {
                    var receiveMessageRequest = new ReceiveMessageRequest {
                        QueueUrl = topic.QueueUrl, MaxNumberOfMessages = 1
                    };
                    var sqsClient = new AmazonSQSClient(settings.AWSAccessKeyID, settings.AWSSecretAccessKey, RegionEndpoint.GetBySystemName(settings.AWSS3Region.SystemName));
                    var receiveMessageResponse = sqsClient.ReceiveMessage(receiveMessageRequest);
                    if (receiveMessageResponse.Messages.Count == 0)
                    {
                        topic.Status = GlacierResult.Incomplete;
                        SaveTopicFile(topic);
                        return(topic.Status);
                    }

                    // Process message
                    string status = GetResponseStatus(receiveMessageResponse);
                    if (string.Equals(status, GlacierUtils.JOB_STATUS_SUCCEEDED, StringComparison.InvariantCultureIgnoreCase))
                    {
                        DownloadGlacierJobOutput(topic.JobId, client, settings.AWSGlacierVault, topic.GetOutputFile());
                        Debug.WriteLine($"Downloaded job output to {topic.GetOutputFile()}");
                        if (topic.ArchiveId != null)
                        {
                            DownloadSuccess?.Invoke($"Glacier archive was downloaded to {topic.GetOutputFile()}");
                        }
                        DeleteTopic(topic);
                        return(GlacierResult.Completed);
                    }
                    else if (string.Equals(status, GlacierUtils.JOB_STATUS_FAILED, StringComparison.InvariantCultureIgnoreCase))
                    {
                        DownloadError?.Invoke("Job failed, cannot download the file");
                        DeleteTopic(topic);
                        return(GlacierResult.JobFailed);
                    }
                    else if (string.Equals(status, GlacierUtils.JOB_STATUS_INPROGRESS, StringComparison.InvariantCultureIgnoreCase))
                    {
                        DownloadWarning?.Invoke("Job in progress, Queue ARN: " + topic.QueueARN);
                        DeleteTopic(topic);
                        return(GlacierResult.JobInProgress);
                    }
                    else
                    {
                        DeleteTopic(topic);
                        return(GlacierResult.Error);
                    }
                }
            }
            catch (AmazonServiceException azex)
            {
                // Handle specific potential errors here
                Debug.WriteLine("AmazonServiceException " + azex.Message);

                if (azex.StatusCode == System.Net.HttpStatusCode.Forbidden)
                {
                    // Invalid credentials
                    BackupError?.Invoke("Invalid AWS credentials were provided while connecting");
                    return(GlacierResult.Incomplete);
                }
                if (azex.InnerException != null &&
                    azex.InnerException is System.Net.WebException &&
                    ((System.Net.WebException)azex.InnerException).Status == System.Net.WebExceptionStatus.NameResolutionFailure)
                {
                    // Not connected to internet
                    BackupError?.Invoke("Network connection failure");
                    return(GlacierResult.Incomplete);
                }
                if (azex.InnerException != null &&
                    azex.InnerException is System.Net.WebException)
                {
                    // Network errors
                    BackupError?.Invoke($"A network error occurred ({((System.Net.WebException)azex.InnerException).Status})");
                    return(GlacierResult.Incomplete);
                }
                if (azex.StatusCode == System.Net.HttpStatusCode.BadRequest
                    //&& topic.Status == GlacierResult.JobRequested
                    && azex.Message.Contains("The specified queue does not exist") &&
                    DateTime.Now - topic.DateRequested < new TimeSpan(24, 0, 0))
                {
                    // Job was recently requested and the queue has not been created yet
                    Debug.WriteLine("Job request may be in progress");
                    return(GlacierResult.JobRequested);
                }

                // TODO Check expiry?
                // Glacier ref: "A job ID will not expire for at least 24 hours after Amazon Glacier completes the job."
                DeleteTopic(topic);
                BackupWarning?.Invoke("An AWS Glacier job has expired, a new job will be issued");

                // Reissue expired job
                InitiateGlacierJob(topic);
                return(topic.Status);
            }
            catch (Exception ex)
            {
                DeleteTopic(topic);
                throw ex;
            }
        }
Ejemplo n.º 31
0
 protected override bool OnError(DownloadError error)
 {
     log.InfoFormat("Failed proxy download, Proxy={0}, Url = {1}, Message = {2}", _proxy, Wire.Url, error.Message);
     return false;
 }
Ejemplo n.º 32
0
 protected abstract bool OnError(DownloadError error);
        protected void EBtnSubmit_Click(object sender, EventArgs e)
        {
            bool      flag            = true;
            int       num             = BasePage.RequestInt32("type");
            int       generalId       = BasePage.RequestInt32("id");
            DataTable contentDataById = ContentManage.GetContentDataById(generalId);

            if (contentDataById == null)
            {
                DynamicPage.WriteErrMsg("对不起,错误的参数!");
            }
            if (contentDataById.Rows.Count > 0)
            {
                string        str     = contentDataById.Rows[0]["DownloadUrl"].ToString();
                string        str2    = contentDataById.Rows[0]["arrServerName"].ToString();
                StringBuilder builder = new StringBuilder();
                if (this.EgvDownloadError.SelectList.Length == 0)
                {
                    DynamicPage.WriteErrMsg("对不起,您还没选择要报错的信息!");
                }
                for (int i = 0; i < this.EgvDownloadError.Rows.Count; i++)
                {
                    CheckBox box = (CheckBox)this.EgvDownloadError.Rows[i].Cells[this.EgvDownloadError.CheckBoxColumnIndex].FindControl("CheckBoxButton");
                    if (box.Checked)
                    {
                        DownloadErrorInfo downloadErrorInfo = new DownloadErrorInfo();
                        if (num == 1)
                        {
                            if (string.IsNullOrEmpty(str))
                            {
                                downloadErrorInfo.InfoId     = generalId;
                                downloadErrorInfo.ErrorUrl   = new InsideStaticLabel().GetInfoPath(contentDataById.Rows[0]["NodeId"].ToString(), contentDataById.Rows[0]["GeneralId"].ToString(), contentDataById.Rows[0]["InputTime"].ToString(), contentDataById.Rows[0]["Title"].ToString());
                                downloadErrorInfo.ErrorDate  = DateTime.Now;
                                downloadErrorInfo.ErrorTimes = 1;
                            }
                            else if (!string.IsNullOrEmpty(str2))
                            {
                                int serverId = DataConverter.CLng(((HiddenField)this.EgvDownloadError.Rows[i].Cells[1].FindControl("HdnUrlID")).Value);
                                int urlId    = DataConverter.CLng(((HiddenField)this.EgvDownloadError.Rows[i].Cells[1].FindControl("HdnServerID")).Value);
                                downloadErrorInfo.InfoId     = generalId;
                                downloadErrorInfo.ErrorUrl   = DownloadError.GetDownloadurlById(str, urlId, serverId);
                                downloadErrorInfo.ErrorDate  = DateTime.Now;
                                downloadErrorInfo.ErrorTimes = 1;
                            }
                            else
                            {
                                downloadErrorInfo.InfoId     = generalId;
                                downloadErrorInfo.ErrorUrl   = DownloadError.GetDownloadurlById(str, i, 0);
                                downloadErrorInfo.ErrorDate  = DateTime.Now;
                                downloadErrorInfo.ErrorTimes = 1;
                            }
                        }
                        else
                        {
                            downloadErrorInfo.InfoId     = generalId;
                            downloadErrorInfo.ErrorUrl   = new InsideStaticLabel().GetInfoPath(contentDataById.Rows[0]["NodeId"].ToString(), contentDataById.Rows[0]["GeneralId"].ToString(), contentDataById.Rows[0]["InputTime"].ToString(), contentDataById.Rows[0]["Title"].ToString());
                            downloadErrorInfo.ErrorDate  = DateTime.Now;
                            downloadErrorInfo.ErrorTimes = 1;
                        }
                        if (!DownloadError.Add(downloadErrorInfo))
                        {
                            flag = false;
                        }
                    }
                }
                if (flag)
                {
                    DynamicPage.WriteSuccessMsg("感谢您的参与,提交成功!", SiteConfig.SiteInfo.VirtualPath + "Category_" + contentDataById.Rows[0]["NodeId"].ToString() + "/index.aspx");
                }
                else
                {
                    DynamicPage.WriteErrMsg("对不起,提交失败!");
                }
            }
            else
            {
                DynamicPage.WriteErrMsg("对不起,错误的参数!");
            }
        }
 protected virtual void OnDownloadError(DownloadEventErrorArgs e)
 {
     DownloadError?.Invoke(this, e);
 }
Ejemplo n.º 35
0
 public static void OnDownloadError(object sender, DownloadErrorEventArgs ev) => DownloadError?.Invoke(sender, ev);
Ejemplo n.º 36
0
 protected override bool OnError(DownloadError error)
 {
     log.InfoFormat("Failed proxy download, Proxy={0}, Url = {1}, Message = {2}", _proxy, Wire.Url, error.Message);
     return(false);
 }
 public DownloadFailed(DownloadError error)
 {
     Error = error;
 }
Ejemplo n.º 38
0
 protected abstract bool OnError(DownloadError error);
Ejemplo n.º 39
0
        private static void VerifySignature(
			string signatureUrl,
			byte[] fileToVerify,
			VerificationError verificationError,
			DownloadError downloadError,
			IsCancelled isCancelled,
			Action onSuccess
		)
        {
            new Detail.AsyncTaskRunnerBuilder<byte[]> ().Do ((object[] args) => {
                return Net.Validator.MakeRequest (() => {
                    return API.V1.DownloadFile (signatureUrl, (progress) => {}, () => { return isCancelled (); });
                });
            }).OnError ((System.Exception e) => {
                downloadError (e);
                return Detail.AsyncTaskRunner<byte[]>.ErrorRecovery.Nothing;
            }).OnCompletion ((byte[] signature) => {
                if (SignatureMatches (signature, fileToVerify) == VerificationStatus.Success) {
                    onSuccess ();
                    return;
                }

                verificationError ();
            }).Run ();
        }