Code:
/ DotNET / DotNET / 8.0 / untmp / Orcas / RTM / ndp / fx / src / xsp / System / Web / Extensions / ui / ScriptResourceAttribute.cs / 1 / ScriptResourceAttribute.cs
//------------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//-----------------------------------------------------------------------------
namespace System.Web.UI {
using System;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using System.Web.Handlers;
using System.Web.Resources;
using System.Web.Script.Serialization;
using System.Web.Util;
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
[AspNetHostingPermission(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
public sealed class ScriptResourceAttribute : Attribute {
private string _scriptName;
private string _scriptResourceName;
private string _typeName;
private static readonly Regex _webResourceRegEx = new Regex(
@"<%\s*=\s*(?WebResource|ScriptResource)\(""(?[^""]*)""\)\s*%>",
RegexOptions.Singleline | RegexOptions.Multiline);
public ScriptResourceAttribute(string scriptName, string scriptResourceName, string typeName) {
if (String.IsNullOrEmpty(scriptName)) {
throw new ArgumentException(AtlasWeb.Common_NullOrEmpty, "scriptName");
}
if (String.IsNullOrEmpty(scriptResourceName)) {
throw new ArgumentException(AtlasWeb.Common_NullOrEmpty, "scriptResourceName");
}
if (String.IsNullOrEmpty(typeName)) {
throw new ArgumentException(AtlasWeb.Common_NullOrEmpty, "typeName");
}
_scriptName = scriptName;
_scriptResourceName = scriptResourceName;
_typeName = typeName;
}
public string ScriptName {
get {
return _scriptName;
}
}
public string ScriptResourceName {
get {
return _scriptResourceName;
}
}
public string TypeName {
get {
return _typeName;
}
}
private static void CopyScriptToStringBuilderWithSubstitution(
string content, Assembly assembly, bool zip, bool notifyScriptLoaded, StringBuilder output) {
// Looking for something of the form: WebResource("resourcename")
MatchCollection matches = _webResourceRegEx.Matches(content);
int startIndex = 0;
foreach (Match match in matches) {
output.Append(content.Substring(startIndex, match.Index - startIndex));
Group group = match.Groups["resourceName"];
string embeddedResourceName = group.Value;
bool isScriptResource = String.Equals(
match.Groups["resourceType"].Value, "ScriptResource", StringComparison.Ordinal);
try {
if (isScriptResource) {
output.Append(ScriptResourceHandler.GetScriptResourceUrl(
assembly, embeddedResourceName, CultureInfo.CurrentUICulture, zip, notifyScriptLoaded));
}
else {
output.Append(ScriptResourceHandler.GetWebResourceUrl(assembly, embeddedResourceName));
}
}
catch (HttpException e) {
throw new HttpException(String.Format(CultureInfo.CurrentCulture,
AtlasWeb.ScriptResourceHandler_UnknownResource,
embeddedResourceName), e);
}
startIndex = match.Index + match.Length;
}
output.Append(content.Substring(startIndex, content.Length - startIndex));
}
internal static ResourceManager GetResourceManager(string resourceName, Assembly assembly) {
if (String.IsNullOrEmpty(resourceName)) {
return null;
}
return new ResourceManager(GetResourceName(resourceName), assembly);
}
private static string GetResourceName(string rawResourceName) {
if (rawResourceName.EndsWith(".resources", StringComparison.OrdinalIgnoreCase)) {
return rawResourceName.Substring(0, rawResourceName.Length - 10);
}
return rawResourceName;
}
internal static string GetScriptFromWebResourceInternal(
Assembly assembly, string resourceName, CultureInfo culture,
bool zip, bool notifyScriptLoaded,
out Encoding encoding, out string contentType) {
ScriptResourceInfo resourceInfo = ScriptResourceInfo.GetInstance(assembly, resourceName);
ScriptResourceInfo releaseResourceInfo = null;
if (resourceName.EndsWith(".debug.js", StringComparison.OrdinalIgnoreCase)) {
// This is a debug script, we'll need to merge the debug resource
// with the release one.
string releaseResourceName = resourceName.Substring(0, resourceName.Length - 9) + ".js";
releaseResourceInfo = ScriptResourceInfo.GetInstance(assembly, releaseResourceName);
}
if ((resourceInfo == ScriptResourceInfo.Empty) &&
((releaseResourceInfo == null) || (releaseResourceInfo == ScriptResourceInfo.Empty))) {
throw new HttpException(AtlasWeb.ScriptResourceHandler_InvalidRequest);
}
ResourceManager resourceManager = null;
ResourceSet neutralSet = null;
ResourceManager releaseResourceManager = null;
ResourceSet releaseNeutralSet = null;
CultureInfo previousCulture = Thread.CurrentThread.CurrentUICulture;
try {
Thread.CurrentThread.CurrentUICulture = culture;
if (!String.IsNullOrEmpty(resourceInfo.ScriptResourceName)) {
resourceManager = GetResourceManager(resourceInfo.ScriptResourceName, assembly);
// The following may throw MissingManifestResourceException
neutralSet = resourceManager.GetResourceSet(CultureInfo.InvariantCulture, true, true);
}
if ((releaseResourceInfo != null) &&
!String.IsNullOrEmpty(releaseResourceInfo.ScriptResourceName)) {
releaseResourceManager = GetResourceManager(releaseResourceInfo.ScriptResourceName, assembly);
releaseNeutralSet = releaseResourceManager.GetResourceSet(CultureInfo.InvariantCulture, true, true);
}
if ((releaseResourceInfo != null) &&
!String.IsNullOrEmpty(releaseResourceInfo.ScriptResourceName) &&
!String.IsNullOrEmpty(resourceInfo.ScriptResourceName) &&
(releaseResourceInfo.TypeName != resourceInfo.TypeName)) {
throw new HttpException(String.Format(
CultureInfo.CurrentCulture,
AtlasWeb.ScriptResourceHandler_TypeNameMismatch,
releaseResourceInfo.ScriptResourceName));
}
StringBuilder builder = new StringBuilder();
encoding = WriteScript(assembly,
resourceInfo, releaseResourceInfo,
resourceManager, neutralSet,
releaseResourceManager, releaseNeutralSet,
zip, notifyScriptLoaded, builder);
contentType = resourceInfo.ContentType;
return builder.ToString();
}
finally {
Thread.CurrentThread.CurrentUICulture = previousCulture;
if (releaseNeutralSet != null) {
releaseNeutralSet.Dispose();
}
if (neutralSet != null) {
neutralSet.Dispose();
}
}
}
private static void RegisterNamespace(StringBuilder builder, string typeName, bool isDebug) {
int lastDot = typeName.LastIndexOf('.');
if (lastDot != -1) {
builder.Append("Type.registerNamespace('");
builder.Append(typeName.Substring(0, lastDot));
builder.Append("');");
if (isDebug) builder.AppendLine();
}
}
private static void WriteNotificationToStringBuilder(bool notifyScriptLoaded, StringBuilder builder, bool isDebug) {
if (notifyScriptLoaded) {
// DevDiv Bugs 131109: Resources and notification should go on a new line even in release mode
// because main script may not end in a semi-colon or may end in a javascript comment.
// Note: If resources exist, this newline isn't necessary because one was already output.
// But it is not worth keeping track of whether a newline has been output.
// A newline is required for resources and notification, better to just output it for both.
builder.AppendLine();
builder.Append("if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();");
}
}
private static bool WriteResource(
StringBuilder builder,
ResourceManager resourceManager,
ResourceSet neutralSet,
bool first,
bool isDebug) {
foreach (DictionaryEntry res in neutralSet) {
string key = (string)res.Key;
string value = resourceManager.GetObject(key) as string;
if (value != null) {
if (first) {
first = false;
}
else {
builder.Append(',');
}
if (isDebug) builder.AppendLine();
builder.Append('"');
builder.Append(JavaScriptString.QuoteString(key));
builder.Append("\":\"");
builder.Append(JavaScriptString.QuoteString(value));
builder.Append('"');
}
}
return first;
}
private static void WriteResourceToStringBuilder(
ScriptResourceInfo resourceInfo,
ScriptResourceInfo releaseResourceInfo,
ResourceManager resourceManager,
ResourceSet neutralSet,
ResourceManager releaseResourceManager,
ResourceSet releaseNeutralSet,
StringBuilder builder) {
if ((resourceManager != null) || (releaseResourceManager != null)) {
string typeName = resourceInfo.TypeName;
if (String.IsNullOrEmpty(typeName)) {
typeName = releaseResourceInfo.TypeName;
}
WriteResources(builder, typeName, resourceManager, neutralSet,
releaseResourceManager, releaseNeutralSet, resourceInfo.IsDebug);
}
}
private static void WriteResources(StringBuilder builder, string typeName,
ResourceManager resourceManager, ResourceSet neutralSet,
ResourceManager releaseResourceManager, ResourceSet releaseNeutralSet,
bool isDebug) {
// DevDiv Bugs 131109: Resources and notification should go on a new line even in release mode
// because main script may not end in a semi-colon or may end in a javascript comment.
builder.AppendLine();
RegisterNamespace(builder, typeName, isDebug);
builder.Append(typeName);
builder.Append("={");
bool first = true;
if (resourceManager != null) {
first = WriteResource(builder, resourceManager, neutralSet, first, isDebug);
}
if (releaseResourceManager != null) {
WriteResource(builder, releaseResourceManager, releaseNeutralSet, first, isDebug);
}
if (isDebug) {
builder.AppendLine();
builder.AppendLine("};");
}
else{
builder.Append("};");
}
}
private static Encoding WriteScript(Assembly assembly,
ScriptResourceInfo resourceInfo, ScriptResourceInfo releaseResourceInfo,
ResourceManager resourceManager, ResourceSet neutralSet,
ResourceManager releaseResourceManager, ResourceSet releaseNeutralSet,
bool zip, bool notifyScriptLoaded, StringBuilder output) {
Encoding encoding = null;
using (StreamReader reader = new StreamReader(
assembly.GetManifestResourceStream(resourceInfo.ScriptName), true)) {
encoding = reader.CurrentEncoding;
if (resourceInfo.IsDebug) {
// Output version information
AssemblyName assemblyName = assembly.GetName();
output.AppendLine("// Name: " + resourceInfo.ScriptName);
output.AppendLine("// Assembly: " + assemblyName.Name);
output.AppendLine("// Version: " + assemblyName.Version.ToString());
output.AppendLine("// FileVersion: " + AssemblyUtil.GetAssemblyFileVersion(assembly));
}
if (resourceInfo.PerformSubstitution) {
CopyScriptToStringBuilderWithSubstitution(
reader.ReadToEnd(), assembly, zip, notifyScriptLoaded, output);
}
else {
output.Append(reader.ReadToEnd());
}
WriteResourceToStringBuilder(resourceInfo, releaseResourceInfo,
resourceManager, neutralSet,
releaseResourceManager, releaseNeutralSet,
output);
WriteNotificationToStringBuilder(notifyScriptLoaded, output, resourceInfo.IsDebug);
}
return encoding;
}
}
}
// File provided for Reference Use Only by Microsoft Corporation (c) 2007.
// Copyright (c) Microsoft Corporation. All rights reserved.
Link Menu

This book is available now!
Buy at Amazon US or
Buy at Amazon UK
- ILGenerator.cs
- Int16AnimationBase.cs
- UnmanagedMemoryAccessor.cs
- _IPv6Address.cs
- StrokeFIndices.cs
- XPathExpr.cs
- ObjectToIdCache.cs
- BooleanConverter.cs
- ThemeDictionaryExtension.cs
- EncryptedPackage.cs
- DataGridViewCellParsingEventArgs.cs
- DateTimeConverter2.cs
- CodePageUtils.cs
- RawStylusActions.cs
- ColorConvertedBitmapExtension.cs
- SpellerHighlightLayer.cs
- CompilerError.cs
- StagingAreaInputItem.cs
- HighlightVisual.cs
- DiscardableAttribute.cs
- IsolationInterop.cs
- URI.cs
- TrustManagerPromptUI.cs
- StylusPlugin.cs
- EncodingNLS.cs
- login.cs
- URI.cs
- XmlWriterTraceListener.cs
- EncodingDataItem.cs
- XPathChildIterator.cs
- ContextStack.cs
- ValueProviderWrapper.cs
- XmlChoiceIdentifierAttribute.cs
- URLMembershipCondition.cs
- OleDbConnectionInternal.cs
- XmlEntity.cs
- SqlClientWrapperSmiStreamChars.cs
- TimeSpan.cs
- SelectionHighlightInfo.cs
- FileDialogCustomPlacesCollection.cs
- WebPartAuthorizationEventArgs.cs
- PropertyConverter.cs
- Brush.cs
- XmlQualifiedNameTest.cs
- MenuItem.cs
- HotSpot.cs
- BindingMemberInfo.cs
- RotateTransform3D.cs
- DataGridViewCellStyleBuilderDialog.cs
- TypeLoadException.cs
- AsnEncodedData.cs
- mansign.cs
- BamlRecordHelper.cs
- Error.cs
- IEnumerable.cs
- InputLanguageCollection.cs
- DbDataAdapter.cs
- AddInContractAttribute.cs
- JsonEnumDataContract.cs
- SqlConnectionFactory.cs
- ServiceAuthorizationBehavior.cs
- CompressEmulationStream.cs
- TdsParserStateObject.cs
- SettingsBindableAttribute.cs
- DiscoveryOperationContextExtension.cs
- RewritingPass.cs
- SynchronizedReadOnlyCollection.cs
- DataGridViewCellValueEventArgs.cs
- CodeTypeDeclaration.cs
- ObjectQueryState.cs
- ZoomPercentageConverter.cs
- SemanticResultKey.cs
- RawStylusActions.cs
- RevocationPoint.cs
- Page.cs
- DataGridViewLinkColumn.cs
- TypeConverterAttribute.cs
- Page.cs
- DataGridViewTextBoxEditingControl.cs
- RepeatInfo.cs
- ReceiveSecurityHeaderEntry.cs
- WinEventTracker.cs
- TextProperties.cs
- GeneratedContractType.cs
- SqlResolver.cs
- ResourceDictionaryCollection.cs
- SocketSettings.cs
- SynchronizationContext.cs
- ResourceDisplayNameAttribute.cs
- ExpressionBuilder.cs
- WebHttpDispatchOperationSelectorData.cs
- InvokePattern.cs
- ElementUtil.cs
- DiagnosticsConfiguration.cs
- basenumberconverter.cs
- ReaderOutput.cs
- XmlComplianceUtil.cs
- FormViewDeletedEventArgs.cs
- TextServicesDisplayAttributePropertyRanges.cs
- InitializerFacet.cs