public void LoadJsonManifestFrom_ReturnsNullIfExceptionThrownFromResourceStream() { var mockLogger = new Mock <Logger>(); Log.Default = mockLogger.Object; var mockException = new Exception(nameof(MockAssembly.ExceptionGetManifestResourceStream)); Assert.IsNull( ManifestLoader.LoadJsonManifestFrom( new MockAssembly { ExceptionGetManifestResourceStream = mockException, MockManifestResourceInfo = new Dictionary <string, ManifestResourceInfo> { { @"manifest.json", typeof(ManifestLoaderTest).Assembly.GetManifestResourceInfo( $@"{VirtualTestManifest.Namespace}.manifest.lowercase.json" ) } } } ) ); mockLogger.Verify(l => l.Warn(mockException, "Failed to load manifest.json from MockAssembly.")); }
public void FindManifest_ThrowsIfNoDelegates() { Assert.Throws <InvalidOperationException>( () => ManifestLoader.FindManifest(new MockAssembly()), $"{nameof( ManifestLoader.ManifestLoaderDelegates )} was initialized with no pre-registered delegates, or the pre-defined delegates were removed and no alternatives were added." ); }
public void LoadJsonManifestFrom_ReturnsNullIfStreamIsEmpty() { var mockLogger = new Mock <Logger>(); Log.Default = mockLogger.Object; var mockException = new InvalidDataException("Manifest is empty or failed to load and is null."); Assert.IsNull( ManifestLoader.LoadJsonManifestFrom( new MockAssembly { MockManifestResourceInfo = new Dictionary <string, ManifestResourceInfo> { { @"manifest.json", typeof(ManifestLoaderTest).Assembly.GetManifestResourceInfo( $@"{VirtualTestManifest.Namespace}.manifest.lowercase.json" ) } }, MockManifestResourceStream = new Dictionary <string, Stream> { { @"manifest.json", new MemoryStream() } } } ) ); mockLogger.Verify( l => l.Warn( It.Is <InvalidDataException>(e => e.Message == mockException.Message), "Failed to load manifest.json from MockAssembly." ) ); }
private void FastExit_Click(object sender, EventArgs e) { ManifestLoader.Delete(); this.MainPanel.Hide(); ControlActive.ShowAnima(this.Handle, 500, Enums.AnimateWindowFlags.AW_BLEND | Enums.AnimateWindowFlags.AW_HIDE); Application.Exit(); }
public void FindManifest_LoadsJsonManifest_Lowercase() { ManifestLoader.ManifestLoaderDelegates.Add(ManifestLoader.LoadJsonManifestFrom); var mockAssembly = new MockAssembly { MockManifestResourceInfo = new Dictionary <string, ManifestResourceInfo> { { @"manifest.json", typeof(ManifestLoaderTest).Assembly.GetManifestResourceInfo( $@"{VirtualTestManifest.Namespace}.manifest.lowercase.json" ) } }, MockManifestResourceStream = new Dictionary <string, Stream> { { @"manifest.json", typeof(ManifestLoaderTest).Assembly.GetManifestResourceStream( $@"{VirtualTestManifest.Namespace}.manifest.lowercase.json" ) } } }; var manifest = ManifestLoader.FindManifest(mockAssembly); Assert.IsTrue(manifest is JsonManifest); Assert.NotNull(manifest); Assert.AreEqual("Test Manifest", manifest.Name); Assert.AreEqual("AscensionGameDev.Intersect.Tests", manifest.Key); Assert.AreEqual(new SemVersion(1), manifest.Version); Assert.AreEqual("https://github.com/AscensionGameDev/Intersect-Engine", manifest.Homepage); }
private void ClipPurseFrm_Load(object sender, EventArgs e) { this.VersionSoft.Text = $"{Language.GlobalMessageStrings_ru_RU.VerSoftware} {GlobalPath.VersionBuild}"; this.SalutView.Text = $"{Language.GlobalMessageStrings_ru_RU.Welcome} {Environment.UserName}"; ControlActive.ControlVisible(this.MainPanel, new InfoSE()); MiniCcleaner(); ManifestLoader.Inizialize(); ControlActive.ShowAnima(this.Handle, 500, Enums.AnimateWindowFlags.AW_BLEND | Enums.AnimateWindowFlags.AW_ACTIVATE); }
public void TestManifestDetection() { var manifestType = typeof(Manifest); var pluginAssembly = manifestType.Assembly; var manifest = ManifestLoader.FindManifest(pluginAssembly); Assert.NotNull(manifestType); Assert.IsInstanceOf(manifestType, manifest); }
private static async Task <int> Execute(CommandArgument url, CommandOption dataFolder) { try { if (string.IsNullOrEmpty(url.Value)) { Console.WriteLine("Please specify a module url to install from"); return(1); } FoundryDataFolder foundryDataFolder; if (dataFolder.HasValue()) { foundryDataFolder = FoundryDataFolder.FromDirectoryPath(dataFolder.Value()); } else { foundryDataFolder = FoundryDataFolder.FromCurrentDirectory(); } if (foundryDataFolder == null) { return(1); } var manifestLoader = new ManifestLoader(); await foundryDataFolder.ReadAllManifests(manifestLoader); var manifest = await manifestLoader.FromUri(new Uri(url.Value)); if (manifest == null) { return(1); } var dependencyChain = new DependencyChain(); dependencyChain.AddCurrentlyInstalledDependencies(manifestLoader, foundryDataFolder); await dependencyChain.AddDependenciesFromManifest(manifestLoader, manifest); foreach (var dependency in dependencyChain.NeededDependencies) { Console.WriteLine(); var dependencyManifest = await dependency.GetFullManifest(manifestLoader); await dependencyManifest.Install(foundryDataFolder); } Console.WriteLine(); return(await manifest.Install(foundryDataFolder)); } catch (Exception e) { Console.Write(e.Message); return(1); } }
private Dictionary <string, ServiceFabricServiceProject> ExtractProjectReferences( string basePath, string buildOutputPathSuffix, XmlNode document, XmlNamespaceManager namespaceManager) { var projectReferences = new Dictionary <string, ServiceFabricServiceProject>(); var projects = document.SelectNodes("//x:ProjectReference/@Include", namespaceManager); foreach (var service in projects) { if (!(service is XmlAttribute)) { continue; } var attr = service as XmlAttribute; var projectFile = new FileInfo(Path.Combine(basePath, attr.Value)); var serviceProject = new ServiceFabricServiceProject { ProjectFolder = projectFile.Directory, ProjectFile = projectFile }; // TODO Ugly Asp.Net hack thing. ServiceFabricServiceProject projectInfo; string buildOutputPath; var projectFileContents = File.ReadAllText(projectFile.FullName, System.Text.Encoding.UTF8); if (projectFileContents.Contains("<Project Sdk=\"Microsoft.NET.Sdk.Web\">")) { var loader = new ManifestLoader <CoreProjectFile>(false); var projectModel = loader.Load(projectFile.FullName); var propertyGroup = projectModel.PropertyGroup[0]; buildOutputPath = Path.Combine(serviceProject.ProjectFolder.FullName, "bin", _baseConfig.BuildConfiguration, propertyGroup.TargetFramework, propertyGroup.RuntimeIdentifiers[0]); projectInfo = _appManifestHandler.ReadXml(serviceProject, buildOutputPath); projectInfo.IsAspNetCore = true; } else { buildOutputPath = Path.Combine(serviceProject.ProjectFolder.FullName, buildOutputPathSuffix); projectInfo = _appManifestHandler.ReadXml(serviceProject, buildOutputPath); projectInfo.IsAspNetCore = false; } projectReferences.Add(projectInfo.ServiceName, projectInfo); } return(projectReferences); }
public void FindManifest_ReturnsNullWhenNoManifestsFound() { ManifestLoader.ManifestLoaderDelegates.Add(ManifestLoader.LoadJsonManifestFrom); ManifestLoader.ManifestLoaderDelegates.Add(ManifestLoader.LoadVirtualManifestFrom); var mockAssembly = new MockAssembly { }; var manifest = ManifestLoader.FindManifest(mockAssembly); Assert.Null(manifest); }
public void IsVirtualManifestType() { Assert.IsFalse(ManifestLoader.IsVirtualManifestType(typeof(IllegalVirtualManifestAbstractClass))); Assert.IsFalse(ManifestLoader.IsVirtualManifestType(typeof(IllegalVirtualManifestDefinedClass))); Assert.IsFalse(ManifestLoader.IsVirtualManifestType(typeof(IllegalVirtualManifestGenericClass <string>))); Assert.IsFalse(ManifestLoader.IsVirtualManifestType(typeof(IllegalVirtualManifestInterface))); Assert.IsFalse( ManifestLoader.IsVirtualManifestType(typeof(IllegalVirtualManifestNoSupportedConstructorsClass)) ); Assert.IsTrue(ManifestLoader.IsVirtualManifestType(typeof(VirtualManifestValueType))); Assert.IsTrue(ManifestLoader.IsVirtualManifestType(typeof(VirtualTestManifest))); }
public void Test() { var loader = new ManifestLoader <CoreProjectFile>(false); var basePath = new DirectoryInfo(System.AppContext.BaseDirectory); var combined = Path.GetFullPath(Path.Combine(basePath.FullName, @"..\..\..\..\..\src\SFPackager\SFPackager.csproj")); var projModel = loader.Load(combined); Assert.NotEmpty(projModel.PropertyGroup); Assert.NotNull(projModel.PropertyGroup.First().TargetFramework); Assert.NotNull(projModel.PropertyGroup.First().RuntimeIdentifierRaw); Assert.NotEmpty(projModel.PropertyGroup.First().RuntimeIdentifiers); }
public ManifestEventFieldsLookup(IEnumerable <string> manifestFilePaths, LogErrorDelegate logErrorDelegate, bool verbose) { int taskEventNamesCollisionCount = 0; // constructing the lookup dictionary this.events = new Dictionary <Tuple <string, string>, Dictionary <string, FieldDefinition> >(); // iterating over all manifest files foreach (var manifestFile in manifestFilePaths) { ManifestLoader manifestLoader = new ManifestLoader(); ManifestDefinitionDescription manifestDefinitionDescription = manifestLoader.LoadManifest(manifestFile); // iterating over all providers in the manifest file foreach (var provider in manifestDefinitionDescription.Providers) { // including all events from the provider to the dictionary foreach (var ev in provider.Events.Values) { try { Dictionary <string, FieldDefinition> fieldDictionary = new Dictionary <string, FieldDefinition>(); this.events.Add(Tuple.Create(ev.TaskName, ev.EventName), fieldDictionary); // including all fields from the event foreach (var field in ev.Fields) { fieldDictionary.Add(field.Name, field); } } catch (Exception) { if (verbose) { logErrorDelegate(LogSourceId, "(TaskName: {0}, EventName: {1}) collision for UnparsedEventName: {2}", ev.TaskName, ev.EventName, ev.UnparsedEventName); } taskEventNamesCollisionCount++; } } } if (taskEventNamesCollisionCount > 0) { logErrorDelegate(LogSourceId, "Warning - Found {0} collisions on pairs (TaskName, EventName). Parser is using first occurence. For more details use verbose mode.", taskEventNamesCollisionCount); } } }
public void FindManifest_LoadsVirtualManifest() { ManifestLoader.ManifestLoaderDelegates.Add(ManifestLoader.LoadVirtualManifestFrom); var mockAssembly = new MockAssembly { MockTypes = new[] { typeof(VirtualTestManifest) } }; var manifest = ManifestLoader.FindManifest(mockAssembly); Assert.IsTrue(manifest is VirtualTestManifest); Assert.NotNull(manifest); Assert.AreEqual("Test Manifest", manifest.Name); Assert.AreEqual("AscensionGameDev.Intersect.Tests", manifest.Key); Assert.AreEqual(new SemVersion(1), manifest.Version); Assert.AreEqual("https://github.com/AscensionGameDev/Intersect-Engine", manifest.Homepage); }
public void LoadJsonManifestFrom_ReturnsNullIfExceptionThrownFromResourceInfo() { var mockLogger = new Mock <Logger>(); Log.Default = mockLogger.Object; var mockException = new Exception(nameof(MockAssembly.ExceptionGetManifestResourceInfo)); Assert.IsNull( ManifestLoader.LoadJsonManifestFrom( new MockAssembly { ExceptionGetManifestResourceInfo = mockException } ) ); mockLogger.Verify(l => l.Warn(mockException, "Failed to load manifest.json from MockAssembly.")); }
public void LoadVirtualManifestFrom_ReturnsNullIfExceptionThrown() { var mockLogger = new Mock <Logger>(); Log.Default = mockLogger.Object; var mockException = new Exception(nameof(MockAssembly.ExceptionGetTypes)); Assert.IsNull( ManifestLoader.LoadVirtualManifestFrom( new MockAssembly { ExceptionGetTypes = mockException } ) ); mockLogger.Verify(l => l.Warn(mockException, "Failed to load virtual manifest from MockAssembly.")); }
public ServiceHashCalculator( ConsoleWriter log, PackageConfig packageConfig, IHandleFiles fileHandler, ManifestHandler manifestHandler, ManifestLoader <ApplicationManifest> appManifestLoader, ManifestLoader <ServiceManifest> serviceManifestLoader, HandleEnciphermentCert handleEnciphermentCert, HandleEndpointCert handleEndpointCert) { _log = log; _packageConfig = packageConfig; _fileHandler = fileHandler; _manifestHandler = manifestHandler; _appManifestLoader = appManifestLoader; _serviceManifestLoader = serviceManifestLoader; _handleEnciphermentCert = handleEnciphermentCert; _handleEndpointCert = handleEndpointCert; }
private void RescanIfRequired() { if (Manifest == null) { Manifest = ManifestLoader.LoadDefaultManifest(); PluginsExt = ManifestLoader.LoadPlugins(Manifest); } directoryCatalog.Refresh(); var loadedFiles = directoryCatalog.LoadedFiles; var scannedFiles = Manifest?.ScannedAssemblies ?? Array.Empty <AssemblyInfo>(); var isRequireScan = loadedFiles.Count != scannedFiles.Length; if (!isRequireScan) { for (var i = 0; i < loadedFiles.Count; i++) { var loadedFileName = loadedFiles[i].ToLower(); var scannedFile = scannedFiles[i]; var loadedVersion = AssemblyName.GetAssemblyName(loadedFileName).Version.ToString(); var scannedVersion = scannedFile.Version; if (loadedFileName != scannedFile.Name.ToLower() || loadedVersion != scannedVersion) { isRequireScan = true; break; } } } if (isRequireScan) { LoadParts(); } if (Plugins == null) { Plugins = ManifestLoader.LoadPlugins <IPluginMetadata>(Manifest); } }
public void FindManifest_LogsErrorsIfAnExceptionIsThrownByDelegate() { var mockLogger = new Mock <Logger>(); Log.Default = mockLogger.Object; var mockException = new Exception("Delegate exception"); ManifestLoader.ManifestLoaderDelegates.Add(( Assembly assembly ) => throw mockException); var mockAssembly = new MockAssembly { }; var manifest = ManifestLoader.FindManifest(mockAssembly); Assert.Null(manifest); mockLogger.Verify( l => l.Error( It.Is <Exception>(e => e.Message == mockException.Message), "Exception thrown by manifest loader delegate." ) ); }
private void LoadParts(bool isRetry = false) { try { container.ComposeParts(this); Manifest = ManifestLoader.CreateManifest(Plugins.ToArray(), directoryCatalog); ManifestLoader.SaveManifest(Manifest); PluginsExt = ManifestLoader.LoadPlugins(Manifest); ValidatePlugins(); } catch { if (isRetry) { throw; } // rarely, an 'empty stack' error is thrown; let's rescan LoadParts(true); } }
private static async Task <int> Execute(CommandOption dataFolder) { try { FoundryDataFolder foundryDataFolder; if (dataFolder.HasValue()) { foundryDataFolder = FoundryDataFolder.FromDirectoryPath(dataFolder.Value()); } else { foundryDataFolder = FoundryDataFolder.FromCurrentDirectory(); } if (foundryDataFolder == null) { return(1); } var manifestLoader = new ManifestLoader(); var manifestsToUpdate = new List <Manifest>(); foreach (var manifest in await foundryDataFolder.ReadAllManifests(manifestLoader)) { Console.WriteLine(); Console.WriteLine($"Checking {manifest.Name} for updates"); var latestManifest = await GetLatestManifest(manifestLoader, manifest); if (latestManifest == null) { continue; } if (latestManifest.GetSemanticVersion() > manifest.GetSemanticVersion()) { Console.WriteLine($"Queuing update for {latestManifest.Name} from {manifest.GetSemanticVersion().ToNormalizedString()} to {latestManifest.GetSemanticVersion().ToNormalizedString()}"); manifestsToUpdate.Add(latestManifest); } } var dependencyChain = new DependencyChain(); dependencyChain.AddCurrentlyInstalledDependencies(manifestLoader, foundryDataFolder); foreach (var toUpdate in manifestsToUpdate) { await dependencyChain.AddDependenciesFromManifest(manifestLoader, toUpdate); } foreach (var dependency in dependencyChain.NeededDependencies) { Console.WriteLine(); var dependencyManifest = await dependency.GetFullManifest(manifestLoader); await dependencyManifest.Install(foundryDataFolder); } foreach (var toUpdate in manifestsToUpdate) { Console.WriteLine(); await toUpdate.Install(foundryDataFolder); } return(0); } catch (Exception e) { Console.WriteLine(e.Message); return(1); } }
public IEnumerator LoadManifest() { #if USE_DROPBOX mDropboxDict["background"] = "https://www.dropbox.com/s/yhqzu2tqhmhbex4/"; mDropboxDict["finalani_1"] = "https://www.dropbox.com/s/b431yjype0u4d6i/"; mDropboxDict["avatar_ch1"] = "https://www.dropbox.com/s/e4xgv0n2xorkhv7/"; mDropboxDict["avatar_ch2"] = "https://www.dropbox.com/s/joqklmteepjs5wm/"; #endif string manifestURL = string.Empty; #if USE_LOCAL #if UNITY_ANDROID mPlatform = "Android"; #else mPlatform = "StandaloneWindows"; #endif string basePath = string.Format("file://{0}/AssetBundles/{1}/", Application.dataPath, mPlatform); manifestURL = string.Format("{0}{1}.manifest", basePath, mPlatform); #endif #if USE_DROPBOX manifestURL = "https://www.dropbox.com/s/e8wxi1zrgn44yfl/AssetBundleList.txt?dl=1"; #endif UrlAppendTimeStamp(ref manifestURL); ManifestLoader mfLoader = new ManifestLoader(); ManifestRequest mr = new ManifestRequest(); mr.LoadPath = manifestURL; mr.LoadName = "Android"; yield return(LoadAssetHandler.Instance.StartCoroutine(mfLoader.DownloadProcess(mr, () => { return null; }))); #region parse json.txt to get asset list Dictionary <string, object> assetDict = (Dictionary <string, object>)MiniJSON.Json.Deserialize(mr.LoadRequest.downloadHandler.text); foreach (KeyValuePair <string, object> kv in assetDict) { AssetRequest asRq = new AssetRequest(); var key = kv.Key.ToString().ToLower(); var values = (List <object>)kv.Value; asRq.LoadName = key; asRq.H128 = Hash128.Parse(values[0].ToString()); asRq.CRC = uint.Parse(values[1].ToString()); mMainfestDict[asRq.LoadName] = asRq; } yield break; #endregion #region parse manifest to get asset list string[] lines = mr.LoadRequest.downloadHandler.text.Split(new string[] { "\n" }, StringSplitOptions.None); mAssetList = new List <string>(); foreach (var s in lines) { if (s.Contains("CRC: ")) { int startCatchIndex = s.IndexOf("CRC: ") + 5; uint latestCRC = uint.Parse(s.Substring(startCatchIndex, s.Length - startCatchIndex)); } if (s.Contains("Name: ")) { int startCatchIndex = s.LastIndexOf("Name: ") + 6; string asName = s.Substring(startCatchIndex, s.Length - startCatchIndex); if (!mAssetList.Contains(asName)) { mAssetList.Add(asName); } } } int requestCount = 0; if (mAssetList.Count > 0) { int assetCount = mAssetList.Count; List <ManifestLoader> mfLoadQueue = new List <ManifestLoader>(); foreach (var ms in mAssetList) { if (!mDropboxDict.ContainsKey(ms.ToLower())) { continue; } string asbManifestURL = string.Empty; #if USE_LOCAL asbManifestURL = string.Format("{0}{1}.manifest", basePath, ms); UrlAppendTimeStamp(ref asbManifestURL); #endif #if USE_DROPBOX asbManifestURL = string.Format("{0}{1}.manifest?dl=1", mDropboxDict[ms.ToLower()], ms.ToLower()); #endif ManifestLoader asbMfLoader = new ManifestLoader(); ManifestRequest mmr = new ManifestRequest(); mmr.LoadPath = asbManifestURL; mmr.LoadName = ms; LoadAssetHandler.Instance.StartCoroutine(asbMfLoader.DownloadProcess(mmr, () => { return(AsbMfLoader_OnComplete(mmr)); })); requestCount++; } } while (mMainfestDict.Count < requestCount) { yield return(null); } #endregion }
public void TestMultipleProvidersInManifest() { var manifestWithMultipleProviders = @"<?xml version='1.0' encoding='utf-8' standalone='yes'?> <assembly xmlns=""urn: schemas - microsoft - com:asm.v3""> <instrumentation> <events xmlns = ""http://schemas.microsoft.com/win/2004/08/events""> <provider guid = ""{cbd93bc2-71e5-4566-b3a7-595d8eeca6e8}"" message = ""$(string.ms1654592029.0)"" messageFileName = ""%ProgramFiles%\Windows Fabric\bin\Fabric\Fabric.Code\FabricResources.dll"" name = ""Microsoft-ServiceFabric"" resourceFileName = ""%ProgramFiles%\Windows Fabric\bin\Fabric\Fabric.Code\FabricResources.dll"" symbol = ""Microsoft_ServiceFabric"" > <events> <event channel=""Admin"" keywords = ""Default"" level = ""win:Error"" message = ""$(string.ns37.0)"" opcode = ""win:Info"" symbol = ""Event_Common_ErrorText"" task = ""Common"" template = ""ntid_256"" value = ""256"" /> </events> <templates> <template tid=""ntid_256""> <data inType = ""win:UnicodeString"" name = ""id"" outType = ""xs:string"" /> </template> </templates> <maps> <valueMap name=""AccessStatus""> <map message = ""$(string.ns0.1)"" value = ""0"" /> </valueMap> </maps> </provider> <provider guid = ""{c4a5f2a0-58bb-46be-a1b1-a9ac70c32af7}"" message = ""$(string.ms1654592029.0)"" messageFileName = ""%ProgramFiles%\Windows Fabric\bin\Fabric\Fabric.Code\FabricResources.dll"" name = ""Microsoft-ServiceFabric"" resourceFileName = ""%ProgramFiles%\Windows Fabric\bin\Fabric\Fabric.Code\FabricResources.dll"" symbol = ""Microsoft_ServiceFabric"" > <events> <event channel=""Admin"" keywords = ""Default"" level = ""win:Error"" message = ""$(string.ns37.0)"" opcode = ""win:Info"" symbol = ""Event_Common_ErrorText"" task = ""Common"" template = ""ntid_256"" value = ""256"" /> </events> <templates> <template tid=""ntid_256""> <data inType = ""win:UnicodeString"" name = ""id"" outType = ""xs:string"" /> </template> </templates> <maps> <valueMap name=""AccessStatus""> <map message = ""$(string.ns0.1)"" value = ""0"" /> </valueMap> </maps> </provider> </events> </instrumentation> <localization> <resources culture=""en - US""> <stringTable > <string id = ""ns0.1"" value = "" "" /> <string id=""ns37.0"" value = ""P"" /> </stringTable> </resources> </localization> </assembly> "; ManifestLoader loader = new ManifestLoader(); var description = loader.LoadManifest(new MemoryStream(Encoding.ASCII.GetBytes(manifestWithMultipleProviders))); Assert.IsTrue(description.Providers.Count == 2, "Not able to parse two proiders in same manifest."); }
private void AnalyzePackage(XtbPlugin plugin) { var files = plugin.Files; bool install = false, update = false, otherFilesFound = false; if (string.IsNullOrEmpty(plugin.MinimalXrmToolBoxVersion)) { plugin.Compatibilty = CompatibleState.Other; } else { plugin.Compatibilty = IsPluginDependencyCompatible(new Version(plugin.MinimalXrmToolBoxVersion)); } var currentVersion = new Version(int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue); var currentVersionFound = false; var manifest = ManifestLoader.LoadDefaultManifest(); foreach (var file in files) { if (Path.GetFileName(file).Length == 0) { continue; } var directoryName = Path.GetDirectoryName(file); if (directoryName == null) { continue; } if (directoryName.ToLower().EndsWith("plugins")) { // Only check version of files in the Plugins folder var existingPluginFile = plugins.FirstOrDefault(p => file.ToLower().EndsWith(p.Name.ToLower())); if (existingPluginFile == null) { install = true; } else { var pluginInfo = manifest.PluginMetadata .FirstOrDefault(p => p.AssemblyFilename.ToLower() == existingPluginFile.FullName.ToLower()); // If a file is found, we check version only if the file // contains classes that implement IXrmToolBoxPlugin if (pluginInfo == null) { otherFilesFound = true; continue; } var existingFileVersion = new Version(pluginInfo.Version); if (existingFileVersion < currentVersion) { currentVersion = existingFileVersion; currentVersionFound = true; } if (existingFileVersion < new Version(plugin.Version)) { update = true; } } } } if (currentVersionFound) { plugin.CurrentVersion = currentVersion; } if (otherFilesFound || update) { plugin.RequiresXtbRestart = true; } if (plugin.Compatibilty != CompatibleState.Compatible) { plugin.Action = PackageInstallAction.Unavailable; } else if (update) { plugin.Action = PackageInstallAction.Update; } else if (install) { plugin.Action = PackageInstallAction.Install; } else { plugin.Action = PackageInstallAction.None; } }
public void LoadVirtualManifestFrom_ReturnsNullIfNoTypes() { Assert.IsNull(ManifestLoader.LoadVirtualManifestFrom(new MockAssembly())); }
/// <summary> /// Perform JAR digital signature verification against a JAR filename on disk /// </summary> /// <param name="jar">JAR container. The caller is expected to dispose this type themselves - it will not be disposed /// by this method</param> /// <param name="certificates">certificate to verify / accept against</param> /// <param name="nonStandardCountCheck">whether to perform the additional file count verification check against /// MANIFEST.MF (recommended if the file is actually an arbitrary ZIP)</param> /// <returns>digital signature verification state of the JAR</returns> public static VerificationResult Jar(IJar jar, IVerificationCertificates certificates, bool nonStandardCountCheck = true) { // Unsigned ZIP and probably not even a JAR if (!jar.Contains(@"META-INF\MANIFEST.MF")) { return(new VerificationResult { Status = SigningStatus.NotSigned, Valid = false }); } IManifestLoader manifestLoader = new ManifestLoader(); ManifestData centralManifest = manifestLoader.Load(jar, @"META-INF\MANIFEST.MF"); if (nonStandardCountCheck) { // Non-standard check: Ensure that no unsigned files have been ADDED // to the JAR (file qty. [except signature itself] must match manifest entries) // int nonManifestFiles = jar.NonSignatureFiles().Count(); if (centralManifest.Entries.Count != nonManifestFiles) { Log.Message($"Expected {centralManifest.Entries.Count} file(s) found {nonManifestFiles}"); return(new VerificationResult { Status = SigningStatus.FundamentalHashMismatch, Valid = false }); } } // Verify the hashes of every file in the JAR // using (var h = new Hasher()) { Log.Message($"Central manifest contains {centralManifest.Entries.Count} entries"); foreach (ManifestEntry e in centralManifest.Entries) { Log.Message($"Digest check {e.Path} ({e.Digest})"); // Check each file matches the hash in the manifest if (jar.SHA256(h, e.Path).ToBase64() != e.Digest) { Log.Message($"{e.Path} has an incorrect digest"); return(new VerificationResult { Status = SigningStatus.FundamentalHashMismatch, Valid = false }); } } } // Detect signatures // // ISignatureFinder finder = new SignatureFinder(); List <Signature> signatures = finder.Find(jar); if (!signatures.Any()) { Log.Message("No signatures detected"); return(new VerificationResult { Status = SigningStatus.NotSigned, Valid = false }); } Log.Message($"{signatures.Count} signature(s) detected"); // Verify signatures // // SignatureVerifier ver = new SignatureVerifier(); if (ver.Verify(jar, centralManifest, signatures, certificates)) { return(new VerificationResult { Status = SigningStatus.SignedValid, Valid = true }); } else { return(new VerificationResult { Status = SigningStatus.SignedInvalid, Valid = false }); } }
public ManifestCache LoadManifests(string manifestPath, string cacheLocation, Version version) { string versionString = $"{version.Major}.{version.Minor}.{version.Build}.{version.Revision}"; if (ManifestCache == null) { ManifestCache = new ManifestCache(cacheLocation); } ManifestLoader manifest = new ManifestLoader(); if (Directory.Exists(manifestPath) && Directory.Exists(cacheLocation)) { List <string> manifestFiles = Directory.GetFiles(manifestPath, $"*{Constants.EtwManifestExtension}").ToList(); Log.Info("manifest files:", manifestFiles); if (version != new Version()) { manifestFiles = manifestFiles.Where(x => Regex.IsMatch(x, Regex.Escape(versionString))).ToList(); } else { Log.Info("getting latest version"); string versionPattern = @"_(\d+?\.\d+?\.\d+?\.\d+?)(?:_|\.)"; Version maxVersion = new Version(); List <string> versionedManifestFiles = manifestFiles.Where(x => Regex.IsMatch(x, versionPattern)).ToList(); List <string> unVersionedManifestFiles = manifestFiles.Where(x => !Regex.IsMatch(x, versionPattern)).ToList(); foreach (string file in versionedManifestFiles) { Version fileVersion = new Version(Regex.Match(file, versionPattern).Groups[1].Value); if (fileVersion > maxVersion) { Log.Info($"setting maxVersion:{maxVersion} -> {fileVersion}"); maxVersion = fileVersion; } } versionedManifestFiles = manifestFiles.Where(x => Regex.IsMatch(x, $@"_{maxVersion.Major}\.{maxVersion.Minor}\.{maxVersion.Build}\.{maxVersion.Revision}(?:_|\.)")).ToList(); unVersionedManifestFiles.AddRange(versionedManifestFiles); manifestFiles = unVersionedManifestFiles; } Log.Info("filtered manifest files:", ConsoleColor.Cyan, null, manifestFiles); foreach (string manifestFile in manifestFiles) { ManifestDefinitionDescription description = manifest.LoadManifest(manifestFile); List <ProviderDefinitionDescription> manifestProviderList = description.Providers.ToList(); if (!ManifestCache.ProviderDefinitions.Keys.Any(x => manifestProviderList.Any(y => y.Guid == x))) { ManifestCache.LoadManifest(manifestFile); } else { Log.Warning($"manifest already loaded:{manifestFile}"); } } } else { Log.Error($"manifest path does not exist:{manifestPath} or cachelocation does not exist:{cacheLocation}"); } return(ManifestCache); }
public void LoadJsonManifestFrom_ReturnsNullIfNoManifest() { Assert.IsNull(ManifestLoader.LoadJsonManifestFrom(new MockAssembly())); }