本文整理汇总了C#中System.CodeDom.Compiler.CodeDomProvider.IsValidIdentifier方法的典型用法代码示例。如果您正苦于以下问题:C# CodeDomProvider.IsValidIdentifier方法的具体用法?C# CodeDomProvider.IsValidIdentifier怎么用?C# CodeDomProvider.IsValidIdentifier使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.CodeDom.Compiler.CodeDomProvider
的用法示例。
在下文中一共展示了CodeDomProvider.IsValidIdentifier方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GenerateIdName
internal static string GenerateIdName(string name, CodeDomProvider codeProvider, bool useSuffix, int additionalCharsToTruncate)
{
if (!useSuffix)
{
name = GetBackwardCompatibleIdentifier(name, codeProvider);
}
if (codeProvider.IsValidIdentifier(name))
{
return name;
}
string str = name.Replace(' ', '_');
if (!codeProvider.IsValidIdentifier(str))
{
if (!useSuffix)
{
str = "_" + str;
}
for (int i = 0; i < str.Length; i++)
{
UnicodeCategory unicodeCategory = char.GetUnicodeCategory(str[i]);
if (((((unicodeCategory != UnicodeCategory.UppercaseLetter) && (UnicodeCategory.LowercaseLetter != unicodeCategory)) && ((UnicodeCategory.TitlecaseLetter != unicodeCategory) && (UnicodeCategory.ModifierLetter != unicodeCategory))) && (((UnicodeCategory.OtherLetter != unicodeCategory) && (UnicodeCategory.NonSpacingMark != unicodeCategory)) && ((UnicodeCategory.SpacingCombiningMark != unicodeCategory) && (UnicodeCategory.DecimalDigitNumber != unicodeCategory)))) && (UnicodeCategory.ConnectorPunctuation != unicodeCategory))
{
str = str.Replace(str[i], '_');
}
}
}
int num2 = 0;
string str2 = str;
while (!codeProvider.IsValidIdentifier(str) && (num2 < 200))
{
num2++;
str = "_" + str;
}
if (num2 >= 200)
{
str = str2;
while (!codeProvider.IsValidIdentifier(str) && (str.Length > 0))
{
str = str.Remove(str.Length - 1);
}
if (str.Length == 0)
{
return str2;
}
if (((additionalCharsToTruncate > 0) && (str.Length > additionalCharsToTruncate)) && codeProvider.IsValidIdentifier(str.Remove(str.Length - additionalCharsToTruncate)))
{
str = str.Remove(str.Length - additionalCharsToTruncate);
}
}
return str;
}
示例2: NameIsLanguageKeyword
static bool NameIsLanguageKeyword (CodeDomProvider codeDomProvider, string[] names)
{
return names.Any (name => !codeDomProvider.IsValidIdentifier (name));
}
示例3: VerifyResourceNames
private static SortedList VerifyResourceNames(Dictionary<string, ResourceData> resourceList, CodeDomProvider codeProvider, ArrayList errors, out Hashtable reverseFixupTable)
{
reverseFixupTable = new Hashtable(0, StringComparer.InvariantCultureIgnoreCase);
SortedList list = new SortedList(StringComparer.InvariantCultureIgnoreCase, resourceList.Count);
foreach (KeyValuePair<string, ResourceData> pair in resourceList)
{
string key = pair.Key;
if ((string.Equals(key, "ResourceManager") || string.Equals(key, "Culture")) || (typeof(void) == pair.Value.Type))
{
errors.Add(key);
}
else
{
if (((key.Length <= 0) || (key[0] != '$')) && (((key.Length <= 1) || (key[0] != '>')) || (key[1] != '>')))
{
if (!codeProvider.IsValidIdentifier(key))
{
string str2 = VerifyResourceName(key, codeProvider, false);
if (str2 == null)
{
errors.Add(key);
goto Label_0185;
}
string item = (string) reverseFixupTable[str2];
if (item != null)
{
if (!errors.Contains(item))
{
errors.Add(item);
}
if (list.Contains(str2))
{
list.Remove(str2);
}
errors.Add(key);
goto Label_0185;
}
reverseFixupTable[str2] = key;
key = str2;
}
ResourceData data = pair.Value;
if (!list.Contains(key))
{
list.Add(key, data);
}
else
{
string str4 = (string) reverseFixupTable[key];
if (str4 != null)
{
if (!errors.Contains(str4))
{
errors.Add(str4);
}
reverseFixupTable.Remove(key);
}
errors.Add(pair.Key);
list.Remove(key);
}
}
Label_0185:;
}
}
return list;
}
开发者ID:pritesh-mandowara-sp,项目名称:DecompliedDotNetLibraries,代码行数:65,代码来源:StronglyTypedResourceBuilder.cs
示例4: VerifyResourceName
private static string VerifyResourceName(string key, CodeDomProvider provider, bool isNameSpace)
{
if (key == null)
{
throw new ArgumentNullException("key");
}
if (provider == null)
{
throw new ArgumentNullException("provider");
}
foreach (char ch in CharsToReplace)
{
if (!isNameSpace || ((ch != '.') && (ch != ':')))
{
key = key.Replace(ch, '_');
}
}
if (provider.IsValidIdentifier(key))
{
return key;
}
key = provider.CreateValidIdentifier(key);
if (provider.IsValidIdentifier(key))
{
return key;
}
key = "_" + key;
if (provider.IsValidIdentifier(key))
{
return key;
}
return null;
}
开发者ID:pritesh-mandowara-sp,项目名称:DecompliedDotNetLibraries,代码行数:33,代码来源:StronglyTypedResourceBuilder.cs
示例5: InternalCreate
private static CodeCompileUnit InternalCreate(Dictionary<string, ResourceData> resourceList, string baseName, string generatedCodeNamespace, string resourcesNamespace, CodeDomProvider codeProvider, bool internalClass, out string[] unmatchable)
{
Hashtable hashtable;
if (baseName == null)
{
throw new ArgumentNullException("baseName");
}
if (codeProvider == null)
{
throw new ArgumentNullException("codeProvider");
}
ArrayList errors = new ArrayList(0);
SortedList list2 = VerifyResourceNames(resourceList, codeProvider, errors, out hashtable);
string str = baseName;
if (!codeProvider.IsValidIdentifier(str))
{
string str2 = VerifyResourceName(str, codeProvider);
if (str2 != null)
{
str = str2;
}
}
if (!codeProvider.IsValidIdentifier(str))
{
throw new ArgumentException(Microsoft.Build.Tasks.SR.GetString("InvalidIdentifier", new object[] { str }));
}
if (!string.IsNullOrEmpty(generatedCodeNamespace) && !codeProvider.IsValidIdentifier(generatedCodeNamespace))
{
string str3 = VerifyResourceName(generatedCodeNamespace, codeProvider, true);
if (str3 != null)
{
generatedCodeNamespace = str3;
}
}
CodeCompileUnit e = new CodeCompileUnit();
e.ReferencedAssemblies.Add("System.dll");
e.UserData.Add("AllowLateBound", false);
e.UserData.Add("RequireVariableDeclaration", true);
CodeNamespace namespace2 = new CodeNamespace(generatedCodeNamespace);
namespace2.Imports.Add(new CodeNamespaceImport("System"));
e.Namespaces.Add(namespace2);
CodeTypeDeclaration declaration = new CodeTypeDeclaration(str);
namespace2.Types.Add(declaration);
AddGeneratedCodeAttributeforMember(declaration);
TypeAttributes attributes = internalClass ? TypeAttributes.AnsiClass : TypeAttributes.Public;
declaration.TypeAttributes = attributes;
declaration.Comments.Add(new CodeCommentStatement("<summary>", true));
declaration.Comments.Add(new CodeCommentStatement(Microsoft.Build.Tasks.SR.GetString("ClassDocComment"), true));
CodeCommentStatement statement = new CodeCommentStatement(Microsoft.Build.Tasks.SR.GetString("ClassComments1"), true);
declaration.Comments.Add(statement);
statement = new CodeCommentStatement(Microsoft.Build.Tasks.SR.GetString("ClassComments3"), true);
declaration.Comments.Add(statement);
declaration.Comments.Add(new CodeCommentStatement("</summary>", true));
CodeTypeReference attributeType = new CodeTypeReference(typeof(DebuggerNonUserCodeAttribute)) {
Options = CodeTypeReferenceOptions.GlobalReference
};
declaration.CustomAttributes.Add(new CodeAttributeDeclaration(attributeType));
CodeTypeReference reference2 = new CodeTypeReference(typeof(CompilerGeneratedAttribute)) {
Options = CodeTypeReferenceOptions.GlobalReference
};
declaration.CustomAttributes.Add(new CodeAttributeDeclaration(reference2));
bool useStatic = internalClass || codeProvider.Supports(GeneratorSupport.PublicStaticMembers);
bool supportsTryCatch = codeProvider.Supports(GeneratorSupport.TryCatchStatements);
EmitBasicClassMembers(declaration, generatedCodeNamespace, baseName, resourcesNamespace, internalClass, useStatic, supportsTryCatch);
foreach (DictionaryEntry entry in list2)
{
string key = (string) entry.Key;
string resourceName = (string) hashtable[key];
if (resourceName == null)
{
resourceName = key;
}
if (!DefineResourceFetchingProperty(key, resourceName, (ResourceData) entry.Value, declaration, internalClass, useStatic))
{
errors.Add(entry.Key);
}
}
unmatchable = (string[]) errors.ToArray(typeof(string));
CodeGenerator.ValidateIdentifiers(e);
return e;
}
开发者ID:pritesh-mandowara-sp,项目名称:DecompliedDotNetLibraries,代码行数:81,代码来源:StronglyTypedResourceBuilder.cs
示例6: VerifyResourceName
public static string VerifyResourceName (string key, CodeDomProvider provider)
{
string keyToUse;
char [] charKey;
// check params
if (key == null)
throw new ArgumentNullException ("Parameter: key must not be null");
if (provider == null)
throw new ArgumentNullException ("Parameter: provider must not be null");
if (key == String.Empty) {
keyToUse = "_";
} else {
// replaces special chars
charKey = key.ToCharArray ();
for (int i = 0; i < charKey.Length; i++)
charKey [i] = VerifySpecialChar (charKey [i]);
keyToUse = new string(charKey);
}
// resolve if keyword
keyToUse = provider.CreateValidIdentifier (keyToUse);
// check if still not valid for provider
if (provider.IsValidIdentifier (keyToUse))
return keyToUse;
else
return null;
}
示例7: VerifyResourceNames
private static SortedList<string, ResourceData> VerifyResourceNames(Dictionary<string, ResourceData> resourceList,
CodeDomProvider codeProvider, List<ResourceErrorData> invalidResources, out Dictionary<string, string> reverseFixupTable)
{
reverseFixupTable = new Dictionary<string, string>(0, StringComparer.InvariantCultureIgnoreCase);
SortedList<string, ResourceData> validResources = new SortedList<string, ResourceData>(resourceList.Count,
StringComparer.InvariantCultureIgnoreCase);
Dictionary<string, ResourceData>.Enumerator resourceListEnumerator = resourceList.GetEnumerator();
try
{
while (resourceListEnumerator.MoveNext())
{
KeyValuePair<string, ResourceData> resourcePair = resourceListEnumerator.Current;
string resourceKey = resourcePair.Key;
if ((string.Equals(resourceKey, ResMgrPropertyName) ||
string.Equals(resourceKey, CultureInfoPropertyName) ||
string.Equals(resourceKey, InternalSyncObjectPropertyName)) ||
(typeof(void) == resourcePair.Value.Type))
{
invalidResources.Add(new ResourceErrorData(resourceKey,
string.Format(CultureInfo.CurrentCulture, CannotCreatePropertyForResource, resourceKey)));
continue;
}
if (((resourceKey.Length <= 0) || (resourceKey[0] != '$')) &&
(((resourceKey.Length <= 1) || (resourceKey[0] != '>')) || (resourceKey[1] != '>')))
{
if (!codeProvider.IsValidIdentifier(resourceKey))
{
string adjustedResourceKey = VerifyResourceName(resourceKey, codeProvider, false);
if (adjustedResourceKey == null)
{
invalidResources.Add(new ResourceErrorData(resourceKey,
string.Format(CultureInfo.CurrentCulture, CannotCreatePropertyForResource, resourceKey)));
continue;
}
string originalResourceKey;
if (reverseFixupTable.TryGetValue(adjustedResourceKey, out originalResourceKey))
{
if (!ContainsInvalidKey(invalidResources, originalResourceKey))
{
invalidResources.Add(new ResourceErrorData(originalResourceKey,
string.Format(CultureInfo.CurrentCulture, CannotCreatePropertyForResource,
originalResourceKey)));
}
if (validResources.ContainsKey(adjustedResourceKey))
validResources.Remove(adjustedResourceKey);
invalidResources.Add(new ResourceErrorData(resourceKey,
string.Format(CultureInfo.CurrentCulture, CannotCreatePropertyForResource, resourceKey)));
continue;
}
reverseFixupTable[adjustedResourceKey] = resourceKey;
resourceKey = adjustedResourceKey;
}
ResourceData resourceData = resourcePair.Value;
if (!validResources.ContainsKey(resourceKey))
{
validResources.Add(resourceKey, resourceData);
continue;
}
string initialResourceKey;
if (reverseFixupTable.TryGetValue(resourceKey, out initialResourceKey))
{
if (!ContainsInvalidKey(invalidResources, initialResourceKey))
{
invalidResources.Add(new ResourceErrorData(initialResourceKey,
string.Format(CultureInfo.CurrentCulture, CannotCreatePropertyForResource,
initialResourceKey)));
}
reverseFixupTable.Remove(resourceKey);
}
invalidResources.Add(new ResourceErrorData(resourcePair.Key,
string.Format(CultureInfo.CurrentCulture, CannotCreatePropertyForResource,
resourcePair.Key)));
validResources.Remove(resourceKey);
}
}
}
finally
{
resourceListEnumerator.Dispose();
}
return validResources;
}
示例8: VerifyResourceName
private static string VerifyResourceName(string key, CodeDomProvider provider, bool isNameSpace)
{
if (null == key)
throw new ArgumentNullException("key");
if (null == provider)
throw new ArgumentNullException("provider");
for (int index = 0; index < charsToReplace.Length; index++)
{
char ch = charsToReplace[index];
if (!isNameSpace || ((ch != '.') && (ch != ':')))
key = key.Replace(ch, ReplacementChar);
}
if (provider.IsValidIdentifier(key))
return key;
key = provider.CreateValidIdentifier(key);
if (provider.IsValidIdentifier(key))
return key;
key = "_" + key;
if (provider.IsValidIdentifier(key))
return key;
return null;
}
示例9: InternalCreate
private static CodeCompileUnit InternalCreate(Type callerType, Dictionary<string, ResourceData> resourceList,
string baseName, string generatedCodeNamespace, string resourcesNamespace,
CodeDomProvider codeProvider, bool internalClass, List<ResourceErrorData> unmatchable, string logicalName)
{
//logicalName added by Ðonny
if (null == baseName)
throw new ArgumentNullException("baseName");
if (null == codeProvider)
throw new ArgumentNullException("codeProvider");
Dictionary<string, string> reverseFixupTable;
SortedList<string, ResourceData> validResources = VerifyResourceNames(resourceList, codeProvider, unmatchable,
out reverseFixupTable);
string verifiedBaseName = baseName;
if (!codeProvider.IsValidIdentifier(verifiedBaseName))
{
string adjustedBaseName = VerifyResourceName(verifiedBaseName, codeProvider);
if (adjustedBaseName != null)
verifiedBaseName = adjustedBaseName;
}
if (!codeProvider.IsValidIdentifier(verifiedBaseName))
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, InvalidIdentifier, verifiedBaseName));
if (!string.IsNullOrEmpty(generatedCodeNamespace) &&
!codeProvider.IsValidIdentifier(generatedCodeNamespace))
{
string adjustedCodeNamespace = VerifyResourceName(generatedCodeNamespace, codeProvider, true);
if (adjustedCodeNamespace != null)
generatedCodeNamespace = adjustedCodeNamespace;
}
CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
codeCompileUnit.ReferencedAssemblies.Add("System.dll");
codeCompileUnit.UserData.Add("AllowLateBound", false);
codeCompileUnit.UserData.Add("RequireVariableDeclaration", true);
CodeNamespace codeNamespace = new CodeNamespace(generatedCodeNamespace);
codeNamespace.Imports.Add(new CodeNamespaceImport("System"));
codeCompileUnit.Namespaces.Add(codeNamespace);
CodeTypeDeclaration codeTypeDeclaration = new CodeTypeDeclaration(verifiedBaseName);
codeNamespace.Types.Add(codeTypeDeclaration);
AddGeneratedCodeAttributeforMember(codeTypeDeclaration);
TypeAttributes typeAttributes = TypeAttributes.AutoLayout;
if (!internalClass)
typeAttributes |= TypeAttributes.Public;
codeTypeDeclaration.TypeAttributes = typeAttributes;
AddComments(codeTypeDeclaration, ClassDocComment);
if (codeProvider.FileExtension.ToLowerInvariant() == "vb")//Visual Basic - generate module
codeTypeDeclaration.UserData.Add("Module", true);
CodeTypeReference debuggerNonUserCodeTypeReference = new CodeTypeReference(typeof(DebuggerNonUserCodeAttribute),
CodeTypeReferenceOptions.GlobalReference);
codeTypeDeclaration.CustomAttributes.Add(new CodeAttributeDeclaration(debuggerNonUserCodeTypeReference));
CodeAttributeDeclaration suppressAttributeTypeDeclaration = new CodeAttributeDeclaration(new CodeTypeReference(typeof(SuppressMessageAttribute)));
suppressAttributeTypeDeclaration.AttributeType.Options = CodeTypeReferenceOptions.GlobalReference;
suppressAttributeTypeDeclaration.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression("Microsoft.Naming")));
suppressAttributeTypeDeclaration.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression("CA1724:TypeNamesShouldNotMatchNamespaces")));
codeTypeDeclaration.CustomAttributes.Add(suppressAttributeTypeDeclaration);
bool useStatic = internalClass || codeProvider.Supports(GeneratorSupport.PublicStaticMembers);
bool supportsTryCatch = codeProvider.Supports(GeneratorSupport.TryCatchStatements);
EmitBasicClassMembers(callerType, codeTypeDeclaration, generatedCodeNamespace, baseName,
resourcesNamespace, internalClass, useStatic, supportsTryCatch, logicalName, codeProvider.FileExtension.ToLowerInvariant() != "vb"); //logicalName added by Ðonny
SortedList<string, ResourceData> formatMethods = new SortedList<string, ResourceData>(validResources.Count,
StringComparer.InvariantCultureIgnoreCase);
// Generate resource fetching properties
foreach (KeyValuePair<string, ResourceData> validResourceEntry in validResources)
{
string initialResourceKey;
if (!reverseFixupTable.TryGetValue(validResourceEntry.Key, out initialResourceKey))
initialResourceKey = validResourceEntry.Key;
if (!DefineResourceFetchingProperty(validResourceEntry.Key, initialResourceKey,
validResourceEntry.Value, codeTypeDeclaration, internalClass, useStatic))
{
unmatchable.Add(new ResourceErrorData(validResourceEntry.Key.ToString(),
string.Format(CultureInfo.CurrentCulture, CannotCreatePropertyForResource,
validResourceEntry.Key.ToString())));
}
else if (typeof(string) == validResourceEntry.Value.Type)
formatMethods.Add(validResourceEntry.Key, validResourceEntry.Value);
}
// Generate resource fetching format methods
foreach (KeyValuePair<string, ResourceData> formatMethodEntry in formatMethods)
{
try
{
string methodName = formatMethodEntry.Key + FormatSuffix;
// Check for duplicate method names
bool uniqueMethodName = true;
//.........这里部分代码省略.........
示例10: VerifyResourceNames
private static SortedList VerifyResourceNames(Dictionary<String, ResourceData> resourceList, CodeDomProvider codeProvider, ArrayList errors, out Hashtable reverseFixupTable)
{
reverseFixupTable = new Hashtable(0, StringComparer.InvariantCultureIgnoreCase);
SortedList cleanedResourceList = new SortedList(StringComparer.InvariantCultureIgnoreCase, resourceList.Count);
foreach(KeyValuePair<String, ResourceData> entry in resourceList) {
String key = entry.Key;
// Disallow a property named ResourceManager or Culture - we add
// those. (Any other properties we add also must be listed here)
// Also disallow resource values of type Void.
if (String.Equals(key, ResMgrPropertyName) ||
String.Equals(key, CultureInfoPropertyName) ||
typeof(void) == entry.Value.Type)
{
errors.Add(key);
continue;
}
// Ignore WinForms design time and hierarchy information.
// Skip resources starting with $ or >>, like "$this.Text",
// ">>$this.Name" or ">>treeView1.Parent".
if ((key.Length > 0 && key[0] == '$') ||
(key.Length > 1 && key[0] == '>' && key[1] == '>')) {
continue;
}
if (!codeProvider.IsValidIdentifier(key)) {
String newKey = VerifyResourceName(key, codeProvider, false);
if (newKey == null) {
errors.Add(key);
continue;
}
// Now see if we've already mapped another key to the
// same name.
String oldDuplicateKey = (String) reverseFixupTable[newKey];
if (oldDuplicateKey != null) {
// We can't handle this key nor the previous one.
// Remove the old one.
if (!errors.Contains(oldDuplicateKey))
errors.Add(oldDuplicateKey);
if (cleanedResourceList.Contains(newKey))
cleanedResourceList.Remove(newKey);
errors.Add(key);
continue;
}
reverseFixupTable[newKey] = key;
key = newKey;
}
ResourceData value = entry.Value;
if (!cleanedResourceList.Contains(key))
cleanedResourceList.Add(key, value);
else {
// There was a case-insensitive conflict between two keys.
// Or possibly one key was fixed up in a way that conflicts
// with another key (ie, "A B" and "A_B").
String fixedUp = (String) reverseFixupTable[key];
if (fixedUp != null) {
if (!errors.Contains(fixedUp))
errors.Add(fixedUp);
reverseFixupTable.Remove(key);
}
errors.Add(entry.Key);
cleanedResourceList.Remove(key);
}
}
return cleanedResourceList;
}
示例11: VerifyResourceName
// Once CodeDom provides a way to verify a namespace name, revisit this method.
private static String VerifyResourceName(String key, CodeDomProvider provider, bool isNameSpace) {
if (key == null)
throw new ArgumentNullException("key");
if (provider == null)
throw new ArgumentNullException("provider");
foreach(char c in CharsToReplace) {
// For namespaces, allow . and ::
if (!(isNameSpace && (c == '.' || c == ':')))
key = key.Replace(c, ReplacementChar);
}
if (provider.IsValidIdentifier(key))
return key;
// Now try fixing up keywords like "for".
key = provider.CreateValidIdentifier(key);
if (provider.IsValidIdentifier(key))
return key;
// make one last ditch effort by prepending _. This fixes keys that start with a number
key = "_" + key;
if (provider.IsValidIdentifier(key))
return key;
return null;
}
示例12: InternalCreate
private static CodeCompileUnit InternalCreate(Dictionary<String, ResourceData> resourceList, String baseName, String generatedCodeNamespace, String resourcesNamespace, CodeDomProvider codeProvider, bool internalClass, out String[] unmatchable)
{
if (baseName == null)
throw new ArgumentNullException("baseName");
if (codeProvider == null)
throw new ArgumentNullException("codeProvider");
// Keep a list of errors describing known strings that couldn't be
// fixed up (like "4"), as well as listing all duplicate resources that
// were fixed up to the same name (like "A B" and "A-B" both going to
// "A_B").
ArrayList errors = new ArrayList(0);
// Verify the resource names are valid property names, and they don't
// conflict. This includes checking for language-specific keywords,
// translating spaces to underscores, etc.
SortedList cleanedResourceList;
Hashtable reverseFixupTable;
cleanedResourceList = VerifyResourceNames(resourceList, codeProvider, errors, out reverseFixupTable);
// Verify the class name is legal.
String className = baseName;
// Attempt to fix up class name, and throw an exception if it fails.
if (!codeProvider.IsValidIdentifier(className)) {
String fixedClassName = VerifyResourceName(className, codeProvider);
if (fixedClassName != null)
className = fixedClassName;
}
if (!codeProvider.IsValidIdentifier(className))
throw new ArgumentException(SR.GetString(SR.InvalidIdentifier, className));
// If we have a namespace, verify the namespace is legal,
// attempting to fix it up if needed.
if (!String.IsNullOrEmpty(generatedCodeNamespace)) {
if (!codeProvider.IsValidIdentifier(generatedCodeNamespace)) {
String fixedNamespace = VerifyResourceName(generatedCodeNamespace, codeProvider, true);
if (fixedNamespace != null)
generatedCodeNamespace = fixedNamespace;
}
// Note we cannot really ensure that the generated code namespace
// is a valid identifier, as namespaces can have '.' and '::', but
// identifiers cannot.
}
CodeCompileUnit ccu = new CodeCompileUnit();
ccu.ReferencedAssemblies.Add("System.dll");
ccu.UserData.Add("AllowLateBound", false);
ccu.UserData.Add("RequireVariableDeclaration", true);
CodeNamespace ns = new CodeNamespace(generatedCodeNamespace);
ns.Imports.Add(new CodeNamespaceImport("System"));
ccu.Namespaces.Add(ns);
// Generate class
CodeTypeDeclaration srClass = new CodeTypeDeclaration(className);
ns.Types.Add(srClass);
AddGeneratedCodeAttributeforMember(srClass);
TypeAttributes ta = internalClass ? TypeAttributes.NotPublic : TypeAttributes.Public;
//ta |= TypeAttributes.Sealed;
srClass.TypeAttributes = ta;
srClass.Comments.Add(new CodeCommentStatement(DocCommentSummaryStart, true));
srClass.Comments.Add(new CodeCommentStatement(SR.GetString(SR.ClassDocComment), true));
CodeCommentStatement comment = new CodeCommentStatement(SR.GetString(SR.ClassComments1), true);
srClass.Comments.Add(comment);
comment = new CodeCommentStatement(SR.GetString(SR.ClassComments3), true);
srClass.Comments.Add(comment);
srClass.Comments.Add(new CodeCommentStatement(DocCommentSummaryEnd, true));
CodeTypeReference debuggerAttrib = new CodeTypeReference(typeof(System.Diagnostics.DebuggerNonUserCodeAttribute));
debuggerAttrib.Options = CodeTypeReferenceOptions.GlobalReference;
srClass.CustomAttributes.Add(new CodeAttributeDeclaration(debuggerAttrib));
CodeTypeReference compilerGenedAttrib = new CodeTypeReference(typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute));
compilerGenedAttrib.Options = CodeTypeReferenceOptions.GlobalReference;
srClass.CustomAttributes.Add(new CodeAttributeDeclaration(compilerGenedAttrib));
// Figure out some basic restrictions to the code generation
bool useStatic = internalClass || codeProvider.Supports(GeneratorSupport.PublicStaticMembers);
bool supportsTryCatch = codeProvider.Supports(GeneratorSupport.TryCatchStatements);
EmitBasicClassMembers(srClass, generatedCodeNamespace, baseName, resourcesNamespace, internalClass, useStatic, supportsTryCatch);
// Now for each resource, add a property
foreach(DictionaryEntry entry in cleanedResourceList) {
String propertyName = (String) entry.Key;
// The resourceName will be the original value, before fixups,
// if any.
String resourceName = (String) reverseFixupTable[propertyName];
if (resourceName == null)
resourceName = propertyName;
bool r = DefineResourceFetchingProperty(propertyName, resourceName, (ResourceData) entry.Value, srClass, internalClass, useStatic);
if (!r) {
errors.Add(entry.Key);
}
}
unmatchable = (String[]) errors.ToArray(typeof(String));
//.........这里部分代码省略.........
示例13: VerifyResourceName
private static string VerifyResourceName(string name, CodeDomProvider provider, bool isNameSpace)
{
if (null == name)
throw new ArgumentNullException("name");
if (null == provider)
throw new ArgumentNullException("provider");
for (int index = 0; index < _charsToReplace.Length; index++)
{
char ch = _charsToReplace[index];
if (!isNameSpace || ((ch != '.') && (ch != ':')))
name = name.Replace(ch, ReplacementChar);
}
if (provider.IsValidIdentifier(name))
return name;
name = provider.CreateValidIdentifier(name);
if (provider.IsValidIdentifier(name))
return name;
name = "_" + name;
if (provider.IsValidIdentifier(name))
return name;
return null;
}
示例14: SanitizeResourceName
string SanitizeResourceName (CodeDomProvider provider, string name)
{
if (provider.IsValidIdentifier (name))
return provider.CreateEscapedIdentifier (name);
var sb = new StringBuilder ();
char ch = name [0];
if (is_identifier_start_character (ch))
sb.Append (ch);
else {
sb.Append ('_');
if (ch >= '0' && ch <= '9')
sb.Append (ch);
}
for (int i = 1; i < name.Length; i++) {
ch = name [i];
if (is_identifier_part_character (ch))
sb.Append (ch);
else
sb.Append ('_');
}
return provider.CreateEscapedIdentifier (sb.ToString ());
}
示例15: DomFromResource
// CodeDOM generation
void DomFromResource (string resfile, CodeCompileUnit unit, Dictionary <string,bool> assemblies,
CodeDomProvider provider)
{
if (String.IsNullOrEmpty (resfile))
return;
string fname, nsname, classname;
fname = Path.GetFileNameWithoutExtension (resfile);
nsname = Path.GetFileNameWithoutExtension (fname);
classname = Path.GetExtension (fname);
if (classname == null || classname.Length == 0) {
classname = nsname;
nsname = "Resources";
} else {
if (!nsname.StartsWith ("Resources", StringComparison.InvariantCulture))
nsname = String.Concat ("Resources.", nsname);
classname = classname.Substring(1);
}
if (!String.IsNullOrEmpty (classname))
classname = classname.Replace ('.', '_');
if (!String.IsNullOrEmpty (nsname))
nsname = nsname.Replace ('.', '_');
if (!provider.IsValidIdentifier (nsname) || !provider.IsValidIdentifier (classname))
throw new ApplicationException ("Invalid resource file name.");
ResourceReader res;
try {
res = new ResourceReader (resfile);
} catch (ArgumentException) {
// invalid stream, probably empty - ignore silently and abort
return;
}
CodeNamespace ns = new CodeNamespace (nsname);
CodeTypeDeclaration cls = new CodeTypeDeclaration (classname);
cls.IsClass = true;
cls.TypeAttributes = TypeAttributes.Public | TypeAttributes.Sealed;
CodeMemberField cmf = new CodeMemberField (typeof(CultureInfo), "_culture");
cmf.InitExpression = new CodePrimitiveExpression (null);
cmf.Attributes = MemberAttributes.Private | MemberAttributes.Final | MemberAttributes.Static;
cls.Members.Add (cmf);
cmf = new CodeMemberField (typeof(ResourceManager), "_resourceManager");
cmf.InitExpression = new CodePrimitiveExpression (null);
cmf.Attributes = MemberAttributes.Private | MemberAttributes.Final | MemberAttributes.Static;
cls.Members.Add (cmf);
// Property: ResourceManager
CodeMemberProperty cmp = new CodeMemberProperty ();
cmp.Attributes = MemberAttributes.Public | MemberAttributes.Final | MemberAttributes.Static;
cmp.Name = "ResourceManager";
cmp.HasGet = true;
cmp.Type = new CodeTypeReference (typeof(ResourceManager));
CodePropertyResourceManagerGet (cmp.GetStatements, resfile, classname);
cls.Members.Add (cmp);
// Property: Culture
cmp = new CodeMemberProperty ();
cmp.Attributes = MemberAttributes.Public | MemberAttributes.Final;
cmp.Attributes = MemberAttributes.Public | MemberAttributes.Final | MemberAttributes.Static;
cmp.Name = "Culture";
cmp.HasGet = true;
cmp.HasSet = true;
cmp.Type = new CodeTypeReference (typeof(CultureInfo));
CodePropertyGenericGet (cmp.GetStatements, "_culture", classname);
CodePropertyGenericSet (cmp.SetStatements, "_culture", classname);
cls.Members.Add (cmp);
// Add the resource properties
Dictionary<string,bool> imports = new Dictionary<string,bool> ();
try {
foreach (DictionaryEntry de in res) {
Type type = de.Value.GetType ();
if (!imports.ContainsKey (type.Namespace))
imports [type.Namespace] = true;
string asname = new AssemblyName (type.Assembly.FullName).Name;
if (!assemblies.ContainsKey (asname))
assemblies [asname] = true;
cmp = new CodeMemberProperty ();
cmp.Attributes = MemberAttributes.Public | MemberAttributes.Final | MemberAttributes.Static;
cmp.Name = SanitizeResourceName (provider, (string)de.Key);
cmp.HasGet = true;
CodePropertyResourceGet (cmp.GetStatements, (string)de.Key, type, classname);
cmp.Type = new CodeTypeReference (type);
cls.Members.Add (cmp);
}
} catch (Exception ex) {
throw new ApplicationException ("Failed to compile global resources.", ex);
}
foreach (KeyValuePair<string,bool> de in imports)
ns.Imports.Add (new CodeNamespaceImport(de.Key));
//.........这里部分代码省略.........