public void Download() { NetworkProtocolProviderFactory networkProtocolProviderFactory = new NetworkProtocolProviderFactory(new UrlProtocolParser()); HttpProtocolProvider httpProtocolProvider = new HttpProtocolProvider(new WebRequestManager(new WebRequestFactory())); networkProtocolProviderFactory.RegisterProvider("http", httpProtocolProvider); networkProtocolProviderFactory.RegisterProvider("https", httpProtocolProvider); EventManager eventManager = new EventManager(); DownloadManager downloadManager = new DownloadManager( new InMemoryDownloadSettings(200, 5, 8096, 5, 5), new MemoryDownloadStreamManager(), networkProtocolProviderFactory, eventManager); downloadManager.Start(); downloadManager.AddNewDownloadTask(new DownloadTaskInfo(new DownloadFileInfo(new Uri("https://androidnetworktester.googlecode.com/files/1mb.txt"), "1mb.txt", 5), true)); downloadManager.AddNewDownloadTask(new DownloadTaskInfo(new DownloadFileInfo(new Uri("http://127.0.0.1:8552/1mb.txt"), "1mb.txt", 5), true)); eventManager.EventSubscriber.RegisterConsumer(new ActionEventConsumer<DownloadTaskFinishedEventMessage>(x => { string txt = Encoding.UTF8.GetString(((MemoryStream)x.DownloadStream).ToArray()); txt.ToString(); })); downloadManager.Shutdown(true); }
public void CheckThatTheDownloaderIsCalledForEachEnumeration() { var collection = new DownloadCollection( string.Empty, new List<IEnumerable<string>> { new List<string> { "A", "B" }, new List<string> { "D", "E", "F" }, new List<string> { "G", "H", "I" } }, "{0}{1}{2}"); var mockDownloader = new Mock<IDownloader>(); mockDownloader.Setup(d => d.Download(collection, It.IsAny<string>())).Returns(new Task<bool>(() => true)); var manager = new DownloadManager(new List<DownloadCollection> { collection }) { Downloader = new FakeDownloader() //mockDownloader.Object }; manager.StartDownloading(); var bob = false; while(!bob) { } //mockDownloader.Verify(d => d.Download(collection, It.IsAny<string>()), Times.Exactly(18)); }
protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); // Set our view from the "main" layout resource SetContentView (Resource.Layout.Main); this.downloadButton = FindViewById<Button> (Resource.Id.downloadButton); this.clickButton = FindViewById<Button> (Resource.Id.clickButton); this.infoLabel = FindViewById<TextView> (Resource.Id.textView1); this.imageview = FindViewById<ImageView> (Resource.Id.imageView1); this.downloadProgress = FindViewById<ProgressBar> (Resource.Id.progressBar); downloadButton.Click += DownloadAsync; clickButton.Click += delegate { clickButton.Text = string.Format ("{0} clicks!", count++); //TODO:Remove the two methods below. TimeTake.LongMethod1(); TimeTake.LongMethod2(); }; manager = new DownloadManager (); manager.DownloadProgressChanged += HandleDownloadProgressChanged; }
public CommandInterpreter(Tester judge, StudentsRepository repository, DownloadManager downloadManager, IOManager inputOutputManager) { this.judge = judge; this.repository = repository; this.downloadManager = downloadManager; this.inputOutputManager = inputOutputManager; }
protected Command(string input, string[] data, Tester judge, StudentsRepository repository, DownloadManager downloadManager, IOManager inputOutputManager) { this.Input = input; this.Data = data; this.judge = judge; this.repository = repository; this.downloadManager = downloadManager; this.inputOutputManager = inputOutputManager; }
public static void Main() { Tester tester = new Tester(); DownloadManager downloadManager = new DownloadManager(); IOManager ioManager=new IOManager(); StudentsRepository repo=new StudentsRepository(new RepositorySorter(), new RepositoryFilter()); CommandInterpreter currentInterpreter=new CommandInterpreter(tester, repo, downloadManager, ioManager); InputReader reader=new InputReader(currentInterpreter); reader.StartReadingCommands(); }
void Init() { //初始化顺序不能变 downloadMgr = gameObject.AddComponent<DownloadManager>(); bundleMgr = gameObject.AddComponent<BundleManager>(); luaMgr = new LuaScriptMgr(); LuaStatic.Load = Utils.LuaLoader; downloadMgr.Init(); bundleMgr.Init(); Utils.DoFile("Init"); }
public StatusDialog UpdateApplication(EventWaitHandle asyncHandle) { var feedManager = new FeedManager(this.publicKey); var newVersions = feedManager.GetNewVersions(feedUrl, this.context.ApplicationVersion); if (dialog == null) { this.dialog = new StatusDialog(); this.dialog.AppTitle = this.context.ApplicationTitle; this.dialogAdapter = new StatusDialogAdapter(dialog); } worker = new UpdateWorker( () => { var downloadManager = new DownloadManager(this.context, dialogAdapter); var files = downloadManager.DownloadFiles(newVersions); var installer = new InstallationManager(this.context, new TraceLogger()); foreach (var file in files.OrderBy(f => f.Key)) { installer.Install(file.Value, file.Key); } }); worker.WorkCompleted += (object sender, System.ComponentModel.RunWorkerCompletedEventArgs e) => { if (dialog != null) { dialog.Close(); dialog.Dispose(); dialogAdapter = null; dialog = null; } if (asyncHandle != null) { asyncHandle.Set(); } }; worker.Start(); return this.dialog; }
public void Start() { /* ConnectServer.FileDownload("http://ctx.me/img/ctx.png", "ctx.png"); ConnectServer.FileDownload("https://ctx.me/img/ctx.png", "ctxSSS.png"); ConnectServer.FileDownload("http://cdimage.debian.org/debian-cd/8.2.0/amd64/iso-cd/debian-8.2.0-amd64-netinst.iso", "debiannet.iso"); ConnectServer.FileDownload("http://cdimage.debian.org/debian-cd/8.2.0/amd64/iso-cd/debian-8.2.0-amd64-netinst.iso", "debianNET2.iso");*/ DownloadManager m = new DownloadManager(); m.FileDownload("http://ctx.me/img/ctx.png", "ctx.png"); m.FileDownload("http://www.gettyimages.com/gi-resources/images/frontdoor/creative/Embed/hero_travel_482206371.jpg", "1.jpg"); m.FileDownload("http://www.planwallpaper.com/static/images/Winter-Tiger-Wild-Cat-Images.jpg", "2.jpg"); m.FileDownload("http://risehighershinebrighter.files.wordpress.com/2014/11/magic-of-blue-universe-images.jpg", "3.jpg"); //zeza server m.FileDownload("http://www.planwallpaper.com/static/images/background-gmail-google-images_FG2XwaO.jpg", "4.jpg"); m.FileDownload("http://cdn.spacetelescope.org/archives/images/large/heic1509a.jpg", "5.jpg"); m.FileDownload("http://www.indiotomato.com/images/icethumbs/1175x465/75/images/Sliders1/CAMPO2.png", "6.jpg"); }
private void InitBaseSys() { //gameObject.AddComponentEx<AppConfig>(); TimerManager.CreateInstance(); InputTimerManager.GetInstance(); DownloadManager.CreateInstance(); WindowRegister.CreateInstance(); //HUIManager.CreateInstance (); //ActorObjManager.CreateInstance (); GameObjectPool.CreateInstance(); TableProtoManager.Instance.PreLoadTableData(); //UISpriteManager.CreateInstance (); //SDKManager.CreateInstance (); //UserManager.CreateInstance (); TimeUtils.CurUnixTime = TimeUtils.ToUtcSeconds(DateTime.Now); //RestManager.CreateInstance(); }
//所有的下载任务都完成了 private void AllDownloadTaskFinished(bool updateVersionTxt) { LogHelper.Log("All Task Finish"); if (updateVersionTxt) { //替换本地的Version.txt为web服务器上的,保持版本最新 Util.CreateFile(this.localPath, versionTxtName, this.remoteVersionData); LogHelper.Log(versionTxtName + "已更新"); } this.LocalVersion = null; this.RemoteVersion = null; this.remoteVersionData = null; //释放downloadmgr DownloadManager.GetInstance().Dispose(); this.isAllFinish = true; }
public void Initialize() { tasks = new Dictionary <string, HttpFileDownloadTask> (); import_manager = new LibraryImportManager(true); import_manager.ImportResult += HandleImportResult; if (download_manager == null) { download_manager = new DownloadManager(2, tmp_download_path); } if (download_manager_iface == null) { download_manager_iface = new DownloadManagerInterface(download_manager); download_manager_iface.Initialize(); } ServiceManager.Get <DBusCommandService> ().ArgumentPushed += OnCommandLineArgument; }
internal static void ScheduleAssetDownloads() { bool need = false; DownloadPackage dlp = new DownloadPackage("Assets", true); List <MinecraftAsset> needDl = new List <MinecraftAsset>(); assets.ForEach(a => { if (a.NeedsDownload()) { needDl.Add(a); Download dl = dlp.ScheduleDownload(a.Key, a.Url); dl.Downloaded += AssetDownloaded; need = true; } }); if (need) { DownloadManager.ScheduleDownload(dlp); } }
private void OnSaveFile(object sender, UserInfo userInfo, string path) { Gtk.Application.Invoke(delegate { PeerSocket peer = P2PManager.KnownPeers[userInfo] as PeerSocket; // Save File Dialog string savePath = Glue.Dialogs.SaveFile(Paths.UserSharedDirectory(MyInfo.Name), path.Substring(1)); if (savePath == null) { return; } try { DownloadManager.AddToAcceptList(peer, path, savePath); CmdManager.AcceptFile(peer, path); } catch (Exception e) { Glue.Dialogs.MessageError("Save File", e.Message); } }); }
/// <summary> /// 根据文件名获得下载地址 /// </summary> /// <param name="fileName">文件名</param> /// <returns></returns> private string GetPublishUrl(string fileName) { if (domainsResult.Result.Count > 0) { string domain = domainsResult.Result[0]; if (domain.StartsWith(".") && !string.IsNullOrWhiteSpace(bucket)) { domain = bucket + domain; } string domainUrl = config.UseHttps ? "https://" + domain : "http://" + domain; return(DownloadManager.CreatePublishUrl(domainUrl, fileName)); } else { MessageBox.Show("无法获得空间的域名"); return(string.Empty); } }
public DownloadListViewModel( StartDownloadCommand startDownloadCommand, DownloadManager downloadManager, DeleteFromDownloadListCommand deleteFromDownloadListCommand) { _startDownloadCommand = startDownloadCommand; _deleteFromDownloadListCommand = deleteFromDownloadListCommand; _downloadManager = downloadManager; DownloadList = _downloadManager.GetDownloadList(); DownloadEventHub.DownloadStart += OnDownloadStart; DownloadEventHub.DownloadPause += OnDownloadPause; DownloadEventHub.DownloadResume += OnDownloadResume; DownloadEventHub.DownloadProgress += OnDownloadProgress; DownloadEventHub.DownloadError += OnDownloadError; DownloadEventHub.DownloadStop += OnDownloadStop; DownloadEventHub.DownloadEnd += OnDownloadEnd; DownloadEventHub.DownloadChapterStart += OnDownloadChapterStart; DownloadEventHub.DownloadChapterEnd += OnDownloadChapterEnd; }
/// <summary> /// 抛给下载器进行下载 /// </summary> private void PushDownloadTask() { DownloadTask firstTask = this.needDownloadTask.Peek(); this.currentTask = firstTask; firstTask.Url = this.remoteUrl + firstTask.FileName; //设置保存本地的目录 firstTask.FileName = this.localPath + firstTask.FileName; string path = Path.GetDirectoryName(firstTask.FileName); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } DownloadManager.GetInstance().downloadProgressChangedCallBack = this.OneTaskProgressChanged; DownloadManager.GetInstance().oneTaskFinished = this.OneTaskFinished; DownloadManager.GetInstance().AsynDownLoadFile(firstTask); }
public ValueTask ExecuteAsync(IConsole console) { var cancellationToken = console.RegisterCancellationHandler(); if (OperatingSystem.IsWindows() && IsAdministrator()) { var downloadManager = new DownloadManager(); downloadManager.InstallDfuUtil(Environment.Is64BitOperatingSystem); } else if (OperatingSystem.IsMacOS()) { _logger.LogInformation("To install on macOS, run: brew install dfu-util"); } else if (OperatingSystem.IsLinux()) { _logger.LogInformation( "To install on Linux, use the package manager to install the dfu-util package"); } return(ValueTask.CompletedTask); }
// ============================================ // PRIVATE Methods // ============================================ // ============================================ // PRIVATE Methods // ============================================ private void AcceptFileQuestion(PeerSocket peer, XmlRequest xml) { string name = (string)xml.Attributes["name"]; string path = (string)xml.Attributes["path"]; string size = (string)xml.Attributes["size"]; if (size == null) { size = "0"; } UserInfo userInfo = peer.Info as UserInfo; StringBuilder questionMsg = new StringBuilder(); questionMsg.AppendFormat("Accept File '<b>{0}</b>' ", name); questionMsg.AppendFormat("(Size <b>{0}</b>)\n", FileUtils.GetSizeString(long.Parse(size))); questionMsg.AppendFormat("From User '<b>{0}</b>' ?", userInfo.Name); // Accept Yes/No Dialog bool accept = Glue.Dialogs.QuestionDialog("Accept File", questionMsg.ToString()); if (accept == false) { return; } // Save File Dialog string savePath = Glue.Dialogs.SaveFile(Paths.UserSharedDirectory(MyInfo.Name), name); if (savePath == null) { return; } // Send Accept File Command Debug.Log("Accept File '{0}' From '{1}', Save as '{2}'", userInfo.Name, path, savePath); DownloadManager.AddToAcceptList(peer, path, savePath); CmdManager.AcceptFile(peer, xml); }
public void StartDownload() { lock (this) { if (Downloading || !CanStart()) { //DoError("Download allready started"); DownloadStatus = EDownloadStatus.failed; DownloadManager.DownloadStateChanged(this, EDownloadStatus.failed); if (DownloadEventListener != null) { DownloadEventListener(this, ESimpleEvent.failed, "Download allready started"); } return; } Downloading = true; DownloadStatus = EDownloadStatus.started; DownloadManager.DownloadStateChanged(this, EDownloadStatus.started); if (DownloadEventListener != null) { DownloadEventListener(this, ESimpleEvent.started, ""); } try { StartDownloadA(); } catch (Exception e) { LogError("failed to download from: " + URL); LogError(e.Message); DownloadStatus = EDownloadStatus.failed; DownloadManager.DownloadStateChanged(this, EDownloadStatus.failed); if (DownloadEventListener != null) { DownloadEventListener(this, ESimpleEvent.failed, ""); } Downloading = false; webClient = null; } } }
void OnGetRemoteVersion(bool succeed, string versionNum = null) { Debug.Log("读取版本号:" + succeed); // 获取了远程版本号 if (null != versionNum) { Debug.Log("version:" + versionNum); if (curVersionNum != versionNum) { lastVersionNum = curVersionNum; curVersionNum = versionNum; FileTool.CreatFile(localVersionFile, Encoding.ASCII.GetBytes(curVersionNum)); } // 下载新的manifest文件 localManifestPath = Path.Combine(localBundlePath, curVersionNum); _localXManifestPath = localBundlePath + "/" + curVersionNum + ".xManifest"; resUrlRoot = patchUrl + "/" + Utility.GetPlatformName() + "/" + curVersionNum; if (!File.Exists(localManifestPath)) { string manifestUrl = patchUrl + "/" + Utility.GetPlatformName() + "/" + curVersionNum + "/" + curVersionNum; Debug.Log(localBundlePath); DownloadManager dm = DownloadManager.instance; dm.OnError += OnDownloadErr; dm.OnFinish += OnAllDownloadOver; curDownloadAllOverCallback = ManifestDownloadFinish; dm.OnFinish += curDownloadAllOverCallback; dm.Push(new DownloadManager.Request(manifestUrl, OnFileDownloadOver, localManifestPath)); dm.Excute(); } else { //进入下一步 ManifestDownloadFinish(); } } else { //未获取远程版本号 Debug.LogError("获取远程版本号失败"); } }
/// <summary> /// 下载热更索引文件 /// </summary> private void LoadConfig() { if (_hotVersionPb.HotVersion == 0) { new FileChecker().DeleteHotfixFile(); EnterGame(); return; } DownloadManager.LoaderQueueComplete = OnQueueEnd; DownloadManager.LoaderQueueError = OnQueueError; if (File.Exists(_hotfixConfigPath) && CheckIndexFile()) { //热更配置文件不存在 List <IDownloadItem> files = CheckHotfixFile(); if (files == null || files.Count == 0) { EnterGame(); } else { if (_isRetry || indexFile.FileTotalSize < ConfirmSize) { LoadHotfixFiles(files); } else { View.ShowUpdateBtn(true); } } } else { View.SetText(I18NManager.Get("Update_WaitDownload")); DownloadManager.Load( _hotVersionPb.Addr + "hotfix_" + _hotVersionPb.Version + "/v" + _hotVersionPb.HotVersion + "/HotfixConfig_v" + _hotVersionPb.HotVersion + ".zip", _hotfixConfigPath, OnHotfixConfigLoaded, OnLoadHotfixConfigError, OnLoadHotfixConfigProgress); } }
private void DisconnectMyPeer() { try { // Disconnect From NyFolder Web Server MyInfo.DisconnectFromWebServer(); } catch (Exception e) { Glue.Dialogs.MessageError("Disconnection From Web Server", e.Message); } try { // Remove All Connected Users this.RemoveAllUsers(); // Remove Custom Command Handler if (DelProtocolEvent != null) { DelProtocolEvent(p2pManager, cmdManager); } // Reset Command Manager & Del Commands Handler this.DelProtocolEvents(); this.cmdManager.DelPeerEventsHandler(); } catch (Exception e) { Glue.Dialogs.MessageError("Remove Protocol Events", e.Message); } try { // Reset Download & Upload Manager UploadManager.Clear(); DownloadManager.Clear(); } catch (Exception e) { Glue.Dialogs.MessageError("Download/Upload Manager Stop", e.Message); } try { // P2P Stop Listening this.p2pManager.StopListening(); } catch (Exception e) { Glue.Dialogs.MessageError("P2P Disconnection Error", e.Message); } }
public void Initialize() { Log.DebugFormat("{0} initialized.", this.ToString()); tasks = new Dictionary <string, HttpFileDownloadTask> (); import_manager = ServiceManager.Get <LibraryImportManager> (); import_manager.ImportResult += HandleImportResult; if (download_manager == null) { download_manager = new DownloadManager(2, tmp_download_path); } if (download_manager_iface == null) { download_manager_iface = new DownloadManagerInterface(download_manager); download_manager_iface.Initialize(); } ServiceManager.Get <DBusCommandService> ().ArgumentPushed += OnCommandLineArgument; }
FileManifest GetFileManifest() { string pathToAgFiles = Path.Combine(SettingsFile.OriginalAppPath, Settings.FILES_FILENAME); DownloadManager dm = new DownloadManager(); Utils.Log("Getting file manifest..."); string filesJson; if (SettingsFile.FileManifest.StartsWith("http")) { dm.DownloadRemoteFile(SettingsFile.FileManifest, pathToAgFiles); filesJson = File.ReadAllText(pathToAgFiles); } else { filesJson = File.ReadAllText(SettingsFile.FileManifest); } Utils.Log("Reading file manifest..."); return(JsonConvert.DeserializeObject <FileManifest>(filesJson)); }
public FormImportDownloads(string filepath, bool isJson, Preferences prefs, DownloadManager downloadManager, Func <string, bool> containedInDownloadList, Action <Download> callback) { InitializeComponent(); this.prefs = prefs; this.downloadManager = downloadManager; this.callback = callback; try { List <string> urls = isJson ? JsonConvert.DeserializeObject <List <string> >(File.ReadAllText(filepath, new UTF8Encoding(false))) : File.ReadAllLines(filepath, new UTF8Encoding(false)).ToList(); totalUrls = urls.Count; urlsToAdd = urls.Where(url => !containedInDownloadList(url) && Util.IsValidUrl(url)).ToList(); } catch (Exception) { totalUrls = 0; urlsToAdd = new List <string>(); } }
static void Main(string[] args) { SpotifyAgent.Auth(); //Test Playlist //Uri link = new Uri("https://open.spotify.com/user/lozza11111/playlist/66Q0HHtNRqqd6Aw79jfPpA?si=n7hwbprgTQu29SWru9b8cg"); Uri link = new Uri(@"https://open.spotify.com/album/3h5a97Q165hNExBkutPTTp?si=DU6EeA6IQiiLQ5mRLSOhMA"); DownloadList newList = DownloadManager.NewList("Test", new Uri(@"D:\Users\Laurence\Desktop\Testing")); DownloadManager.AddTracksLink(link, newList); newList.TrackFormat = Format.mp3; newList.TrackQuality = Quality._320kbps; DownloadManager.EnqueueList(newList); DownloadManager.DequeueList(newList); Console.ReadLine(); }
public void OnSndEvent(PeerSocket peer, XmlRequest xml) { Gtk.Application.Invoke(delegate { string what = (string)xml.Attributes["what"]; if (what == "folder-list") { UserInfo userInfo = peer.Info as UserInfo; FolderViewer folderViewer = notebookViewer.LookupPage(userInfo); folderViewer.Fill((string)xml.Attributes["path"], xml.BodyText); } else if (what == "file") { try { DownloadManager.GetFilePart(peer, xml); } catch (Exception e) { Glue.Dialogs.MessageError("Download File Part", e.Message); } } }); }
private void CheckUpdates() { Uri host = new Uri(DataManager.Get <ISettingsManager>().Settings.DownloadUrl); if (!Reachability.IsHostReachable("http://" + host.Host)) { return; } var info = new DirectoryInfo(DataManager.Get <ISettingsManager>().Settings.DocPath); var dir = _CurrentDir.FullName.Replace(info.FullName, "").Trim('/'); ThreadPool.QueueUserWorkItem(delegate { var downloads = DownloadManager.GetDocuments(dir); //var updates = downloads.Where(d => d.Stato == DownloadStato.Update); _downloads = downloads.ToList(); if (Activity == null) { return; } Activity.RunOnUiThread(() => { try { EdicolaGridAdapter adapter = (EdicolaGridAdapter)_EdicolaGridView.Adapter; adapter.CheckUpdates(_downloads); } catch (Exception ex) { Log.Error("", ex.Message); } }); }); }
/// <summary> /// Returns stream to read file from DC or from share /// Allows to read non-downloaded files /// </summary> /// <param name="magnet"></param> /// <returns>Stream to read data according to the magnet or null</returns> public DcStream GetStream(Magnet magnet) { DcStream stream = null; // first of all try to find an item in the share if (Share != null) { var items = Share.Search(new SearchQuery { Query = magnet.TTH, SearchType = SearchType.TTH }); if (items.Count > 0) { // we have an item in the share... stream = new DcStream(items[0].SystemPath, magnet); } } if (stream == null) { var item = DownloadManager.GetDownloadItem(magnet.TTH); if (item != null) { stream = new DcStream(item); } } if (stream != null) { lock (_streams) { _streams.Add(stream); } stream.Disposed += StreamDisposed; } return(stream); }
public static SessionInfo Connect(string Username, string Password) { if (Username != null && Password != null) { try { if (DownloadManager.hasInternet) { Download dl = DownloadManager.ScheduleDownload("minecraft session info", String.Format(MinecraftData.MinecraftLoginUrl, Username, Password), true); dl.WaitForComplete(); string result = Encoding.ASCII.GetString(dl.Data); if (result.ToUpper() == "BAD LOGIN") { throw new Exception("Bad Login!"); } string[] arguments = result.Split(':'); SessionInfo si = new SessionInfo(); si.username = arguments[2]; si.sessionid = arguments[3]; return(si); } else { SessionInfo si = new SessionInfo(); si.username = Username; si.sessionid = ""; return(si); } } catch (Exception ex) { App.Log("An error occured while loging in to minecraft: " + ex.ToString()); throw ex; } } else { throw new Exception("Missing login info"); } }
public void PostJob_Normal() { CancellationToken cancellationToken = CancellationToken.None; int concurrentDownloads = 3; int numJobs = 10; var manager = new DownloadManager(concurrentDownloads); var songsDir = Path.GetFullPath(@"Output\DownloadManager_Tests\PostJob_Tests"); var jobs = GetDefaultJobs(songsDir, numJobs); manager.Start(cancellationToken); foreach (var job in jobs) { job.OnJobFinished += OnJobFinished_Default; manager.TryPostJob(job, out var postedJob); } manager.CompleteAsync().Wait(); foreach (var job in jobs) { Assert.IsTrue(job.Result.Successful); } foreach (var job in jobs) { if (manager.TryGetJob(job.SongHash, out var foundJob)) { Assert.IsTrue(foundJob.Result.Successful); } else { Assert.Fail("Couldn't find a job"); } } if (manager.TryGetJob("asdfasdf", out var fakeJob)) { Assert.Fail(); } else { Assert.IsNull(fakeJob); } }
public FrmChannel() { InitializeComponent(); OdeoApplication.RootDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase); TextLogger.DirectoryName = OdeoApplication.RootDirectory; try { // The startup worker initializes the application. Among other things, it reads the // saved user preferences from disk and creates the OdeoApplication.Preferences object. this.StartupWorker = new BackgroundWorker(this); this.StartupWorker.WorkerReportsProgress = true; this.StartupWorker.DoWork += new DoWorkEventHandler(StartupWorker_DoWork); this.StartupWorker.ProgressChanged += new ProgressChangedEventHandler(StartupWorker_ProgressChanged); this.StartupWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(StartupWorker_RunWorkerCompleted); _channelManager = new ChannelManager(this); _channelManager.Channel.Library = OdeoApplication.Preferences.Library; _channelManager.Channel.Name = OdeoApplication.Preferences.Username; _channelManager.Channel.Link = String.Format(OdeoApplication.Preferences.BaseUrl, OdeoApplication.Preferences.Username); _channelManager.Synchronized += new RunWorkerCompletedEventHandler(Synchronized); _downloadManager = new DownloadManager(this); _downloadManager.HttpResponseReceived += new ProgressChangedEventHandler(HttpResponseReceived); _downloadManager.HttpDataReceived += new ProgressChangedEventHandler(HttpDataReceived); _downloadManager.HttpDownloadComplete += new RunWorkerCompletedEventHandler(HttpDownloadComplete); this.DownloadList = new Tasklist(); this.DownloadList.BackColor = Color.White; this.DownloadList.Location = new Point(0, 0); this.DownloadList.Size = new Size(this.MainPanel.Width, this.MainPanel.Height); this.MainPanel.Controls.Add(this.DownloadList); } catch (Exception ex) { OdeoApplication.TraceException("FrmChannel::Constructor", ex); } }
// ファイルパスからGoogleドライブIDや最終更新日などの情報を引けるDictionaryを作成する private IEnumerator SetFilePathDictionary(string fileDictFileID) { WWW www; fileDataDictionary = new Dictionary <string, string[]>(); if (useGoogleDrive) { www = new WWW(GoogleDriveFileDownloadPath + fileDictFileID); } else { www = new WWW(baseURL + "/FileList.dat"); } while (!www.isDone) { yield return(null); } if ((www == null) || (www.error != null)) { Debug.LogError("### FileDictionary download error! ###"); } else { string text = DownloadManager.ConvertDonwloadDataToString(www.bytes); foreach (var s in text.Split(',')) { string[] v = s.Split(':'); if (!useGoogleDrive) { v[1] = ""; } fileDataDictionary[v[0]] = new string[] { v[1], v[2] }; Debug.Log(v[0] + ": " + v[1] + ", " + v[2]); } } }
public IActionResult GetAttachmet([FromRoute] int topicId, [FromRoute] int attachmentId) { if (!_topicPermissions.IsAssociatedTo(User.Identity.GetUserIdentity(), topicId)) { return(Forbidden()); } try { var attachment = _attachmentsManager.GetAttachmentById(attachmentId); string fileName = Path.Combine(Constants.AttachmentFolder, topicId.ToString(), attachment.Path); var hash = DownloadManager.AddFile(fileName, HttpContext.Connection.RemoteIpAddress); return(Ok(new StringWrapper() { Value = hash })); } catch (InvalidOperationException) { return(NotFound()); } }
/// <summary> /// Downloads required asset from the cloud /// </summary> /// <returns>Asynchronous task</returns> private async Task DownloadAsset(IProgress <SourceVariant> progress) { ScenarioManager.Instance.logPanel.EnqueueInfo($"Started a download process of the {name} agent."); ScenarioManager.Instance.ReportAssetDownload(assetGuid); Progress <Tuple <string, float> > downloadProgress = null; if (progress != null) { downloadProgress = new Progress <Tuple <string, float> >(p => { PreparationProgress = p.Item2; progress.Report(this); }); } assetModel = await DownloadManager.GetAsset(BundleConfig.BundleTypes.Vehicle, assetGuid, name, downloadProgress); ScenarioManager.Instance.ReportAssetFinishedDownload(assetGuid); if (AcquirePrefab()) { ScenarioManager.Instance.logPanel.EnqueueInfo($"Agent {name} has been downloaded."); } }
public override sealed void SetStandardValues() { SoundOutDeviceID = SoundOutManager.DefaultDevicePlaceholder; DisableNotificationInGame = true; ShowMagicArrowBelowCursor = true; WaveSourceBits = 16; SampleRate = -1; var language = Languages.FirstOrDefault(x => x.Code == Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName); Language = language == null ? "zh" : language.Code; Notification = NotificationType.Top; ApplicationDesign = new ApplicationDesign(); ApplicationDesign.SetStandard(); NotificationShowTime = 5000; RememberTrackImportPlaylist = false; PlaylistToImportTrack = null; LoadAlbumCoverFromInternet = true; DownloadAlbumCoverQuality = ImageQuality.Maximum; SaveCoverLocal = true; TrimTrackname = true; ShowArtistAndTitle = true; SoundOutMode = WasapiOut.IsSupportedOnCurrentPlatform ? SoundOutMode.WASAPI : SoundOutMode.DirectSound; Latency = 100; IsCrossfadeEnabled = false; CrossfadeDuration = 4; UseThinHeaders = true; MinimizeToTray = false; ShowNotificationIfMinimizeToTray = true; Downloader = new DownloadManager(); TabControlTransition = TransitionType.Left; ShowProgressInTaskbar = true; DownloadSettings = new DownloadSettings(); DownloadSettings.SetDefault(); CheckForAnyListenUpdates = true; CheckForYoutubeDlUpdates = true; Passwords = new List <PasswordEntry>(); FileNameFormat = 1; DownloadBitrate = 1; }
public void StartDownloading() { var file = new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/Parlament/" + DocumentID.ToString() + ".pdf"); if (file.Exists()) { var targetUri = Android.Net.Uri.FromFile(file); var intent = new Intent(Intent.ActionView); intent.SetDataAndType(targetUri, "application/pdf"); context.StartActivity(intent); } else { IntentFilter intentFilter = new IntentFilter(DownloadManager.ActionDownloadComplete); context.RegisterReceiver(broadcastReceiver, intentFilter); downloadManager = (DownloadManager)context.GetSystemService(Android.Content.Context.DownloadService); Toast.MakeText(context, "Pobieranie dokumentu pdf w tle. Poczekaj na zakończenie pobieranie i ponownie kliknij na dokument.", ToastLength.Long).Show(); downloadId = FileDownloader.DownloadFile("http://mojepanstwo.pl/docs/" + DocumentID.ToString() + "/download", DocumentID.ToString() + ".pdf", downloadManager); } }
private void LoadRaceTrack() { try { DownloadManager.Download("http://localhost:50248/races/track", OnRaceTrackLoaded); } catch (Exception e) { Debug.Log(e.ToString()); var track = new Track { StartPosition = new StartPosition { X = 0, Y = 0 }, Tiles = new TileType[][] { new TileType[] { TileType.Crossroads } } }; Create(track); } }
private string GetStreamDescription(MediaStreamInfo stream) { if (stream is VideoStreamInfo) { VideoStreamInfo VStream = stream as VideoStreamInfo; return(string.Format("{0} {1}p ({2}mb)", VStream.VideoEncoding, DownloadManager.GetVideoHeight(VStream), VStream.Size / 1024 / 1024)); } else if (stream is AudioStreamInfo) { AudioStreamInfo AStream = stream as AudioStreamInfo; return(string.Format("{0} {1}kbps ({2}mb)", AStream.AudioEncoding, AStream.Bitrate / 1024, AStream.Size / 1024 / 1024)); } else if (stream is MuxedStreamInfo) { MuxedStreamInfo MStream = stream as MuxedStreamInfo; return(string.Format("{0} {1}p ({2}mb) (with audio)", MStream.VideoEncoding, DownloadManager.GetVideoHeight(MStream), MStream.Size / 1024 / 1024)); } else { return(""); } }
static void Main(string[] args) { string uri = "net.pipe://localhost/test"; DownloadManager dm = new DownloadManager(); dm.CopyFileCallBack = delegate(string file) { return string.Format("get : {0}", file); }; using (ServiceHost host = new ServiceHost(dm)) { NetNamedPipeBinding binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None); host.AddServiceEndpoint(typeof(IDownloadManager), binding, uri); host.Open(); Console.WriteLine("press enter key to terminate"); Console.ReadLine(); host.Close(); } }
private void UncompUpdateListData(string patchFile, int index, DownloadManager.DoUpdateListCallback cb, object parm) { try { using (FileStream fileStream = new FileStream(patchFile, FileMode.Open)) { using (ZipInputStream zipInputStream = new ZipInputStream(fileStream)) { byte[] array = new byte[4096]; for (int i = 0; i < index; i++) { zipInputStream.GetNextEntry(); } ZipEntry nextEntry = zipInputStream.GetNextEntry(); using (MemoryStream memoryStream = new MemoryStream()) { int count; while ((count = zipInputStream.Read(array, 0, array.Length)) != 0) { memoryStream.Write(array, 0, count); } memoryStream.Seek(0L, SeekOrigin.Begin); if (cb != null) { cb(memoryStream, parm); } } } } } catch { this.FileError = true; } }
private void addRequestToWaitingList(DownloadManager.WWWRequest request) { if (this.succeedRequest.ContainsKey(request.url) || this.isInWaitingList(request.url)) { return; } int num = this.waitingRequests.FindIndex((DownloadManager.WWWRequest x) => x.priority < request.priority); num = ((num != -1) ? num : this.waitingRequests.Count); this.waitingRequests.Insert(num, request); }
private void SaveCacheBundleFileFromWWW(DownloadManager.WWWRequest request) { try { string cachedPatchFilePath = this.GetCachedPatchFilePath(request.bundleName); string directoryName = Path.GetDirectoryName(cachedPatchFilePath); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } string text = cachedPatchFilePath + ".tmp"; File.WriteAllBytes(text, request.www.bytes); File.Copy(text, cachedPatchFilePath, true); File.Delete(text); request.www.Dispose(); } catch { this.FileError = true; } }
private int SortByUpdateData(DownloadManager.UpdateBundleData aItem, DownloadManager.UpdateBundleData bItem) { bool flag = aItem.processingIndex >= 0; bool flag2 = bItem.processingIndex >= 0; if (flag && !flag2) { return -1; } if (flag2 && !flag) { return 1; } if (flag && flag2) { if (aItem.processingIndex < bItem.processingIndex) { return -1; } if (bItem.processingIndex < aItem.processingIndex) { return 1; } if (aItem.dataIndex < bItem.dataIndex) { return -1; } if (bItem.dataIndex < aItem.dataIndex) { return 1; } } return string.Compare(aItem.bundleName, bItem.bundleName); }
public void Awake() { /* string path = Application.dataPath.Substring (0, Application.dataPath.Length - 5); path = path.Substring(0, path.LastIndexOf('/')); downloadFolder = path + "/Documents/downloads"; */ //Debug.Log ("[GamedoniaFiles] Awake executed"); downloadFolder = Application.persistentDataPath + "/downloads"; downloads = new ArrayList (); downloadeds = new ArrayList (); downloadManager = new DownloadManager(downloadFolder); downloadManager.maxConcurrentDownloads = 4; _instance = this; downloadManager.DownloadDidFinishLoading += (object sender, DownloadManagerEvent e) => { if (DownloadDidFinishLoading != null) this.DownloadDidFinishLoading (sender, e); }; downloadManager.DownloadDidFail += (object sender, DownloadManagerEvent e) => { if (DownloadDidFail != null) this.DownloadDidFail (sender, e); }; downloadManager.DownloadDidReceiveData += (object sender, DownloadManagerEvent e) => { if (DownloadDidReceiveData != null) this.DownloadDidReceiveData (sender, e); }; downloadManager.DownloadDidStart += (object sender, DownloadManagerEvent e) => { if (DownloadDidStart != null) this.DownloadDidStart (sender, e); }; downloadManager.DownloadDidFinishLoadingAll += (object sender, DownloadManagerEvent e) => { if (DownloadDidFinishLoadingAll != null) this.DownloadDidFinishLoadingAll (sender, e); }; downloadManager.DownloadDidStartLoadingAllForManager += (object sender, DownloadManagerEvent e) => { if (DownloadDidStartLoadingAllForManager != null) this.DownloadDidStartLoadingAllForManager (sender, e); }; }
private DownloadManager.WWWRequest download(DownloadManager.WWWRequest request) { request.url = this.formatUrl(request.url); DownloadManager.WWWRequest result; if ((result = this.FindRequestFormUrl(request.url)) != null) { return result; } if (request.priority == -1) { request.priority = 0; } this.addRequestToWaitingList(request); return request; }
public override sealed void SetStandardValues() { SoundOutDeviceID = SoundOutManager.DefaultDevicePlaceholder; DisableNotificationInGame = true; ShowMagicArrowBelowCursor = true; WaveSourceBits = 16; SampleRate = -1; var language = Languages.FirstOrDefault(x => x.Code == Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName); Language = language == null ? "en" : language.Code; Notification = NotificationType.Top; ApplicationDesign = new ApplicationDesign(); ApplicationDesign.SetStandard(); NotificationShowTime = 5000; RememberTrackImportPlaylist = false; PlaylistToImportTrack = null; LoadAlbumCoverFromInternet = true; DownloadAlbumCoverQuality = ImageQuality.Maximum; SaveCoverLocal = false; TrimTrackname = true; ShowArtistAndTitle = true; SoundOutMode = WasapiOut.IsSupportedOnCurrentPlatform ? SoundOutMode.WASAPI : SoundOutMode.DirectSound; Latency = 100; IsCrossfadeEnabled = false; CrossfadeDuration = 4; UseThinHeaders = true; MinimizeToTray = false; ShowNotificationIfMinimizeToTray = true; Downloader = new DownloadManager(); TabControlTransition = TransitionType.Left; ShowProgressInTaskbar = true; AppCommunicationSettings = new AppCommunicationSettings(); AppCommunicationSettings.SetStandard(); DownloadSettings = new DownloadSettings(); DownloadSettings.SetDefault(); CheckForHurricaneUpdates = true; CheckForYoutubeDlUpdates = true; Passwords = new List<PasswordEntry>(); }
public ChangeAbsolutePathCommand(string input, string[] data, Tester judge, StudentsRepository repository, DownloadManager downloadManager, IOManager inputOutputManager) : base(input, data, judge, repository, downloadManager, inputOutputManager) { }
/// <summary> /// Visible only for unit testing. /// Do NOT call this method. /// </summary> public static void _internal_doInitialise(Biller biller, BillerFactory factory) { Unibiller.biller = biller; biller.onBillerReady += (success) => { if (onBillerReady != null) { if (success) { // Download manager needs Unibill to be initialised to get purchase receipts. downloadManager = factory.instantiateDownloadManager (biller); downloadManager.onDownloadCompletedEvent += onDownloadCompletedEvent; downloadManager.onDownloadFailedEvent += onDownloadFailedEvent; downloadManager.onDownloadProgressedEvent += onDownloadProgressedEvent; onBillerReady(biller.State == Unibill.Impl.BillerState.INITIALISED ? UnibillState.SUCCESS : UnibillState.SUCCESS_WITH_ERRORS); } else { onBillerReady(UnibillState.CRITICAL_ERROR); } } }; biller.onPurchaseCancelled += _onPurchaseCancelled; biller.onPurchaseComplete += _onPurchaseComplete; biller.onPurchaseFailed += _onPurchaseFailed; biller.onPurchaseRefunded += _onPurchaseRefunded; biller.onTransactionsRestored += _onTransactionsRestored; biller.Initialise(); }
private void Application_Load(object sender, EventArgs e) { this.downloadManager = new DownloadManager(this); //this.downloadManager.ConcurentDownloadCount = ApplicationConfig.Instance().ConcurrentDownloadCount; this.Visible = false; this.SuspendLayout(); this.InitControl(); this.ResumeLayout(); this.Visible = true; CelotApplication.Instance().ViewTransferEnable = true; if (CelotApplication.Instance().ViewIntent != null) { String ip = (string)CelotApplication.Instance().ViewIntent.Data; this.downloadManager.ClearDownloadMap(); this.downloadManager.add(ip); if (this.downloadManager.DownloadFileName != null && !"".Equals(this.downloadManager.DownloadFileName) && this.downloadManager.DownloadFileName.Length != 0) { this.downloadManager.SetAllDownloadFile(this.downloadManager.DownloadFileName); } this.initDownloadInfoPanel(); this.setDataToDownloadGrid(); CelotApplication.Instance().ViewIntent = null; } }
public DownloadManagerEvent(DownloadManager downloadManager, Download download, int errorCode) { this.download = download; this.downloadManager = downloadManager; this.errorCode = errorCode; }
private IEnumerator CompressFromPatchPath(string bundleName, DownloadManager.UpdateBundleData updateData) { return null; //DownloadManager.<CompressFromPatchPath>c__Iterator7 <CompressFromPatchPath>c__Iterator = new DownloadManager.<CompressFromPatchPath>c__Iterator7(); //<CompressFromPatchPath>c__Iterator.updateData = updateData; //<CompressFromPatchPath>c__Iterator.bundleName = bundleName; //<CompressFromPatchPath>c__Iterator.<$>updateData = updateData; //<CompressFromPatchPath>c__Iterator.<$>bundleName = bundleName; //<CompressFromPatchPath>c__Iterator.<>f__this = this; //return <CompressFromPatchPath>c__Iterator; }
public App() { // Load Embedded DLLs from Resources. emdll = new EmbeddedDLL(); siteExtensions = new DLL_Manager<ISiteExtension, ISiteExtensionCollection>(); databaseExtensions = new DLL_Manager<IDatabaseExtension, IDatabaseExtensionCollection>(); assemblyInfo = new AssemblyInformation(); AppDomain.CurrentDomain.AssemblyResolve += emdll.ResolveAssembly; SiteExtensions.DLLAppDomain.AssemblyResolve += emdll.ResolveAssembly; DatabaseExtensions.DLLAppDomain.AssemblyResolve += emdll.ResolveAssembly; // Handle unhandled exceptions DispatcherUnhandledException += App_DispatcherUnhandledException; AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; // Initialize Collections mangaArchiveCacheCollection = new ObservableCollection<MangaArchiveCacheObject>(); // Create a File System Watcher for Manga Objects mangaObjectArchiveWatcher = new FileSystemWatcher(MANGA_ARCHIVE_DIRECTORY, MANGA_ARCHIVE_FILTER); mangaObjectArchiveWatcher.EnableRaisingEvents = false; // Create a File System Watcher for Manga Chapter Objects chapterObjectArchiveWatcher = new FileSystemWatcher(CHAPTER_ARCHIVE_DIRECTORY, CHAPTER_ARCHIVE_FILTER); chapterObjectArchiveWatcher.IncludeSubdirectories = true; chapterObjectArchiveWatcher.EnableRaisingEvents = false; // Create IO class objects fileStorage = new Core.IO.Storage.Manager.BaseInterfaceClasses.FileStorage(); zipStorage = new Core.IO.Storage.Manager.BaseInterfaceClasses.ZipStorage(); downloadManager = new IO.Network.DownloadManager(); Startup += App_Startup; InitializeComponent(); }
public PrintFilteredStudentsCommand(string input, string[] data, Tester judge, StudentsRepository repository, DownloadManager downloadManager, IOManager inputOutputManager) : base(input, data, judge, repository, downloadManager, inputOutputManager) { }
public DownloadManagerEvent(DownloadManager downloadManager, Download download) { this.download = download; this.downloadManager = downloadManager; }