public void ResourceNotFoundWithContextTest() { var resourceManager = new ResourceManager("resources.pri.standalone"); resourceManager.ResourceNotFound += (sender, args) => { if (args.Name == "abc") { String value; if (args.Context.QualifierValues[KnownResourceQualifierName.Language].StartsWith("en-US")) { value = "USValue"; } else if (args.Context.QualifierValues[KnownResourceQualifierName.Language].StartsWith("en-GB")) { value = "GBValue"; } else { value = "OtherValue"; } var candidate = new ResourceCandidate(ResourceCandidateKind.String, value); args.SetResolvedCandidate(candidate); } }; var resourceContext = resourceManager.CreateResourceContext(); resourceContext.QualifierValues[KnownResourceQualifierName.Language] = "en-US"; var resourceMap = resourceManager.MainResourceMap.GetSubtree("resources"); var resourceCandidate = resourceMap.GetValue("abc", resourceContext); var resource = resourceCandidate.ValueAsString; Assert.AreEqual(resource, "USValue"); Assert.AreEqual(resourceCandidate.QualifierValues[KnownResourceQualifierName.Language], "en-US"); resourceContext.QualifierValues[KnownResourceQualifierName.Language] = "en-GB"; resourceCandidate = resourceMap.GetValue("abc", resourceContext); resource = resourceCandidate.ValueAsString; Assert.AreEqual(resource, "GBValue"); Assert.AreEqual(resourceCandidate.QualifierValues[KnownResourceQualifierName.Language], "en-GB"); resourceCandidate = resourceMap.TryGetValue("abc", resourceContext); resource = resourceCandidate.ValueAsString; Assert.AreEqual(resource, "GBValue"); Assert.AreEqual(resourceCandidate.QualifierValues[KnownResourceQualifierName.Language], "en-GB"); resourceContext.QualifierValues[KnownResourceQualifierName.Language] = "fr-FR"; resourceCandidate = resourceMap.GetValue("abc", resourceContext); resource = resourceCandidate.ValueAsString; Assert.AreEqual(resource, "OtherValue"); Assert.AreEqual(resourceCandidate.QualifierValues[KnownResourceQualifierName.Language], "fr-FR"); var ex = Assert.ThrowsException <Exception>(() => resourceMap.GetValue("xyz", resourceContext)); Assert.AreEqual((uint)ex.HResult, 0x80073b17); // HRESULT_FROM_WIN32(ERROR_MRM_NAMED_RESOURCE_NOT_FOUND) resourceCandidate = resourceMap.TryGetValue("xyz", resourceContext); Assert.IsNull(resourceCandidate); }
/// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="args">Details about the launch request and process.</param> protected override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args) { m_resourceLoader = new ResourceLoader(); m_resourceManager = new ResourceManager(); // Fall back to other resource loaders if the resource is not found in MRT, in this case .net. // This enables carrying forward existing assets without the need to convert them. m_resourceManager.ResourceNotFound += (sender, args) => { var candidate = new ResourceCandidate( ResourceCandidateKind.String, LegacyResources.ResourceManager.GetString(args.Name, LegacyResources.Culture)); args.SetResolvedCandidate(candidate); }; m_window = new MainWindow(m_resourceLoader, m_resourceManager); //Get the Window's HWND var windowNative = m_window.As <IWindowNative>(); m_window.Title = "MRT Core C# sample"; m_window.Activate(); // The Window object doesn't have Width and Height properties in WInUI 3 Desktop yet. // To set the Width and Height, you can use the Win32 API SetWindowPos. // Note, you should apply the DPI scale factor if you are thinking of DPI instead of pixels. SetWindowSize(windowNative.WindowHandle, 550, 500); }
public void ResourceNotFoundTest() { var resourceManager = new ResourceManager("resources.pri.standalone"); resourceManager.ResourceNotFound += (sender, args) => { if (args.Name == "abc") { var candidate = new ResourceCandidate(ResourceCandidateKind.String, "abcValue"); args.SetResolvedCandidate(candidate); } }; var resourceMap = resourceManager.MainResourceMap.GetSubtree("resources"); var resourceCandidate = resourceMap.GetValue("abc"); var resource = resourceCandidate.ValueAsString; Assert.AreEqual(resource, "abcValue"); resource = resourceMap.TryGetValue("abc").ValueAsString; Assert.AreEqual(resource, "abcValue"); var ex = Assert.ThrowsException <Exception>(() => resourceMap.GetValue("xyz")); Assert.AreEqual((uint)ex.HResult, 0x80073b17); // HRESULT_FROM_WIN32(ERROR_MRM_NAMED_RESOURCE_NOT_FOUND) resourceCandidate = resourceMap.TryGetValue("xyz"); Assert.IsNull(resourceCandidate); }
public void NoResourceFileTest() { var resourceManager = new ResourceManager("NoSuchFile.pri"); var resourceMap = resourceManager.MainResourceMap; var resourceChildMap = resourceMap.GetSubtree("anyname"); var resourceContext = resourceManager.CreateResourceContext(); Assert.IsTrue(resourceContext.QualifierValues.ContainsKey(KnownResourceQualifierName.Language)); // No resource file, and not handled by fallback var resourceCandidate = resourceMap.GetValue("abc"); Assert.IsNull(resourceCandidate); // add fallback handler resourceManager.ResourceNotFound += (sender, args) => { if (args.Name == "abc") { var candidate = new ResourceCandidate(ResourceCandidateKind.String, "abcValue"); args.SetResolvedCandidate(candidate); } }; resourceCandidate = resourceMap.GetValue("abc"); Assert.AreEqual(resourceCandidate.Kind, ResourceCandidateKind.String); Assert.AreEqual(resourceCandidate.ValueAsString, "abcValue"); resourceCandidate = resourceMap.GetValue("xyz"); Assert.IsNull(resourceCandidate); }
public static async Task WriteCodeFile(this IMatrixProject project, StorageFolder folder, IBuildService buildService) { // *** // *** Get the template from the resource file. // *** buildService.FireBuildEvent(BuildEventArgs.BuildEventType.Information, "Reading code template."); ResourceContext resourceContext = ResourceContext.GetForViewIndependentUse(); ResourceMap resourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("CodeBuilder/Code"); ResourceCandidate resourceValue = resourceMap.GetValue("cpp", resourceContext); string template = resourceValue.ValueAsString; // *** // *** Fill in the template parameters. // *** string contents = String.Format(template, project.Name, project.ColorMatrix.BackgroundColor.R, project.ColorMatrix.BackgroundColor.G, project.ColorMatrix.BackgroundColor.B, project.AccelerometerScaling, project.Elasticity, project.SortParticles.ToString().ToLower()); // *** // *** Write the file. // *** buildService.FireBuildEvent(BuildEventArgs.BuildEventType.Information, $"Writing C++ code file '{project.CppFileName()}'."); StorageFile file = await folder.CreateFileAsync(project.CppFileName(), CreationCollisionOption.ReplaceExisting); await FileIO.WriteTextAsync(file, contents, Windows.Storage.Streams.UnicodeEncoding.Utf8); }
private async void tsLocation_Toggled(object sender, RoutedEventArgs e) { _settings.IsLocationActivated = tsLocation.IsOn; if (tsLocation.IsOn && _geo == null) { // Initialise GeoLocator var access = await Geolocator.RequestAccessAsync(); switch (access) { case GeolocationAccessStatus.Allowed: _geo = new Geolocator(); _geo.DesiredAccuracy = PositionAccuracy.Default; tblLocationError.Text = ""; break; default: // There was a problem initialising GeoLocator // Show an error to the user ResourceCandidate resource = ResourceManager.Current.MainResourceMap.GetValue("Resources/uidLocationError", ResourceContext.GetForCurrentView()); tblLocationError.Text = resource.ValueAsString; // Turn off location toggle tsLocation.IsOn = false; break; } } // Update settings file Storage.SaveSettingsInIsoStorage(_settings); }
static void Main() { Application.SetHighDpiMode(HighDpiMode.SystemAware); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var resourceManager = new ResourceManager("winforms_unpackaged_app.pri"); // Fall back to other resource loaders if the resource is not found in MRT, in this case .net. // This enables carrying forward existing assets without the need to convert them. resourceManager.ResourceNotFound += (sender, args) => { var candidate = new ResourceCandidate( ResourceCandidateKind.String, LegacyResources.ResourceManager.GetString(args.Name, LegacyResources.Culture)); args.SetResolvedCandidate(candidate); }; var resourceLoader = new ResourceLoader(); // Create a custom resource context. Set the language to German. var overrideResourceContext = resourceManager.CreateResourceContext(); overrideResourceContext.QualifierValues["Language"] = "de-DE"; // The resource manager and the resource loader do disk I/O and should be centrally cached. // Since both end up loading the same file, ideally an app should only use one. // The resource manager is a superset of the resource loader in terms of functionality. Application.Run(new AppForm(resourceManager, resourceLoader, overrideResourceContext)); }
private TaskItem ProcessContentItem(ITaskItem asset, Func <ResourceCandidate, string> resourceToTargetPath, Func <string, string> pathEncoder) { if ( !asset.MetadataNames.OfType <string>().Contains("Link") && !asset.MetadataNames.OfType <string>().Contains("DefiningProjectDirectory") ) { Log.LogMessage($"Skipping '{asset.ItemSpec}' because 'Link' or 'DefiningProjectDirectory' metadata is not set."); return(null); } var fullPath = asset.GetMetadata("FullPath"); var relativePath = asset.GetMetadata("Link"); if (string.IsNullOrEmpty(relativePath)) { relativePath = fullPath.Replace(asset.GetMetadata("DefiningProjectDirectory"), ""); } if (IsImageAsset(asset.ItemSpec)) { var resourceCandidate = ResourceCandidate.Parse(fullPath, relativePath); if (!UseHighDPIResources && int.TryParse(resourceCandidate.GetQualifierValue("scale"), out var scale) && scale > HighDPIThresholdScale) { Log.LogMessage($"Skipping '{asset.ItemSpec}' of scale {scale} because {nameof(UseHighDPIResources)} is false."); return(null); } var targetPath = resourceToTargetPath(resourceCandidate); if (targetPath == null) { Log.LogMessage($"Skipping '{asset.ItemSpec}' as it's not supported on {TargetPlatform}."); return(null); } Log.LogMessage($"Retargeting image '{asset.ItemSpec}' to '{targetPath}'."); return(new TaskItem( asset.ItemSpec, new Dictionary <string, string>() { { "LogicalName", targetPath }, { "AssetType", "image" } })); } else { var encodedRelativePath = pathEncoder(relativePath); Log.LogMessage($"Retargeting generic '{asset.ItemSpec}' to '{encodedRelativePath}'."); return(new TaskItem( asset.ItemSpec, new Dictionary <string, string>() { { "LogicalName", encodedRelativePath }, { "AssetType", "generic" } })); } }
private void OnUseContext(object sender, RoutedEventArgs e) { ResourceMap map = _resourceManager.MainResourceMap; ResourceCandidate candidate = map.TryGetValue("Resources/GoodEvening", _resourceContext); textGoodEvening.Text = candidate.ValueAsString; }
private IEnumerable <ITaskItem> GetResourcesForItem(ITaskItem resource) { this.Log().Info("Resources file found : {0}".InvariantCultureFormat(resource.ItemSpec)); var resourceCandidate = ResourceCandidate.Parse(resource.ItemSpec, resource.ItemSpec); var language = resourceCandidate.GetQualifierValue("language"); if (language == null) { // TODO: Add support for resources without a language qualifier this.Log().Info("No language found, resources ignored"); yield break; } this.Log().Info("Language found : {0}".InvariantCultureFormat(language)); var resourceFile = resource.ItemSpec; var sourceLastWriteTime = new FileInfo(resourceFile).LastWriteTimeUtc; var resources = WindowsResourcesReader.Read(resourceFile); var comment = CommentPattern.InvariantCultureFormat(this.GetType().Name, resourceFile); this.Log().Info("{0} resources found".InvariantCultureFormat(resources.Count)); if (TargetPlatform == "android") { yield return(GenerateAndroidResources(language, sourceLastWriteTime, resources, comment)); } else if (TargetPlatform == "ios") { yield return(GenerateiOSResources(language, sourceLastWriteTime, resources, comment)); } yield return(GenerateUnoPRIResources(language, sourceLastWriteTime, resources, comment)); }
// Obtains a resource string given the name of the string resource, and optional starting // and neutral resource cultures (e.g. "de-DE"). // Thread-safe provided that the call to Initialize() happened only once on one thread // and has already completed successfully, and that the WinRT APIs called below // continue to be thread-safe. // Throws exceptions public override String GetString(String stringName, String startingCulture, String neutralResourcesCulture) { Debug.Assert(stringName != null); Debug.Assert(_resourceMap != null); // Should have been initialized by now ResourceCandidate resourceCandidate = null; stringName = UriUtility.UriEncode(stringName); if (startingCulture == null && neutralResourcesCulture == null) { #pragma warning disable 618 resourceCandidate = _resourceMap.GetValue(stringName); #pragma warning restore 618 } else { Debug.Assert(_clonedResourceContext != null); // Should have been initialized by now Debug.Assert(_clonedResourceContextFallBackList != null); // Should have been initialized by now Debug.Assert(s_globalResourceContextFallBackList != null); // Should have been initialized by now Debug.Assert(s_globalResourceContextFallBackList.Length > 0); // Should never be empty // We need to modify the culture fallback list used by the Modern Resource Manager // The starting culture has to be looked up first, and neutral resources culture has // to be looked up last. string newResourceFallBackList = null; newResourceFallBackList = (startingCulture == null ? "" : startingCulture + ";") + s_globalResourceContextFallBackList + // Our tests do not test this line of code, so be extra careful if you modify or move it. (neutralResourcesCulture == null ? "" : ";" + neutralResourcesCulture); lock (_clonedResourceContext) { // s_globalResourceContextFallBackList may have changed on another thread by now. // We cannot prevent that from happening because it may have happened on a native // thread, and we do not share the same lock mechanisms with native code. // The worst that can happen is that a string is unexpectedly missing // or in the wrong language. if (!String.Equals(newResourceFallBackList, _clonedResourceContextFallBackList, StringComparison.Ordinal)) { _clonedResourceContext.Languages = StringToReadOnlyList(newResourceFallBackList); _clonedResourceContextFallBackList = newResourceFallBackList; } resourceCandidate = _resourceMap.GetValue(stringName, _clonedResourceContext); } } if (resourceCandidate != null) { return(resourceCandidate.ValueAsString); } return(null); }
public override bool Execute() { LogExtensionPoint.AmbientLoggerFactory.AddProvider(new TaskLoggerProvider(Log)); this.Log().Info("Generating resources for platform : {0}".InvariantCultureFormat(TargetPlatform)); try { GeneratedFiles = Resources // TODO: Add support for other resources file names .Where(resource => resource.ItemSpec?.EndsWith("Resources.resw") ?? false) // TODO: Merge duplicates (based on file name and qualifiers) .Select(resource => { this.Log().Info("Resources file found : {0}".InvariantCultureFormat(resource.ItemSpec)); var resourceCandidate = ResourceCandidate.Parse(resource.ItemSpec, resource.ItemSpec); var language = resourceCandidate.GetQualifierValue("language"); if (language == null) { // TODO: Add support for resources without a language qualifier this.Log().Info("No language found, resources ignored"); return(null); } this.Log().Info("Language found : {0}".InvariantCultureFormat(language)); var resourceFile = resource.ItemSpec; var sourceLastWriteTime = new FileInfo(resourceFile).LastWriteTimeUtc; var resources = WindowsResourcesReader.Read(resourceFile); var comment = CommentPattern.InvariantCultureFormat(this.GetType().Name, resourceFile); this.Log().Info("{0} resources found".InvariantCultureFormat(resources.Count)); if (TargetPlatform == "android") { return(GenerateAndroidResources(language, sourceLastWriteTime, resources, comment)); } else if (TargetPlatform == "ios") { return(GenerateiOSResources(language, sourceLastWriteTime, resources, comment)); } return(null); }) .Trim() .ToArray(); return(true); } catch (Exception ex) { this.Log().Error($"Failed to generate resources. Details: {ex.Message}"); } return(false); }
public void When_Parse(string relativePath, string logicalPath, string scale, string language, string custom) { var resourceCandidate = ResourceCandidate.Parse(null, relativePath); Assert.AreEqual(logicalPath, resourceCandidate.LogicalPath); Assert.AreEqual(scale, resourceCandidate.GetQualifierValue("scale")); Assert.AreEqual(language, resourceCandidate.GetQualifierValue("language")); Assert.AreEqual(custom, resourceCandidate.GetQualifierValue("custom")); }
public override bool Execute() { LogExtensionPoint.AmbientLoggerFactory.AddProvider(new TaskLoggerProvider(Log)); this.Log().Info($"Retargeting UWP assets to {TargetPlatform}."); Func<ResourceCandidate, string> resourceToTargetPath; switch (TargetPlatform) { case "ios": resourceToTargetPath = resource => iOSResourceConverter.Convert(resource, DefaultLanguage); break; case "android": resourceToTargetPath = resource => AndroidResourceConverter.Convert(resource, DefaultLanguage); break; default: this.Log().Info($"Skipping unknown platform {TargetPlatform}"); return true; } Assets = ContentItems.Where(content => IsAsset(content.ItemSpec)).ToArray(); RetargetedAssets = Assets .Select(asset => { if (!asset.MetadataNames.Contains("Link")) { this.Log().Info($"Skipping '{asset.ItemSpec}' because 'Link' metadata is not set."); return null; } var fullPath = asset.GetMetadata("FullPath"); var relativePath = asset.GetMetadata("Link"); var resourceCandidate = ResourceCandidate.Parse(fullPath, relativePath); if (!UseHighDPIResources && int.TryParse(resourceCandidate.GetQualifierValue("scale"), out var scale) && scale > HighDPIThresholdScale) { this.Log().Info($"Skipping '{asset.ItemSpec}' of scale {scale} because {nameof(UseHighDPIResources)} is false."); return null; } var targetPath = resourceToTargetPath(resourceCandidate); if (targetPath == null) { this.Log().Info($"Skipping '{asset.ItemSpec}' as it's not supported on {TargetPlatform}."); return null; } this.Log().Info($"Retargeting '{asset.ItemSpec}' to '{targetPath}'."); return new TaskItem(asset.ItemSpec, new Dictionary<string, string>() { { "LogicalName", targetPath } }); }) .Trim() .ToArray(); return true; }
public string LocalizedStringOf(string key) { try { ResourceCandidate resource = ResourceManager.Current.MainResourceMap.GetValue("Resources/" + key + "/text", ResourceContext.GetForCurrentView()); return(resource.ValueAsString); } catch (Exception) { return("[" + key + "]"); } }
public MainPage() { this.InitializeComponent(); ResourceCandidate rc = ResourceManager.Current.MainResourceMap.GetValue("Resources/txtDiff/Text", ResourceContext.GetForCurrentView()); string foreground = rc.ValueAsString; try { //try to set the user name from local settings ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings; if (localSettings.Values["usrName"] != null) { App.usrName = (String)localSettings.Values["usrName"]; } //if not saved, user name defaults to User Name else { App.usrName = "User Name"; localSettings.Values["usrName"] = App.usrName; } //same as above, but with difficulty setting if (localSettings.Values["difficulty"] != null) { App.gmDifficulty = (int)localSettings.Values["difficulty"]; } //if not saved, user name defaults to User Name else { App.gmDifficulty = 4; localSettings.Values["difficulty"] = App.gmDifficulty; } } catch (Exception settingNotFound) { //user name defaults to "User Name" string errMsg = settingNotFound.Message; App.usrName = "User Name"; App.gmDifficulty = 4; } //loading the sources of the card images into memory App.posCard = new BitmapImage(new Uri(base.BaseUri, "/Resources/CardPos.png")); App.negCard = new BitmapImage(new Uri(base.BaseUri, "/Resources/CardNeg.png")); App.deckCard = new BitmapImage(new Uri(base.BaseUri, "/Resources/DeckCard.png")); //populate the card pool Card[] pool = createCardPool(); //create new AI and user objects en = new SkyNet(pool, "AI"); pl = new User(pool, App.usrName); }
public static string Translate(this string src) { Contract.Requires(src != null); ResourceCandidate res = ResourceMap.GetValue(src, ResourceContext); if (res == null) { return($"!!{src}!!"); } return(res.IsMatchAsDefault ? res.ValueAsString.ToPseudo() : res.ValueAsString); }
public void When_Convert(string expectedPath, string logicalPath, int?scale, string language, string custom) { var qualifiers = new List <ResourceQualifier> { new ResourceQualifier("scale", scale?.ToString()), new ResourceQualifier("language", language), new ResourceQualifier("custom", custom) } .AsReadOnly(); var resourceCandidate = new ResourceCandidate(qualifiers, null, logicalPath); var actualPath = AndroidResourceConverter.Convert(resourceCandidate, DefaultLanguage); Assert.AreEqual(expectedPath, actualPath); }
public void ResourceNotFoundWithContextTest() { var resourceManager = new ResourceManager("resources.pri.standalone"); resourceManager.ResourceNotFound += (sender, args) => { if (args.Name == "abc") { String value; if (args.Context.QualifierValues[KnownResourceQualifierName.Language].StartsWith("en-US")) { value = "USValue"; } else if (args.Context.QualifierValues[KnownResourceQualifierName.Language].StartsWith("en-GB")) { value = "GBValue"; } else { value = "OtherValue"; } var candidate = new ResourceCandidate(ResourceCandidateKind.String, value); args.SetResolvedCandidate(candidate); } }; var resourceContext = resourceManager.CreateResourceContext(); resourceContext.QualifierValues[KnownResourceQualifierName.Language] = "en-US"; var resourceMap = resourceManager.MainResourceMap.GetSubtree("resources"); var resourceCandidate = resourceMap.GetValue(resourceContext, "abc"); var resource = resourceCandidate.ValueAsString; Assert.AreEqual(resource, "USValue"); Assert.AreEqual(resourceCandidate.QualifierValues[KnownResourceQualifierName.Language], "en-US"); resourceContext.QualifierValues[KnownResourceQualifierName.Language] = "en-GB"; resourceCandidate = resourceMap.GetValue(resourceContext, "abc"); resource = resourceCandidate.ValueAsString; Assert.AreEqual(resource, "GBValue"); Assert.AreEqual(resourceCandidate.QualifierValues[KnownResourceQualifierName.Language], "en-GB"); resourceContext.QualifierValues[KnownResourceQualifierName.Language] = "fr-FR"; resourceCandidate = resourceMap.GetValue(resourceContext, "abc"); resource = resourceCandidate.ValueAsString; Assert.AreEqual(resource, "OtherValue"); Assert.AreEqual(resourceCandidate.QualifierValues[KnownResourceQualifierName.Language], "fr-FR"); }
public void ResourceNotFoundTest() { var resourceManager = new ResourceManager("resources.pri.standalone"); resourceManager.ResourceNotFound += (sender, args) => { if (args.Name == "abc") { var candidate = new ResourceCandidate(ResourceCandidateKind.String, "abcValue"); args.SetResolvedCandidate(candidate); } }; var resourceMap = resourceManager.MainResourceMap.GetSubtree("resources"); var resourceCandidate = resourceMap.GetValue("abc"); var resource = resourceCandidate.ValueAsString; Assert.AreEqual(resource, "abcValue"); }
public static async Task WriteInstructionsFile(this IMatrixProject project, StorageFolder folder, IBuildService buildService) { buildService.FireBuildEvent(BuildEventArgs.BuildEventType.Information, "Reading instructions template."); ResourceContext resourceContext = ResourceContext.GetForViewIndependentUse(); ResourceMap resourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("CodeBuilder/Code"); ResourceCandidate resourceValue = resourceMap.GetValue("instructions", resourceContext); string template = resourceValue.ValueAsString; string contents = String.Format(template, project.CppFileName(), project.HeaderFileName(), project.MakeFileName(), project.Name); buildService.FireBuildEvent(BuildEventArgs.BuildEventType.Information, $"Writing instructions file '{project.InstructionsFileName()}'."); StorageFile file = await folder.CreateFileAsync(project.InstructionsFileName(), CreationCollisionOption.ReplaceExisting); await FileIO.WriteTextAsync(file, contents, Windows.Storage.Streams.UnicodeEncoding.Utf8); }
/// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="args">Details about the launch request and process.</param> protected override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args) { m_resourceLoader = new ResourceLoader(); m_resourceManager = new ResourceManager(); // Fall back to other resource loaders if the resource is not found in MRT, in this case .net. // This enables carrying forward existing assets without the need to convert them. m_resourceManager.ResourceNotFound += (sender, args) => { var candidate = new ResourceCandidate( ResourceCandidateKind.String, LegacyResources.ResourceManager.GetString(args.Name, LegacyResources.Culture)); args.SetResolvedCandidate(candidate); }; m_window = new MainWindow(m_resourceLoader, m_resourceManager); m_window.Activate(); }
private async void ReadCredentials() { ResourceContext rc = ResourceContext.GetForViewIndependentUse(); ResourceMap map = ResourceManager.Current.MainResourceMap; ResourceCandidate resource = map.GetValue("Files/Assets/api_credentials.json", rc); Debug.WriteLine("I am in the constructor!!"); Debug.WriteLine(resource.ValueAsString); Stream file = (await resource.GetValueAsStreamAsync()).AsStreamForRead(); file.Position = 0; byte[] bytes = new byte[file.Length]; Debug.WriteLine("File Length is : " + file.Length); file.Read(bytes, 0, (int)file.Length); String json = System.Text.Encoding.UTF8.GetString(bytes); int index = json.IndexOf('{'); json = json.Substring(index); JsonObject creds = JsonObject.Parse(json); clientID = creds.GetNamedString("clientID"); clientSecret = creds.GetNamedString("clientSecret"); }
private void AppStartup(object sender, StartupEventArgs e) { m_resourceLoader = new ResourceLoader(); m_resourceManager = new ResourceManager(); // Fall back to other resource loaders if the resource is not found in MRT, in this case .net. // This enables carrying forward existing assets without the need to convert them. m_resourceManager.ResourceNotFound += (sender, args) => { var candidate = new ResourceCandidate( ResourceCandidateKind.String, LegacyResources.ResourceManager.GetString(args.Name, LegacyResources.Culture)); args.SetResolvedCandidate(candidate); }; m_window = new MainWindow(m_resourceLoader, m_resourceManager); m_window.Show(); this.InitializeComponent(); }
public void NoResourceFileTest() { var resourceManager = new ResourceManager("NoSuchFile.pri"); var resourceMap = resourceManager.MainResourceMap; var resourceChildMap = resourceMap.GetSubtree("anyname"); var resourceContext = resourceManager.CreateResourceContext(); Assert.IsTrue(resourceContext.QualifierValues.ContainsKey(KnownResourceQualifierName.Language)); // No resource file, and not handled by fallback var ex = Assert.ThrowsException <Exception>(() => resourceMap.GetValue("abc")); Assert.AreEqual((uint)ex.HResult, 0x80070490); // HRESULT_FROM_WIN32(ERROR_NOT_FOUND) var resourceCandidate = resourceMap.TryGetValue("abc"); Assert.IsNull(resourceCandidate); // add fallback handler resourceManager.ResourceNotFound += (sender, args) => { if (args.Name == "abc") { var candidate = new ResourceCandidate(ResourceCandidateKind.String, "abcValue"); args.SetResolvedCandidate(candidate); } }; resourceCandidate = resourceMap.GetValue("abc"); Assert.AreEqual(resourceCandidate.Kind, ResourceCandidateKind.String); Assert.AreEqual(resourceCandidate.ValueAsString, "abcValue"); resourceCandidate = resourceMap.TryGetValue("abc"); Assert.AreEqual(resourceCandidate.Kind, ResourceCandidateKind.String); Assert.AreEqual(resourceCandidate.ValueAsString, "abcValue"); ex = Assert.ThrowsException <Exception>(() => resourceMap.GetValue("xyz")); Assert.AreEqual((uint)ex.HResult, 0x80070490); // HRESULT_FROM_WIN32(ERROR_NOT_FOUND) resourceCandidate = resourceMap.TryGetValue("xyz"); Assert.IsNull(resourceCandidate); }
private IEnumerable <ITaskItem> GetResourcesForItem(ITaskItem resource) { Log.LogMessage($"Resources file found : {resource.ItemSpec}"); var resourceCandidate = ResourceCandidate.Parse(resource.ItemSpec, resource.ItemSpec); var language = resourceCandidate.GetQualifierValue("language"); if (language == null) { // TODO: Add support for resources without a language qualifier Log.LogMessage("No language found, resources ignored"); yield break; } Log.LogMessage($"Language found : {language}"); var resourceFile = resource.ItemSpec; var sourceLastWriteTime = new FileInfo(resourceFile).LastWriteTimeUtc; var resources = WindowsResourcesReader.Read(resourceFile); var comment = string.Format(CultureInfo.InvariantCulture, CommentPattern, this.GetType().Name, resourceFile); Log.LogMessage($"{resources.Count} resources found"); if (Path.GetFileNameWithoutExtension(resource.ItemSpec).Equals("Resources", StringComparison.OrdinalIgnoreCase)) { if (TargetPlatform == "android") { yield return(GenerateAndroidResources(language, sourceLastWriteTime, resources, comment, resource)); } else if (TargetPlatform == "ios") { yield return(GenerateiOSResources(language, sourceLastWriteTime, resources, comment)); } } yield return(GenerateUnoPRIResources(language, sourceLastWriteTime, resources, comment, resource)); }
// Adapted from https://docs.microsoft.com/en-us/windows/uwp/maps-and-location/display-poi#add-a-mapicon private void AddPointsToMap() { ResourceCandidate resource = ResourceManager.Current.MainResourceMap.GetValue("Resources/uidPhoto", ResourceContext.GetForCurrentView()); int i = 0; // Create a MapIcon for each Geopoint in list foreach (Geopoint point in _coordinates) { MapIcon mapIcon = new MapIcon(); mapIcon.Location = point; mapIcon.NormalizedAnchorPoint = new Point(0.5, 1.0); mapIcon.ZIndex = 0; mapIcon.Title = resource.ValueAsString + " " + (i + 1); // Add the MapIcon to the map MapControl.MapElements.Add(mapIcon); i++; } MapControl.MapElementClick += MapControl_MapElementClick; }
public string GetLocalizedValue(object value, string suffix, CultureIdentifier culture, params object[] args) { if (value == null) { return("<!! NULL !!>"); } ILocalizable localizableValue = value as ILocalizable; string localizedValue; object valueKey = Tuple.Create(value, suffix); if (!localizedValueMap.TryGetValue(valueKey, out localizedValue)) { string valueType = value.GetType().Name; string valueName = value.ToString(); Enum enumValue = value as Enum; bool isFlags = enumValue != null && enumValue.GetType().GetTypeInfo().GetCustomAttributes <FlagsAttribute>().Any(); if (isFlags && ((int)value) != 0) { List <string> localizedEnumParts = new List <string>(); foreach (var flag in Enum.GetValues(enumValue.GetType())) { if (((int)flag != 0) && enumValue.HasFlag((Enum)flag)) { localizedEnumParts.Add(GetRawLocalizedValue(flag, culture)); } } localizedValue = string.Join(", ", localizedEnumParts); } else if (localizableValue != null) { // If it's localized, then we'll let them determine // the appropriate way to get the raw localized value localizedValue = localizableValue.ToString(this); } else { string localizedValueKey = string.Format("{0}_{1}", valueType, valueName); if (!string.IsNullOrWhiteSpace(suffix)) { localizedValueKey = localizedValueKey + "_" + suffix; } #if NETFX_CORE ResourceContext context = new ResourceContext(); context.Languages = new string[] { ResolveCulture(culture).ToString() }; ResourceCandidate localizedCandidate = map.GetValue(localizedValueKey, context); if (localizedCandidate == null) { System.Diagnostics.Debug.WriteLine($"Unable to find localized value {localizedValueKey}"); } localizedValue = localizedCandidate?.ValueAsString ?? "!! Missing Resource for " + localizedValueKey + " !!"; #else localizedValue = this.ResourceLoader.GetString(localizedValueKey, ResolveCulture(culture)) ?? "!! Missing Resource for " + localizedValueKey + " !!"; #endif } localizedValueMap[valueKey] = localizedValue; } if (localizableValue != null) { args = args == null || args.Length == 0 ? localizableValue.LocalizedContext : args; } if (args != null && args.Length > 0) { return(string.Format(localizedValue, args)); } return(localizedValue); }
/// <summary> /// Provides an implementation of the AppDomain.AssemblyResolve handler that /// will attempt to lookup .NET Satellite Assemblies that have been re-packaged /// as MRT Resource Packs. /// Note that if you already use the AssemblyResolve handler to perform other /// assembly look-up tasks, you will need to incorporate this code into your /// existing handler /// </summary> /// <param name="sender">Unused</param> /// <param name="args">Information about the assembly that failed to load</param> /// <returns>The newly-loaded assembly, or null if it can't be found</returns> internal static Assembly AssemblyResolveHandler(object sender, ResolveEventArgs args) { Debug.WriteLine("---- Begin AssemblyResolve event handler ----"); Debug.WriteLine(string.Format("Requested Assembly='{0}'", args.Name)); // First, we need to get the base filename and language from the full assembly name string. // It's of the form "AssemblyName, Version=a.b.c.d, Culture=xx-yy, PublicKeyToken=xxxx, etc." // We don't need to parse it by hand; the AssemblyName class will do it for us AssemblyName fullAssemblyName = new AssemblyName(args.Name); string desiredAssemblyName = fullAssemblyName.Name; string desiredCulture = fullAssemblyName.CultureName; Debug.WriteLine("Requested Assembly Name='{0}', language='{1}'", desiredAssemblyName, desiredCulture); // The only expected exceptions are for use in a non-AppX context (when the app is sharing // code with (eg) a Windows 7 desktop app) or for missing fallback resources. try { // A ResourceContext includes things like the current language, scale factor etc. // In a normal UWP you would use GetForCurrentView(), but this is a Win32 app // and it doesn't have 'views'. We will use the generic context instead ResourceContext resourceContext = ResourceContext.GetForViewIndependentUse(); // Override whatever the context's language is with the language requested by .NET // This would cover the case where (eg) .NET code had explicitly set a different // culture from the user's preferred culture. resourceContext.Languages = new[] { desiredCulture }; // Get the current WinRT ResourceManager instance. Note this would require a // 'using' alias if we were trying to mix and match .NET resource code and // WinRT resource code in the same file, since they both have a type with this name. ResourceManager resourceManager = ResourceManager.Current; // The resource manager groups together different resources types under different sub-trees. // All files are under the "Files" subtree, so we retrieve that // (This is optional - we could prepend "files/" to the resource name instead) ResourceMap fileResources = resourceManager.MainResourceMap.GetSubtree("Files"); // TODO: Add your own naming conventions here, if necessary // This is the filename as it appeared on-disk when the package was created. At a minimum, you // need to add ".dll" on the end, but you might also need to prepend a folder name or do other // modifications to match your configuration. string targetFileName = string.Format(@"{0}.dll", desiredAssemblyName); // From all the resources available, we want to look for the one with the target filename NamedResource desiredResource = fileResources[targetFileName]; #if DEBUG_CANDIDATES // Print out the list of candidates and their qualifiers, in sorted order // Useful if something isn't resolving the way you expect. See MSDN for more information // on the properties being used. int i = 0; Debug.WriteLine(" Candidates:"); foreach (ResourceCandidate candidate in desiredResource.ResolveAll(resourceContext)) { Debug.WriteLine(" {0}: {1}, Match={2}, Default={3}", i, candidate.ValueAsString, candidate.IsMatch, candidate.IsDefault); Debug.WriteLine(" Qualifiers:"); foreach (var qualifier in candidate.Qualifiers) { Debug.WriteLine(" {0}={1}, Match={2}, Default={3}", qualifier.QualifierName, qualifier.QualifierValue, qualifier.IsMatch, qualifier.IsDefault); } ++i; } #endif // Get the best-matching candidate (filename) to load as an assembly // NOTE: If this throws the following exception: // // The ResourceMap or NamedResource has an item that does not have default or neutral // resource. (Exception from HRESULT: 0x80073B0C) // // then double-check your MakePRI command and ensure it didn't complain about missing files: // // MakePRI: warning 0xdef01051: No default or neutral resource given for '<filename>'. // The application may throw an exception for certain user configurations when // retrieving the resources. // ResourceCandidate bestCandidate = desiredResource.Resolve(resourceContext); // Candidates have various properties, but we really only need the value at this point string absoluteFileName = bestCandidate.ValueAsString; // Now we have the filename, we should be able to do this: // // Assembly resourceAssembly = Assembly.LoadFrom(absoluteFileName); // // but due to a limitation with .NET and Windows resource packages, we need // to use an "Unsafe" load operation. To make sure we don't accidentally load // assemblies that really are unsafe (eg, from the network) we use this helper // function to validate the input first. // In this scenario the extra protections are uneccessary, but for anyone who copies // this code into a broader context, it will be useful. Assembly resourceAssembly = LoadAssemblyFromPackageGraph(absoluteFileName, Package.Current); Debug.WriteLine("Resolved Assembly Name='{0}', language='{1}'", absoluteFileName, resourceAssembly.GetName().CultureName); // Finally, return the assembly we have loaded return(resourceAssembly); } catch (Exception ex) { // This is expected to fail for non-AppX contexts. if (ex.HResult == KnownMrtFailureCodes.MrtNeedsAppXPackagedApp) { Debug.WriteLine("Info: MRT only works for AppX packaged apps; returning null."); return(null); } // This happens if you are missing a fallback file, but might not be fatal. // See comment above about MakePRI warnings if (ex.HResult == KnownMrtFailureCodes.MissingDefaultOrNeutralResource) { Debug.WriteLine("Error: No neutral resource supplied; returning null."); return(null); } // Otherwise, something else went wrong that needs to be looked at. Console.WriteLine("Excpetion while trying to find assembly: {0}\r\n{1}", ex.Message, ex.ToString()); throw; } finally { Debug.WriteLine("---- End AssemblyResolve event handler ----"); } }
public void NoResourceFileWithContextTest() { var resourceManager = new ResourceManager("NoSuchFile.pri"); var resourceMap = resourceManager.MainResourceMap; var resourceChildMap = resourceMap.GetSubtree("anyname"); var resourceContext = resourceManager.CreateResourceContext(); Assert.IsTrue(resourceContext.QualifierValues.ContainsKey(KnownResourceQualifierName.Language)); // No resource file, and not handled by fallback var resourceCandidate = resourceMap.GetValue("abc"); Assert.IsNull(resourceCandidate); // add fallback handler resourceManager.ResourceNotFound += (sender, args) => { if (args.Name == "abc") { String value; if (args.Context.QualifierValues.ContainsKey(KnownResourceQualifierName.Language)) { if (args.Context.QualifierValues[KnownResourceQualifierName.Language].StartsWith("en-US")) { value = "USValue"; } else if (args.Context.QualifierValues[KnownResourceQualifierName.Language].StartsWith("en-GB")) { value = "GBValue"; } else { value = "OtherValue"; } } else { value = "UnknownValue"; } var candidate = new ResourceCandidate(ResourceCandidateKind.String, value); args.SetResolvedCandidate(candidate); } }; resourceContext.QualifierValues[KnownResourceQualifierName.Language] = "en-US"; resourceCandidate = resourceMap.GetValue(resourceContext, "abc"); Assert.AreEqual(resourceCandidate.Kind, ResourceCandidateKind.String); Assert.AreEqual(resourceCandidate.ValueAsString, "USValue"); Assert.AreEqual(resourceCandidate.QualifierValues[KnownResourceQualifierName.Language], "en-US"); resourceContext.QualifierValues[KnownResourceQualifierName.Language] = "en-GB"; resourceCandidate = resourceMap.GetValue(resourceContext, "abc"); Assert.AreEqual(resourceCandidate.Kind, ResourceCandidateKind.String); Assert.AreEqual(resourceCandidate.ValueAsString, "GBValue"); Assert.AreEqual(resourceCandidate.QualifierValues[KnownResourceQualifierName.Language], "en-GB"); resourceContext.QualifierValues[KnownResourceQualifierName.Language] = "fr-FR"; resourceCandidate = resourceMap.GetValue(resourceContext, "abc"); Assert.AreEqual(resourceCandidate.Kind, ResourceCandidateKind.String); Assert.AreEqual(resourceCandidate.ValueAsString, "OtherValue"); Assert.AreEqual(resourceCandidate.QualifierValues[KnownResourceQualifierName.Language], "fr-FR"); resourceCandidate = resourceMap.GetValue(resourceContext, "xyz"); Assert.IsNull(resourceCandidate); }