private static bool SingleFile(HttpWebResponse response, ref FileDownload currentTask) { var downloadPath = Path.Combine(currentTask.Destination, currentTask.FileName); const int BUFFER_SIZE = 16 * 1024; long intLen = response.ContentLength; byte[] buffer = new byte[intLen]; //NOt a zip, then no extraction needed. using (FileStream fileStream = new FileStream(downloadPath, FileMode.OpenOrCreate, FileAccess.Write)) { if (!string.IsNullOrEmpty(currentTask.Url)) { using (var responseStream = response.GetResponseStream()) { buffer = new byte[BUFFER_SIZE]; int bytesRead; do { bytesRead = responseStream.Read(buffer, 0, BUFFER_SIZE); fileStream.Write(buffer, 0, bytesRead); } while (bytesRead > 0); } fileStream.Close(); return(true); } else { return(false); } } }
/// <summary> /// 修改文件下载 /// </summary> /// <param name="fileDownloadInfo">文件下载信息</param> /// <returns>修改成功标识</returns> public bool Update(FileDownload fileDownloadInfo) { DBHelper dbHelper = new DBHelper(ConnectionString, DbProviderType.SqlServer); string strSql = @"Update FileDownload Set [UserId]=@UserId ,[Name]=@Name ,[Title]=@Title ,[Category]=@Category ,[Type]=@Type ,[Src]=@Src ,[State]=@State ,[HeadImg]=@HeadImg ,[Description]=@Description ,[Synopsis]=@Synopsis Where ID=@ID"; List <DbParameter> parametersList = new List <DbParameter>(); parametersList.Add(new SqlParameter("@ID", fileDownloadInfo.Id)); parametersList.Add(new SqlParameter("@UserId", fileDownloadInfo.UserId)); parametersList.Add(new SqlParameter("@Title", fileDownloadInfo.Title)); parametersList.Add(new SqlParameter("@HeadImg", fileDownloadInfo.HeadImg)); parametersList.Add(new SqlParameter("@Description", fileDownloadInfo.Description)); parametersList.Add(new SqlParameter("@Name", fileDownloadInfo.Name)); parametersList.Add(new SqlParameter("@Category", fileDownloadInfo.Category)); parametersList.Add(new SqlParameter("@Src", fileDownloadInfo.Src)); parametersList.Add(new SqlParameter("@State", (int)fileDownloadInfo.State)); parametersList.Add(new SqlParameter("@Type", (int)fileDownloadInfo.Type)); parametersList.Add(new SqlParameter("@Synopsis", fileDownloadInfo.Synopsis)); return(dbHelper.ExecuteNonQuery(strSql, parametersList) > 0); }
/// <summary> /// 更新 /// </summary> /// <param name="id"></param> /// <returns></returns> public ActionResult Edit(int id) { FileDownload data = downService.Get(id); InitData(); DownloadViewModel model = new DownloadViewModel(); if (data != null) { model.Id = data.Id; model.FileName = data.Name; model.FileTitle = data.Title; model.CategoryName = data.CategoryName; model.UserName = data.UserName; model.State = (int)data.State; model.UserId = data.UserId; model.Description = data.Description; model.FileImg = data.HeadImg; model.SmallFileImg = GetThumb(data.HeadImg); model.FileType = data.Type; model.Src = data.Src; model.Category = data.Category; #region 类别可用判断 预留 //if (cdEnabledList != null && cdEnabledList.Count > 0 && cdEnabledList.Where(g => g.Id == data.Category).Count() > 0) //{ // model.Category = data.Category; //} #endregion return(View(model)); } return(View()); }
public async System.Threading.Tasks.Task <IActionResult> Download([FromBody] FileDownload filename) { using (ApitemplatereportContext context = new ApitemplatereportContext()) { TblFileDetail file = context.TblFileDetails.Where(file => file.Filename == filename.filename).FirstOrDefault(); if (file != null) { var path = _webHostEnvironment.WebRootPath + "\\Template\\" + file.Filename; try { var memory = new MemoryStream(); using (var stream = System.IO.File.OpenRead(path)) await stream.CopyToAsync(memory); memory.Position = 0; return(new FileStreamResult(memory, "application/octec-stream")); } catch (Exception ex) { Console.WriteLine(ex); } } } return(NotFound()); }
public ActionResult Detail(int id) { FileDownload data = downService.Get(id); if (data != null) { return(View(new DownloadViewModel { Id = data.Id, FileName = data.Name, FileTitle = data.Title, CategoryName = data.CategoryName, UserName = data.UserName, State = (int)data.State, Category = data.Category, UserId = data.UserId, Description = data.Description, FileImg = data.HeadImg, FileType = data.Type, Src = data.Src, CreateTime = data.CreateDate.ToString("yyyy-MM-dd HH;MM") })); } else { return(View()); } }
/// <summary> /// Performs the mapping of the read file to the to the model. /// </summary> public DrugProductMapper(FileDownload filedownload) { // DRUG_CODE Map(m => m.DrugCode).Index(0); // PRODUCT_CATEGORIZATION Map(m => m.ProductCategorization).Index(1); // CLASS Map(m => m.DrugClass).Index(2); // DRUG_IDENTIFICATION_NUMBER Map(m => m.DrugIdentificationNumber).Index(3); // BRAND_NAME Map(m => m.BrandName).Index(4); // DESCRIPTOR Map(m => m.Descriptor).Index(5); // PEDIATRIC_FLAG Map(m => m.PediatricFlag).Index(6); // ACCESSION_NUMBER Map(m => m.AccessionNumber).Index(7); // NUMBER_OF_AIS Map(m => m.NumberOfAis).Index(8); // LAST_UPDATE_DATE Map(m => m.LastUpdate).Index(9); // AI_GROUP_NO Map(m => m.AiGroupNumber).Index(10); // CLASS_F Map(m => m.DrugClassFrench).Index(11); // BRAND_NAME_F Map(m => m.BrandNameFrench).Index(12); // DESCRIPTOR_F Map(m => m.DescriptorFrench).Index(13); // Map the Filedownload to each object Map(m => m.FileDownload).ConvertUsing(row => filedownload); }
public static void AddIconDownloadHandler(string uniqueKey, FileDownload handler) { handler.OnDownloadCompleted += OnIconDownloadCompleted; handler.OnDownloadFailed += OnIconDownloadFailed; IconDownloader.Add(uniqueKey, handler); }
async Task StartDownloadFileAsync(string username, string password, string filepath) { FileDownload temp = new FileDownload(); temp = await RestAPIs.DownloadFile(username, username, filepath); var path = WorkingFolder; if (path.EndsWith("\\")) { path = path.Substring(0, path.Length - 2); } if (temp.FilePath.StartsWith("\\")) { temp.FilePath = temp.FilePath.Substring(1); } path += "\\" + temp.FilePath; new System.IO.DirectoryInfo(path).Create(); if (path.EndsWith("\\")) { path = path.Substring(0, path.Length - 2); } File.WriteAllBytes(path + "\\" + temp.FileName, temp.FileContent); updatedFile++; progressBar.Value = (updatedFile / FolderData.Count) * 100; }
public static void GetFile(Instance instance) { Directory.CreateDirectory(GetCachePath()); var file = GetCachePath() + instance.Version.Version + ".jar"; if (!File.Exists(file)) { var fileStruct = new FileDownload() { Name = instance.Version.Version + ".jar", Url = instance.Version.GetClientUrl(), DownloadFileCompleted = DownloadFileCompleted }; if (DownloadInProgress.ContainsKey(fileStruct)) { var value = DownloadInProgress[fileStruct]; value.Add(instance); DownloadInProgress[fileStruct] = value; } else { var instances = new List <Instance> { instance }; DownloadInProgress.Add(fileStruct, instances); Manager.GetSingleton.DownloadManager.Files.Enqueue(fileStruct); } } }
public void RunAsync_IOException() { // ARRANGE byte[] expected = new byte[FactoryNode.Node.Size.Value]; new Random().NextBytes(expected); IInternalDracoonClient c = FactoryClients.InternalDracoonClientMock(); Stream s = new MemoryStream(); FileDownloadCallbackMock callback = new FileDownloadCallbackMock(); FileDownload f = new FileDownload(c, "id1", FactoryNode.Node, s); f.AddFileDownloadCallback(callback); Mock.Arrange(() => c.Builder.PostFileDownload(Arg.AnyLong)).Returns(FactoryRestSharp.PostFileDownloadMock(123)).OnAllThreads(); Mock.Arrange(() => c.Executor.DoSyncApiCall <ApiDownloadToken>(Arg.IsAny <IRestRequest>(), RequestType.PostDownloadToken, 0)) .Returns(FactoryNode.ApiDownloadToken).OnAllThreads(); DracoonWebClientExtension wc = Mock.Create <DracoonWebClientExtension>(); Mock.Arrange(() => Mock.Create <DownloadProgressChangedEventArgs>().BytesReceived).IgnoreInstance().Returns(expected.Length); Mock.Arrange(() => c.Executor.ExecuteWebClientDownload(Arg.IsAny <WebClient>(), Arg.IsAny <Uri>(), RequestType.GetDownloadChunk, Arg.IsAny <Thread>(), Arg.AnyInt)) .Raises(() => wc.DownloadProgressChanged += null, null, Mock.Create <DownloadProgressChangedEventArgs>()).Returns(expected).OnAllThreads(); Mock.Arrange(() => s.Write(Arg.IsAny <byte[]>(), Arg.AnyInt, Arg.AnyInt)).Throws(new IOException()).OnAllThreads(); Mock.Arrange(() => c.Builder.ProvideChunkDownloadWebClient(Arg.AnyLong, Arg.AnyLong)).Returns(wc).OnAllThreads(); Mock.Arrange(() => callback.OnFailed(Arg.AnyString, Arg.IsAny <DracoonException>())).Occurs(1); // ACT f.RunAsync(); while (f.RunningThread.IsAlive) { } s.Close(); // ASSERT Mock.Assert(callback); }
static void Main(string[] args) { NetworkCredential credential = new NetworkCredential("username", "password"); WebdavSession session = new WebdavSession(credential); Resource resource = new Resource(session); resource.DownloadProgress += new DownloadProgressEventHandler(DownloadProgress); try { FileDownload fileDownload = resource.DownloadFile("http://myserver/dav/file1.txt", "c:\\temp\\file1.txt"); //Press ENTER to abort download Console.Read(); fileDownload.Abort(); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.Read(); } //Press ENTER to exit. Console.Read(); }
/// <summary> /// 开始进行主要文件下载,下载至缓存目录 /// </summary> IEnumerator StartDownloadMainConfig() { if (ErrorCode != emErrorCode.None) { yield break; } //下载主配置文件 for (int i = 0; i < Common.MAIN_CONFIG_NAME_ARRAY.Length; ++i) { file_download_ = new FileDownload(current_url_ , Common.CACHE_PATH , Common.MAIN_CONFIG_NAME_ARRAY[i]); file_download_.Start(); while (!file_download_.IsDone) { yield return(null); } if (file_download_.IsFailed) { Error(emErrorCode.DownloadMainConfigFileFailed , Common.MAIN_CONFIG_NAME_ARRAY[i] + " download failed!"); yield break; } file_download_ = null; UpdateCompleteValue(i, Common.MAIN_CONFIG_NAME_ARRAY.Length); } yield return(null); }
/// <summary> /// 开始进行主要文件下载,下载至缓存目录 /// </summary> IEnumerator StartDownloadMainConfig() { Debug.Log("AssetUpdater:StartDownloadMainConfig"); if (ErrorCode != EmErrorCode.None) { yield break; } //下载主配置文件 _file_download = new FileDownload(_current_ab_url , DownLoadCommon.CACHE_PATH , DownLoadCommon.MAIN_MANIFEST_FILE_NAME); _file_download.Start(); while (!_file_download.IsDone) { yield return(null); } if (_file_download.IsFailed) { Error(EmErrorCode.DownloadMainConfigFileFailed , DownLoadCommon.MAIN_MANIFEST_FILE_NAME + " download failed!"); yield break; } _file_download = null; UpdateCompleteValue(1f, 1f); yield return(null); }
public ActionResult ReturnSoldNote(int NoteID) { SellerNote notedetail = db.SellerNotes.Where(m => m.id == NoteID).SingleOrDefault(); var user = db.Users.Where(m => m.EmailID == System.Web.HttpContext.Current.User.Identity.Name).SingleOrDefault(); var attechment = db.SellerNotesAttechments.Where(m => m.NoteID == notedetail.id).SingleOrDefault(); if (user.id == notedetail.SellerID) { FileDownload obj = new FileDownload(); var ListOfFile = obj.GetFile(attechment.FilePath).ToList(); using (var memoryStream = new MemoryStream()) { using (var zipArchiv = new ZipArchive(memoryStream, ZipArchiveMode.Create, true)) { for (int i = 0; i < ListOfFile.Count(); i++) { zipArchiv.CreateEntryFromFile(ListOfFile[i].FilePath, ListOfFile[i].FileName); } } return(File(memoryStream.ToArray(), "application/zip", "Attachments.zip")); } } return(null); }
private FileDownload CreateFileDownloadInternally(string actionId, long nodeId, Stream output, IFileDownloadCallback callback) { _client.Executor.CheckApiServerVersion(); #region Parameter Validation CheckDownloadActionId(actionId); nodeId.MustPositive(nameof(nodeId)); output.CheckStreamCanWrite(nameof(output)); #endregion FileDownload download = null; Node nodeToDownload = GetNode(nodeId); // Validation will be done in "GetNode" if (nodeToDownload.IsEncrypted.GetValueOrDefault(false)) { UserKeyPair keyPair = _client.AccountImpl.GetAndCheckUserKeyPair(); download = new EncFileDownload(_client, actionId, nodeToDownload, output, keyPair.UserPrivateKey); } else { download = new FileDownload(_client, actionId, nodeToDownload, output); } _runningDownloads.Add(actionId, download); download.AddFileDownloadCallback(callback); download.AddFileDownloadCallback(this); return(download); }
IEnumerator StartDownLuaZip() { Debug.Log("AssetUpdater:StartDownLuaZip"); if (ErrorCode != EmErrorCode.None) { yield break; } //下载主配置文件 _file_download = new FileDownload(_current_url , DownLoadCommon.CACHE_PATH , "/LuaScript.zip"); _file_download.Start(); while (!_file_download.IsDone) { UpdateCompleteValue(_file_download.CompletedSize, _file_download.TotalSize); yield return(null); } if (_file_download.IsFailed) { Error(EmErrorCode.DownloadFailed , " download luazip failed!"); yield break; } _file_download = null; UpdateCompleteValue(1f, 1f); }
private void DownloadIndex(Action <string> onFinished) { try { var ec = new FileDownload(); var pd = new ProgressDialog(this); pd.SetMessage(Resources.GetText(Resource.String.Download_LoadingData)); pd.SetCancelable(false); pd.Show(); ec.OnFinishedAction = (result) => { MainThread.BeginInvokeOnMainThread(() => { onFinished.Invoke(result); pd.Hide(); }); }; ec.OnError = (message) => { MainThread.BeginInvokeOnMainThread(() => { pd.Hide(); PopupHelper.ErrorDialog(this, Resource.String.Download_ErrorDownloading, message); }); }; ec.Execute(GpxFileProvider.GetIndexUrl()); } catch (Exception ex) { PopupHelper.ErrorDialog(this, Resource.String.Download_ErrorDownloading, ex.Message); } }
public bool DownloadFile(ref FileDownload CurrentTask) { //ISSUE : Although the Synchronous downloader works. It will freeze the UI. This is a known devil. try { HttpWebRequest request; HttpWebResponse response; request = (HttpWebRequest)HttpWebRequest.Create(CurrentTask.Url); //request.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko"; request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:78.0) Gecko/20100101 Firefox/78.0"; request.Accept = "text/html, application/xhtml+xml, */*"; ////.Connection = "Keep-Alive"; request.Headers.Add("Accept-Language", "en-IN"); request.Headers.Add("Accept-Encoding", "gzip, deflate"); request.Headers.Add("DNT", "1"); request.CookieContainer = cookieJar; using (response = (HttpWebResponse)request.GetResponse()) { return(Extract.Writer(response, ref CurrentTask)); } } catch (Exception Ex) { CurrentTask.Status = Ex.Message.ToString(); CurrentTask.Progress = 0; return(false); } }
public void Process(byte[] buffer, Connection connection) { var key = connection.AesKey.GetClientKey(); var iv = connection.AesKey.GetClientIv(); var aes = new AesCryptography() { CipherMode = System.Security.Cryptography.CipherMode.CBC, KeySize = AesKeySize.KeySize128, PaddingMode = System.Security.Cryptography.PaddingMode.PKCS7 }; var decrypted = aes.Decrypt(buffer, key, iv, out var sucess); if (sucess) { var msg = new ByteBuffer(decrypted); var fileName = msg.ReadString(); var fileLength = msg.ReadInt64(); var length = msg.ReadInt32(); var bytes = msg.ReadBytes(length); FileDownload handler; if (Authentication.FileDownloader.ContainsKey(connection.UniqueKey)) { handler = Authentication.FileDownloader[connection.UniqueKey]; if (handler.FileName != fileName) { handler.SetFileData(connection.UniqueKey, fileName, fileLength); handler.Close(); handler.Reset(); } } else { handler = new FileDownload(); handler.SetFileData(connection.UniqueKey, fileName, fileLength); Authentication.AddDownloadHandler(connection.UniqueKey, handler); } if (!handler.Completed) { if (!handler.IsOpen) { handler.Open(); } handler.Save(bytes); } } else { connection.Disconnect(); Global.WriteLog($"Failed to decrypt file packet.", "Black"); } }
public override void Uninitialize() { if (_fileDownload != null) { _fileDownload.Abort(null); _fileDownload = null; } }
public async Task AFileIsDownloadedOnFileDownload() { var url = "https://m.media-amazon.com/images/I/61-gczrW31L._AC_UY218_.jpg"; FileDownload fileDownload = new FileDownload(); var file = await fileDownload.Download(url); Assert.True(file.Length > 0); }
private static void DownloadFileCompleted(FileDownload fileDownload) { var instances = DownloadInProgress[fileDownload]; foreach (var instance in instances) { File.Copy(fileDownload.Url, instance.InstanceLocation.Path + Manager.GetSingleton.GetConfig().MinecraftFolderPath + fileDownload.Name + ".jar"); } }
public async Task DownloadNonExistingFileTest() { // Upload file var filename = Unique.String + ".png"; // Get download url var download = new FileDownload(filename); var content = await download.DownloadAsync(); }
public static object PublishFile(string template, string report, dynamic dy, bool isDownload = true) { var result = new ReportTable { ErrCode = 0, ErrMsg = "ok" }; try { var appSettings = new AppSettings(); var contentRootPath = appSettings.Get("HostingEnvironment.ContentRootPath", HostContext.AppHost.MapProjectPath("~/")); var templatePath = HostContext.AppHost.MapProjectPath($"{ Path.Combine(contentRootPath, "template")}"); var reportPath = HostContext.AppHost.MapProjectPath($"{ Path.Combine(contentRootPath, "report")}"); if (!Directory.Exists(templatePath)) { Directory.CreateDirectory(templatePath); } if (!Directory.Exists(reportPath)) { Directory.CreateDirectory(reportPath); } var templateFilePath = Path.Combine(templatePath, template); var reportFilePath = Path.Combine(reportPath, report); Console.WriteLine("templateFilePath:" + templateFilePath); Console.WriteLine("reportFilePath:" + reportFilePath); FileInfo templateFile = new FileInfo(templateFilePath); //将现有文件复制到新文件,不允许覆盖现有文件 templateFile.CopyTo(reportFilePath); if (Report(reportFilePath, dy)) { result.FilePath = reportFilePath; if (isDownload) { var obj = FileDownload.Download(report, "report"); return(obj); } } return(result); } catch (Exception ex) { Console.WriteLine("PublishFile报错:" + ex.Message); return(result); } }
private void Button_Click(object sender, RoutedEventArgs e) { _downloadService = new FileDownload(); _fileIOservice = new FileIOService(PATH); _downloadService.Download(); _view = _fileIOservice.LoadData(); if (_view != null) { thrList.ItemsSource = _view; } }
public bool Add(FileDownload fileDownloadInfo) { //参数验证 if (fileDownloadInfo == null) { ErrorMsg = ErrorCode.ParameterNull; return(false); } fileDownloadInfo.Synopsis = DisposeHtmlStr(fileDownloadInfo.Description); return(_fileDownloadProvider.Add(fileDownloadInfo)); }
/// <summary> /// Removes All Download Files that match the Program type but do not match the file hash. /// </summary> /// <param name="downloadedFile">Search for all download files not matching this one.</param> protected void RemoveOldFiles(FileDownload downloadedFile) { List <FileDownload> oldIds = this.DrugDbContext.FileDownload .Where(p => p.ProgramCode == downloadedFile.ProgramCode && p.Hash != downloadedFile.Hash) .Select(f => new FileDownload { Id = f.Id, Version = f.Version }) .ToList(); oldIds.ForEach(s => this.Logger.LogInformation($"Deleting old Download file with hash: {s}")); this.DrugDbContext.RemoveRange(oldIds); }
private string CreateFileToken(string fileName) { var fileDownload = new FileDownload() { FileName = fileName, ValidFrom = DateTime.Now }; var token = JsonConvert.SerializeObject(fileDownload); return(HexaEncode.Encode(RC4Encrypt.Encrypt(token))); }
public void ShouldCauseException() { string targetFolder = "tmp"; using ILoggerFactory loggerFactory = LoggerFactory.Create(builder => builder.AddConsole()); ILogger <FileDownloadService> logger = loggerFactory.CreateLogger <FileDownloadService>(); FileDownloadService service = new FileDownloadService(logger, null); FileDownload fd = Task.Run(async() => await service.GetFileFromUrl(new System.Uri("https://localhost/fake.txt"), "tmp", true).ConfigureAwait(true)).Result; Assert.ThrowsAsync <AggregateException>(() => Task.Run(async() => await service.GetFileFromUrl(new System.Uri("https://localhost/fake.txt"), targetFolder, true).ConfigureAwait(true))); Directory.Delete(Path.Combine(Directory.GetCurrentDirectory(), targetFolder)); }
private void RunThread() { while (IsRunning) { _currentFile = _downloadManager.Files.Dequeue(); if (!_currentFile.Equals(default(FileDownload))) { _client.DownloadFile(_currentFile.Url, GetCachePath() + _currentFile.Name); } } }
public async Task GetDownloadUrlAsyncTest() { // Upload file var filePath = FileHelper.TestFilePath; var upload = new FileUpload("image/png", Unique.String + ".png"); var filename = await upload.UploadFileAsync(filePath); // Get download url var download = new FileDownload(filename); var url = await download.GetDownloadUrl(); Assert.IsFalse(string.IsNullOrWhiteSpace(url)); Console.WriteLine("Download url: {0}", url); }
async void item_DoubleClick(object sender, EventArgs e) { var item = (CloudFiles)((FileTile)sender).Tag; if(item.DoubleClick()) { SaveFileDialog filedialog = new SaveFileDialog(); var result = filedialog.ShowDialog(); if(result != System.Windows.Forms.DialogResult.OK) { return; } System.IO.Stream stream = await item.GetSteam(); down = new FileDownload(filedialog.FileName, stream, (long)item.GetFileSize()); down.StreamCompleteCallback += down_StreamCompleteCallback; down.StreamControlCallBack += down_StreamControlCallBack; down.StreamProgressCallback += down_StreamProgressCallback; down.Start(); } else { NavigateToItem(item); } }
public async void Initialise() { downloader = new FileDownload(EXT_RESOURCE_LINK, OUTPUT); await DeleteDirectory(); }
public async Task DownloadNonExistingFileTest() { // Upload file var filename = Unique.String + ".png"; // Get download url var download = new FileDownload(filename); var content = await download.DownloadAsync(); }
public async Task DownloadFileAsyncTest() { // Upload a new file var filename = await FileHelper.UploadTestFileAsync(); var downloadTo = FileHelper.GenerateNewDownloadFilePath(); // Download the file var handler = new FileDownload(filename); handler.DownloadCompleted += (s, e) => { Console.WriteLine("Download completed. Downloaded {0} bytes.", e.Result.Length); }; handler.DownloadProgressChanged += (s, e) => { Console.WriteLine("Downloading {0} bytes out of {1}.", e.BytesReceived, e.TotalBytesToReceive); }; await handler.DownloadFileAsync(downloadTo); Assert.IsTrue(FileHelper.Md5ChecksumMatch(downloadTo)); }