The Asp.NET 2.0 allows to provide JS files in embedded resources using WebResource.axd.
The procedure is well described here and here. Note that adding [assembly: WebResourceAttribute] attibute is important.
However the methods ClientScript.RegisterClientScriptResource and ClientScript.GetWebResourceUrl do not throw exceptions, if embedded resource is missing. They just generate invalid urls that can't be visually checked because parameters are encrypted.
For easier identification of the error it is a good practice to check existence of resource prior to call using Debug.Assert or throw exception.
Type rstype = typeof(ClassInAssemblyWithResource);
Debug.Assert(null != rstype.Assembly.GetManifestResourceInfo(sFullName));
return page.ClientScript.GetWebResourceUrl(rstype, sFullName);
OR better way
StreamHelper.EnsureWebResourceValid(sFullName, rsType.Assembly,true)
page.ClientScript.RegisterClientScriptResource(rsType, FileName)
where EnsureWebResourceValid is the following function
public static bool EnsureWebResourceValid(string ResName, Assembly Asm,bool ThrowException)
{
bool bRet = StreamHelper.EnsureManifestResourceExist(ResName, Asm, ThrowException);
if(bRet==true)
{ //find the attribute
bRet = false;
// Iterate through the attributes for the assembly.
foreach (Attribute attr in Attribute.GetCustomAttributes(Asm))
{
//Check for WebResource attributes.
if (attr.GetType() == typeof(WebResourceAttribute))
{
WebResourceAttribute wra = (WebResourceAttribute)attr;
Debug.WriteLine ("Resource in the assembly: " + wra.WebResource.ToString() +
" with ContentType = " + wra.ContentType.ToString() +
" and PerformsSubstitution = " + wra.PerformSubstitution.ToString() );
if (wra.WebResource== ResName)
{
bRet = true;
break;
}
}
}//foreach
} //ManifestResourceExist
if(bRet==false)
{
string sMsg="Embedded resource " + ResName + " in assembly " + Asm.FullName + " doesn't have WebResourceAttribute ";
if (ThrowException == true)
{
throw new ApplicationException(sMsg);
}
else
{
Debug.Assert(false, sMsg);
}
}
return bRet;
}
//'if ThrowException=true, then Throw exception if resource not found
public static bool EnsureManifestResourceExist(string ResName, Assembly Asm, bool ThrowException)
{ //NOTE: If resource is located in subfolder of C# project, path of subfolder should be specified (it is included as part of namespace)
//' Resources are named using a fully qualified name ((including namespace).
bool bRet=true;
ManifestResourceInfo info = Asm.GetManifestResourceInfo(ResName);
if (info == null)
{
bRet=false;
string sMsg = "Couldn't find embedded resource " + ResName + " in assembly " + Asm.FullName;
if (ThrowException)
{
throw new ApplicationException(sMsg);
}
else
{
Debug.Assert(false, sMsg);
}
}
return bRet;
}
I've submitted a suggestion to MS.
posted @ Friday, May 26, 2006 10:21 AM