public void InstallProject(DownloadSession parentDownloadSession, string directory, string projectName, string projectVersion, uint?deployMode, string solutionName = null, string solutionVersion = null) { if (String.Equals(projectVersion, Constants.LatestVersionString)) { projectVersion = GetLatestProjectRelease(projectName); } DownloadSession downloadSession = parentDownloadSession != null ? parentDownloadSession : new DownloadSession(String.Format("Installing project {0} (version {1})", projectName, projectVersion)); downloadSession.ResetRegisteredFiles(); ProjectRelease projectRelease = downloadSession.GetProjectRelease(projectName, projectVersion, this.LeagueCDNBaseURL); if (deployMode != null) { projectRelease.EnumerateFiles().ForEach(x => x.DeployMode = (ReleaseManifestFile.DeployMode)deployMode); } using (ProjectReleaseInstallation installation = new ProjectReleaseInstallation(projectRelease, directory, solutionName, solutionVersion)) { foreach (ReleaseManifestFileEntry file in projectRelease.EnumerateFiles()) { RemoteAsset remoteAsset = projectRelease.GetRemoteAsset(file); downloadSession.RegisterFile(remoteAsset, installation.GetFileInstaller(remoteAsset)); } downloadSession.DoWork(); if (parentDownloadSession == null) { downloadSession.Dispose(); } } }
public DownloadSessionStateChangedEventArgs(DownloadSession session, DownloadState oldState, DownloadState newState) { Session = session; OldState = oldState; NewState = newState; }
public void DownloadFiles(string directory, string projectName, string projectVersion, string filter = null, string filesRevision = null, bool saveManifest = false) { if (String.Equals(projectVersion, Constants.LatestVersionString)) { projectVersion = GetLatestProjectRelease(projectName); } using (DownloadSession downloadSession = new DownloadSession(String.Format("Downloading files from project {0} (version {1})", projectName, projectVersion))) { ProjectRelease projectRelease = downloadSession.GetProjectRelease(projectName, projectVersion, this.LeagueCDNBaseURL); if (saveManifest) { string manifestPath = String.Format("{0}/{1}/releases/{2}/releasemanifest", directory, projectName, projectVersion); Directory.CreateDirectory(Path.GetDirectoryName(manifestPath)); projectRelease.ReleaseManifest.Write(manifestPath); } List <ReleaseManifestFileEntry> files = FilterFiles(projectRelease.EnumerateFiles(), filter, filesRevision); ProjectReleaseFileInstaller fileInstaller = new ProjectReleaseSimpleFileInstaller(directory, projectRelease, false); foreach (ReleaseManifestFileEntry file in files) { downloadSession.RegisterFile(projectRelease.GetRemoteAsset(file), fileInstaller); } downloadSession.DoWork(); } }
private static void IsSuccessfulAndFileExists(DownloadSession downloadSession) { Assert.AreEqual(DownloadState.Success, downloadSession.State); Assert.True(File.Exists(downloadSession.TargetFileName)); var fileInfo = new FileInfo(downloadSession.TargetFileName); Assert.AreEqual(downloadSession.TotalBytes, fileInfo.Length); }
public static void Main(string[] args) { using (_downloadSession = new DownloadSession(key, "Spoti")) { #region login login: Console.Write("Username:"******"Password:"******"Login Failed. Try again.."); goto login; } Console.WriteLine("Login Succeeded"); #endregion Console.Write("Track Url:"); var turl = Console.ReadLine(); var link = new Link(turl, _downloadSession); int t = -1; _downloadSession.OnReportProgress += delegate(int i) { if (i != t) { Console.Title = String.Format("{0}% Loaded", i); t = i; } }; var cts = new CancellationTokenSource(); using (var track = new Track(link, _downloadSession)) { link.Dispose(); var task = _downloadSession.TrackToFileAsync(track, "test.wave", cts); Console.WriteLine("Press enter to terminate .. "); Console.Read(); } _downloadSession.LogOut(); Console.Read(); } }
public void RangeDownloadFiles(string directory, string projectName, bool ignoreOlderFiles = false, string filter = null, string startRevision = null, string endRevision = null, bool saveManifest = false) { List <string> releases = GetProjectReleases(projectName); uint startRevisionValue = startRevision == null ? 0 : GetReleaseValue(startRevision); uint endRevisionValue = endRevision == null?GetReleaseValue(releases[0]) : GetReleaseValue(endRevision); // Check if specified releases exist startRevisionValue = Math.Max(startRevisionValue, GetReleaseValue(releases.Last())); endRevisionValue = Math.Min(endRevisionValue, GetReleaseValue(releases[0])); using (DownloadSession downloadSession = new DownloadSession(String.Format("Downloading files from project {0} (revisions {1} to {2})", projectName, GetReleaseString(startRevisionValue), GetReleaseString(endRevisionValue)))) { for (uint r = startRevisionValue; r <= endRevisionValue; r++) { downloadSession.ResetRegisteredFiles(); string releaseString = GetReleaseString(r); ProjectRelease projectRelease; try { projectRelease = downloadSession.GetProjectRelease(projectName, releaseString, this.LeagueCDNBaseURL); } catch (Exception) { continue; } if (saveManifest) { string manifestPath = String.Format("{0}/{1}/releases/{2}/releasemanifest", directory, projectName, releaseString); Directory.CreateDirectory(Path.GetDirectoryName(manifestPath)); projectRelease.ReleaseManifest.Write(manifestPath); } List <ReleaseManifestFileEntry> files = FilterFiles(projectRelease.EnumerateFiles(), filter, (r != startRevisionValue || ignoreOlderFiles) ? releaseString : null); if (files.Count > 0) { ProjectReleaseFileInstaller fileInstaller = new ProjectReleaseSimpleFileInstaller(directory, projectRelease, true); foreach (ReleaseManifestFileEntry file in files) { downloadSession.RegisterFile(projectRelease.GetRemoteAsset(file), fileInstaller); } downloadSession.DoWork(); } } } }
public void Download_ShouldBeFailedAndFileNotExist_WhenGivenBadUrl() { // given new download session with invalid URI var downloadUri = new Uri("https://www.y0u7ub3.c0m/w47ch?v=M29PRpdYbaM"); var targetFileName = randomizer.GetString(8) + ".test"; var downloadSession = new DownloadSession(downloadUri, targetFileName); // when I try to download the file // then it should throw an exception with no parameters... Assert.CatchAsync(async() => { await downloadSession.DownloadAsync(); }); // and it shouldn't throw an exception with throwOnFailure = false... Assert.DoesNotThrowAsync(async() => { await downloadSession.DownloadAsync(false); }); // ... and it should be marked as failed and file should not exists Assert.AreEqual(DownloadState.Failed, downloadSession.State); Assert.AreEqual(0, downloadSession.DownloadedBytes); Assert.IsNotNull(downloadSession.Error); Assert.False(File.Exists(downloadSession.TargetFileName)); }
public static DownloadSession BeginDownload(this PSCmdlet cmdlet, ISearchResult searchResult) { UpdateSession session = new UpdateSession(); UpdateDownloader downloader = session.CreateDownloader(); downloader.Updates = searchResult.Updates; downloader.Priority = DownloadPriority.dpExtraHigh; ProgressAdapter adapter = new ProgressAdapter(cmdlet, downloader); DownloadProgressChangedCallback progressCallback = new DownloadProgressChangedCallback(adapter); DownloadCompletedCallback completedCallback = new DownloadCompletedCallback(downloader); object state = new object(); downloader.BeginDownload(progressCallback, completedCallback, state); return(DownloadSession.From(completedCallback)); }
public void InstallSolution(string directory, string solutionName, string solutionVersion, string localization, uint?deployMode) { if (String.Equals(solutionVersion, Constants.LatestVersionString)) { solutionVersion = GetLatestSolutionRelease(solutionName); } using (DownloadSession downloadSession = new DownloadSession(String.Format("Installing solution {0} (version {1})", solutionName, solutionVersion))) { SolutionRelease solutionRelease = downloadSession.GetSolutionRelease(solutionName, solutionVersion, this.LeagueCDNBaseURL); using (SolutionReleaseInstallation solutionReleaseInstallation = solutionRelease.CreateInstallation(directory, localization)) { foreach (SolutionManifestProjectEntry project in solutionReleaseInstallation.LocalizedEntry.Projects) { InstallProject(downloadSession, directory, project.Name, project.Version, deployMode, solutionName, solutionVersion); } } } }
public DownloadProgressChangedEventArgs(DownloadSession session) { Session = session; }
private static void IsPaused(DownloadSession downloadSession) { Assert.AreEqual(DownloadState.Paused, downloadSession.State); Assert.True(File.Exists(downloadSession.PartFilename)); }
private static void IsCancelled(DownloadSession downloadSession) { Assert.AreEqual(DownloadState.Cancelled, downloadSession.State); Assert.False(File.Exists(downloadSession.PartFilename)); Assert.False(File.Exists(downloadSession.TargetFileName)); }
public Task <bool> UpdateDownloadSession(DownloadSession downloadSession) { return(Task.Run(() => Runtime.Client.AsyncServiceManager.Create(CommerceRuntimeManager.Runtime).UpdateDownloadSessionStatus((DownloadSession)downloadSession))); }
/// <summary> /// This is a demo of using TraceEvent to activate a 'real time' provider that is listening to /// the MyEventSource above. Normally this event source would be in a different process, but /// it also works if this process generate the events and I do that here for simplicity. /// </summary> public static int Run() { // Today you have to be Admin to turn on ETW events (anyone can write ETW events). if (!(TraceEventSession.IsElevated() ?? false)) { Console.WriteLine("To turn on ETW events you need to be Administrator, please run from an Admin process."); Debugger.Break(); return(-1); } // To listen to ETW events you need a session, which allows you to control which events will be produced // Note that it is the session and not the source that buffers events, and by default sessions will buffer // 64MB of events before dropping events. Thus even if you don't immediately connect up the source and // read the events you should not lose them. // // As mentioned below, sessions can outlive the process that created them. Thus you may need a way of // naming the session so that you can 'reconnect' to it from another process. This is what the name // is for. It can be anything, but it should be descriptive and unique. If you expect multiple versions // of your program to run simultaneously, you need to generate unique names (e.g. add a process ID suffix) // however this is dangerous because you can leave data collection on if the program ends unexpectedly. var sessionName = "SimpleMontitorSession"; using (var session = new TraceEventSession(sessionName)) { /* BY DEFAULT ETW SESSIONS SURVIVE THE DEATH OF THE PROESS THAT CREATES THEM! */ // Unlike most other resources on the system, ETW session live beyond the lifetime of the // process that created them. This is very useful in some scenarios, but also creates the // very real possibility of leaving 'orphan' sessions running. // // To help avoid this by default TraceEventSession sets 'StopOnDispose' so that it will stop // the ETW session if the TraceEventSession dies. Thus executions that 'clean up' the TraceEventSession // will clean up the ETW session. This covers many cases (including throwing exceptions) // // However if the process is killed manually (including control C) this cleanup will not happen. // Thus best practices include // // * Add a Control C handler that calls session.Dispose() so it gets cleaned up in this common case // * use the same session name (say your program name) run-to-run so you don't create many orphans. // // By default TraceEventSessions are in 'create' mode where it assumes you want to create a new session. // In this mode if a session already exists, it is stopped and the new one is created. // // Here we install the Control C handler. It is OK if Dispose is called more than once. Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e) { session.Dispose(); }; /*****************************************************************************************************/ // Hook up events. To so this first we need a 'Parser. which knows how to part the events of a particular Event Provider. // In this case we get a DynamicTraceEventSource, which knows how to parse any EventSource provider. This parser // is so common, that TraceEventSource as a shortcut property called 'Dynamic' that fetches this parsers. // For debugging, and demo purposes, hook up a callback for every event that 'Dynamic' knows about (this is not EVERY // event only those know about by RegisteredTraceEventParser). However the 'UnhandledEvents' handler below will catch // the other ones. Dictionary <int, DownloadSession> data = new Dictionary <int, DownloadSession>(); session.Source.Dynamic.All += delegate(TraceEvent e) { // ETW buffers events and only delivers them after buffering up for some amount of time. Thus // there is a small delay of about 2-4 seconds between the timestamp on the event (which is very // accurate), and the time we actually get the event. We measure that delay here. int sizeIndex = e.PayloadIndex("size"); if (sizeIndex >= 0) { try { int pidIndex = e.PayloadIndex("PID"); int pid = (int)e.PayloadValue(pidIndex); int bytes = (int)e.PayloadValue(sizeIndex); lock (data) { if (data.TryGetValue(pid, out DownloadSession info)) { info.AddTotal(bytes); } else { data[pid] = new DownloadSession(pid, (int)e.PayloadValue(sizeIndex)); } } } catch { } } }; bool running = true; Task.Run(async() => { while (running) { try { await Task.Delay(1000); lock (data) { Console.Clear(); Console.SetCursorPosition(0, 0); Console.WriteLine("{0,-6} {1,11} {2,11} {3,-30}", "PID", "Total Bytes", "Bytes/sec", "Name"); foreach (var datum in data.OrderByDescending(x => x.Value.Difference).Take(5)) { Console.WriteLine("{0,-6} {1,11} {2,11} {3,-30}", datum.Value.PID, DownloadSession.FormatBytes(datum.Value.Total), DownloadSession.FormatBytes(datum.Value.Difference, 1, "/s"), datum.Value.ProcessName); datum.Value.Update(); } } } catch { } } }); // At this point we have created a TraceEventSession, hooked it up to a TraceEventSource, and hooked the // TraceEventSource to a TraceEventParser (you can do several of these), and then hooked up callbacks // up to the TraceEventParser (again you can have several). However we have NOT actually told any // provider (EventSources) to actually send any events to our TraceEventSession. // We do that now. // Enable my provider, you can call many of these on the same session to get events from other providers. // Because this EventSource did not define any keywords, I can only turn on all events or none. var restarted = session.EnableProvider("Microsoft-Windows-Kernel-Network"); if (restarted) // Generally you don't bother with this warning, but for the demo we do. { Console.WriteLine("The session {0} was already active, it has been restarted.", sessionName); } Console.Clear(); Console.SetCursorPosition(0, 0); Console.WriteLine("{0,-6} {1,11} {2,11} {3,-30}", "PID", "Total Bytes", "Bytes/sec", "Name"); // go into a loop processing events can calling the callbacks. Because this is live data (not from a file) // processing never completes by itself, but only because someone called 'source.Dispose()'. session.Source.Process(); running = false; Console.WriteLine(); Console.WriteLine("Stopping the collection of events."); Console.ReadLine(); } return(0); }