/// <summary> /// Install all of the packages from the specified packages.config file /// </summary> /// <param name="binariesOnly">Only install binaries (do not modify web.config)</param> public IEnumerable<string> InstallPackages(string sitePhysicalPath, string packagesConfigPath, string source = "", bool binariesOnly = true, Version targetFramework = null) { if (string.IsNullOrEmpty(packagesConfigPath)) { throw new ArgumentNullException("packagesConfig"); } // parse config and get all packages if (!_fileSystem.FileExists(packagesConfigPath)) { throw new FileNotFoundException(string.Format("Packages config was not found at: '{0}'.", packagesConfigPath)); } XmlDocument doc = new XmlDocument(); doc.LoadXml(_fileSystem.FileReadAllText(packagesConfigPath)); List<PackageName> packages = new List<PackageName>(); XmlNodeList xmlPackages = doc.GetElementsByTagName("package"); foreach (XmlNode p in xmlPackages) { PackageName package = new PackageName(p.Attributes["id"].Value, new SemanticVersion(p.Attributes["version"].Value)); packages.Add(package); if (p.Attributes["source"] != null && !string.IsNullOrEmpty(p.Attributes["source"].Value)) { source += (";" + p.Attributes["source"].Value); } } return InstallPackages(sitePhysicalPath, packages, source.Trim(';'), binariesOnly, targetFramework); }
void IVsPackageInstaller.InstallPackage(string source, Project project, string packageId, string version, bool ignoreDependencies) { var package = new PackageName(packageId, new SemanticVersion(version)); Assert.IsNull(source, "Not expecting source, should resolve by itself"); Assert.IsNotNull(project, "Expecting a project"); Assert.IsFalse(ignoreDependencies, "Should be complete install"); Assert.IsTrue(this.ExpectedPackages.Any(x => x.Equals(package)), $"Unexpected package {packageId}"); this.InstallPackageAction?.Invoke(project); if (this.simulateInstallerException) { throw new Exception("Oops"); } IList<PackageName> packages = new List<PackageName>(); if (!this.installedPackages.TryGetValue(project, out packages)) { var packageList = new List<PackageName>(); this.installedPackages[project] = packageList; packages = packageList; } var newEntry = new PackageName(packageId, new SemanticVersion(version)); Assert.IsFalse(packages.Contains(newEntry), "The same package was attempted to be installed twice. Id:{0}, version: {1}", packageId, version); packages.Add(newEntry); }
void CreatePackageReferenceNode ( bool installed = true, bool installPending = false, PackageName updatedPackage = null) { node = new PackageReferenceNode (null, packageReference, installed, installPending, updatedPackage); }
public override IEnumerable<string> GetPackageLookupPaths (string packageId, SemanticVersion version) { var packageName = new PackageName (packageId, version); List<string> filePaths = null; if (packageLookupPaths.TryGetValue (packageName, out filePaths)) { return filePaths; } return Enumerable.Empty<string> (); }
public void NuGetHelper_SuccessfulCalls() { // Setup var package = new PackageName(Guid.NewGuid().ToString("N"), new SemanticVersion("1.0")); var availablePackages = new[] { package }; ConfigurableServiceProvider sp = CreateServiceProvider(); sp.RegisterService(typeof(SComponentModel), ConfigurableComponentModel.CreateWithExports(MefTestHelpers.CreateExport<IVsPackageInstaller>(new ConfigurablePackageInstaller(availablePackages, simulateInstallerException: false))), replaceExisting: true); // Act + Verify Assert.IsTrue(NuGetHelper.TryInstallPackage(sp, new ProjectMock("prj"), package.Id, package.Version.ToNormalizedString()), "The package is expected to be installed successfully"); }
/// <summary> /// Initialize a new instance of <see cref="PackageOperationEventArgs"/> using the corresponding NuGet abstraction. /// </summary> internal PackageOperationEventArgs(PackageName name, string installPath) { Name = name; InstallPath = installPath; }
public void Parse(string path, string referencesXPathFilter, string packagesHintPathRegexSearchPattern, string libHintPathRegexSearchPattern, HashSet <IPackageName> packagesUsedInCsproj, string[] csporjReferenceExcludes, string addstring = null, string defaultVersion = null) { string hintPathRegexSearchPattern; string libPathPattern = @"^\.\.\\lib"; string packagesPathPattern = @"^\.\.\\packages"; XmlDocument projDefinition = new XmlDocument(); projDefinition.Load(path); XmlNamespaceManager nsmgr = new XmlNamespaceManager(projDefinition.NameTable); nsmgr.AddNamespace(_csprojNamespaceAlias, _csprojNamespace); var otherPackagesReferences = projDefinition.SelectNodes(referencesXPathFilter, nsmgr); if (otherPackagesReferences == null) { throw new Exception(String.Format("Packages not found for csproj {0} by filter {1}", path, referencesXPathFilter)); } ; foreach (XmlElement reference in otherPackagesReferences) { XmlNode referenceNode = reference.SelectSingleNode("csprojNameSpace:HintPath", nsmgr); if (referenceNode != null) { if (csporjReferenceExcludes.Contains(referenceNode.InnerText)) { logger.Info(string.Format("Skipping reference {0} as it is in exclusion list", referenceNode.InnerText)); continue; } string datasourceAddstring = ""; string datasourceDefaultVersion = null; if (Regex.Matches(referenceNode.InnerText, libPathPattern, RegexOptions.IgnoreCase).Count != 0) { hintPathRegexSearchPattern = libHintPathRegexSearchPattern; datasourceAddstring = addstring; datasourceDefaultVersion = defaultVersion; } else if (Regex.Matches(referenceNode.InnerText, packagesPathPattern, RegexOptions.IgnoreCase).Count != 0) { hintPathRegexSearchPattern = packagesHintPathRegexSearchPattern; } else { //logger.Error(new Exception(string.Format("{0} does not fit neither {1} nor {2} pattern to search package names for", referenceNode.InnerText, packagesPathPattern, libPathPattern))); //continue; throw new Exception(string.Format("{0} does not fit neither {1} nor {2} pattern to search package names for", referenceNode.InnerText, packagesPathPattern, libPathPattern)); } var packagePath = referenceNode.InnerText; var matches = Regex.Matches(packagePath, hintPathRegexSearchPattern, RegexOptions.IgnoreCase); if (matches.Count == 0) { //logger.Error(new Exception(String.Format("Packages not found for csproj {0} by regex filter {1}", path, hintPathRegexSearchPattern))); //continue; throw new Exception(String.Format("Packages not found for csproj {0} by regex filter {1}", path, hintPathRegexSearchPattern)); } foreach (Match match in matches) { logger.Info(string.Format("parsed package with name {0} from {1}", match.Groups[1].Value, path)); var packageName = string.Format("{0}{1}", match.Groups[1].Value, datasourceAddstring); var version = datasourceDefaultVersion ?? match.Groups[2].Value; var pack = new PackageName(packageName, new SemanticVersion(version)); packagesUsedInCsproj.Add(pack); } } else { logger.Info(string.Format("skipping '{0}' reference for csproj {1}", reference.Attributes[0].Value, path)); } } }
private static string GetPath(PackageState packageState, string userName, PackageName packageName) { return(string.Format("{0}/{1}", GetDirectoryPath(packageState, userName), GetPackagePath(packageName))); }
public void FileShareFeedShouldUsePackageFromCache() { using (var acmeWeb = CreateSamplePackage()) { DownloadPackage(FileShare.PackageId, FileShare.Version.ToString(), FileShare.Id, acmeWeb.DirectoryPath).AssertSuccess(); var result = DownloadPackage(FileShare.PackageId, FileShare.Version.ToString(), FileShare.Id, acmeWeb.DirectoryPath); result.AssertSuccess(); result.AssertOutput("Checking package cache for package {0} v{1}", FileShare.PackageId, FileShare.Version); result.AssertOutputMatches(string.Format("Package was found in cache\\. No need to download. Using file: '{0}'", PackageName.ToRegexPattern(FileShare.PackageId, FileShare.Version, FileShare.DownloadFolder))); AssertPackageHashMatchesExpected(result, acmeWeb.Hash); AssertPackageSizeMatchesExpected(result, acmeWeb.Size); AssertStagePackageOutputVariableSet(result, FileShare); } }
public void BindingWorkflow_InstallPackages_FailureOnOneProject_Continues() { // Setup const string failureMessage = "Failure for project1"; const string project1Name = "project1"; const string project2Name = "project2"; var testSubject = this.CreateTestSubject(); var progressEvents = new ConfigurableProgressStepExecutionEvents(); var cts = new CancellationTokenSource(); ProjectMock project1 = new ProjectMock(project1Name); ProjectMock project2 = new ProjectMock(project2Name); var nugetPackage = new PackageName("mypackage", new SemanticVersion("1.1.0")); var packages = new[] { nugetPackage }; ConfigurablePackageInstaller packageInstaller = this.PrepareInstallPackagesTest(testSubject, packages, project1, project2); packageInstaller.InstallPackageAction = (p) => { packageInstaller.InstallPackageAction = null; throw new Exception(failureMessage); }; // Act testSubject.InstallPackages(new ConfigurableProgressController(), cts.Token, progressEvents); // Verify packageInstaller.AssertNoInstalledPackages(project1); packageInstaller.AssertInstalledPackages(project2, packages); outputWindowPane.AssertOutputStrings(string.Format(CultureInfo.CurrentCulture, Strings.FailedDuringNuGetPackageInstall, nugetPackage.Id, project1Name, failureMessage)); }
void AddUpdatedPackagesForProject (string packageId1, string version1, string packageId2, string version2) { var packageName1 = new PackageName (packageId1, new SemanticVersion (version1)); var packageName2 = new PackageName (packageId2, new SemanticVersion (version2)); updatedPackagesInSolution.AddUpdatedPackages (project, packageName1, packageName2); }
protected string GenerateCommandLineCommands(string ManifestFile, string currentAbi, string currentResourceOutputFile) { // For creating Resource.designer.cs: // Running command: C:\Program Files (x86)\Android\android-sdk-windows\platform-tools\aapt // "package" // "-M" "C:\Users\Jonathan\AppData\Local\Temp\ryob4gaw.way\AndroidManifest.xml" // "-J" "C:\Users\Jonathan\AppData\Local\Temp\ryob4gaw.way" // "-F" "C:\Users\Jonathan\AppData\Local\Temp\ryob4gaw.way\resources.apk" // "-S" "c:\users\jonathan\documents\visual studio 2010\Projects\MonoAndroidApplication4\MonoAndroidApplication4\obj\Debug\res" // "-I" "C:\Program Files (x86)\Android\android-sdk-windows\platforms\android-8\android.jar" // "--max-res-version" "10" // For packaging: // Running command: C:\Program Files (x86)\Android\android-sdk-windows\platform-tools\aapt // "package" // "-f" // "-m" // "-M" "AndroidManifest.xml" // "-J" "src" // "--custom-package" "androidmsbuildtest.androidmsbuildtest" // "-F" "bin\packaged_resources" // "-S" "C:\Users\Jonathan\Documents\Visual Studio 2010\Projects\AndroidMSBuildTest\AndroidMSBuildTest\obj\Debug\res" // "-I" "C:\Program Files (x86)\Android\android-sdk-windows\platforms\android-8\android.jar" // "--extra-packages" "com.facebook.android:my.another.library" var cmd = new CommandLineBuilder(); cmd.AppendSwitch("package"); if (MonoAndroidHelper.LogInternalExceptions) { cmd.AppendSwitch("-v"); } if (NonConstantId) { cmd.AppendSwitch("--non-constant-id"); } cmd.AppendSwitch("-f"); cmd.AppendSwitch("-m"); string manifestFile; string manifestDir = Path.Combine(Path.GetDirectoryName(ManifestFile), currentAbi != null ? currentAbi : "manifest"); Directory.CreateDirectory(manifestDir); manifestFile = Path.Combine(manifestDir, Path.GetFileName(ManifestFile)); ManifestDocument manifest = new ManifestDocument(ManifestFile); manifest.SdkVersion = AndroidSdkPlatform; if (!string.IsNullOrEmpty(VersionCodePattern)) { try { manifest.CalculateVersionCode(currentAbi, VersionCodePattern, VersionCodeProperties); } catch (ArgumentOutOfRangeException ex) { LogCodedError("XA0003", ManifestFile, 0, ex.Message); return(string.Empty); } } if (currentAbi != null && string.IsNullOrEmpty(VersionCodePattern)) { manifest.SetAbi(currentAbi); } if (!manifest.ValidateVersionCode(out string error, out string errorCode)) { LogCodedError(errorCode, ManifestFile, 0, error); return(string.Empty); } manifest.ApplicationName = ApplicationName; manifest.Save(LogCodedWarning, manifestFile); cmd.AppendSwitchIfNotNull("-M ", manifestFile); var designerDirectory = Path.IsPathRooted(JavaDesignerOutputDirectory) ? JavaDesignerOutputDirectory : Path.Combine(WorkingDirectory, JavaDesignerOutputDirectory); Directory.CreateDirectory(designerDirectory); cmd.AppendSwitchIfNotNull("-J ", JavaDesignerOutputDirectory); if (PackageName != null) { cmd.AppendSwitchIfNotNull("--custom-package ", PackageName.ToLowerInvariant()); } if (!string.IsNullOrEmpty(currentResourceOutputFile)) { cmd.AppendSwitchIfNotNull("-F ", currentResourceOutputFile + ".bk"); } // The order of -S arguments is *important*, always make sure this one comes FIRST cmd.AppendSwitchIfNotNull("-S ", resourceDirectory.TrimEnd('\\')); if (AdditionalResourceDirectories != null) { foreach (var dir in AdditionalResourceDirectories) { var resdir = dir.ItemSpec.TrimEnd('\\'); if (Directory.Exists(resdir)) { cmd.AppendSwitchIfNotNull("-S ", resdir); } } } if (AdditionalAndroidResourcePaths != null) { foreach (var dir in AdditionalAndroidResourcePaths) { var resdir = Path.Combine(dir.ItemSpec, "res"); if (Directory.Exists(resdir)) { cmd.AppendSwitchIfNotNull("-S ", resdir); } } } if (LibraryProjectJars != null) { foreach (var jar in LibraryProjectJars) { cmd.AppendSwitchIfNotNull("-j ", jar); } } cmd.AppendSwitchIfNotNull("-I ", JavaPlatformJarPath); // Add asset directory if it exists if (!string.IsNullOrWhiteSpace(AssetDirectory)) { var assetDir = AssetDirectory.TrimEnd('\\'); if (!Path.IsPathRooted(assetDir)) { assetDir = Path.Combine(WorkingDirectory, assetDir); } if (!string.IsNullOrWhiteSpace(assetDir) && Directory.Exists(assetDir)) { cmd.AppendSwitchIfNotNull("-A ", assetDir); } } if (!string.IsNullOrWhiteSpace(UncompressedFileExtensions)) { foreach (var ext in UncompressedFileExtensions.Split(new char[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries)) { cmd.AppendSwitchIfNotNull("-0 ", ext.StartsWith(".", StringComparison.OrdinalIgnoreCase) ? ext : $".{ext}"); } } if (!string.IsNullOrEmpty(ExtraPackages)) { cmd.AppendSwitchIfNotNull("--extra-packages ", ExtraPackages); } cmd.AppendSwitch("--auto-add-overlay"); if (!string.IsNullOrEmpty(ResourceSymbolsTextFileDirectory)) { cmd.AppendSwitchIfNotNull("--output-text-symbols ", ResourceSymbolsTextFileDirectory); } if (!string.IsNullOrWhiteSpace(ExtraArgs)) { cmd.AppendSwitch(ExtraArgs); } if (!AndroidUseLatestPlatformSdk) { cmd.AppendSwitchIfNotNull("--max-res-version ", ApiLevel); } return(cmd.ToString()); }
public Task<IPackage> Exists(PackageName name, SemanticVersion version) { throw new NotImplementedException(); }
private void process(JArray processors, Dictionary <string, string> mapData) { if (processors == null || processors.Count == 0) { return; } fireEvent(MFile.Library, "processors", processors.Count, 0); for (int i = 0; i < processors.Count; i++) { var item = processors[i]; var name = item["jar"]?.ToString(); if (name == null) { continue; } var outputs = item["outputs"] as JObject; if (outputs != null) { var valid = true; foreach (var outitem in outputs) { var key = Mapper.Interpolation(outitem.Key, mapData); var value = Mapper.Interpolation(outitem.Value.ToString(), mapData); if (!File.Exists(key) || !IOUtil.CheckSHA1(key, value)) { valid = false; break; } } if (valid) // skip processing if already done { fireEvent(MFile.Library, "processors", processors.Count, i + 1); continue; } } // jar var jar = PackageName.Parse(name); var jarpath = Path.Combine(Minecraft.Library, jar.GetPath()); var jarfile = new JarFile(jarpath); var jarManifest = jarfile.GetManifest(); // mainclass string mainclass = null; var hasMainclass = jarManifest?.TryGetValue("Main-Class", out mainclass) ?? false; if (!hasMainclass || string.IsNullOrEmpty(mainclass)) { continue; } // classpath var classpathObj = item["classpath"]; var classpath = new List <string>(); if (classpathObj != null) { foreach (var libname in classpathObj) { var lib = Path.Combine(Minecraft.Library, PackageName.Parse(libname?.ToString()).GetPath()); classpath.Add(lib); } } classpath.Add(jarpath); // arg var argsArr = item["args"] as JArray; string[] args = null; if (argsArr != null) { var arrStrs = argsArr.Select(x => x.ToString()).ToArray(); args = Mapper.Map(arrStrs, mapData, Minecraft.Library); } startJava(classpath.ToArray(), mainclass, args); fireEvent(MFile.Library, "processors", processors.Count, i + 1); } }
public void Run() { PackageRoute = "src/main/java/" + PackageName.Replace(".", "/"); if (Argument.Equals("PlanObject")) { Directory.CreateDirectory(RootDirectory + PackageRoute + "/entity"); foreach (Ac4yClass planObject in Ac4yModule.ClassList) { new PlanObjectGenerator() { OutputPath = RootDirectory + PackageRoute + "/entity/" , DbName = DbName , Package = PackageName } .Generate(planObject); } } if (Argument.Equals("Pom")) { new PomXmlGenerator() { OutputPath = RootDirectory , ArtifactId = ArtifactId , GroupId = GroupId , Version = Version }.Generate(); } if (Argument.Equals("Hibernate")) { Directory.CreateDirectory(RootDirectory + "/src/main/resources/"); new HibernateCfgXmlGenerator() { OutputPath = RootDirectory + "/src/main/resources/" , JdbcString = JdbcString , Username = Username , Password = Password }.Generate(); } if (Argument.Equals("WebXml")) { Directory.CreateDirectory(RootDirectory + "src/main/webapp/WEB-INF"); new WebXmlGenerator() { OutputPath = RootDirectory + "src/main/webapp/WEB-INF/" , PackageName = PackageName }.Generate(); } if (Argument.Equals("ODataServlet")) { Directory.CreateDirectory(RootDirectory + PackageRoute + "/web"); new ODataServletGenerator() { OutputPath = RootDirectory + PackageRoute + "/web/" , Package = PackageName }.Generate(); } if (Argument.Equals("cors")) { Directory.CreateDirectory(RootDirectory + PackageRoute + "/cors"); new CORSFilterGenerator() { OutputPath = RootDirectory + PackageRoute + "/cors/" , PackageName = PackageName }.Generate(); } if (Argument.Equals("Util")) { Directory.CreateDirectory(RootDirectory + PackageRoute + "/util"); new UtilGenerator() { OutputPath = RootDirectory + PackageRoute + "/util/" , Package = PackageName }.Generate(); } if (Argument.Equals("Storage")) { Directory.CreateDirectory(RootDirectory + PackageRoute + "/data"); new StorageClassGenerator() { OutputPath = RootDirectory + PackageRoute + "/data/" , Package = PackageName }.Generate(Ac4yModule); } if (Argument.Equals("HibernateCap")) { Directory.CreateDirectory(RootDirectory + PackageRoute + "/connection"); foreach (Ac4yClass ac4yClass in Ac4yModule.ClassList) { new HibernateCapGenerator() { OutputPath = RootDirectory + PackageRoute + "/connection/" , Package = PackageName }.Generate(ac4yClass, Ac4yModule); } } if (Argument.Equals("FilterExpressionVisitor")) { Directory.CreateDirectory(RootDirectory + PackageRoute + "/service"); new FilterExpressionVisitorGenerator() { OutputPath = RootDirectory + PackageRoute + "/service/" , Package = PackageName }.Generate(); } if (Argument.Equals("EdmProvider")) { Directory.CreateDirectory(RootDirectory + PackageRoute + "/service"); new EdmProviderGenerator() { OutputPath = RootDirectory + PackageRoute + "/service/" , Package = PackageName }.Generate(Ac4yModule); } if (Argument.Equals("EntityProcessor")) { Directory.CreateDirectory(RootDirectory + PackageRoute + "/service"); new EntityProcessorGenerator() { OutputPath = RootDirectory + PackageRoute + "/service/" , Package = PackageName }.Generate(); } if (Argument.Equals("EntityCollectionProcessor")) { Directory.CreateDirectory(RootDirectory + PackageRoute + "/service"); new EntityCollectionProcessorGenerator() { OutputPath = RootDirectory + PackageRoute + "/service/" , Package = PackageName }.Generate(); } if (Argument.Equals("PrimitiveProcessor")) { Directory.CreateDirectory(RootDirectory + PackageRoute + "/service"); new PrimitiveProcessorGenerator() { OutputPath = RootDirectory + PackageRoute + "/service/" , Package = PackageName }.Generate(); } if (Argument.Equals("OpenApi")) { new OpenApiDocumentGenerator() { OutputPath = RootDirectory , ODataUrl = ODataURL , Parameter = Ac4yModule , Version = Version }.Generate(); } } // run
/// <summary> /// Process record. /// </summary> protected override void ProcessRecord() { IEnumerable <Sid> sids; switch (ParameterSetName) { case "sddl": sids = Sddl.Select(s => new Sid(s)); break; case "name": sids = Name.Select(s => NtSecurity.LookupAccountName(s)); break; case "service": sids = ServiceName.Select(s => NtSecurity.GetServiceSid(s)); break; case "il": sids = IntegrityLevel.Select(s => NtSecurity.GetIntegritySid(s)); break; case "il_raw": sids = IntegrityLevelRaw.Select(s => NtSecurity.GetIntegritySidRaw(s)); break; case "package": sids = PackageName.Select(s => TokenUtils.DerivePackageSidFromName(s)); if (RestrictedPackageName != null) { sids = sids.Select(s => TokenUtils.DeriveRestrictedPackageSidFromSid(s, RestrictedPackageName)); } if (AsCapability) { sids = sids.Select(s => NtSecurity.PackageSidToCapability(s)); } break; case "known": sids = KnownSid.Select(s => KnownSids.GetKnownSid(s)); break; case "token": using (NtToken token = NtToken.OpenProcessToken()) { Sid temp = null; if (PrimaryGroup) { temp = token.PrimaryGroup; } else if (Owner) { temp = token.Owner; } else if (LogonGroup) { temp = token.LogonSid.Sid; } else if (AppContainer) { temp = token.AppContainerSid; } else if (Label) { temp = token.IntegrityLevelSid.Sid; } else { temp = token.User.Sid; } sids = new[] { temp }; } break; case "cap": sids = CapabilityName.Select(s => CapabilityGroup ? NtSecurity.GetCapabilityGroupSid(s) : NtSecurity.GetCapabilitySid(s)); break; case "sid": sids = new[] { new Sid(SecurityAuthority, RelativeIdentifier ?? new uint[0]) }; break; case "rawsa": sids = new[] { new Sid(new SidIdentifierAuthority(SecurityAuthorityByte), RelativeIdentifier) }; break; case "logon": sids = new[] { NtSecurity.GetLogonSessionSid() }; break; case "trust": sids = new[] { NtSecurity.GetTrustLevelSid(TrustType, TrustLevel) }; break; case "ace": sids = AccessControlEntry.Select(a => a.Sid); break; case "relsid": sids = new[] { Sibling?BaseSid.CreateSibling(RelativeIdentifier) : BaseSid.CreateRelative(RelativeIdentifier) }; break; case "bytes": sids = new[] { new Sid(Byte) }; break; default: throw new ArgumentException("No SID type specified"); } if (AsSddl) { WriteObject(sids.Select(s => s.ToString()), true); } else if (AsName) { WriteObject(sids.Select(s => s.Name), true); } else { WriteObject(sids, true); } }
public IList <string> Merge(List <TypeDefinition> subclasses, List <string> selectedWhitelistAssemblies, string applicationClass, bool embed, string bundledWearApplicationName, IEnumerable <string> mergedManifestDocuments) { string applicationName = ApplicationName; var manifest = doc.Root; if (manifest == null || manifest.Name != "manifest") { throw new Exception("Root element must be 'manifest'"); } var manifest_package = (string)manifest.Attribute("package"); if (!string.IsNullOrWhiteSpace(manifest_package)) { PackageName = manifest_package; } manifest.SetAttributeValue(XNamespace.Xmlns + "android", "http://schemas.android.com/apk/res/android"); if (manifest.Attribute(androidNs + "versionCode") == null) { manifest.SetAttributeValue(androidNs + "versionCode", "1"); } if (manifest.Attribute(androidNs + "versionName") == null) { manifest.SetAttributeValue(androidNs + "versionName", "1.0"); } app = CreateApplicationElement(manifest, applicationClass, subclasses, selectedWhitelistAssemblies); if (app.Attribute(androidNs + "label") == null && applicationName != null) { app.SetAttributeValue(androidNs + "label", applicationName); } var existingTypes = new HashSet <string> ( app.Descendants().Select(a => (string)a.Attribute(attName)).Where(v => v != null)); if (!string.IsNullOrEmpty(bundledWearApplicationName)) { if (!app.Elements("meta-data").Any(e => e.Attributes(androidNs + "name").Any(a => a.Value == bundledWearApplicationName))) { app.Add(new XElement("meta-data", new XAttribute(androidNs + "name", "com.google.android.wearable.beta.app"), new XAttribute(androidNs + "resource", "@xml/wearable_app_desc"))); } } // If no <uses-sdk> is specified, add it with both minSdkVersion and // targetSdkVersion set to TargetFrameworkVersion if (!manifest.Elements("uses-sdk").Any()) { manifest.AddFirst( new XElement("uses-sdk", new XAttribute(androidNs + "minSdkVersion", SdkVersionName), new XAttribute(androidNs + "targetSdkVersion", SdkVersionName))); } // If no minSdkVersion is specified, set it to TargetFrameworkVersion var uses = manifest.Element("uses-sdk"); if (uses.Attribute(androidNs + "minSdkVersion") == null) { int minSdkVersion; if (!int.TryParse(SdkVersionName, out minSdkVersion)) { minSdkVersion = 11; } minSdkVersion = Math.Min(minSdkVersion, 11); uses.SetAttributeValue(androidNs + "minSdkVersion", minSdkVersion.ToString()); } string targetSdkVersion; var tsv = uses.Attribute(androidNs + "targetSdkVersion"); if (tsv != null) { targetSdkVersion = tsv.Value; } else { targetSdkVersion = SdkVersionName; uses.AddBeforeSelf(new XComment("suppress UsesMinSdkAttributes")); } int?tryTargetSdkVersion = MonoAndroidHelper.SupportedVersions.GetApiLevelFromId(targetSdkVersion); if (!tryTargetSdkVersion.HasValue) { throw new InvalidOperationException(string.Format("The targetSdkVersion ({0}) is not a valid API level", targetSdkVersion)); } int targetSdkVersionValue = tryTargetSdkVersion.Value; foreach (var t in subclasses) { if (t.IsAbstract) { continue; } if (PackageName == null) { PackageName = t.Namespace; } var name = JavaNativeTypeManager.ToJniName(t).Replace('/', '.'); var compatName = JavaNativeTypeManager.ToCompatJniName(t).Replace('/', '.'); if (((string)app.Attribute(attName)) == compatName) { app.SetAttributeValue(attName, name); } Func <TypeDefinition, string, int, XElement> generator = GetGenerator(t); if (generator == null) { continue; } try { // activity not present: create a launcher for it IFF it has attribute if (!existingTypes.Contains(name) && !existingTypes.Contains(compatName)) { XElement fromCode = generator(t, name, targetSdkVersionValue); if (fromCode == null) { continue; } IEnumerable <MethodDefinition> constructors = t.Methods.Where(m => m.IsConstructor).Cast <MethodDefinition> (); if (!constructors.Any(c => !c.HasParameters && c.IsPublic)) { string message = $"The type '{t.FullName}' must provide a public default constructor"; SequencePoint sourceLocation = FindSource(constructors); if (sourceLocation != null && sourceLocation.Document?.Url != null) { log.LogError( subcategory: String.Empty, errorCode: "XA4213", helpKeyword: String.Empty, file: sourceLocation.Document.Url, lineNumber: sourceLocation.StartLine, columnNumber: sourceLocation.StartColumn, endLineNumber: sourceLocation.EndLine, endColumnNumber: sourceLocation.EndColumn, message: message); } else { log.LogCodedError("XA4213", message); } continue; } app.Add(fromCode); } foreach (var d in app.Descendants().Where(a => ((string)a.Attribute(attName)) == compatName)) { d.SetAttributeValue(attName, name); } } catch (InvalidActivityNameException ex) { log.LogErrorFromException(ex); } } var icon = app.Attribute(androidNs + "icon"); if (icon == null) { var activity = app.Element("activity"); if (activity != null) { var activityIcon = activity.Attribute(androidNs + "icon"); if (activityIcon != null) { app.Add(new XAttribute(androidNs + "icon", activityIcon.Value)); } } } PackageName = AndroidAppManifest.CanonicalizePackageName(PackageName); if (!PackageName.Contains('.')) { throw new InvalidOperationException("/manifest/@package attribute MUST contain a period ('.')."); } manifest.SetAttributeValue("package", PackageName); var providerNames = AddMonoRuntimeProviders(app); if (Debug) { app.Add(new XComment("suppress ExportedReceiver")); app.Add(new XElement("receiver", new XAttribute(androidNs + "name", "mono.android.Seppuku"), new XElement("intent-filter", new XElement("action", new XAttribute(androidNs + "name", "mono.android.intent.action.SEPPUKU")), new XElement("category", new XAttribute(androidNs + "name", "mono.android.intent.category.SEPPUKU." + PackageName))))); if (app.Attribute(androidNs + "debuggable") == null) { app.Add(new XAttribute(androidNs + "debuggable", "true")); } } if (Debug || NeedsInternet) { AddInternetPermissionForDebugger(); } if (!embed) { AddFastDeployPermissions(); } AddAddOns(app, SdkDir, SdkVersionName, Addons); // If the manifest has android:installLocation, but we are targeting // API 7 or lower, remove it for the user and show a warning if (manifest.Attribute(androidNs + "installLocation") != null) { if (targetSdkVersionValue < 8) { manifest.Attribute(androidNs + "installLocation").Remove(); Console.Error.WriteLine("monodroid: warning 1 : installLocation cannot be specified for Android versions less than 2.2. Attribute installLocation ignored."); } } AddInstrumentations(manifest, subclasses, targetSdkVersionValue); AddPermissions(app, selectedWhitelistAssemblies); AddPermissionGroups(app, selectedWhitelistAssemblies); AddPermissionTrees(app, selectedWhitelistAssemblies); AddUsesPermissions(app, selectedWhitelistAssemblies); AddUsesFeatures(app, selectedWhitelistAssemblies); AddSupportsGLTextures(app, selectedWhitelistAssemblies); ReorderActivityAliases(app); ReorderElements(app); if (mergedManifestDocuments != null) { foreach (var mergedManifest in mergedManifestDocuments) { try { MergeLibraryManifest(mergedManifest); } catch (Exception ex) { log.LogWarningFromException(ex); } } } return(providerNames); SequencePoint FindSource(IEnumerable <MethodDefinition> methods) { if (methods == null) { return(null); } SequencePoint ret = null; foreach (MethodDefinition method in methods.Where(m => m != null && m.HasBody && m.DebugInformation != null)) { foreach (Instruction ins in method.Body.Instructions) { SequencePoint seq = method.DebugInformation.GetSequencePoint(ins); if (seq == null) { continue; } if (ret == null || seq.StartLine < ret.StartLine) { ret = seq; } break; } } return(ret); } }
public AzureBlob GetBlobReference(PackageState packageState, string userName, PackageName packageName) { var path = GetPath(packageState, userName, packageName); return(new AzureBlob(container.GetBlockBlobReference(path))); }
private void EnsurePackageFiles() { if (_files != null && _expandedFolderPath != null && _expandedFileSystem.DirectoryExists(_expandedFolderPath)) { return; } _files = new Dictionary<string, PhysicalPackageFile>(); _supportedFrameworks = null; var packageName = new PackageName(Id, Version); // Only use the cache for expanded folders under %temp%. if (_expandedFileSystem == _tempFileSystem) { _expandedFolderPath = _cachedExpandedFolder.GetOrAdd(packageName, _ => GetExpandedFolderPath()); } else { _expandedFolderPath = GetExpandedFolderPath(); } using (Stream stream = GetStream()) { Package package = Package.Open(stream); // unzip files inside package var files = from part in package.GetParts() where ZipPackage.IsPackageFile(part) select part; // now copy all package's files to disk foreach (PackagePart file in files) { string path = UriUtility.GetPath(file.Uri); string filePath = Path.Combine(_expandedFolderPath, path); using (Stream partStream = file.GetStream()) { // only copy the package part to disk if there doesn't exist // a file with the same name. if (!_expandedFileSystem.FileExists(filePath)) { using (Stream targetStream = _expandedFileSystem.CreateFile(filePath)) { partStream.CopyTo(targetStream); } } } var packageFile = new PhysicalPackageFile { SourcePath = _expandedFileSystem.GetFullPath(filePath), TargetPath = path }; _files[path] = packageFile; } } }
public void ShouldUsePackageFromCache() { DownloadPackage(FeedzPackage.PackageId, FeedzPackage.Version.ToString(), FeedzPackage.Id, PublicFeedUri) .AssertSuccess(); var result = DownloadPackage(FeedzPackage.PackageId, FeedzPackage.Version.ToString(), FeedzPackage.Id, PublicFeedUri); result.AssertSuccess(); result.AssertOutput("Checking package cache for package {0} v{1}", FeedzPackage.PackageId, FeedzPackage.Version); result.AssertOutputMatches(string.Format("Package was found in cache\\. No need to download. Using file: '{0}'", PackageName.ToRegexPattern(FeedzPackage.PackageId, FeedzPackage.Version, FeedzPackage.DownloadFolder))); AssertPackageHashMatchesExpected(result, ExpectedPackageHash); AssertPackageSizeMatchesExpected(result, ExpectedPackageSize); AssertStagePackageOutputVariableSet(result, FeedzPackage); }
private void UninstallPackagesForReinstall( IProjectManager projectManager, bool updateDependencies, ILogger logger, Dictionary<PackageName, IPackage> verifiedPackagesInSourceRepository, out HashSet<IPackage> packagesToBeReinstalled) { packagesToBeReinstalled = new HashSet<IPackage>(); logger = logger ?? NullLogger.Instance; try { InitializeLogger(logger, projectManager); var packages = projectManager.LocalRepository.GetPackages().ToArray(); foreach (IPackage package in packages) { IDisposable disposableAction = StartReinstallOperation(package.Id, package.Version.ToString()); try { logger.Log(MessageLevel.Info, VsResources.ReinstallProjectPackage, package, projectManager.Project.ProjectName); IPackage packageInSourceRepository; PackageName packageName = new PackageName(package.Id, package.Version); if (!verifiedPackagesInSourceRepository.TryGetValue(packageName, out packageInSourceRepository)) { packageInSourceRepository = SourceRepository.FindPackage(package.Id, package.Version); verifiedPackagesInSourceRepository[packageName] = packageInSourceRepository; } if (packageInSourceRepository != null) { packagesToBeReinstalled.Add(packageInSourceRepository); RunSolutionAction( () => { // We set remove dependencies to false since we will remove all the packages anyways UninstallPackage( projectManager, package.Id, package.Version, forceRemove: true, removeDependencies: false, logger: logger); }); } else { logger.Log( MessageLevel.Warning, VsResources.PackageRestoreSkipForProject, package.GetFullName(), projectManager.Project.ProjectName); } } catch (PackageNotInstalledException e) { logger.Log(MessageLevel.Warning, ExceptionUtility.Unwrap(e).Message); } catch (Exception e) { logger.Log(MessageLevel.Error, ExceptionUtility.Unwrap(e).Message); } finally { ClearLogger(projectManager); disposableAction.Dispose(); } } } finally { ClearLogger(projectManager); } }
public void ShouldUseMavenSnapshotPackageFromCache() { if (CalamariEnvironment.IsRunningOnMac && TestEnvironment.IsCI && !CalamariEnvironment.IsRunningOnMono) { Assert.Inconclusive("As of November 2018, this test is failing under dotnet core on the cloudmac under teamcity - we were getting an error 'SSL connect error' when trying to download from 'https://repo.maven.apache.org/maven2/'. Marking as inconclusive so we can re-enable the build - it had been disabled for months :("); } DownloadPackage(MavenPublicFeed.PackageId, MavenPublicFeed.Version.ToString(), MavenPublicFeed.Id, MavenPublicFeedUri, feedType: FeedType.Maven, versionFormat: VersionFormat.Maven) .AssertSuccess(); var result = DownloadPackage(MavenPublicFeed.PackageId, MavenPublicFeed.Version.ToString(), MavenPublicFeed.Id, MavenPublicFeedUri, feedType: FeedType.Maven, versionFormat: VersionFormat.Maven); result.AssertSuccess(); result.AssertOutput("Checking package cache for package {0} v{1}", MavenPublicFeed.PackageId, MavenPublicFeed.Version); result.AssertOutputMatches($"Package was found in cache\\. No need to download. Using file: '{PackageName.ToRegexPattern(MavenPublicFeed.PackageId, MavenPublicFeed.Version, MavenPublicFeed.DownloadFolder)}'"); AssertPackageHashMatchesExpected(result, ExpectedMavenPackageHash); AssertPackageSizeMatchesExpected(result, ExpectedMavenPackageSize); AssertStagePackageOutputVariableSet(result, MavenPublicFeed); }
public void BindingWorkflow_InstallPackages() { // Setup var testSubject = this.CreateTestSubject(); var progressEvents = new ConfigurableProgressStepExecutionEvents(); ProjectMock project1 = new ProjectMock("project1"); ProjectMock project2 = new ProjectMock("project2"); var nugetPackage = new PackageName("mypackage", new SemanticVersion("1.1.0")); var packages = new[] { nugetPackage }; ConfigurablePackageInstaller packageInstaller = this.PrepareInstallPackagesTest(testSubject, packages, project1, project2); // Act testSubject.InstallPackages(new ConfigurableProgressController(), CancellationToken.None, progressEvents); // Verify packageInstaller.AssertInstalledPackages(project1, packages); packageInstaller.AssertInstalledPackages(project2, packages); progressEvents.AssertProgressMessages( string.Format(CultureInfo.CurrentCulture, Strings.EnsuringNugetPackagesProgressMessage, nugetPackage.Id, ((Project)project1).Name), string.Empty, string.Format(CultureInfo.CurrentCulture, Strings.EnsuringNugetPackagesProgressMessage, nugetPackage.Id, ((Project)project2).Name), string.Empty); progressEvents.AssertProgress( 0, .5, .5, 1.0); }
public void PrivateNuGetFeedShouldUsePackageFromCache() { DownloadPackage(FeedzPackage.PackageId, FeedzPackage.Version.ToString(), FeedzPackage.Id, AuthFeedUri, AuthFeedUsername, AuthFeedPassword) .AssertSuccess(); var result = DownloadPackage(FeedzPackage.PackageId, FeedzPackage.Version.ToString(), FeedzPackage.Id, AuthFeedUri, AuthFeedUsername, AuthFeedPassword); result.AssertSuccess(); result.AssertOutput("Checking package cache for package {0} v{1}", FeedzPackage.PackageId, FeedzPackage.Version); result.AssertOutputMatches($"Package was found in cache\\. No need to download. Using file: '{PackageName.ToRegexPattern(FeedzPackage.PackageId, FeedzPackage.Version, FeedzPackage.DownloadFolder)}'"); AssertPackageHashMatchesExpected(result, ExpectedPackageHash); AssertPackageSizeMatchesExpected(result, ExpectedPackageSize); AssertStagePackageOutputVariableSet(result, FeedzPackage); }
private void EnsurePackageFiles() { if (_files != null && _expandedFolderPath != null && _expandedFileSystem.DirectoryExists(_expandedFolderPath)) { return; } _files = new Dictionary<string, PhysicalPackageFile>(); _supportedFrameworks = null; var packageName = new PackageName(Id, Version); // Only use the cache for expanded folders under %temp%, or set from unit tests if (_expandedFileSystem == _tempFileSystem || _forceUseCache) { Tuple<string, DateTimeOffset> cacheValue; DateTimeOffset lastModifiedTime = _fileSystem.GetLastModified(_packagePath); // if the cache doesn't exist, or it exists but points to a stale package, // then we invalidate the cache and store the new entry. if (!_cachedExpandedFolder.TryGetValue(packageName, out cacheValue) || cacheValue.Item2 < lastModifiedTime) { cacheValue = Tuple.Create(GetExpandedFolderPath(), lastModifiedTime); _cachedExpandedFolder[packageName] = cacheValue; } _expandedFolderPath = cacheValue.Item1; } else { _expandedFolderPath = GetExpandedFolderPath(); } using (Stream stream = GetStream()) { var package = new ZipArchive(stream); // unzip files inside package var files = from part in package.Entries where ZipPackage.IsPackageFile(part) select part; // now copy all package's files to disk foreach (ZipArchiveEntry file in files) { string path = file.FullName.Replace('/', '\\').Replace("%2B", "+"); string filePath = Path.Combine(_expandedFolderPath, path); bool copyFile = true; if (copyFile) { using (Stream partStream = file.Open()) { try { using (Stream targetStream = _expandedFileSystem.CreateFile(filePath)) { partStream.CopyTo(targetStream); } } catch (Exception) { // if the file is read-only or has an access denied issue, we just ignore it } } } var packageFile = new PhysicalPackageFile { SourcePath = _expandedFileSystem.GetFullPath(filePath), TargetPath = path }; _files[path] = packageFile; } } }
=> GetPackageVersionsAsync(PackageName, preRelease, cancelationToken);
internal IPackage FindPackage(Func<string, IPackage> openPackage, string packageId, SemanticVersion version) { var lookupPackageName = new PackageName(packageId, version); string packagePath; // If caching is enabled, check if we have a cached path. Additionally, verify that the file actually exists on disk since it might have moved. if (_enableCaching && _packagePathLookup.TryGetValue(lookupPackageName, out packagePath) && FileSystem.FileExists(packagePath)) { // When depending on the cached path, verify the file exists on disk. return GetPackage(openPackage, packagePath); } // Lookup files which start with the name "<Id>." and attempt to match it with all possible version string combinations (e.g. 1.2.0, 1.2.0.0) // before opening the package. To avoid creating file name strings, we attempt to specifically match everything after the last path separator // which would be the file name and extension. return (from path in GetPackageLookupPaths(packageId, version) let package = GetPackage(openPackage, path) where lookupPackageName.Equals(new PackageName(package.Id, package.Version)) select package).FirstOrDefault(); }
public void AssertUninstall(PackageName package) { Assert.IsTrue(this.uninstallEvents.Remove(package), "Expected uninstall event for package {0}, but did not receive one.", package); }
public void ShouldUseMavenSnapshotPackageFromCache() { DownloadPackage(MavenPublicFeed.PackageId, MavenPublicFeed.Version.ToString(), MavenPublicFeed.Id, MavenPublicFeedUri, feedType: FeedType.Maven, versionFormat: VersionFormat.Maven) .AssertSuccess(); var result = DownloadPackage(MavenPublicFeed.PackageId, MavenPublicFeed.Version.ToString(), MavenPublicFeed.Id, MavenPublicFeedUri, feedType: FeedType.Maven, versionFormat: VersionFormat.Maven); result.AssertSuccess(); result.AssertOutput("Checking package cache for package {0} v{1}", MavenPublicFeed.PackageId, MavenPublicFeed.Version); result.AssertOutputMatches(string.Format("Package was found in cache\\. No need to download. Using file: '{0}'", PackageName.ToRegexPattern(MavenPublicFeed.PackageId, MavenPublicFeed.Version, MavenPublicFeed.DownloadFolder))); AssertPackageHashMatchesExpected(result, ExpectedMavenPackageHash); AssertPackageSizeMatchesExpected(result, ExpectedMavenPackageSize); AssertStagePackageOutputVariableSet(result, MavenPublicFeed); }
protected override IEnumerable <Command> OnCreate(IMetadata sourceMetadata, IMetadata targetMetadata, IComparerContext context) { if (IsLegacy) { var command = new Command(); command.Append($"DECLARE EXTERNAL FUNCTION {FunctionName.AsSqlIndentifier()}"); var inputs = FunctionArguments .Where(x => x.ArgumentPosition != ReturnArgument) .OrderBy(x => x.ArgumentPosition) .Select(CreateLegacyArgumentDefinition); command.Append($" {string.Join(", ", inputs)}"); command.AppendLine(); var @return = FunctionArguments.First(x => x.ArgumentPosition == ReturnArgument); command.Append($"RETURNS{(ReturnArgument != 0 ? " PARAMETER" : string.Empty)} {CreateLegacyArgumentDefinition(@return)}"); command.AppendLine(); command.Append($"ENTRY_POINT '{SqlHelper.DoubleSingleQuotes(EntryPoint)}' MODULE_NAME '{SqlHelper.DoubleSingleQuotes(ModuleName)}'"); yield return(command); } else { var command = new PSqlCommand(); command.Append("CREATE OR ALTER FUNCTION"); if (PackageName != null) { command.Append($" {PackageName.AsSqlIndentifier()}.{FunctionName.AsSqlIndentifier()}"); } else { command.Append($" {FunctionName.AsSqlIndentifier()}"); } var inputs = FunctionArguments .Where(x => x.ArgumentPosition != ReturnArgument) .OrderBy(x => x.ArgumentPosition) .Select(x => CreateNewArgumentDefinition(x, sourceMetadata, targetMetadata, context)); var @return = FunctionArguments.First(x => x.ArgumentPosition == ReturnArgument); var output = CreateNewArgumentDefinition(@return, sourceMetadata, targetMetadata, context); command.Append($" ({string.Join(", ", inputs)}) RETURNS {output}"); command.AppendLine(); command.Append("AS"); command.AppendLine(); if (context.EmptyBodiesEnabled) { command.Append("BEGIN"); command.AppendLine(); command.Append("END"); } else { command.Append(FunctionSource); } if (EntryPoint != null) { command.AppendLine(); command.Append($"EXTERNAL NAME '{EntryPoint}'"); } if (EngineName != null) { command.AppendLine(); command.Append($"ENGINE {EngineName.AsSqlIndentifier()}"); } yield return(command); } }
static void AssertStagePackageOutputVariableSet(CalamariResult result, SampleFeedPackage testFeed) { var newPacakgeRegex = PackageName.ToRegexPattern(testFeed.PackageId, testFeed.Version, testFeed.DownloadFolder); result.AssertOutputVariable("StagedPackage.FullPathOnRemoteMachine", Does.Match(newPacakgeRegex + ".*")); }
public virtual void Generate(Stream stream, PackageName name) { throw new NotImplementedException(); }
public void AddPackageLookupPath (PackageName packageName, params string[] filePaths) { packageLookupPaths.Add (packageName, filePaths.ToList ()); }
public virtual void Delete(string apiKey, PackageName name) { throw new NotImplementedException(); }
/// <summary> /// Find-Package /// </summary> /// <param name="openPackage">Delegate function which is actually finding a package</param> /// <param name="packageId">Package Id</param> /// <param name="version">Package version</param> /// <param name="nugetRequest"></param> /// <returns></returns> private IPackage FindPackage(Func<string, Request, IPackage> openPackage, string packageId, SemanticVersion version, NuGetRequest nugetRequest) { if (nugetRequest == null) { return null; } nugetRequest.Debug(Resources.Messages.SearchingRepository, "FindPackage", packageId); var lookupPackageName = new PackageName(packageId, version); //handle file cache here if we want to support local package cache later // Lookup files which start with the name "<Id>." and attempt to match it with all possible version string combinations (e.g. 1.2.0, 1.2.0.0) // before opening the package. To avoid creating file name strings, we attempt to specifically match everything after the last path separator // which would be the file name and extension. return (from path in GetPackageLookupPaths(packageId, version) let package = GetPackage(openPackage, path, nugetRequest) where lookupPackageName.Equals(new PackageName(package.Id, package.Version)) select package).FirstOrDefault(); }
public bool Equals(PackageWithAssemblyResult other) => PackageName.Equals(other.PackageName);
private static IVersionSpec GetVersionConstraint(IDictionary<PackageName, PackageReference> packageReferences, IPackage package) { IVersionSpec defaultVersionConstraint = VersionUtility.ParseVersionSpec(package.Version.ToString()); PackageReference packageReference; var key = new PackageName(package.Id, package.Version); if (!packageReferences.TryGetValue(key, out packageReference)) { return defaultVersionConstraint; } return packageReference.VersionConstraint ?? defaultVersionConstraint; }
public override int GetHashCode() => PackageName.GetHashCode();
public Task<IPackage> Exists(PackageName name) { throw new NotImplementedException(); }
string GenerateCommandLineCommands(string ManifestFile, string currentAbi, string currentResourceOutputFile) { var cmd = new CommandLineBuilder(); cmd.AppendSwitch("link"); if (MonoAndroidHelper.LogInternalExceptions) { cmd.AppendSwitch("-v"); } string manifestDir = Path.Combine(Path.GetDirectoryName(ManifestFile), currentAbi != null ? currentAbi : "manifest"); Directory.CreateDirectory(manifestDir); string manifestFile = Path.Combine(manifestDir, Path.GetFileName(ManifestFile)); ManifestDocument manifest = new ManifestDocument(ManifestFile, this.Log); manifest.SdkVersion = AndroidSdkPlatform; if (!string.IsNullOrEmpty(VersionCodePattern)) { try { manifest.CalculateVersionCode(currentAbi, VersionCodePattern, VersionCodeProperties); } catch (ArgumentOutOfRangeException ex) { Log.LogCodedError("XA0003", ManifestFile, 0, ex.Message); return(string.Empty); } } if (currentAbi != null && string.IsNullOrEmpty(VersionCodePattern)) { manifest.SetAbi(currentAbi); } if (!manifest.ValidateVersionCode(out string error, out string errorCode)) { Log.LogCodedError(errorCode, ManifestFile, 0, error); return(string.Empty); } manifest.ApplicationName = ApplicationName; manifest.Save(manifestFile); cmd.AppendSwitchIfNotNull("--manifest ", manifestFile); if (!string.IsNullOrEmpty(JavaDesignerOutputDirectory)) { var designerDirectory = Path.IsPathRooted(JavaDesignerOutputDirectory) ? JavaDesignerOutputDirectory : Path.Combine(WorkingDirectory, JavaDesignerOutputDirectory); Directory.CreateDirectory(designerDirectory); cmd.AppendSwitchIfNotNull("--java ", JavaDesignerOutputDirectory); } if (PackageName != null) { cmd.AppendSwitchIfNotNull("--custom-package ", PackageName.ToLowerInvariant()); } if (AdditionalResourceArchives != null) { foreach (var item in AdditionalResourceArchives) { var flata = Path.Combine(WorkingDirectory, item.ItemSpec); if (File.Exists(flata)) { cmd.AppendSwitchIfNotNull("-R ", flata); } else { Log.LogDebugMessage("Archive does not exist: " + flata); } } } if (CompiledResourceFlatArchive != null) { var flata = Path.Combine(WorkingDirectory, CompiledResourceFlatArchive.ItemSpec); if (File.Exists(flata)) { cmd.AppendSwitchIfNotNull("-R ", flata); } else { Log.LogDebugMessage("Archive does not exist: " + flata); } } cmd.AppendSwitch("--auto-add-overlay"); if (!string.IsNullOrWhiteSpace(UncompressedFileExtensions)) { foreach (var ext in UncompressedFileExtensions.Split(new char [] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries)) { cmd.AppendSwitchIfNotNull("-0 ", ext); } } if (!string.IsNullOrEmpty(ExtraPackages)) { cmd.AppendSwitchIfNotNull("--extra-packages ", ExtraPackages); } cmd.AppendSwitchIfNotNull("-I ", JavaPlatformJarPath); if (!string.IsNullOrEmpty(ResourceSymbolsTextFile)) { cmd.AppendSwitchIfNotNull("--output-text-symbols ", ResourceSymbolsTextFile); } if (ProtobufFormat) { cmd.AppendSwitch("--proto-format"); } var extraArgsExpanded = ExpandString(ExtraArgs); if (extraArgsExpanded != ExtraArgs) { Log.LogDebugMessage(" ExtraArgs expanded: {0}", extraArgsExpanded); } if (!string.IsNullOrWhiteSpace(extraArgsExpanded)) { cmd.AppendSwitch(extraArgsExpanded); } if (!string.IsNullOrWhiteSpace(AssetsDirectory)) { var assetDir = AssetsDirectory.TrimEnd('\\'); if (!Path.IsPathRooted(assetDir)) { assetDir = Path.Combine(WorkingDirectory, assetDir); } if (!string.IsNullOrWhiteSpace(assetDir) && Directory.Exists(assetDir)) { cmd.AppendSwitchIfNotNull("-A ", assetDir); } } cmd.AppendSwitchIfNotNull("-o ", currentResourceOutputFile); return(cmd.ToString()); }
public Task<Stream> GetStream(PackageName name, SemanticVersion version) { throw new NotImplementedException(); }
protected string GenerateCommandLineCommands(string ManifestFile, string currentAbi, string currentResourceOutputFile) { // For creating Resource.Designer.cs: // Running command: C:\Program Files (x86)\Android\android-sdk-windows\platform-tools\aapt // "package" // "-M" "C:\Users\Jonathan\AppData\Local\Temp\ryob4gaw.way\AndroidManifest.xml" // "-J" "C:\Users\Jonathan\AppData\Local\Temp\ryob4gaw.way" // "-F" "C:\Users\Jonathan\AppData\Local\Temp\ryob4gaw.way\resources.apk" // "-S" "c:\users\jonathan\documents\visual studio 2010\Projects\MonoAndroidApplication4\MonoAndroidApplication4\obj\Debug\res" // "-I" "C:\Program Files (x86)\Android\android-sdk-windows\platforms\android-8\android.jar" // "--max-res-version" "10" // For packaging: // Running command: C:\Program Files (x86)\Android\android-sdk-windows\platform-tools\aapt // "package" // "-f" // "-m" // "-M" "AndroidManifest.xml" // "-J" "src" // "--custom-package" "androidmsbuildtest.androidmsbuildtest" // "-F" "bin\packaged_resources" // "-S" "C:\Users\Jonathan\Documents\Visual Studio 2010\Projects\AndroidMSBuildTest\AndroidMSBuildTest\obj\Debug\res" // "-I" "C:\Program Files (x86)\Android\android-sdk-windows\platforms\android-8\android.jar" // "--extra-packages" "com.facebook.android:my.another.library" var cmd = new CommandLineBuilder(); cmd.AppendSwitch("package"); if (MonoAndroidHelper.LogInternalExceptions) { cmd.AppendSwitch("-v"); } if (NonConstantId) { cmd.AppendSwitch("--non-constant-id"); } cmd.AppendSwitch("-f"); cmd.AppendSwitch("-m"); string manifestFile; string manifestDir = Path.Combine(Path.GetDirectoryName(ManifestFile), currentAbi != null ? currentAbi : "manifest"); Directory.CreateDirectory(manifestDir); manifestFile = Path.Combine(manifestDir, Path.GetFileName(ManifestFile)); ManifestDocument manifest = new ManifestDocument(ManifestFile, this.Log); manifest.SdkVersion = AndroidSdkPlatform; if (currentAbi != null) { if (!string.IsNullOrEmpty(VersionCodePattern)) { manifest.CalculateVersionCode(currentAbi, VersionCodePattern, VersionCodeProperties); } else { manifest.SetAbi(currentAbi); } } else if (!string.IsNullOrEmpty(VersionCodePattern)) { manifest.CalculateVersionCode(null, VersionCodePattern, VersionCodeProperties); } manifest.ApplicationName = ApplicationName; manifest.Save(manifestFile); cmd.AppendSwitchIfNotNull("-M ", manifestFile); Directory.CreateDirectory(JavaDesignerOutputDirectory); cmd.AppendSwitchIfNotNull("-J ", JavaDesignerOutputDirectory); if (PackageName != null) { cmd.AppendSwitchIfNotNull("--custom-package ", PackageName.ToLowerInvariant()); } if (!string.IsNullOrEmpty(currentResourceOutputFile)) { cmd.AppendSwitchIfNotNull("-F ", currentResourceOutputFile + ".bk"); } // The order of -S arguments is *important*, always make sure this one comes FIRST cmd.AppendSwitchIfNotNull("-S ", ResourceDirectory.TrimEnd('\\')); if (AdditionalResourceDirectories != null) { foreach (var resdir in AdditionalResourceDirectories) { cmd.AppendSwitchIfNotNull("-S ", resdir.ItemSpec.TrimEnd('\\')); } } if (AdditionalAndroidResourcePaths != null) { foreach (var dir in AdditionalAndroidResourcePaths) { cmd.AppendSwitchIfNotNull("-S ", Path.Combine(dir.ItemSpec.TrimEnd(System.IO.Path.DirectorySeparatorChar), "res")); } } if (LibraryProjectJars != null) { foreach (var jar in LibraryProjectJars) { cmd.AppendSwitchIfNotNull("-j ", jar); } } cmd.AppendSwitchIfNotNull("-I ", JavaPlatformJarPath); // Add asset directory if it exists if (!string.IsNullOrWhiteSpace(AssetDirectory) && Directory.Exists(AssetDirectory)) { cmd.AppendSwitchIfNotNull("-A ", AssetDirectory.TrimEnd('\\')); } if (!string.IsNullOrWhiteSpace(UncompressedFileExtensions)) { foreach (var ext in UncompressedFileExtensions.Split(new char[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries)) { cmd.AppendSwitchIfNotNull("-0 ", ext); } } if (!string.IsNullOrEmpty(ExtraPackages)) { cmd.AppendSwitchIfNotNull("--extra-packages ", ExtraPackages); } // TODO: handle resource names if (ExplicitCrunch) { cmd.AppendSwitch("--no-crunch"); } cmd.AppendSwitch("--auto-add-overlay"); var extraArgsExpanded = ExpandString(ExtraArgs); if (extraArgsExpanded != ExtraArgs) { Log.LogDebugMessage(" ExtraArgs expanded: {0}", extraArgsExpanded); } if (!string.IsNullOrWhiteSpace(extraArgsExpanded)) { cmd.AppendSwitch(extraArgsExpanded); } if (!AndroidUseLatestPlatformSdk) { cmd.AppendSwitchIfNotNull("--max-res-version ", ApiLevel); } return(cmd.ToString()); }
public void BindingWorkflow_InstallPackages_Cancellation() { // Setup var testSubject = this.CreateTestSubject(); var progressEvents = new ConfigurableProgressStepExecutionEvents(); var cts = new CancellationTokenSource(); ProjectMock project1 = new ProjectMock("project1"); ProjectMock project2 = new ProjectMock("project2"); var nugetPackage = new PackageName("mypackage", new SemanticVersion("1.1.0")); var packages = new[] { nugetPackage }; ConfigurablePackageInstaller packageInstaller = this.PrepareInstallPackagesTest(testSubject, packages, project1, project2); packageInstaller.InstallPackageAction = (p) => { cts.Cancel(); // Cancel the next one (should complete the first one) }; // Act testSubject.InstallPackages(new ConfigurableProgressController(), cts.Token, progressEvents); // Verify packageInstaller.AssertInstalledPackages(project1, packages); packageInstaller.AssertNoInstalledPackages(project2); }
public PackageBlob(PackageName name, AzureBlob blob) { Name = name; Blob = blob; }
void AddFileToLocalRepositoryLookupPath (PackageReference packageReference, string filePath) { filePath = filePath.ToNativePath (); var packageName = new PackageName (packageReference.Id, packageReference.Version); repository.LocalPackageRepository.AddPackageLookupPath (packageName, filePath); }
/// <summary> /// The get package name. /// </summary> /// <param name="moduleInfo"> /// The module info. /// </param> /// <returns> /// The <see cref="PackageName" />. /// </returns> /// <exception cref="System.ArgumentNullException">The <paramref name="moduleInfo"/> is <c>null</c>.</exception> public static PackageName GetPackageName(this ModuleInfo moduleInfo) { Argument.IsNotNull(() => moduleInfo); return PackageNameCacheStorage.GetFromCacheOrFetch(moduleInfo, () => { string packageId; string packageVersion = string.Empty; string @ref = moduleInfo.Ref; if (@ref.Contains(',')) { var indexOf = @ref.IndexOf(','); packageId = @ref.Substring(0, indexOf).Trim(); packageVersion = @ref.Substring(indexOf + 1).Trim(); } else { packageId = @ref.Trim(); } PackageName packageName = null; if (!string.IsNullOrEmpty(packageId)) { try { Log.Debug("Initializing package name from Id:'{0}' and Version:'{1}'", packageId, packageVersion); packageName = new PackageName(packageId, string.IsNullOrEmpty(packageVersion) ? null : new SemanticVersion(packageVersion)); } catch (Exception e) { Log.Error(e); } } return packageName; }); }
void AddUpdatedPackageForProject (string packageId, string version) { var packageName = new PackageName (packageId, new SemanticVersion (version)); updatedPackagesInSolution.AddUpdatedPackages (project, packageName); }
IEnumerable <string> PackageFiles(string packageId, IVersion version = null) { return(fileSystem.EnumerateFilesRecursively(GetPackagesDirectory(), PackageName.ToSearchPatterns(packageId, version, supportedExtensions))); }
private void CopyNativeBinaries(IProjectSystem projectSystem, IFileSystem packagesFileSystem, PackageName packageName) { const string nativeBinariesFolder = "NativeBinaries"; string nativeBinariesPath = Path.Combine(packageName.Name, nativeBinariesFolder); if (packagesFileSystem.DirectoryExists(nativeBinariesPath)) { IEnumerable<string> nativeFiles = packagesFileSystem.GetFiles(nativeBinariesPath, "*.*", recursive: true); foreach (string file in nativeFiles) { string targetPath = Path.Combine(Constants.BinDirectory, file.Substring(nativeBinariesPath.Length + 1)); // skip over NativeBinaries/ word using (Stream stream = packagesFileSystem.OpenFile(file)) { projectSystem.AddFile(targetPath, stream); } } } }
private void BuildPlatformXml() { var doc = new XmlDocument(); var xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null); var root = doc.DocumentElement; doc.InsertBefore(xmlDeclaration, root); var rootNode = doc.CreateElement("platform"); var xmlns = doc.CreateAttribute("xmlns"); xmlns.Value = "http://ns.adobe.com/air/extension/19.0"; rootNode.Attributes.Append(xmlns); doc.AppendChild(rootNode); XmlNode packagedDependenciesNode = doc.CreateElement("packagedDependencies"); // rootJar XmlNode baseJarNode = doc.CreateElement("packagedDependency"); baseJarNode.AppendChild(doc.CreateTextNode($"{GroupId}-{ArtifactId}-{Version}.jar")); packagedDependenciesNode.AppendChild(baseJarNode); XmlNode packagedResourcesNode = doc.CreateElement("packagedResources"); if (HasResources) { XmlNode resourceNode = doc.CreateElement("packagedResource"); XmlNode packageNameNode = doc.CreateElement("packageName"); XmlNode folderNameNode = doc.CreateElement("folderName"); packageNameNode.AppendChild(PackageName != null ? doc.CreateTextNode($"{PackageName.Replace("-", ".")}") : doc.CreateTextNode($"{GroupId}.{ArtifactId}".Replace("-", "."))); folderNameNode.AppendChild(doc.CreateTextNode($"{GroupId}-{ArtifactId}-{Version}-res")); resourceNode.AppendChild(packageNameNode); resourceNode.AppendChild(folderNameNode); packagedResourcesNode.AppendChild(resourceNode); } foreach (var dependency in _dependencies) { XmlNode dependencyJarNode = doc.CreateElement("packagedDependency"); dependencyJarNode.AppendChild( doc.CreateTextNode($"{dependency.GroupId}-{dependency.ArtifactId}-{dependency.Version}.jar")); packagedDependenciesNode.AppendChild(dependencyJarNode); if (!dependency.HasResources) { continue; } XmlNode resourceNode = doc.CreateElement("packagedResource"); XmlNode packageNameNode = doc.CreateElement("packageName"); XmlNode folderNameNode = doc.CreateElement("folderName"); packageNameNode.AppendChild(dependency.PackageName != null ? doc.CreateTextNode($"{dependency.PackageName}") : doc.CreateTextNode($"{dependency.GroupId}-{dependency.ArtifactId}")); folderNameNode.AppendChild( doc.CreateTextNode($"{dependency.GroupId}-{dependency.ArtifactId}-{dependency.Version}-res")); resourceNode.AppendChild(packageNameNode); resourceNode.AppendChild(folderNameNode); packagedResourcesNode.AppendChild(resourceNode); } rootNode.AppendChild(packagedDependenciesNode); if (packagedResourcesNode.HasChildNodes) { rootNode.AppendChild(packagedResourcesNode); } doc.Save($"{BuildDirectory}/platforms/android/platform.xml"); }
public bool IsCurrentPackage(PackageName name) { return(CurrentPackage.name == name); }
private static string GetPackagePath(PackageName packageName) { return(string.Format("{0}/{1}/{0}.{1}.nupkg", packageName.Id, packageName.Version)); }
public void Parse(string path, string referencesXPathFilter, string packagesHintPathRegexSearchPattern, string libHintPathRegexSearchPattern, HashSet<IPackageName> packagesUsedInCsproj, string[] csporjReferenceExcludes, string addstring = null, string defaultVersion= null) { string hintPathRegexSearchPattern; string libPathPattern = @"^\.\.\\lib"; string packagesPathPattern = @"^\.\.\\packages"; XmlDocument projDefinition = new XmlDocument(); projDefinition.Load(path); XmlNamespaceManager nsmgr = new XmlNamespaceManager(projDefinition.NameTable); nsmgr.AddNamespace(_csprojNamespaceAlias, _csprojNamespace); var otherPackagesReferences = projDefinition.SelectNodes(referencesXPathFilter, nsmgr); if (otherPackagesReferences == null) { throw new Exception(String.Format("Packages not found for csproj {0} by filter {1}", path, referencesXPathFilter)); }; foreach (XmlElement reference in otherPackagesReferences) { XmlNode referenceNode = reference.SelectSingleNode("csprojNameSpace:HintPath", nsmgr); if (referenceNode != null) { if (csporjReferenceExcludes.Contains(referenceNode.InnerText)) { logger.Info(string.Format("Skipping reference {0} as it is in exclusion list", referenceNode.InnerText)); continue; } string datasourceAddstring = ""; string datasourceDefaultVersion = null; if (Regex.Matches(referenceNode.InnerText, libPathPattern, RegexOptions.IgnoreCase).Count != 0) { hintPathRegexSearchPattern = libHintPathRegexSearchPattern; datasourceAddstring = addstring; datasourceDefaultVersion = defaultVersion; } else if (Regex.Matches(referenceNode.InnerText, packagesPathPattern, RegexOptions.IgnoreCase).Count != 0) { hintPathRegexSearchPattern = packagesHintPathRegexSearchPattern; } else { //logger.Error(new Exception(string.Format("{0} does not fit neither {1} nor {2} pattern to search package names for", referenceNode.InnerText, packagesPathPattern, libPathPattern))); //continue; throw new Exception(string.Format("{0} does not fit neither {1} nor {2} pattern to search package names for", referenceNode.InnerText, packagesPathPattern, libPathPattern)); } var packagePath = referenceNode.InnerText; var matches = Regex.Matches(packagePath, hintPathRegexSearchPattern, RegexOptions.IgnoreCase); if (matches.Count == 0) { //logger.Error(new Exception(String.Format("Packages not found for csproj {0} by regex filter {1}", path, hintPathRegexSearchPattern))); //continue; throw new Exception(String.Format("Packages not found for csproj {0} by regex filter {1}", path, hintPathRegexSearchPattern)); } foreach (Match match in matches) { logger.Info(string.Format("parsed package with name {0} from {1}", match.Groups[1].Value, path)); var packageName = string.Format("{0}{1}", match.Groups[1].Value, datasourceAddstring); var version = datasourceDefaultVersion ?? match.Groups[2].Value; var pack = new PackageName(packageName, new SemanticVersion(version)); packagesUsedInCsproj.Add(pack); } } else { logger.Info(string.Format("skipping '{0}' reference for csproj {1}", reference.Attributes[0].Value, path)); } } }
void AddUpdatedPackageForProject(string packageId, string version) { var packageName = new PackageName(packageId, new SemanticVersion(version)); updatedPackagesInSolution.AddUpdatedPackages(project, packageName); }