public ActionResult Download(DownloadViewModel viewModel) { if (ModelState.IsValid == false) { return(View(viewModel)); } BackgroundJob.Enqueue(() => _downloader.Download(viewModel.Url)); return(RedirectToAction("Download")); }
public async Task <ActionResult> DownloadSignIn(string id) { string filename = String.Format("{0}.docx", id); DownloadViewModel viewModel = new DownloadViewModel( blobId: filename ); DownloadPayload blobData = await viewModel.GetStream(); return(File(blobData.Stream, blobData.ContentType, filename)); }
public async Task <ActionResult> GetSignInUrl(string id) { string filename = String.Format("{0}.docx", id); DownloadViewModel viewModel = new DownloadViewModel( blobId: filename ); string blobUrl = await viewModel.GetSecureUrl(); return(Redirect(blobUrl)); }
// // GET: /Search/Download/5 public ActionResult Download(string selectedTrialKey, string selectedTxId) { var trialList = GetMultiChainClient().ListStreamKeyItems(GetTrialStream(), selectedTrialKey); var trialModel = trialList.Result.Where(item => item.TxId == selectedTxId).FirstOrDefault(); var jsonTrialViewModel = Utility.HexadecimalEncoding.FromHexString(trialModel.Data); var trialViewModel = JsonConvert.DeserializeObject <TrialViewModel>(jsonTrialViewModel); if (string.IsNullOrEmpty(trialViewModel.DocumentUrl)) { ViewBag.Error = "File was not uploaded for this trial."; return(View("Error")); } var serverFileHash = Utility.GetHash(trialViewModel.DocumentUrl); if (string.IsNullOrEmpty(serverFileHash)) { ViewBag.Error = "File not found on the server. It could have been moved or deleted from the server."; return(View("Error")); } if (serverFileHash != trialViewModel.DocumentHash) { ViewBag.Error = string.Format("Blockchain detected Hash ({0}) mismatch. <br/>File seems to be modified. <br/>Download Terminated!<br/><br/>{1}", trialViewModel.DocumentHash, trialList.RawJson); return(View("Error")); } //continue with logging download request, and actual file download var downloadViewModel = new DownloadViewModel() { TrialName = trialViewModel.TrialName, Description = trialViewModel.TrialDescription, StudyNumber = trialViewModel.StudyNumber, ProtocolName = trialViewModel.ProtocolName, Location = trialViewModel.Location, DownloadedOn = DateTime.UtcNow, DownloadedBy = HttpContext.User.Identity.Name }; var downloadTrialModel = GetTrialModel(trialViewModel.TrialName, downloadViewModel); //Create a download entry for the Current logged in User, requesting for the TrialKey file download MultiChainClient mcClient = GetMultiChainClient(); var info = mcClient.PublishStream(GetTrialDownloadStream(), downloadTrialModel.TrialName, downloadTrialModel.TrialData); info.AssertOk(); //Download the selected file string filePath = Path.Combine(Server.MapPath(trialViewModel.DocumentUrl)); var stream = System.IO.File.OpenRead(filePath); return(File(stream, "application/octet-stream", Path.GetFileName(trialViewModel.DocumentUrl))); }
private async Task HandleDownloadAsync(DownloadOperation download, bool start) { DownloadViewModel Selected = Downloads.FirstOrDefault(p => p.Address == download.RequestedUri.ToString()); try { // LogStatus("Running: " + download.Guid, NotifyType.StatusMessage); // Store the download so we can pause/resume. // activeDownloads.Add(download); Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress); if (start) { // Start the download and attach a progress handler. await download.StartAsync().AsTask(cts.Token, progressCallback); } else { // The download was already running when the application started, re-attach the progress handler. await download.AttachAsync().AsTask(cts.Token, progressCallback); } ResponseInformation response = download.GetResponseInformation(); // GetResponseInformation() returns null for non-HTTP transfers (e.g., FTP). string statusCode = response != null?response.StatusCode.ToString() : String.Empty; // download completed Selected.Status = "decompressing..."; Selected.IsDownloadVisible = false; // Unzip var zipFile = await ApplicationData.Current.LocalFolder.GetFileAsync(Selected.FullFileName); var unzipFolder = await FileHelper.GetFolderNotNullAsync( ApplicationData.Current.LocalFolder, "cards"); await ZipHelper.UnZipFileAsync(zipFile, unzipFolder); // end Selected.Complete(); } catch (TaskCanceledException) { // LogStatus("Canceled: " + download.Guid, NotifyType.StatusMessage); } catch (Exception) { if (Selected != null) { await Selected.Delete(); } } finally { // activeDownloads.Remove(download); } }
public ActionResult DownloadDownload(DownloadViewModel downloadViewModel) { var download = (Download)Session["download"]; if (download != null) { download.Name = downloadViewModel.Name; download.FileName = downloadViewModel.Name + ".zip"; download.Status = DownloadStatus.Pending; _downloadService.SaveDownload(download); } return(RedirectToAction("Download")); }
/// <summary> /// Gets called when a download is done. Does not necessarily indicate an error /// unless the NSError parameter is not null. /// </summary> /// <param name="session">NSUrl Session.</param> /// <param name="task">Session Task.</param> /// <param name="error">Error received.</param> public override void DidCompleteWithError(NSUrlSession session, NSUrlSessionTask task, NSError error) { if (error == null) { AppSettings.CurrentSettings.MmpkDownloadDate = DateTime.Now; // Save user settings Task.Run(() => AppSettings.SaveSettings(Path.Combine(DownloadViewModel.GetDataFolder(), "AppSettings.xml"))); return; } // If error indeed occured, cancel the task task.Cancel(); }
private TrialModel GetTrialModel(string key, DownloadViewModel downloadViewModel) { //Populate from collection //a. Generate Json without trial-key string jsonDownloadModel = JsonConvert.SerializeObject(downloadViewModel); //b. Generate Hex from json as source string hexString = Utility.HexadecimalEncoding.ToHexString(jsonDownloadModel); return(new TrialModel() { TrialName = key, TrialData = hexString }); }
public Download() { try { mLog.Info("Start load dowmload page."); InitializeComponent(); this.DataContext = DownloadViewModel.GetInstance(); Test(); } catch (Exception e) { mLog.Error("An error has occurred in the init download xaml,error:{0}", e.ToString()); MMS.UI.Default.MessageBox.Error(String.Format("初始化下载页面出现异常.错误:{0}", e.Message)); } }
/// <summary> /// Overrides the behavior of the application when it has entered background mode /// </summary> /// <param name="application">Main Application.</param> public override async void DidEnterBackground(UIApplication application) { // Begin Finite-Length Task. this.taskID = UIApplication.SharedApplication.BeginBackgroundTask(null); // Start saving the user choices. await Task.Run(() => AppSettings.SaveSettings(Path.Combine(DownloadViewModel.GetDataFolder(), "AppSettings.xml"))); // End Finite-Length Task, finished. if (this.taskID != -1) { UIApplication.SharedApplication.EndBackgroundTask(this.taskID); this.taskID = -1; } }
public override void LoadView() { // Create the view model. ViewModel = new DownloadViewModel(); // Create the views. View = new UIView { BackgroundColor = ApplicationTheme.BackgroundColor, TintColor = ApplicationTheme.ActionBackgroundColor }; _progressView = new UIActivityIndicatorView { TranslatesAutoresizingMaskIntoConstraints = false }; _progressView.HidesWhenStopped = true; _retryButton = new UIButton { TranslatesAutoresizingMaskIntoConstraints = false }; _statusLabel = new UILabel { TranslatesAutoresizingMaskIntoConstraints = false, TextAlignment = UITextAlignment.Center, Text = "MapDownloadInProgressStatusLabel".Localize() }; if (UIDevice.CurrentDevice.CheckSystemVersion(13, 0)) { _progressView.ActivityIndicatorViewStyle = UIActivityIndicatorViewStyle.Large; } _progressView.Color = ApplicationTheme.AccessoryButtonColor; // Add subviews View.AddSubviews(_progressView, _retryButton, _statusLabel); NSLayoutConstraint.ActivateConstraints(new[] { _statusLabel.CenterXAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.CenterXAnchor), _progressView.CenterXAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.CenterXAnchor), _retryButton.CenterXAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.CenterXAnchor), _progressView.CenterYAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.CenterYAnchor), _statusLabel.BottomAnchor.ConstraintEqualTo(_progressView.TopAnchor, -ApplicationTheme.Margin), _retryButton.TopAnchor.ConstraintEqualTo(_progressView.BottomAnchor, 16), _progressView.WidthAnchor.ConstraintEqualTo(44), _progressView.HeightAnchor.ConstraintEqualTo(44), _retryButton.WidthAnchor.ConstraintEqualTo(_progressView.WidthAnchor), _statusLabel.WidthAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.WidthAnchor) }); }
public async void Create(DownloadViewModel model) { Download download = new Download(); download.Date = DateTime.Now; download.FileId = model.FileId; download.AppUserId = model.AppUserId; if (ModelState.IsValid) { await db.Downloads.AddAsync(download); db.Entry(download).State = EntityState.Added; await db.SaveChangesAsync(); } }
protected override void Establish_context() { base.Establish_context(); DownloadSlotsViewModel = new Mock <IDownloadSlotsViewModel>(); Download = new Mock <IDownloadModel>(); Download.SetupGet(download => download.SaveFolderPath).Returns(savingFolder); Download.SetupGet(download => download.FileName).Returns(savingFileName); Download.SetupSet(download => download.State = It.IsAny <DownloadState>()). Callback <DownloadState>(state => LastSettingState = state); FileSystemManager = new Mock <IFileSystemManager>(); DownloadViewModel = new DownloadViewModel(Download.Object, DownloadSlotsViewModel.Object, FileSystemManager.Object); SavePath = System.IO.Path.Combine(savingFolder, savingFileName); }
private void EnqueueDownload(DownloadViewModel download) { // Cancel and remove downloads with the same file path var existingDownloads = Downloads.Where(d => d.FilePath == download.FilePath).ToArray(); foreach (var existingDownload in existingDownloads) { existingDownload.Cancel(); Downloads.Remove(existingDownload); } // Bind progress manager download.ProgressManager = ProgressManager; download.Start(); Downloads.Insert(0, download); }
public ActionResult Edit([Bind(Include = "id_item,title,description,id_file,course_code")] DownloadViewModel download) { if (ModelState.IsValid) { db.FormItemFields.SingleOrDefault(fif => fif.id_item == download.id_item && fif.id_fcontrol == 39).strvalue = download.title; db.FormItemFields.SingleOrDefault(fif => fif.id_item == download.id_item && fif.id_fcontrol == 40).strvalue = download.description; db.FormItemFields.SingleOrDefault(fif => fif.id_item == download.id_item && fif.id_fcontrol == 41).intvalue = download.id_file; db.FormItemFields.SingleOrDefault(fif => fif.id_item == download.id_item && fif.id_fcontrol == 95).strvalue = download.course_code; db.SaveChanges(); //string url = Url.Action("Index", "Downloads", new { /*id = address.PersonID*/ }); return(Json(new { success = true /*, url = url*/ })); } ViewBag.course_code = GetCourses(); return(PartialView("_Edit", download)); }
public async Task <ActionResult> Download() { var model = new DownloadViewModel(); model.BeforeThread = Thread.CurrentThread.ManagedThreadId.ToString(); // I/O-bound operation var client = new HttpClient(); var before = DateTime.Now; await client.GetStringAsync("http://www.google.com"); var after = DateTime.Now; model.AfterThread = Thread.CurrentThread.ManagedThreadId.ToString(); model.Elapsed = (after - before).TotalMilliseconds; return(View(model)); }
// This is async void on purpose because this is supposed to be always ran in background private void EnqueueAndStartDownload(DownloadViewModel download) { // Cancel existing downloads for this file path to prevent writing to the same file foreach (var existingDownload in Downloads.Where(d => d.FilePath == download.FilePath)) { existingDownload.Cancel(); } // Add to list Downloads.Add(download); // Bind progress manager download.ProgressManager = ProgressManager; // Start download download.Start(); }
public ActionResult Downloads() { DownloadViewModel model = new DownloadViewModel(); model.DownloadPath = PathManager.GetDownloadPath(); FileInfo[] fileInfos = new DirectoryInfo(model.DownloadPath).GetFiles(); Tuple <string, string>[] Files = new Tuple <string, string> [fileInfos.Length]; for (int i = 0; i < Files.Length; i++) { Files[i] = new Tuple <string, string>(fileInfos[i].Name, ToFileSize(fileInfos[i].Length)); } model.Files = Files; return(View(model)); }
private void TreeViewItem_Collapsed(object sender, RoutedEventArgs e) { TreeView treeView = sender as TreeView; TreeViewItem selectedTreeViewItem = e.OriginalSource as TreeViewItem; if (selectedTreeViewItem != null && treeView != null) { foreach (DownloadViewModel treeViewItem in treeView.Items) { DownloadViewModel selecedDownloadViewModel = selectedTreeViewItem.DataContext as DownloadViewModel; if (selecedDownloadViewModel != null && treeViewItem.DatasetTitle == selecedDownloadViewModel.DatasetTitle) { treeViewItem.Expanded = false; break; } } } }
private void BtnSubscribe_OnClick(object sender, RoutedEventArgs e) { var btn = (ToggleButton)sender; if (btn == null) { return; } var subscribe = btn.IsChecked.Value; var existsInList = false; foreach (var download in _selectedFilesForDownload) { if (download.DatasetTitle == _selectedDataset.Title) { existsInList = true; download.Subscribe = subscribe; download.AutoAddFiles = subscribe; download.AutoDeleteFiles = subscribe; if (!download.Files.Any()) { _selectedFilesForDownload.Remove(download); } break; } } if (!existsInList && subscribe) { var download = new DownloadViewModel(_selectedDataset, subscribe); _selectedFilesForDownload.Add(download); } lbProjections.ItemsSource = _selectedDataset.Projections; lbFormats.ItemsSource = _selectedDataset.Formats; MenuSubscribe.Visibility = subscribe ? Visibility.Visible : Visibility.Hidden; MenuSubscribe.IsPopupOpen = subscribe; BtnAutoDeleteFiles.IsChecked = subscribe; BtnAutoAddFiles.IsChecked = subscribe; BindNewList(); }
private void EnqueueAndStartDownload(DownloadViewModel download) { var existingDownloads = Downloads.Where(d => d.FilePath == download.FilePath).ToArray(); foreach (var existingDownload in existingDownloads) { existingDownload.Cancel(); Downloads.Remove(existingDownload); } Downloads.Add(download); download.ProgressManager = ProgressManager; download.Start(); }
/// <summary> /// Overrides the behavior of the application when it has entered background mode /// </summary> /// <param name="application">Main Application.</param> public override void DidEnterBackground(UIApplication application) { // Begin Finite-Length Task. _taskId = UIApplication.SharedApplication.BeginBackgroundTask(null); // Start saving the user choices. Task.Run(() => { try { AppSettings.LocalizedCurrentLocationString = "CurrentLocationLabel".Localize(); AppSettings.SaveSettings(Path.Combine(DownloadViewModel.GetDataFolder(), "AppSettings.xml")); UIApplication.SharedApplication.EndBackgroundTask(_taskId); } catch (Exception ex) { ErrorLogger.Instance.LogException(ex); } }); }
private void AddDownload(DownloadViewModel download) { // Find an existing download for this file path var existingDownload = Downloads.FirstOrDefault(d => d.FilePath == download.FilePath); // If it exists - cancel and remove it if (existingDownload != null) { if (existingDownload.CanCancel) { existingDownload.Cancel(); } Downloads.Remove(existingDownload); } // Add to list Downloads.Add(download); }
protected override void OnCreate(Bundle savedInstanceState) { AndroidApplication = Application as AndroidApplication; AndroidApplication.Logger.Debug(() => $"DownloadActivity:OnCreate"); base.OnCreate(savedInstanceState); // Set our view from the layout resource SetContentView(Resource.Layout.activity_download); RvDownloads = FindViewById <EmptyRecyclerView>(Resource.Id.rvDownloads); NoDataView = FindViewById <LinearLayout>(Resource.Id.layNoData); NoDataText = FindViewById <TextView>(Resource.Id.txtNoData); ProgressSpinner = FindViewById <ProgressSpinnerView>(Resource.Id.progressBar); DownloadButton = FindViewById <FloatingActionButton>(Resource.Id.fab_download); RvDownloads.SetLayoutManager(new LinearLayoutManager(this)); RvDownloads.AddItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.Vertical)); RvDownloads.SetEmptyView(NoDataView); var factory = AndroidApplication.IocContainer.Resolve <ViewModelFactory>(); ViewModel = new ViewModelProvider(this, factory).Get(Java.Lang.Class.FromType(typeof(DownloadViewModel))) as DownloadViewModel; Adapter = new DownloadRecyclerItemAdapter(this, ViewModel); RvDownloads.SetAdapter(Adapter); Lifecycle.AddObserver(ViewModel); SetupViewModelObservers(); ViewModel.Initialise(); Task.Run(() => ViewModel.FindEpisodesToDownload()); DownloadButton.Click += (sender, e) => ViewModel.DownloadAllPodcastsWithNetworkCheck(); ExitPromptDialogFragment = SupportFragmentManager.FindFragmentByTag(EXIT_PROMPT_TAG) as OkCancelDialogFragment; SetupFragmentObservers(ExitPromptDialogFragment); NetworkPromptDialogFragment = SupportFragmentManager.FindFragmentByTag(NETWORK_PROMPT_TAG) as OkCancelDialogFragment; SetupFragmentObservers(NetworkPromptDialogFragment); AndroidApplication.Logger.Debug(() => $"DownloadActivity:OnCreate - end"); }
/// <summary> /// Gets called when the download has been completed. /// </summary> /// <param name="session">NSUrl Session.</param> /// <param name="downloadTask">Download task.</param> /// <param name="location">NSUrl Location.</param> public override void DidFinishDownloading(NSUrlSession session, NSUrlSessionDownloadTask downloadTask, NSUrl location) { // The download location is the location of the file var sourceFile = location.Path; // Copy over to documents folder. Note that we must use NSFileManager here! File.Copy() will not be able to access the source location. var fileManager = NSFileManager.DefaultManager; // Remove any existing files in our destination NSError error; fileManager.Remove(Path.Combine(DownloadViewModel.GetDataFolder(), AppSettings.CurrentSettings.PortalItemName), out error); var success = fileManager.Copy(sourceFile, Path.Combine(DownloadViewModel.GetDataFolder(), AppSettings.CurrentSettings.PortalItemName), out error); if (!success) { Console.WriteLine("Error during the copy: {0}", error.LocalizedDescription); } this.InvokeOnMainThread(() => this.controller.LoadMapView()); }
public JsonResult Edit(DownloadViewModel model) { ResultRetrun rmodel = new ResultRetrun(); if (ModelState.IsValid) { FileDownload data = downService.Get(model.Id); data.Title = model.FileTitle; data.Name = model.FileName; data.Description = !string.IsNullOrEmpty(model.Description) ? model.Description.Replace("\r\n", "") : string.Empty; data.Category = model.Category; data.State = (PublishState)model.State; data.HeadImg = model.FileImg; data.Src = model.Src; data.Type = string.IsNullOrEmpty(model.Extension) ? model.FileType : getFileFormat(model.Extension); rmodel.isSuccess = downService.Update(data); } return(Json(rmodel)); }
private async Task InitializeAsync() { // Test if download path has been specified by user, if not, prompt // If download path exists, check if valid if (string.IsNullOrEmpty(Settings.Default.DownloadPath) || !Directory.Exists(Settings.Default.DownloadPath)) { this.PromptUserForDownloadDirectory(); } // Test if AppViewModel singleton instance exists if (AppViewModel.Instance == null) { // Set data context for the main screen and load main screen AppViewModel.Instance = AppViewModel.Create(); this.DataContext = AppViewModel.Instance; } // Make instance of the DownloadViewModel and set it as datacontext. // This will set the active view as the DownloadView try { var downloadViewModel = new DownloadViewModel(); AppViewModel.Instance.DisplayViewModel = downloadViewModel; await downloadViewModel.ConnectToPortalAsync(); } catch (Exception ex) { // If unexpected exception happens during download, ignore it and load existing map System.Windows.MessageBox.Show( "An error has occured during the map download: " + ex.Message + " The previously downloaded map will now be loaded.", "Unhandled Exception", MessageBoxButton.OK, MessageBoxImage.Error); } finally { await this.LoadMmpkAsync(); } }
public async Task <IActionResult> Downloads(DownloadViewModel model, Paging <BlogEntry> paging) { if (paging.SortColumn == null) { paging.SetSortExpression(p => p.PublishDate); paging.SortDirection = SortDirection.Descending; } IQueryable <BlogEntry> query = this.unitOfWork.BlogEntries .AsNoTracking() .Include(b => b.BlogEntryFiles); if (model.SearchTerm != null) { query = query.Where(u => u.Header.Contains(model.SearchTerm)); } model.BlogEntries = await query .GetPagedResultAsync(paging); return(this.View(model)); }
/// <summary> /// Sets the home location for the user and saves it into settings. /// </summary> /// <param name="locationText">Location text.</param> /// <returns>Async task</returns> private async void SetHomeLocationAsync(string locationText) { try { GeocodeResult homeLocation = await _viewModel.GetSearchedLocationAsync(locationText); Feature homeFeature = await _viewModel.GetRoomFeatureAsync(locationText); if (homeFeature != null) { AppSettings.CurrentSettings.HomeCoordinates = new[] { new SerializableKeyValuePair <string, double>("X", homeLocation.DisplayLocation.X), new SerializableKeyValuePair <string, double>("Y", homeLocation.DisplayLocation.Y), new SerializableKeyValuePair <string, double>("WKID", homeLocation.DisplayLocation.SpatialReference.Wkid) }; AppSettings.CurrentSettings.HomeFloorLevel = homeFeature .Attributes[AppSettings.CurrentSettings.RoomsLayerFloorColumnName].ToString(); AppSettings.CurrentSettings.HomeLocation = locationText; } else { AppSettings.CurrentSettings.HomeCoordinates = null; AppSettings.CurrentSettings.HomeFloorLevel = null; AppSettings.CurrentSettings.HomeLocation = null; } await Task.Run(() => AppSettings.SaveSettings(Path.Combine(DownloadViewModel.GetDataFolder(), "AppSettings.xml"))); _viewModel.UpdateHomeLocation(); } catch (Exception ex) { ErrorLogger.Instance.LogException(ex); } NavigationController.PopViewController(true); }
public IActionResult Downloads(int id) { List <DownloadCategory> categories = _downloadProvider.DownloadCategoriesGet(UserId()); DownloadCategory activeCategory = categories.Where(d => d.Id == id).FirstOrDefault(); if (activeCategory == null) { activeCategory = categories[0]; } List <ViewDownloadViewItem> downloads = new List <ViewDownloadViewItem>(); foreach (DownloadItem item in activeCategory.Downloads) { downloads.Add(new ViewDownloadViewItem(item.Id, item.Name, item.Description, item.Version, item.Filename, item.Icon, item.Size)); } DownloadViewModel model = new DownloadViewModel(categories, activeCategory.Name, downloads); return(View(model)); }
public async Task<ActionResult> Download(Guid notificationId, Guid id) { var model = new DownloadViewModel { MovementId = id }; ViewBag.MovementNumber = await mediator.SendAsync(new GetMovementNumberByMovementId(id)); return View(model); }