Using embedded WebResources throughout Webresource.axd - asp.net

The question's simple: how could one use embedded resources in asp.net applications? What are the steps to include a resource in the assembly, and how to reference it? What are the gotchas that could be encountered?

Edit: For a version without referencing Page and ClientScript, see What is the right way to handle Embedded Resources on a Razor View?
After spending a half of a day I've learned these:
to embed a resource one needs to set it's Build Action to Embedded Resource (in VS Solution Explorer rightclick the file -> Properties)
next AsssemblyInfo.vb must be modified to make this resources available for WebResource queries. Add [Assembly: System.Web.UI.WebResource("MyWebResourceProj.Test.css", "text/css")] to AssemblyInfo.vb located in MyProject folder of the project.
The name consists of root namespace/assembly name +'.'+filename. To be 100% sure of the name, use the following code snippet to look it up:
Dim resNames = Assembly.LoadFile("YourDll.dll").GetManifestResourceNames()
Note that the assembly's Root Namespace must be the same as the Assembly Name (this took me about 4 hours to realize. At least with .Net v4 that is the case)
If there are references inside the css ( <%=WebResource("NS.image.jpg")%> ) than pass PerformSubstitution:=true for that css's WebResource attribute.
Referencing the resource can be done with Page.ClientScript.GetWebResourceUrl(GetType(MyWebResourceProj.ConssumingPage), "MyWebResourceProj.Test.css")
Note that instead of GetType(Typename) one could use Me.GetType(), but again, that won't work if the class is inherited, so beware!
Resources:
Debugging ASP.NET 2.0 Web Resources: Decrypting the URL and Getting the Resource Name

Using embedded resources through WebResource.axd is a pain in the neck, as you can see from your own answer. You have to keep assemblyinfo.vb|cs in sync, and it always seems damn near impossible to get all the namespace & assembly names right in all the right places.
When you finally get it to work, your reward is an include script line that that looks like a core memory dump.
I suggest an alternative. Write yourself a very simple web handler (e.g. MyResourceLoader.ashx. Then add a method to your class that simply serves it's own embedded resources, in whatever way you think is meaningful. You can use reflection to get the classes, like WebResource does, or just hardcode whatever you need into your loader, if it's just for a specific purpose. A public method in your class might look like:
public static Stream GetResource(string resourceName) {
// get the resource from myself, which is easy and doesn't require
// anything in assemblyinfo, and return it as a stream. As a bonus,
// you can parse it dynamically or even return things that aren't
// just embedded, but generated completely in code!
}
Or if you decide to make something more general purpose, you can get all fancy and return more data using a class, e.g.
class ResourceInfo
{
public Stream Data;
public string MimeType;
public string FileName;
}
Now you have the ability to serve up your embedded resources any way you want, e.g.
<script language="javascript" src="/MyResourceLoader.ashx/MyControlScript.js">
I think MS made a mess of that WebResource business. Luckily its' pretty straightforward to do your own thing.

Related

best approach to implement getRealPath()

I am working on struts 2.0 . I am designing a web application.
I am using Jasper Report in my application. I want to access the *.jrxml files in my action class. I don't want to give hard coded path to the files. So to get the path dynamically I googled it and got the solution that I can get the path using getRealPath() method. But I found two implementation of doing this:
Using HttpSession to get object of ServletContext and using the getRealPath() method of the ServletContext object.
Like this:
HttpSession session = request.getSession();
String realPath = session.getServletContext().getRealPath("/");
The second approach to do it directly using the static method getServletContext() of ServletActionContext. And then we can get the real path of the application using the getRealPath() method.
Like this:
String realPath = ServletActionContext.getServletContext().getRealPath("/");
Please tell me, is there any difference between the above two and also please tell me whether there is any other way to get the path?
Neither is "better", really, and I'd argue that neither is particularly good, either.
I might try getting the context path in an initialization servlet and stick it into the application context, then make your action(s) ApplicationAware and retrieve the value from the map.
This has the added benefit of aiding testability and removing the static references in the action.
That said, I see zero reason to go through the extra mechanics of your first approach: it adds a lot of noise for no perceivable benefit; I'm not even sure why it wuld be considered.
I'd also be a little wary of tying your actions to a path like this unless there's a real need, what's the specific use? In general you shouldn't need to access intra-app resources by their path.

How is the auto-generated ASP namespace realized for an ASP.NET website project, from start (build) to finish (runtime)?

The 'ASP' namespace seems to be a generated because it's not used in the website project's source code, anywhere (or at least not explicitly used by the programmer of the website). I would like to know how it is fully realized.
For example:
Is it the responsibility of MSBuild to drive creation of the ASP namespace and
if so, where is that instruction found? I
know the C# compiler won't create a namespace from nothing of
its own volition, so the ASP namespace must be fed into it,
even if not used by the website programmer. Maybe it's
generated into the source code by a different tool. The
'Temporary ASP.NET Files' folder might have some bearing on it. As you
can see, I want all the gory details in order to unlock and understand
that namespace ...
Visual Studio seems to have tooling that allows the ASP namespace to be used (IntelliSense support for it) but that masks my understanding of it.
How is the 'ASP' namespace realized in a website from start to finish?
(I haven't found a good article that explains all this.)
Here the ASP namespace is shown in .NET Reflector. (This image taken from Rick Strahl's blog)
The ASP. namespace can be used to Load dynamically a custom control with more safe that the cast will works.
You can control what name the custom control can take in the ASP. namespace by placing the ClassName="ControlClass" on the declaration of the name space and the dynamic control now will have a reference to ASP.ControlClass to make a secure cast when you use the LoadControl
You can read the full steps on MSDN http://msdn.microsoft.com/en-us/library/c0az2h86(v=vs.100).aspx
When you do not use the ASP. namespace and left the control takes an automatic name, then the case may fail (I do not know why, but its fail on my sever time to time) The reference that there created are
namespace ASP
{
[CompilerGlobalScope]
public class Control_Class_nameByDirectory : ControlClass
{
[DebuggerNonUserCode]
public ControlClass();
protected override bool SupportAutoEvents { get; }
[DebuggerNonUserCode]
protected override void FrameworkInitialize();
}
}
And when you try to make a cast like (ControlClass)LoadControl("~/module/Control.ascs") it may fail because is recognize it as Control_Class_nameByDirectory and not as ControlClass
Now if you declare the ClassName on the control header as MSD says, the result is the control to get the same ClassName as the one you have define :
namespace ASP
{
[CompilerGlobalScope]
public class ControlClass : global::ControlClass
{
[DebuggerNonUserCode]
public ControlClass();
protected override bool SupportAutoEvents { get; }
[DebuggerNonUserCode]
protected override void FrameworkInitialize();
}
}
and here you can use the ASP.ControlClass to cast the control with out worry if its fail.
So following the steps that described here http://msdn.microsoft.com/en-us/library/c0az2h86(v=vs.100).aspx you can avoid issues like that. (and that I have face them)
The issue of failing to case a custom control with out reference to ASP. namespace have been seen both on Dot net 4.0 and 4.5 versions. And the worst is that is a random failure - meaning that some times is happens, some time not, and I was unable to find the reason.
I'm going to assume that you're looking for the prefix on server control tags... if that's not the case, let me know.
The prefix is registered in the web.config file under configuration/system.Web/pages/controls. You can modify it if you want, or register additional prefixes for your own control libraries.
MSDN info here: http://msdn.microsoft.com/en-us/library/ms164640.aspx
This namespace is used on the code that ASP.NET generates from parsing your .aspx and .ascx files.
I have no idea why you care, though. It's just a namespace. There's nothing "special" about it, and you shouldn't be referencing anything in that namespace.
To understand how all of this works, read "ASP.NET Life Cycle".

Setting the WebServiceWrapper endpointURI at run time

I'm in the middle of switching from Flex Builder 3 to Flash Builder 4, and one of the problems I have run into is that support for web services in 4 is substantially different. In both IDE's I am able to import a WSDL for my web service and it will generate the appropriate client classes for communicating with the service. The generated code in each is different.
In my Flex3 code I was able to access the endpointURI property of the mx.rpc.soap.AbstractWebService, but in the Flex4 code that is generated, the new class extends com.adobe.fiber.services.wrapper.WebServiceWrapper which does not have the endpointURI property.
My project has mulitple game servers and the player picks which server they want to play on. In the past if the player wanted server 1, I would set the endpoint URI to http://game1.server.com/service.asmx, and like wise if they wanted server 2 I would set the endpoint to http://game2.server.com/service.asmx.
What am I looking for to accomplish this in Flash Builder 4?
Short Answer:
var s:ClassThatExtendsWebServiceWrapper = new ClassThatExtendsWebServiceWrapper;
s.serviceControl.endpointURI = 'http://service.com/service.asmx';
Long Answer:
Well I finally found a solution. Adobe seems to have made this much harder than it should have been.
Web Service classes that are generated by Flash Builder 4 extend the com.adobe.fiber.services.wrapper.WebServiceWrapper. WebServiceWrapper has a property called serviceControl that can be used to control the service. The problem is that not all the members of serviceControl are accessible at the application code level. Lets assume that I have a web service called GameService. When I use the data tool to connect to the web service by providing a WSDL, Flash Builder will create two classes for me automcatically.
internal class _Super_GameService extends
com.adobe.fiber.services.wrapper.WebServiceWrapper
{ ... }
public class GameService extends _Super_GameService
{}
_Super_GameService contains all the automatically generated code to make calls to the web service. GameService contains no code itself, but unlike _Super_GameService, it is public. The idea here is that any enhancements that we need to make can be made to GameService, then later on if we need to update, _Super_GameService can be regenerated, but out changes to GameService will not be overwritten by the code generation tool.
Now this leads us to usage of these generated classes. Typically all I should have to do is create an instance of GameService and call a method on it. In this example DoSomethingAwesome is a method available on the web service.
var gs:GameService = new GameService();
var token:AsyncToken = gs.DoSomethingAwesome();
Now this will call the service using the URI of the service specified in the WSDL file. In my situation I wanted GameService to connect to a different URI. This should have been simple, but things fell apart.
My first problem was that viewing the documentation on WebServiceWrapper (http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/com/adobe/fiber/services/wrapper/WebServiceWrapper.html) did not render properly in Firefox. So when I was reading the documentation I wasn't getting the full picture. This really needs to be fixed by Adobe.
Viewing the documentation in another browser helped me find out about the serviceControl property of WebServiceWrapper. serviceControl is declared as a mx.rpc.soap.AbstractWebService. AbstractWebService does have an endpointURI property which makes the following code valid.
var gs:GameService = new GameService();
gs.serviceControl.endpointURI = 'http://game1.service.com/GameService.asmx';
The other problem I had is that for some reason the endpointURI property of serviceControl does not appear in the Intellisense context menu. So since I didn't see serviceControl in the online documentation at first, and I didn't see endpointURI in intellisense, I didn't realize the property was there to be set.
If you look at the source for AbstractWebserivce, (http://opensource.adobe.com/svn/opensource/flex/sdk/trunk/frameworks/projects/rpc/src/mx/rpc/soap/AbstractWebService.as) there doesn't seem to be an Exclude tag to explain why endpointURI does not appear in the Intellisense context menu. So I don't know what is going on there.
You should be able to override the endpointURI on the WebService. But I'm not sure where to do that with the generated code since I use <s:WebService/>.
This is the only way I could get it to work, in the generated stub for your service:
import com.adobe.fiber.core.model_internal;
Also:
/**
* Override super.init() to provide any initialization customization if needed.
*/
protected override function preInitializeService():void
{
_needWSDLLoad = false; // to prevent loading the default WSDL
super.preInitializeService();
// Initialization customization goes here
wsdl = "http://localhost/yourservice?wsdl";
_needWSDLLoad = true;
model_internal::loadWSDLIfNecessary();

Problems with DOCTYPE resolution and ASP.Net

In a previous question I mentioned some work with a 3rd party DLL whose interface uses a series of XML inputs that are defined using DTDs. Everything has gone smoothly so far, but I still have this nagging issue with resolving the Document Type Declaration in the generated input values.
What I can't figure out is what the deciding factor is in determining where to look for the referenced DTD file. If I have a declaration that looks like this:
<!DOCTYPE ElementName SYSTEM "ElementName.dtd">
My initial thinking was that the application's current execution path is where a parser would look for the DTD. However, when I attempt to use an XML control in ASP.Net, the error I get baffles me...
Could not find file 'c:\Program Files\Microsoft Visual
Studio
9.0\Common7\IDE\ElementName.dtd'
Why is it looking for the DTD there?
Are there any XML gurus out there who can help me out on this one. I really don't have any control over the XML that is returned from this DLL so what am I supposed to do. Is there a way to "register" a DTD with the operating system? Like the GAC?
Unfortunately the library that generated the XML used a relative url for the dtd rather than a fully qualified one. As such the XmlControl's XmlDocument is using an XmlResolver class to convert the relative path to a fully qualified one. By default it uses an XmlUrlResolver (that is a concrete XmlResolver). This will try to map the location of the dtd to a location it thinks is relative to the Xml document. Trouble is, where is the XmlDocument? Probably in memory which is not relative to anything and the XmlUrlResolver is using the process location instead which in your case is Visual Studio which is located at 'c:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe'.
So what can you do? Well I suppose you have to crate you own XmlResolver that inherits from XmlUrlResolver an overrides the ResolveUri method and does something appropriate. Having done that you will have to:
Create an XmlReaderSettings class and set the XmlReolver property to the class you just created.
Create an XmlReader using XmlReader.Create() passing in your document and the XmlSettings object.
Create an XmlDocument and call Load passing in the XmlReader and finally.
Set the XmlDocument property of your XmlControl to the XmlDocument.
Frankly that is all a bit of a pain, so if it where me I would just use string.Replace to remove the DTD declaration from the document before processing it into XML.
If you are feeling really brave you can create a resolver that inherits directly from XmlResolver. Once you have done that you can override the GetEntity method and then you can get the dtd document from wherever you like. I wrote one once that got dtds from files embedded as resource files, but unfortunately, I don't have the code any more :-(
If you do not actually care about validating each and every document against its DTD, you could set the XmlResolver property to null on your XmlTextReader (or XmlDocument) to ignore the DTD altogether.

ASP.NET Localized web site -- updating on the fly

I think I have a solution to this, but is there a better way, or is this going to break on me?
I am constructing a localized web site using global/local resx files. It is a requirement that non-technical users can edit the strings and add new languages through the web app.
This seems easy enough -- I have a form to display strings and the changes are saved with code like this snippet:
string filename = MapPath("App_GlobalResources/strings.hu.resx");
XmlDocument xDoc = new XmlDocument();
XmlNode xNode;
xDoc.Load(filename);
xNode = xDoc.SelectSingleNode("//root/data[#name='PageTitle']/value");
xNode.InnerText = txtNewTitle.Text;
xDoc.Save(filename);
Is this going to cause problems on a busy site? If it causes a momentary delay for recompilation, that's no big deal. And realistically, this form won't see constant, heavy use. What does the community think?
I've used a similar method before for a very basic "CMS". The site wasn't massively used but it didn't cause me any problems.
I don't think changing a resx will cause a recycle.
We did something similar, but used a database to store the user modified values. We then provided a fallback mechanism to serve the overridden value of a localized key.
That said, I think your method should work fine.
Have you considered creating a Resource object? You would need to wrap your settings into a single object that all the client code would use. Something like:
public class GuiResources
{
public string PageTitle
{
get return _pageTitle;
}
// Fired once when the class is first created.
void LoadConfiguration()
{
// Load settings from config section
_pageTitle = // Value from config
}
}
You could make it a singleton or a provider, that way the object is loaded only one time. Also you could make it smart to look at the current thread to get the culture info so you know what language to return.
Then in your web.config file you can create a custom section and set restartOnExternalChanges="true". That way, your app will get the changed when they are made.

Resources