public Task <IEnumerable <Package> > Install(CanonicalName canonicalName, bool?autoUpgrade = null, bool?force = null, bool?download = null, bool?pretend = null, CanonicalName replacingPackage = null) { if (!canonicalName.IsCanonical) { return(InvalidCanonicalNameResult <IEnumerable <Package> >(canonicalName)); } var completedThisPackage = false; CurrentTask.Events += new PackageInstallProgress((name, progress, overallProgress) => { if (overallProgress == 100) { completedThisPackage = true; } }); GetTelemetry(); // ensure this value is cached before the install. return((Remote.InstallPackage(canonicalName, autoUpgrade, force, download, pretend, replacingPackage) as Task <PackageManagerResponseImpl>).Continue(response => { if (response.PotentialUpgrades != null) { throw new PackageHasPotentialUpgradesException(response.UpgradablePackage, response.PotentialUpgrades); } return response.Packages; })); }
public void InstalledPackage(CanonicalName canonicalName) { _packages.Value.Add(Package.GetPackage(canonicalName)); Package.GetPackage(canonicalName).IsInstalled = true; Task.Factory.StartNew(() => { if (PackageManager.Instance.Telemetry) { // ping the coapp server to tell it that a package installed try { Logger.Message("Pinging `http://coapp.org/telemetry/?anonid={0}&pkg={1}` ".format(PackageManager.Instance.AnonymousId, canonicalName)); var req = HttpWebRequest.Create("http://coapp.org/telemetry/?anonid={0}&pkg={1}".format(PackageManager.Instance.AnonymousId, canonicalName)); req.BetterGetResponse().Close(); } catch { // who cares... } } }, TaskCreationOptions.AttachedToParent); try { Event <PackageInstalled> .Raise(canonicalName); } catch (Exception e) { Logger.Error("CRITICAL: PackageInstalled event delegate thru an exception of type '{0}' -- {1}".format(e.GetType(), e.StackTrace)); } }
/// <summary>For template/generic definitions: MyType%1</summary> public void SetParameterCounts(int templateParameterCount, int genericParameterCount) { var count = templateParameterCount + genericParameterCount; NativeName.SetTemplateParameterCount(count); CanonicalName.SetTemplateParameterCount(count); }
private Task <TReturnType> InvalidCanonicalNameResult <TReturnType>(CanonicalName canonicalName) { var failedResult = new TaskCompletionSource <TReturnType>(); failedResult.SetException(new InvalidCanonicalNameException(canonicalName)); return(failedResult.Task); }
internal int WhoWins(CanonicalName negative, CanonicalName positive) { if (positive == negative) { return(0); } foreach (var p in Priorities) { int pos = 0; int neg = 0; foreach (var key in GetCanonicalNames(p).Where(each => this[p, each, null].IsTrue())) { pos = Math.Max(positive.MatchQuality(key), pos); neg = Math.Max(negative.MatchQuality(key), neg); } if (pos == neg) { continue; } return(pos - neg); } // didn't find a rule that can distinguish. // if the packages differ by version only, use that to decide if (positive.DiffersOnlyByVersion(negative)) { return(((long)(ulong)positive.Version - (long)(ulong)negative.Version) > 0 ? 1 : -1); } // nothing to decide with! return(0); }
public PackageReference(CanonicalName canonicalName, string packageDirectory, IEnumerable<LibraryReference> libraries, DeveloperLibraryType type) { CanonicalName = canonicalName; PackageDirectory = packageDirectory; Libraries = libraries; Type = type; }
/// <summary>For template/generic references: MyType;Str</summary> public void AddTemplateArgument(string?name) { if (!String.IsNullOrEmpty(name)) { NativeName.AddTemplateArgument(name); CanonicalName.AddTemplateArgument(name); } }
internal static FourPartVersion GetCurrentPackageVersion(CanonicalName canonicalName) { var activePkg = PackageManagerImpl.Instance.InstalledPackages.Where(each => canonicalName.DiffersOnlyByVersion(each.CanonicalName)) .OrderBy(each => each, new Toolkit.Extensions.Comparer <Package>((packageA, packageB) => GeneralPackageSettings.Instance.WhoWins(packageA, packageB))) .FirstOrDefault(); return(activePkg == null ? 0 : activePkg.Version); }
public void UnableToDownloadPackage(CanonicalName packageCanonicalName) { try { Event <UnableToDownloadPackage> .Raise(packageCanonicalName); } catch (Exception e) { Logger.Error("CRITICAL: UnableToDownloadPackage event delegate thru an exception of type '{0}' -- {1}".format(e.GetType(), e.StackTrace)); } }
public Task RemovePackage(CanonicalName canonicalName, bool forceRemoval) { if (!canonicalName.IsCanonical) { return(InvalidCanonicalNameResult <IEnumerable <Package> >(canonicalName)); } return(Remote.RemovePackage(canonicalName, forceRemoval)); }
public override int GetHashCode() { unchecked { var hashCode = (CanonicalName != null ? CanonicalName.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (TargetId != null ? TargetId.GetHashCode() : 0); return(hashCode); } }
public void RemovingPackageProgress(CanonicalName canonicalName, int percentComplete) { try { Event <PackageRemoveProgress> .Raise(canonicalName, percentComplete); } catch (Exception e) { Logger.Error("CRITICAL: PackageRemoveProgress event delegate thru an exception of type '{0}' -- {1}".format(e.GetType(), e.StackTrace)); } }
public void GeneralPackageSetting(int priority, CanonicalName canonicalName, string key, string value) { _gpi.Value.Add(new GeneralPackageInformation() { Priority = priority, CanonicalName = canonicalName, Key = key, Value = value }); }
public override T ReadJson(JsonReader reader, Type objectType, T existingValue, bool hasExistingValue, JsonSerializer serializer) { var value = reader.Value as string; if (string.IsNullOrWhiteSpace(value)) { return(null); } return(CanonicalName.FromValue <T>(value)); }
internal static Package GetPackage(CanonicalName canonicalName) { if (!canonicalName.IsCanonical) { throw new CoAppException("GetPackage requries that CanonicalName must not be a partial name."); } lock (Packages) { return(Packages.GetOrAdd(canonicalName, () => new Package(canonicalName))); } }
public void RemovedPackage(CanonicalName canonicalName) { _packages.Value.Add(Package.GetPackage(canonicalName)); Package.GetPackage(canonicalName).IsInstalled = false; try { Event <PackageRemoved> .Raise(canonicalName); } catch (Exception e) { Logger.Error("CRITICAL: PackageRemoved event delegate thru an exception of type '{0}' -- {1}".format(e.GetType(), e.StackTrace)); } }
public static Package GetPackage(CanonicalName canonicalName) { lock (AllPackages) { if (null != canonicalName && canonicalName.IsCanonical) { return(AllPackages.GetOrAdd(canonicalName, () => new Package { CanonicalName = canonicalName })); } return(null); } }
public bool Equals(Element element) { if (element == null) { return(false); } if (element == this) { return(true); } return(CanonicalName.Equals(element.CanonicalName)); }
internal string GetValue(CanonicalName canonicalName, string key) { string result = null; foreach (var p in Priorities) { int lastMatch = 0; foreach (var name in GetCanonicalNameStrings(p).Where(name => GetKeys(p, name).ContainsIgnoreCase(key))) { var m = canonicalName.MatchQuality(name); if (m > lastMatch) { result = this[p, canonicalName, key]; lastMatch = m; } } } return result; }
internal string this[int priority, CanonicalName canonicalName, string key] { get { var retval = string.IsNullOrEmpty(key) ? PackageManagerSettings.PerPackageSettings[priority.ToString()][canonicalName].StringValue : PackageManagerSettings.PerPackageSettings[priority.ToString()][canonicalName, key].StringValue; return string.IsNullOrEmpty(retval) ? null : retval; } set { if (string.IsNullOrEmpty(key)) { PackageManagerSettings.PerPackageSettings[priority.ToString()][canonicalName].StringValue = value.IsTrue() ? value : null; } else { PackageManagerSettings.PerPackageSettings[priority.ToString()][canonicalName, key].StringValue = string.IsNullOrEmpty(value) ? null : value; } } }
/// <summary> /// Gets a specific <see cref="RecordSet"/> identified by a <paramref name="recordSetName"/>. /// </summary> /// <exception cref="RecordSetNotFoundException"></exception> public static async Task <RecordSet> GetRecordSetAsync(this IElementEndpoint <Zone> endpoint, CanonicalName recordSetName, CancellationToken cancellationToken = default) { var zone = await endpoint.ReadAsync(cancellationToken); var recordSet = zone.RecordSets.FirstOrDefault(rrs => rrs.Name.Equals(recordSetName)); if (recordSet == null) { throw new RecordSetNotFoundException(recordSetName); } return(recordSet); }
/// <summary> /// Removes redundent leading namespaces (regarding the kind of /// reference being wrapped) from the canonical name. /// </summary> /// <returns>The friendly shortened name</returns> protected override string Shorten() { if (CanonicalName.StartsWith("refs/heads/", StringComparison.Ordinal)) { return(CanonicalName.Substring("refs/heads/".Length)); } if (CanonicalName.StartsWith("refs/remotes/", StringComparison.Ordinal)) { return(CanonicalName.Substring("refs/remotes/".Length)); } throw new ArgumentException( string.Format(CultureInfo.InvariantCulture, "'{0}' does not look like a valid branch name.", CanonicalName)); }
/// <summary> /// Removes redundent leading namespaces (regarding the kind of /// reference being wrapped) from the canonical name. /// </summary> /// <returns>The friendly shortened name</returns> protected override string Shorten() { if (CanonicalName.LooksLikeLocalBranch()) { return(CanonicalName.Substring(Reference.LocalBranchPrefix.Length)); } if (CanonicalName.LooksLikeRemoteTrackingBranch()) { return(CanonicalName.Substring(Reference.RemoteTrackingBranchPrefix.Length)); } throw new ArgumentException( string.Format(CultureInfo.InvariantCulture, "'{0}' does not look like a valid branch name.", CanonicalName)); }
public bool GetObjectNeedsUpate(StatusCustomizationHazardousCondition checkUpdateFrom) { if (!Code.Equals(checkUpdateFrom.Code)) { return(true); } if (!CanonicalName.Equals(checkUpdateFrom.CanonicalName)) { return(true); } if (!DisplayName.Equals(checkUpdateFrom.DisplayName)) { return(true); } return(false); }
internal string this[int priority, CanonicalName canonicalName, string key] { get { var retval = string.IsNullOrEmpty(key) ? PackageManagerSettings.PerPackageSettings[priority.ToString()][canonicalName].StringValue : PackageManagerSettings.PerPackageSettings[priority.ToString()][canonicalName, key].StringValue; return(string.IsNullOrEmpty(retval) ? null : retval); } set { if (string.IsNullOrEmpty(key)) { PackageManagerSettings.PerPackageSettings[priority.ToString()][canonicalName].StringValue = value.IsTrue() ? value : null; } else { PackageManagerSettings.PerPackageSettings[priority.ToString()][canonicalName, key].StringValue = string.IsNullOrEmpty(value) ? null : value; } } }
public Task <Package> GetPackageDetails(CanonicalName canonicalName, bool forceRefresh = false) { return(Package.GetPackage(canonicalName).AsResultTask()); /* * if (!canonicalName.IsCanonical) { * return InvalidCanonicalNameResult<Package>(canonicalName); * } * * return GetPackage(canonicalName, forceRefresh).Continue(pkg => { * if (forceRefresh || pkg.IsPackageDetailsStale) { * Remote.GetPackageDetails(canonicalName).Wait(); * } * return pkg; * }); * */ }
internal string GetValue(CanonicalName canonicalName, string key) { string result = null; foreach (var p in Priorities) { int lastMatch = 0; foreach (var name in GetCanonicalNameStrings(p).Where(name => GetKeys(p, name).ContainsIgnoreCase(key))) { var m = canonicalName.MatchQuality(name); if (m > lastMatch) { result = this[p, canonicalName, key]; lastMatch = m; } } } return(result); }
public override int GetHashCode() { int hash = 1; if (ResourceName.Length != 0) { hash ^= ResourceName.GetHashCode(); } if (HasId) { hash ^= Id.GetHashCode(); } if (HasName) { hash ^= Name.GetHashCode(); } if (HasCountryCode) { hash ^= CountryCode.GetHashCode(); } if (HasTargetType) { hash ^= TargetType.GetHashCode(); } if (Status != global::Google.Ads.GoogleAds.V5.Enums.GeoTargetConstantStatusEnum.Types.GeoTargetConstantStatus.Unspecified) { hash ^= Status.GetHashCode(); } if (HasCanonicalName) { hash ^= CanonicalName.GetHashCode(); } if (HasParentGeoTarget) { hash ^= ParentGeoTarget.GetHashCode(); } if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return(hash); }
public Task <Package> GetPackage(CanonicalName canonicalName, bool forceRefresh = false) { if (null == canonicalName) { return(CoTask.AsResultTask <Package>(null)); } if (!canonicalName.IsCanonical) { return(InvalidCanonicalNameResult <Package>(canonicalName)); } var pkg = Package.GetPackage(canonicalName); if (forceRefresh || pkg.IsPackageInfoStale) { return((Remote.FindPackages(canonicalName, null, null, null) as Task <PackageManagerResponseImpl>).Continue(response => pkg)); } return(pkg.AsResultTask()); }
internal BaseService(IServiceFactory factory, JsonDictionary discoveryDoc, FactoryParameters param) : this(factory) { discoveryDoc.ThrowIfNull("discoveryDoc"); this.discoveryDoc = discoveryDoc; // Set required properties Version = discoveryDoc.GetMandatoryValue <string>("version"); Name = discoveryDoc.GetMandatoryValue <string>("name").Replace(" ", ""); CanonicalName = discoveryDoc.GetValueAsNull("canonicalName") as string; if (!string.IsNullOrEmpty(CanonicalName)) { CanonicalName = CanonicalName.Replace(" ", ""); } // Set optional properties Id = discoveryDoc.GetValueAsNull("id") as string; Labels = discoveryDoc.GetValueAsStringListOrEmpty("labels").ToList().AsReadOnly(); Features = discoveryDoc.GetValueAsStringListOrEmpty("features").ToList().AsReadOnly(); DocumentationLink = discoveryDoc.GetValueAsNull("documentationLink") as string; Protocol = discoveryDoc.GetValueAsNull("protocol") as string; Description = discoveryDoc.GetValueAsNull("description") as string; Title = discoveryDoc.GetValueAsNull("title") as string; Scopes = LoadScopes(); Parameters = LoadParameters(); // Load resources rootResource = CreateResource(new KeyValuePair <string, object>("", discoveryDoc)); // Sets the Server URL (Base Path will be set on the concete class) if (param != null && param.ServerUrl != null) { ServerUrl = param.ServerUrl; } else { ServerUrl = discoveryDoc.GetMandatoryValue("rootUrl") as string; } }
/// <summary> /// Determines if the name contains the given fragment /// </summary> /// <param name="Name"></param> /// <returns></returns> public bool ContainsName(FileSystemName Name) { int StartIdx = 0; for (;;) { int Idx = CanonicalName.IndexOf(Name.CanonicalName, StartIdx); if (Idx == -1) { return(false); } if (Idx == 0 || CanonicalName[Idx - 1] == '/') { int EndIdx = Idx + Name.CanonicalName.Length; if (EndIdx < CanonicalName.Length && CanonicalName[EndIdx] == '/') { return(true); } } StartIdx = Idx + 1; } }
public Entry(Area area, Entry parent, string cname, string fullname, string localName, long time, long size, bool ignored, FileAttributes attribs) { Area = area; Parent = parent; FullName = fullname; LocalName = localName; CanonicalName = localName == ".vrmeta" ? localName : cname; ModificationTime = DateTime.FromFileTimeUtc(time); Ignored = ignored; Length = size; if (IsDirectory) { m_Hash = string.Empty; if ((attribs & FileAttributes.ReparsePoint) != 0) { Attributes = Attributes | Objects.Attributes.Symlink; CanonicalName = CanonicalName.Substring(0, CanonicalName.Length - 1); } if (localName == ".versionr/" && parent != null) { parent.IsVersionrRoot = true; } } else if (Utilities.Symlink.ExistsForFile(FullName, CanonicalName)) { Attributes = Attributes | Objects.Attributes.Symlink; Length = 0; } if ((attribs & FileAttributes.Hidden) != 0) { Attributes = Attributes | Objects.Attributes.Hidden; } if ((attribs & FileAttributes.ReadOnly) != 0) { Attributes = Attributes | Objects.Attributes.ReadOnly; } }
public string GenerateUpdateJsonFromObject(StatusCustomizationHazardousCondition updateFrom) { // form the json (determine the fields that need to be updated) var sb = new StringBuilder(); var sw = new StringWriter(sb); var writer = new JsonTextWriter(sw) { Formatting = Formatting.None }; writer.WriteStartObject(); writer.WritePropertyName(@"income_source"); writer.WriteStartObject(); if (!Code.Equals(updateFrom.Code)) { writer.WritePropertyName("code"); writer.WriteValue(updateFrom.Code); } if (!CanonicalName.Equals(updateFrom.CanonicalName)) { writer.WritePropertyName("canonical_name"); writer.WriteValue(updateFrom.CanonicalName); } if (!DisplayName.Equals(updateFrom.DisplayName)) { writer.WritePropertyName("display_name"); writer.WriteValue(updateFrom.DisplayName); } writer.WriteEndObject(); writer.WriteEndObject(); return(sw.ToString()); }
public Task RemovePackage(CanonicalName canonicalName, bool? force) { var response = Event<GetResponseInterface>.RaiseFirst(); if (CancellationRequested) { response.OperationCanceled("remove-package"); return FinishedSynchronously; } if (Event<CheckForPermission>.RaiseFirst(PermissionPolicy.RemovePackage)) { if (canonicalName.IsPartial) { response.Error("Invalid Canonical Name", "InstallPackage", "Canonical name '{0}' is not a complete canonical name".format(canonicalName)); } var package = SearchForPackages(canonicalName).FirstOrDefault(); if (package == null) { response.UnknownPackage(canonicalName); return FinishedSynchronously; } if (package.CanonicalName.Matches(CanonicalName.CoAppItself) && package.IsActive) { response.Error("remove-package", "canonical-name", "Active CoApp Engine may not be removed"); return FinishedSynchronously; } if (!package.IsInstalled) { response.Error("remove-package", "canonical-name", "package '{0}' is not installed.".format(canonicalName)); return FinishedSynchronously; } if (package.IsBlocked) { response.PackageBlocked(canonicalName); return FinishedSynchronously; } if (true != force) { UpdateDependencyFlags(); if (package.PackageSessionData.IsDependency) { response.FailedPackageRemoval(canonicalName, "Package '{0}' is a required dependency of another package.".format(canonicalName)); return FinishedSynchronously; } } // seems like a good time to check if we're supposed to bail... if (CancellationRequested) { response.OperationCanceled("remove-package"); return FinishedSynchronously; } try { // send back the progress to the client. CurrentTask.Events += new IndividualProgress(percentage => response.RemovingPackageProgress(package.CanonicalName, percentage)); package.Remove(); response.RemovingPackageProgress(canonicalName, 100); response.RemovedPackage(canonicalName); Signals.RemovedPackage(canonicalName); } catch (OperationCompletedBeforeResultException e) { response.FailedPackageRemoval(canonicalName, e.Message); return FinishedSynchronously; } } return FinishedSynchronously; }
private void RemovePackage(CanonicalName canonicalVersion) { RemovePackages(new[] {canonicalVersion}); }
public Task InstallPackage(CanonicalName canonicalName, Action<string, int, int> installProgress, Action<string> packageInstalled) { return Task.Factory.StartNew(() => { CurrentTask.Events += new PackageInstallProgress( (name, progress, overallProgress) => installProgress(name, progress, overallProgress)); CurrentTask.Events += new PackageInstalled(name => packageInstalled(name)); return EPM.Install(canonicalName); }); }
internal override IEnumerable<Package> FindPackages(CanonicalName canonicalName) { Scan(); return _packageList.Where(each => each.CanonicalName.Matches(canonicalName)); }
public Task BlockPackage(CanonicalName packageName) { return EPM.SetGeneralPackageInformation(50, packageName, "state", PackageState.Blocked.ToString()); }
public bool IsInstalled(CanonicalName packageCanonicalName) { return base.IsInstalled(packageCanonicalName); }
internal static Package GetPackage(CanonicalName canonicalName) { if (!canonicalName.IsCanonical) { throw new CoAppException("GetPackage requries that CanonicalName must not be a partial name."); } lock (Packages) { return Packages.GetOrAdd(canonicalName, () => new Package(canonicalName)); } }
public Task SetGeneralPackageInformation(int priority, CanonicalName canonicalName, string key, string value) { GeneralPackageSettings.Instance[priority, canonicalName, key] = value; return FinishedSynchronously; }
public Task UpgradeExistingPackage(CanonicalName canonicalName, bool? autoUpgrade, Action<string, int, int> installProgress, Action<string> packageInstalled, CanonicalName packageToUpgradeFrom) { return Task.Factory.StartNew(() => { CurrentTask.Events += new PackageInstallProgress( (name, progress, overallProgress) => installProgress(name, progress, overallProgress)); if (packageInstalled != null) { CurrentTask.Events += new PackageInstalled(name => packageInstalled(name)); } return EPM.Install(canonicalName, autoUpgrade, replacingPackage: packageToUpgradeFrom). ContinueWith( t => LastTimeInstalled = DateTime.Now); }); }
public RemoveEvent(CanonicalName canonicalName, int progress) { CanonicalName = canonicalName; Progress = progress; }
public DownloadEvent(CanonicalName canonicalName, int progress) { CanonicalName = canonicalName; Progress = progress; }
private void InsertIntoFeed(CanonicalName pkgCanonicalName, FourPartVersion pkgVersion, Uri location, AtomItem item = null) { FeedBlob.Lock(blob => { // update the feed var feed = new AtomFeed(); //load the feed from the _canonicalFeedUrl if we can try { var originalFeed = LoadFeed(blob); foreach (AtomItem i in originalFeed.Items.Where(each => each is AtomItem)) { if (_feedName == "current") { // if an older version of this package is in the current feed, if (i.Model.CanonicalName.DiffersOnlyByVersion(pkgCanonicalName) && i.Model.CanonicalName.Version < pkgVersion) { // push it to the archive feed. try { if (FeedHandlers["archive"] != null) { FeedHandlers["archive"].InsertIntoFeed(i.Model.CanonicalName, i.Model.Version, i.Model.Locations[0]); // and skip it continue; } } catch { } } } feed.Add(i); } } catch { } item = item ?? _packageManager.GetAtomItem(pkgCanonicalName).Result; if (item != null) { // first, make sure that the feeds contains the intended feed location. item.Model.Feeds = item.Model.Feeds ?? new XList<Uri>(); if (!item.Model.Feeds.Contains(_canonicalFeedUrl)) { item.Model.Feeds.Insert(0, _canonicalFeedUrl); } item.Model.Locations = item.Model.Locations ?? new XList<Uri>(); if (!item.Model.Locations.Contains(location)) { item.Model.Locations.Insert(0, location); } // drop dead urls item.Model.Feeds = item.Model.Feeds.Distinct().Where(Peek).ToXList(); item.Model.Locations = item.Model.Locations.Distinct().Where(Peek).ToXList(); foreach (var l in item.Links.ToArray().Where(each => !Peek(each.Uri))) { item.Links.Remove(l); } if (item.Model.Locations.Any()) { // if we've got at least one valid location, add the item to the feed. feed.Add(item); } } SaveFeed(blob, feed); // regenerate the webpi feed based on the items in this feed SaveWebPiFeed(feed); }); }
private void RemovePackages(CanonicalName[] canonicalVersions) { if (!IsWorking) { IsWorking = true; Task.Factory.StartNew(() => { var taskCount = canonicalVersions.Length; if (canonicalVersions.Length > 0) { for (var index = 0; index < taskCount; index++) { var taskNumber = index; var v = canonicalVersions[index]; /* Session.RemoteService.RemovePackage( v, messages: new PackageManagerMessages { RemovingPackageProgress = (canonicalName, progress) => { Progress = (progress / taskCount) + taskNumber * 100 / taskCount; }, RemovedPackage = (canonicalName) => { Package.GetPackage(canonicalName).IsInstalled = false; }, OperationCanceled = CancellationRequestedDuringRemove, }).Wait(); * */ } } }).ContinueWith(antecedent => OnFinished(), TaskContinuationOptions.AttachedToParent); } }
private void RemovePackages(CanonicalName[] canonicalVersions) { if (!IsWorking) { IsWorking = true; Task.Factory.StartNew(() => { var taskCount = canonicalVersions.Length; if (canonicalVersions.Length > 0) { int taskNumber = 0; CurrentTask.Events += new PackageRemoveProgress((name, progress) => Progress = (progress/taskCount) + taskNumber*100/taskCount); for (var index = 0; index < taskCount; index++) { taskNumber = index; _packageManager.RemovePackage(canonicalVersions[index], false).Wait(); } } }).ContinueWith(antecedent => { _finalText = "Packages have been removed.".format(SelectedPackage.Version); OnFinished(); }, TaskContinuationOptions.AttachedToParent); } }
public Task SetPackageWanted(CanonicalName canonicalName, bool wanted) { Package.GetPackage(canonicalName).IsWanted = wanted; return FinishedSynchronously; }
private Package(CanonicalName canonicalName) { CanonicalName = canonicalName; Packages.Changed += x => Changed(); PackageDependencies.CollectionChanged += (x, y) => Changed(); }
/// <summary> /// Gets packages from all visible feeds based on criteria /// </summary> /// <param name="canonicalName"> </param> /// <param name="location"> </param> /// <returns> </returns> internal IEnumerable<Package> SearchForPackages(CanonicalName canonicalName, string location = null, bool lookDeep = false) { try { lock (this) { if (!string.IsNullOrEmpty(location) ) { // asking a specific feed. just use that one. var feed = Feeds.FirstOrDefault(each => each.IsLocationMatch(location)); if( feed == null ) { return Enumerable.Empty<Package>(); } return feed.FindPackages(canonicalName).Distinct().ToArray(); } var feeds = Feeds.Where(each => (lookDeep & each.FeedState == FeedState.Passive) || each.FeedState == FeedState.Active).ToArray(); if( canonicalName.IsCanonical || lookDeep == false) { // they are not asking for more than one version of a given package. // or we're just not interested in going deep. var result = feeds.SelectMany(each => each.FindPackages(canonicalName)).Distinct().ToArray(); if (result.Length != 0 || lookDeep == false) { return result; } } // we're either searching for more than a single package, or we didn't find what we were looking for, var feedLocations = feeds.Select(each => each.Location).ToArray(); var packages = feeds.SelectMany(each => each.FindPackages(canonicalName)).Distinct().ToArray(); var otherFeeds = packages.SelectMany(each => each.FeedLocations).Distinct().Where(each => !feedLocations.Contains(each.AbsoluteUri)); // given a list of other feeds that we're not using, we can search each of those feeds for newer versions of the packages that we already have. var tf = TransientFeeds(otherFeeds, lookDeep); return packages.Union(packages.SelectMany(p => tf.SelectMany(each => each.FindPackages(p.CanonicalName.OtherVersionFilter)))).Distinct().ToArray(); } } catch (InvalidOperationException) { // this can happen if the collection changes during the operation (and can actually happen in the middle of .ToArray() // since, locking the hell out of the collections isn't worth the effort, we'll just try again on this type of exception // and pray the collection won't keep changing :) Logger.Message("PERF HIT [REPORT THIS IF THIS IS CONSISTENT!]: Rerunning SearchForPackages!"); return SearchForPackages(canonicalName, location, lookDeep); } }
internal static FourPartVersion GetCurrentPackageVersion(CanonicalName canonicalName) { var activePkg = PackageManagerImpl.Instance.InstalledPackages.Where(each => canonicalName.DiffersOnlyByVersion(each.CanonicalName)) .OrderBy(each => each, new Toolkit.Extensions.Comparer<Package>((packageA, packageB) => GeneralPackageSettings.Instance.WhoWins(packageA, packageB))) .FirstOrDefault(); return activePkg == null ? 0 : activePkg.Version; }
public Task DownloadProgress(string requestReference, int? downloadProgress) { try { var cn = new CanonicalName(requestReference); if (null != cn && cn.IsCanonical) { var package = SearchForPackages(cn).FirstOrDefault(); if (package != null) { package.PackageSessionData.DownloadProgress = Math.Max(package.PackageSessionData.DownloadProgress, downloadProgress.GetValueOrDefault()); } } } catch { // suppress any exceptions... we just don't care! } return FinishedSynchronously; }
public Task UnblockPackage(CanonicalName packageName) { return EPM.SetGeneralPackageInformation(50, packageName, "state", null); }
public Task FindPackages(CanonicalName canonicalName, Expression<Func<IPackage, bool>> filter, Expression<Func<IEnumerable<IPackage>, IEnumerable<IPackage>>> collectionFilter, string location) { var response = Event<GetResponseInterface>.RaiseFirst(); if (CancellationRequested) { response.OperationCanceled("find-package"); return FinishedSynchronously; } canonicalName = canonicalName ?? CanonicalName.CoAppPackages; if (Event<CheckForPermission>.RaiseFirst(PermissionPolicy.EnumeratePackages)) { UpdateDependencyFlags(); IEnumerable<IPackage> query = filter == null ? SearchForPackages(canonicalName, location) : SearchForPackages(canonicalName, location).Where(each => filter.Compile()(each)); if( collectionFilter != null ) { query = collectionFilter.Compile()(query); } var results = (Package[]) query.ToArrayOfType(typeof(Package)); if (results.Length > 0 ) { foreach (var pkg in results) { if (CancellationRequested) { response.OperationCanceled("find-packages"); return FinishedSynchronously; } response.PackageInformation(pkg); } } else { response.NoPackagesFound(); } } return FinishedSynchronously; }
public Task SetState(CanonicalName packageName, PackageState state) { return EPM.SetGeneralPackageInformation(50, packageName, "state", state.ToString()); }
public Task GetPackageDetails(CanonicalName canonicalName) { var response = Event<GetResponseInterface>.RaiseFirst(); if (CancellationRequested) { response.OperationCanceled("get-package-details"); return FinishedSynchronously; } if (canonicalName.IsPartial) { response.Error("Invalid Canonical Name", "GetPackageDetails", "Canonical name '{0}' is not a complete canonical name".format(canonicalName)); } var package = SearchForPackages(canonicalName).FirstOrDefault(); if (package == null) { return FinishedSynchronously; } response.PackageDetails(package.CanonicalName, package.PackageDetails); return FinishedSynchronously; }
public Task RemovePackage(CanonicalName canonicalName, Action<string, int> removeProgress, Action<string> packageRemoved) { return Task.Factory.StartNew(() => { CurrentTask.Events += new PackageRemoveProgress( (name, progress) => removeProgress(name, progress)); CurrentTask.Events += new PackageRemoved(name => packageRemoved(name)); return EPM.RemovePackage(canonicalName, false); }); }
public Task InstallPackage(CanonicalName canonicalName, bool? autoUpgrade, bool? force, bool? download, bool? pretend, CanonicalName replacingPackage) { var response = Event<GetResponseInterface>.RaiseFirst(); if (CancellationRequested) { response.OperationCanceled("install-package"); return FinishedSynchronously; } double[] overallProgress = {0.0}; double[] eachTaskIsWorth = {0.0}; int[] lastProgress = {0}; Package currentPackageInstalling = null; var numberOfPackagesToInstall = 0; var numberOfPackagesToDownload = 0; CurrentTask.Events += new IndividualProgress(percentage => { overallProgress[0] += ((percentage - lastProgress[0])*eachTaskIsWorth[0])/100; lastProgress[0] = percentage; // ReSharper disable PossibleNullReferenceException ... this is what I really want. :[ // ReSharper disable AccessToModifiedClosure response.InstallingPackageProgress(currentPackageInstalling.CanonicalName, percentage, (int)(overallProgress[0]*100)); // ReSharper restore AccessToModifiedClosure // ReSharper restore PossibleNullReferenceException }); var unwantedPackages = new List<Package>(); if( null != replacingPackage ) { if( replacingPackage.DiffersOnlyByVersion(canonicalName)) { unwantedPackages.AddRange(SearchForPackages(replacingPackage)); } } using (var manualResetEvent = new ManualResetEvent(true)) { try { lock (_manualResetEvents) { _manualResetEvents.Add(manualResetEvent); } var packagesTriedToDownloadThisTask = new List<Package>(); if (canonicalName.IsPartial) { response.Error("Invalid Canonical Name", "InstallPackage", "Canonical name '{0}' is not a complete canonical name".format(canonicalName)); } var package = SearchForPackages(canonicalName).FirstOrDefault(); if (package == null) { response.UnknownPackage(canonicalName); return FinishedSynchronously; } if (package.IsBlocked) { response.PackageBlocked(canonicalName); return FinishedSynchronously; } var installedPackages = package.InstalledPackages.ToArray(); // is the user authorized to install this? if (null != replacingPackage) { if (replacingPackage.DiffersOnlyByVersion(canonicalName)) { if (!Event<CheckForPermission>.RaiseFirst(PermissionPolicy.UpdatePackage)) { return FinishedSynchronously; } } } else { if( package.LatestInstalledThatUpdatesToThis != null ) { if (!Event<CheckForPermission>.RaiseFirst(PermissionPolicy.UpdatePackage)) { return FinishedSynchronously; } } else { if (!Event<CheckForPermission>.RaiseFirst(PermissionPolicy.InstallPackage)) { return FinishedSynchronously; } } } // if this is an explicit update or upgrade, // - check to see if there is a compatible package already installed that is marked do-not-update // fail if so. if (null != replacingPackage && unwantedPackages.Any( each => each.IsBlocked )) { response.PackageBlocked(canonicalName); return FinishedSynchronously; } // mark the package as the client requested. package.PackageSessionData.DoNotSupercede = (false == autoUpgrade); package.PackageSessionData.UpgradeAsNeeded = (true == autoUpgrade); package.PackageSessionData.IsWanted = true; // the resolve-acquire-install-loop do { // if the world changes, this will get set somewhere between here and the // other end of the do-loop. manualResetEvent.Reset(); if (CancellationRequested) { response.OperationCanceled("install-package"); return FinishedSynchronously; } IEnumerable<Package> installGraph; try { UpdateDependencyFlags(); installGraph = GenerateInstallGraph(package).ToArray(); } catch (OperationCompletedBeforeResultException) { // we encountered an unresolvable condition in the install graph. // messages should have already been sent. response.FailedPackageInstall(canonicalName, package.LocalLocations.FirstOrDefault(), "One or more dependencies are unable to be resolved."); return FinishedSynchronously; } // seems like a good time to check if we're supposed to bail... if (CancellationRequested) { response.OperationCanceled("install-package"); return FinishedSynchronously; } if (download == false && pretend == true) { // we can just return a bunch of foundpackage messages, since we're not going to be // actually installing anything, nor trying to download anything. foreach (var p in installGraph) { response.PackageInformation(p); } return FinishedSynchronously; } // we've got an install graph. // let's see if we've got all the files var missingFiles = (from p in installGraph where !p.HasLocalLocation select p).ToArray(); if (download == true) { // we want to try downloading all the files that we're missing, regardless if we've tried before. // unless we've already tried in this task once. foreach (var p in missingFiles.Where(packagesTriedToDownloadThisTask.Contains)) { packagesTriedToDownloadThisTask.Add(p); p.PackageSessionData.CouldNotDownload = false; } } if (numberOfPackagesToInstall != installGraph.Count() || numberOfPackagesToDownload != missingFiles.Count()) { // recalculate the rest of the install progress based on the new install graph. numberOfPackagesToInstall = installGraph.Count(); numberOfPackagesToDownload = missingFiles.Count(); eachTaskIsWorth[0] = (1.0 - overallProgress[0])/(numberOfPackagesToInstall + numberOfPackagesToDownload); } if (missingFiles.Any()) { // we've got some packages to install that don't have files. foreach (var p in missingFiles.Where(p => !p.PackageSessionData.HasRequestedDownload)) { SessionData.Current.RequireRemoteFile(p.CanonicalName, p.RemotePackageLocations, PackageManagerSettings.CoAppPackageCache, false,(rrfState) => { Updated(); //shake loose anything that might be waiting for this. return rrfState.LocalLocation; }); p.PackageSessionData.HasRequestedDownload = true; } } else { // check to see if this package requires trust. bool ok = true; foreach (var pkg in installGraph.Where(pkg => pkg.RequiresTrustedPublisher && !TrustedPublishers.ContainsIgnoreCase(pkg.PublicKeyToken))) { response.FailedPackageInstall(pkg.CanonicalName, pkg.LocalLocations.FirstOrDefault(), "Package requires a trusted publisher key of '{0}'.".format(pkg.PublicKeyToken)); ok = false; } if( ok == false) { return FinishedSynchronously; } if (pretend == true) { // we can just return a bunch of found-package messages, since we're not going to be // actually installing anything, and everything we needed is downloaded. foreach (var p in installGraph) { response.PackageInformation(p); } return FinishedSynchronously; } var failed = false; // no missing files? Check // complete install graph? Check foreach (var p in installGraph) { currentPackageInstalling = p; // seems like a good time to check if we're supposed to bail... if (CancellationRequested) { response.OperationCanceled("install-package"); return FinishedSynchronously; } var validLocation = currentPackageInstalling.PackageSessionData.LocalValidatedLocation; try { if (!currentPackageInstalling.IsInstalled) { if (string.IsNullOrEmpty(validLocation)) { // can't find a valid location response.FailedPackageInstall(currentPackageInstalling.CanonicalName, currentPackageInstalling.LocalLocations.FirstOrDefault(), "Can not find local valid package"); currentPackageInstalling.PackageSessionData.PackageFailedInstall = true; } else { lastProgress[0] = 0; // GS01: We should put a softer lock here to keep the client aware that packages // are being installed on other threads... lock (typeof (MSIBase)) { if (Engine.DoesTheServiceNeedARestart) { // something has changed where we need restart the service before we can continue. // and the one place we don't wanna be when we issue a shutdown in in Install :) ... Engine.RestartService(); response.OperationCanceled("install-package"); return FinishedSynchronously; } // install progress is now handled by the delegate at the beginning of this function. currentPackageInstalling.Install(); } overallProgress[0] += ((100 - lastProgress[0])*eachTaskIsWorth[0])/100; response.InstallingPackageProgress(currentPackageInstalling.CanonicalName, 100, (int)(overallProgress[0]*100)); response.InstalledPackage(currentPackageInstalling.CanonicalName); Signals.InstalledPackage(currentPackageInstalling.CanonicalName); } } } catch (Exception e) /* (PackageInstallFailedException pife) */ { Logger.Error("FAILED INSTALL"); Logger.Error(e); response.FailedPackageInstall(currentPackageInstalling.CanonicalName, validLocation, "Package failed to install."); currentPackageInstalling.PackageSessionData.PackageFailedInstall = true; if (!currentPackageInstalling.PackageSessionData.AllowedToSupercede) { throw new OperationCompletedBeforeResultException(); // user specified packge as critical. } failed = true; break; } } if (!failed) { if( unwantedPackages.Any()) { foreach (Package eachPkg in unwantedPackages) { eachPkg.IsWanted = false; } } else { var olderpkgs = package.InstalledPackages.Where(each => each.IsWanted && package.IsNewerThan(each)).ToArray(); if( olderpkgs.Length > 0 ) { //anthing older? if( olderpkgs.Length > 1) { // hmm. more than one. // is there just a single thing we're updating? olderpkgs = olderpkgs.Where(package.IsAnUpdateFor).ToArray(); } // if we can get down to one, let's unwant that. if (olderpkgs.Length == 1) { ((Package)olderpkgs[0]).IsWanted = false; } } } // W00T ... We did it! // check for restart required... if (Engine.DoesTheServiceNeedARestart) { // something has changed where we need restart the service before we can continue. // and the one place we don't wanna be when we issue a shutdown in in Install :) ... response.Restarting(); Engine.RestartService(); return FinishedSynchronously; } return FinishedSynchronously; } // otherwise, let's run it thru again. maybe it'll come together. } //---------------------------------------------------------------------------- // wait until either the manualResetEvent is set, but check every second or so // to see if the client has cancelled the operation. while (!manualResetEvent.WaitOne(500)) { if (CancellationRequested) { response.OperationCanceled("install-package"); return FinishedSynchronously; } // we can also use this opportunity to update progress on any outstanding download tasks. overallProgress[0] += missingFiles.Sum(missingFile => ((missingFile.PackageSessionData.DownloadProgressDelta*eachTaskIsWorth[0])/100)); } } while (true); } catch (OperationCompletedBeforeResultException) { // can't continue with options given. return FinishedSynchronously; } finally { // remove manualResetEvent from the mre list lock (_manualResetEvents) { _manualResetEvents.Remove(manualResetEvent); } } } }
public InstallEvent(CanonicalName canonicalName, int progress) { CanonicalName = canonicalName; Progress = progress; }
public static Package GetPackage(CanonicalName canonicalName) { lock (AllPackages) { if(null != canonicalName && canonicalName.IsCanonical) { return AllPackages.GetOrAdd(canonicalName, () => new Package { CanonicalName = canonicalName }); } return null; } }