Why doesn't my ScriptReference find the Embedded Resource? - c#

I have an AJAX control project that has a .js file which is configured as an embedded resource.
My main web application references this project, and when I try to load up the control I get this error:
Assembly does not contain a Web resource with name 'MyFile.js'.
Here is my implementation of getScriptReferences:
public IEnumerable GetScriptReferences()
{
// create reference to the JS
ScriptReference jsReference = new ScriptReference();
jsReference.Assembly = "MyNamespace";
jsReference.Name = "MyNamespace.MyFile.js";
return new ScriptReference[] { jsReference };
}
I'm not quite sure what I'm missing. I've tried changing the Name parameter to be just the file name, the namespace and file name, the namespace, assembly, and file name...and I"m not having any luck. Any suggestions are appreciated.

You have to define the web resource in code on the assembly that contains your embedded resource. Typically you would do this in an AssemblyInfo.vb or .cs file.
[assembly: System.Web.UI.WebResource(
"MyNamespace.MyFile.js",
"text/javascript", PerformSubstitution = true)]
See this article if you need some more help.

Did you make sure to add an entry for the Javascript file into your AssemblyInfo.cs? Something like:
[assembly: WebResource("MyNamespace.MyFile.js", "text/javascript")]
Otherwise, the assembly won't allow access to the resource.

Related

C# Read text file from resources rather than locally [duplicate]

I have a web application project. I generated the DLL and import it in another project. I implemented VirtualPathProvider.
I followed this web site: http://support.microsoft.com/kb/910441/en-us?spid=8940&sid=global, and everything works until I add another site master.
I added site_export.master and changed its Build Action to Embedded Resource.
I changed my page to use the new site master.
GetManifestResourceStream() returns null when I load site_export.master.
I call GetManifestResourceNames() to check if site_export.master exists in the DLL and it does. It's in the list. All of the name spaces match. I didn't list the name space out here.
Why can't GetManifestResourceStream() load my new site_export.master? It loads site.master just fine. I know my DLL is loaded because I can see other files in the DLL.
Remember the following issues...
Step 1. Build action set to embedded resource see
C#’s GetManifestResourceStream Gotcha
Step 2. Use namespace.resourcename see GetManifestResourceStream() returns null ?
Actually, this method returns null if a private resource in another assembly is accessed and the caller does not have ReflectionPermission with the ReflectionPermissionFlag.MemberAccess flag.
Side-hint. To make sure you're in the right assembly and with right name: dump and evaluate all the resources available in your target assembly
string[] names = assembly.GetManifestResourceNames();
(in my case, I misused a namespace from another assembly)
I did this to make it work:
Step 1: Select the resource (CRDF.xsl in my case) and right click > Properties.
Set Build Action to "EmbeddedResource" and Logical Name to name of your choice, e.g. CRDFXSL.
Step 2 : Change your Source code like this:
Assembly _assembly;
_assembly = Assembly.GetExecutingAssembly();
xslStream = _assembly.GetManifestResourceStream("CRDFXSL");
_xmlReader = XmlReader.Create(xslStream);
Thus everything went smoooooooth..
Hint and Caution:
If the "Assembly name" and "Default namespace" does not match in the project file then also GetManifestResourceStream would return null. GetManifestResourceNames still returns the names of assemblies but during loading the manifest would not work.
Try this:
Dim ctx As Windows.ApplicationModel.Resources.Core.ResourceContext = New Windows.ApplicationModel.Resources.Core.ResourceContext()
ctx.Languages = {Globalization.CultureInfo.CurrentUICulture.Name}
Dim rmap As Windows.ApplicationModel.Resources.Core.ResourceMap = Windows.ApplicationModel.Resources.Core.ResourceManager.Current.MainResourceMap
Dim res = rmap.GetValue("Assets/sample.png", ctx)
Dim resFile = Await res.GetValueAsFileAsync
The Windows.ApplicationModel.Resources.Core.ResourceManager.Current.MainResourceMap list all resources.

Adding Existing File. No Reference Found

I've added a .cs file from an existing project to my new project. The file exists in the new projects directory after adding it.
I've included HTTP.cs. When I do the following, I get HTTP Reference not found:
private HTTP http = new HTTP();
What else do I need to do to reference this .cs file?
Include the namespace of the HTTP via the using keyword, like this:
using NamespaceWhereHTTPClassLives;
OR
Fully qualify the type name like this:
private NamespaceWhereHTTPClassLives.HTTP http = new NamespaceWhereHTTPClassLives.HTTP();

I can't read my embedded XML file from my second C# project

I have a Visual Studio Solution with two projects inside.
The first project is a windows service, and this project contains one XML file inside a folder (called Configurations). This XML file is called Databases.xml. I have changed Databases.xml Build Action from content to embedded resource, and now I want to access this XML file from my other project in my solution, which is a WPF application.
I have therefore added an reference to my windows service project inside my WPF project, and would now like to access my XML file from my WPF project.
My problem is that when I am trying to access the embedded resource then I can't find out which type to use and what the path/namespace to my assembly and XML file should be. When I am using the
string[] names = this.GetType().Assembly.GetManifestResourceNames();
my names array is filled out with some resources from my WPF project. What I want is to access the ResourceNames and of course my Databases.xml file from my Windows Service project.
Please help me since this problem is driving me nuts.
If you need any additional information, please let me know.
My Solution Update 26-07-2013
I found out that the real problem occured when I couldn't use my first windows Service projects namespace as a type for my assembly. my Windows Service consists of a service class (with OnStart() and OnStop() method inside), and in order to use this class as my namespace type, I needed to add another reference to my WPF project. I needed to add a reference to System.ServiceProcess namespace, in order to use my Windows Service Class as a type for my assembly in my WPF Project.
In Order to access my Databases.xml file, I have come up with this solution. Remember to insert your own projects name and class name instead of my placeholders (<Windows Service Project Name> etc).
//Remember to add a reference to System.ServiceProcess in order to be able to use your WIndows Service Project as an assembly type.
using (Stream stream = typeof(<Windows Service Project Name>.<Windows Service Class Name>).Assembly.GetManifestResourceStream("<Windows Service Project Name>.<Folder Name>.Databases.xml"))
{
//Load XML File here, for instance with XmlDocument Class
XmlDocument doc = new XmlDocument();
doc.Load(stream);
}
So my real problem was that I didn't include the System.ServiceProcess reference to my second project.
You've to refer to Windows Service project Assembly to make it work
The problem with your code is This.GetType().Assesmbly gives current Assembly In your case WPF Assembly and obviously you'll not find what you need there.
Try this
Assembly windowsServiceAssembly = typeof(SomeTypeFromThatAssembly).Assembly;
string[] names = windowsServiceAssembly.GetManifestResourceNames();
Hope this helps.
If your class is static class then use this methods:
internal static string GetFromResources(string resourceName)
{
var asm = Assembly.GetExecutingAssembly();
var resource = asm.GetManifestResourceNames().First(res => res.EndsWith(resourceName, StringComparison.OrdinalIgnoreCase));
using (var stream = asm.GetManifestResourceStream(resource))
{
if (stream == null) return string.Empty;
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
For example if your embedded resource file names on the this project is 'MyFile.txt' then use this static method same this code:
var myFileData = GetFromResources("MyFile.txt");

Why does GetManifestResourceStream returns null while the resource name exists when calling GetManifestResourceNames?

I have a web application project. I generated the DLL and import it in another project. I implemented VirtualPathProvider.
I followed this web site: http://support.microsoft.com/kb/910441/en-us?spid=8940&sid=global, and everything works until I add another site master.
I added site_export.master and changed its Build Action to Embedded Resource.
I changed my page to use the new site master.
GetManifestResourceStream() returns null when I load site_export.master.
I call GetManifestResourceNames() to check if site_export.master exists in the DLL and it does. It's in the list. All of the name spaces match. I didn't list the name space out here.
Why can't GetManifestResourceStream() load my new site_export.master? It loads site.master just fine. I know my DLL is loaded because I can see other files in the DLL.
Remember the following issues...
Step 1. Build action set to embedded resource see
C#’s GetManifestResourceStream Gotcha
Step 2. Use namespace.resourcename see GetManifestResourceStream() returns null ?
Actually, this method returns null if a private resource in another assembly is accessed and the caller does not have ReflectionPermission with the ReflectionPermissionFlag.MemberAccess flag.
Side-hint. To make sure you're in the right assembly and with right name: dump and evaluate all the resources available in your target assembly
string[] names = assembly.GetManifestResourceNames();
(in my case, I misused a namespace from another assembly)
I did this to make it work:
Step 1: Select the resource (CRDF.xsl in my case) and right click > Properties.
Set Build Action to "EmbeddedResource" and Logical Name to name of your choice, e.g. CRDFXSL.
Step 2 : Change your Source code like this:
Assembly _assembly;
_assembly = Assembly.GetExecutingAssembly();
xslStream = _assembly.GetManifestResourceStream("CRDFXSL");
_xmlReader = XmlReader.Create(xslStream);
Thus everything went smoooooooth..
Hint and Caution:
If the "Assembly name" and "Default namespace" does not match in the project file then also GetManifestResourceStream would return null. GetManifestResourceNames still returns the names of assemblies but during loading the manifest would not work.
Try this:
Dim ctx As Windows.ApplicationModel.Resources.Core.ResourceContext = New Windows.ApplicationModel.Resources.Core.ResourceContext()
ctx.Languages = {Globalization.CultureInfo.CurrentUICulture.Name}
Dim rmap As Windows.ApplicationModel.Resources.Core.ResourceMap = Windows.ApplicationModel.Resources.Core.ResourceManager.Current.MainResourceMap
Dim res = rmap.GetValue("Assets/sample.png", ctx)
Dim resFile = Await res.GetValueAsFileAsync
The Windows.ApplicationModel.Resources.Core.ResourceManager.Current.MainResourceMap list all resources.

Loading ResourceDictionary dynamically

I have a folder in my project, Templates, full of (compiled) XAML ResourceDictionaries.
In a UserControl, I want to load all the templates into the ResourceDictionary. I would use code like the following:
public MyView()
{
InitializeComponent();
foreach (var resourceUri in new GetResourceUrisFromTemplatesFolder())
Resources.MergedDictionaries.Add(
new ResourceDictionary
{ Source = new Uri(resourceUri, UriKind.Relative) });
}
What I need to write is the GetResourceUrisFromTemplatesFolder method. I need it to discover all the resources from that folder.
The URIs could take a form like /MyAssembly;component/MyNS/Templates/Template12345.xaml or ../../Templates/Template12345.xaml
Is this possible?
Do I have to manually convert the names from the assembly's compiled resources (MyAssembly.g.resources)?
BTW, one can also manually load a ResourceDictionary as it seems:
ResourceDictionary dict = new ResourceDictionary();
System.Windows.Application.LoadComponent(dict,
new System.Uri("/SomeAssembly;component/SomeResourceDictionary.xaml",
System.UriKind.Relative));
After that, can talk to that dict object using foreach on the Keys property it has etc
At http://msdn.microsoft.com/en-us/library/ms596995(v=vs.95).aspx says
The XAML file that is loaded can be either an application definition file (App.xaml, for example) >or a page file (MainPage.xaml, for example). The XAML file can be in one of the following locations:
Included in the application package.
Embedded in the application assembly.
Embedded within a library assembly at the site of origin.
Do I have to manually convert the names from the assembly's compiled resources (MyAssembly.g.resources)?
That might be the case and i myself would approach it that way, however the question about how to do just that has been answered already so it should be not that much of an issue. Make sure that the dictionaries' compile action matches, and you probably want to prefix the names with a pack uri.

Categories

Resources