1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
|
//------------------------------------------------------------------------------
// <copyright file="CodeExporter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">Microsoft</owner>
//------------------------------------------------------------------------------
namespace System.Xml.Serialization {
using System;
using System.Collections;
using System.IO;
using System.ComponentModel;
using System.Xml.Schema;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Reflection;
using System.Globalization;
using System.Diagnostics;
using System.Security.Permissions;
/// <include file='doc\CodeExporter.uex' path='docs/doc[@for="CodeExporter"]/*' />
///<internalonly/>
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
public abstract class CodeExporter {
Hashtable exportedMappings;
Hashtable exportedClasses; // TypeMapping -> CodeTypeDeclaration
CodeNamespace codeNamespace;
CodeCompileUnit codeCompileUnit;
bool rootExported;
TypeScope scope;
CodeAttributeDeclarationCollection includeMetadata = new CodeAttributeDeclarationCollection();
CodeGenerationOptions options;
CodeDomProvider codeProvider;
CodeAttributeDeclaration generatedCodeAttribute;
internal CodeExporter(CodeNamespace codeNamespace, CodeCompileUnit codeCompileUnit, CodeDomProvider codeProvider, CodeGenerationOptions options, Hashtable exportedMappings) {
if (codeNamespace != null)
CodeGenerator.ValidateIdentifiers(codeNamespace);
this.codeNamespace = codeNamespace;
if (codeCompileUnit != null) {
if (!codeCompileUnit.ReferencedAssemblies.Contains("System.dll"))
codeCompileUnit.ReferencedAssemblies.Add("System.dll");
if (!codeCompileUnit.ReferencedAssemblies.Contains("System.Xml.dll"))
codeCompileUnit.ReferencedAssemblies.Add("System.Xml.dll");
}
this.codeCompileUnit = codeCompileUnit;
this.options = options;
this.exportedMappings = exportedMappings;
this.codeProvider = codeProvider;
}
internal CodeCompileUnit CodeCompileUnit {
get { return codeCompileUnit; }
}
internal CodeNamespace CodeNamespace {
get {
if (codeNamespace == null)
codeNamespace = new CodeNamespace();
return codeNamespace;
}
}
internal CodeDomProvider CodeProvider {
get {
if (codeProvider == null)
codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
return codeProvider;
}
}
internal Hashtable ExportedClasses {
get {
if (exportedClasses == null)
exportedClasses = new Hashtable();
return exportedClasses;
}
}
internal Hashtable ExportedMappings {
get {
if (exportedMappings == null)
exportedMappings = new Hashtable();
return exportedMappings;
}
}
internal bool GenerateProperties {
get { return (options & CodeGenerationOptions.GenerateProperties) != 0; }
}
internal CodeAttributeDeclaration GeneratedCodeAttribute {
get {
if (generatedCodeAttribute == null) {
CodeAttributeDeclaration decl = new CodeAttributeDeclaration(typeof(GeneratedCodeAttribute).FullName);
Assembly a = Assembly.GetEntryAssembly();
if (a == null) {
a = Assembly.GetExecutingAssembly();
if (a == null) {
a = typeof(CodeExporter).Assembly;
}
}
AssemblyName assemblyName = a.GetName();
decl.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(assemblyName.Name)));
string version = GetProductVersion(a);
decl.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(version == null ? assemblyName.Version.ToString() : version)));
generatedCodeAttribute = decl;
}
return generatedCodeAttribute;
}
}
internal static CodeAttributeDeclaration FindAttributeDeclaration(Type type, CodeAttributeDeclarationCollection metadata) {
foreach (CodeAttributeDeclaration attribute in metadata) {
if (attribute.Name == type.FullName || attribute.Name == type.Name) {
return attribute;
}
}
return null;
}
private static string GetProductVersion(Assembly assembly) {
object[] attributes = assembly.GetCustomAttributes(true);
for ( int i = 0; i<attributes.Length; i++ ) {
if (attributes[i] is AssemblyInformationalVersionAttribute) {
AssemblyInformationalVersionAttribute version = (AssemblyInformationalVersionAttribute)attributes[i];
return version.InformationalVersion;
}
}
return null;
}
/// <include file='doc\XmlCodeExporter.uex' path='docs/doc[@for="XmlCodeExporter.IncludeMetadata"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public CodeAttributeDeclarationCollection IncludeMetadata {
get { return includeMetadata; }
}
internal TypeScope Scope {
get { return scope; }
}
internal void CheckScope(TypeScope scope) {
if (this.scope == null) {
this.scope = scope;
}
else if (this.scope != scope) {
throw new InvalidOperationException(Res.GetString(Res.XmlMappingsScopeMismatch));
}
}
internal abstract void ExportDerivedStructs(StructMapping mapping);
internal abstract void EnsureTypesExported(Accessor[] accessors, string ns);
internal static void AddWarningComment(CodeCommentStatementCollection comments, string text) {
Debug.Assert(comments != null);
comments.Add(new CodeCommentStatement(Res.GetString(Res.XmlCodegenWarningDetails, text), false));
}
internal void ExportRoot(StructMapping mapping, Type includeType) {
if (!rootExported) {
rootExported = true;
ExportDerivedStructs(mapping);
for (StructMapping derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) {
if (!derived.ReferencedByElement && derived.IncludeInSchema && !derived.IsAnonymousType) {
CodeAttributeDeclaration include = new CodeAttributeDeclaration(includeType.FullName);
include.Arguments.Add(new CodeAttributeArgument(new CodeTypeOfExpression(derived.TypeDesc.FullName)));
includeMetadata.Add(include);
}
}
Hashtable typesIncluded = new Hashtable();
foreach (TypeMapping m in Scope.TypeMappings) {
if (m is ArrayMapping) {
ArrayMapping arrayMapping = (ArrayMapping) m;
if (ShouldInclude(arrayMapping) && !typesIncluded.Contains(arrayMapping.TypeDesc.FullName)) {
CodeAttributeDeclaration include = new CodeAttributeDeclaration(includeType.FullName);
include.Arguments.Add(new CodeAttributeArgument(new CodeTypeOfExpression(arrayMapping.TypeDesc.FullName)));
includeMetadata.Add(include);
typesIncluded.Add(arrayMapping.TypeDesc.FullName, string.Empty);
EnsureTypesExported(arrayMapping.Elements, arrayMapping.Namespace);
}
}
}
}
}
private static bool ShouldInclude(ArrayMapping arrayMapping) {
if (arrayMapping.ReferencedByElement)
return false;
if (arrayMapping.Next != null)
return false;
if (arrayMapping.Elements.Length == 1) {
TypeKind kind = arrayMapping.Elements[0].Mapping.TypeDesc.Kind;
if (kind == TypeKind.Node)
return false;
}
for (int i = 0; i < arrayMapping.Elements.Length; i++) {
if (arrayMapping.Elements[i].Name != arrayMapping.Elements[i].Mapping.DefaultElementName) {
// in the case we need custom attributes to serialize an array instance, we cannot include arrau mapping without explicit reference.
return false;
}
}
return true;
}
internal CodeTypeDeclaration ExportEnum(EnumMapping mapping, Type type) {
CodeTypeDeclaration codeClass = new CodeTypeDeclaration(mapping.TypeDesc.Name);
codeClass.Comments.Add(new CodeCommentStatement(Res.GetString(Res.XmlRemarks), true));
codeClass.IsEnum = true;
if (mapping.IsFlags && mapping.Constants.Length > 31) {
codeClass.BaseTypes.Add(new CodeTypeReference(typeof(long)));
}
codeClass.TypeAttributes |= TypeAttributes.Public;
CodeNamespace.Types.Add(codeClass);
for (int i = 0; i < mapping.Constants.Length; i++) {
ExportConstant(codeClass, mapping.Constants[i], type, mapping.IsFlags, 1L << i);
}
if (mapping.IsFlags) {
// Add [FlagsAttribute]
CodeAttributeDeclaration flags = new CodeAttributeDeclaration(typeof(FlagsAttribute).FullName);
codeClass.CustomAttributes.Add(flags);
}
CodeGenerator.ValidateIdentifiers(codeClass);
return codeClass;
}
internal void AddTypeMetadata(CodeAttributeDeclarationCollection metadata, Type type, string defaultName, string name, string ns, bool includeInSchema) {
CodeAttributeDeclaration attribute = new CodeAttributeDeclaration(type.FullName);
if (name == null || name.Length == 0) {
attribute.Arguments.Add(new CodeAttributeArgument("AnonymousType", new CodePrimitiveExpression(true)));
}
else {
if (defaultName != name) {
attribute.Arguments.Add(new CodeAttributeArgument("TypeName", new CodePrimitiveExpression(name)));
}
}
if (ns != null && ns.Length != 0) {
attribute.Arguments.Add(new CodeAttributeArgument("Namespace", new CodePrimitiveExpression(ns)));
}
if (!includeInSchema) {
attribute.Arguments.Add(new CodeAttributeArgument("IncludeInSchema", new CodePrimitiveExpression(false)));
}
if (attribute.Arguments.Count > 0) {
metadata.Add(attribute);
}
}
internal static void AddIncludeMetadata(CodeAttributeDeclarationCollection metadata, StructMapping mapping, Type type) {
if (mapping.IsAnonymousType)
return;
for (StructMapping derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) {
CodeAttributeDeclaration attribute = new CodeAttributeDeclaration(type.FullName);
attribute.Arguments.Add(new CodeAttributeArgument(new CodeTypeOfExpression(derived.TypeDesc.FullName)));
metadata.Add(attribute);
AddIncludeMetadata(metadata, derived, type);
}
}
internal static void ExportConstant(CodeTypeDeclaration codeClass, ConstantMapping constant, Type type, bool init, long enumValue) {
CodeMemberField field = new CodeMemberField(typeof(int).FullName, constant.Name);
field.Comments.Add(new CodeCommentStatement(Res.GetString(Res.XmlRemarks), true));
if (init)
field.InitExpression = new CodePrimitiveExpression(enumValue);
codeClass.Members.Add(field);
if (constant.XmlName != constant.Name) {
CodeAttributeDeclaration attribute = new CodeAttributeDeclaration(type.FullName);
attribute.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(constant.XmlName)));
field.CustomAttributes.Add(attribute);
}
}
internal static object PromoteType(Type type, object value) {
if (type == typeof(sbyte)) {
return ((IConvertible)value).ToInt16(null);
}
else if (type == typeof(UInt16)) {
return ((IConvertible)value).ToInt32(null);
}
else if (type == typeof(UInt32)) {
return ((IConvertible)value).ToInt64(null);
}
else if (type == typeof(UInt64)) {
return ((IConvertible)value).ToDecimal(null);
}
else {
return value;
}
}
internal CodeMemberProperty CreatePropertyDeclaration(CodeMemberField field, string name, string typeName) {
CodeMemberProperty prop = new CodeMemberProperty();
prop.Type = new CodeTypeReference(typeName);
prop.Name = name;
prop.Attributes = (prop.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
//add get
CodeMethodReturnStatement ret = new CodeMethodReturnStatement();
ret.Expression = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), field.Name);
prop.GetStatements.Add(ret);
CodeAssignStatement propertySet = new CodeAssignStatement();
CodeExpression left = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), field.Name);
CodeExpression right = new CodePropertySetValueReferenceExpression();
propertySet.Left = left;
propertySet.Right = right;
if (EnableDataBinding)
{
prop.SetStatements.Add(propertySet);
prop.SetStatements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), RaisePropertyChangedEventMethod.Name, new CodePrimitiveExpression(name)));
}
else
prop.SetStatements.Add(propertySet);
return prop;
}
internal static string MakeFieldName(string name) {
return CodeIdentifier.MakeCamel(name) + "Field";
}
internal void AddPropertyChangedNotifier(CodeTypeDeclaration codeClass)
{
if (EnableDataBinding && codeClass != null)
{
if (codeClass.BaseTypes.Count == 0)
{
codeClass.BaseTypes.Add(typeof(object));
}
codeClass.BaseTypes.Add(new CodeTypeReference(typeof(System.ComponentModel.INotifyPropertyChanged)));
codeClass.Members.Add(PropertyChangedEvent);
codeClass.Members.Add(RaisePropertyChangedEventMethod);
}
}
bool EnableDataBinding {
get { return (options & CodeGenerationOptions.EnableDataBinding) != 0; }
}
internal static CodeMemberMethod RaisePropertyChangedEventMethod
{
get
{
CodeMemberMethod raisePropertyChangedEventMethod = new CodeMemberMethod();
raisePropertyChangedEventMethod.Name = "RaisePropertyChanged";
raisePropertyChangedEventMethod.Attributes = MemberAttributes.Family | MemberAttributes.Final;
CodeArgumentReferenceExpression propertyName = new CodeArgumentReferenceExpression("propertyName");
raisePropertyChangedEventMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), propertyName.ParameterName));
CodeVariableReferenceExpression propertyChanged = new CodeVariableReferenceExpression("propertyChanged");
raisePropertyChangedEventMethod.Statements.Add(new CodeVariableDeclarationStatement(typeof(PropertyChangedEventHandler), propertyChanged.VariableName, new CodeEventReferenceExpression(new CodeThisReferenceExpression(), PropertyChangedEvent.Name)));
CodeConditionStatement ifStatement = new CodeConditionStatement(new CodeBinaryOperatorExpression(propertyChanged, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null)));
raisePropertyChangedEventMethod.Statements.Add(ifStatement);
ifStatement.TrueStatements.Add(new CodeDelegateInvokeExpression(propertyChanged, new CodeThisReferenceExpression(), new CodeObjectCreateExpression(typeof(PropertyChangedEventArgs), propertyName)));
return raisePropertyChangedEventMethod;
}
}
internal static CodeMemberEvent PropertyChangedEvent
{
get
{
CodeMemberEvent propertyChangedEvent = new CodeMemberEvent();
propertyChangedEvent.Attributes = MemberAttributes.Public;
propertyChangedEvent.Name = "PropertyChanged";
propertyChangedEvent.Type = new CodeTypeReference(typeof(PropertyChangedEventHandler));
propertyChangedEvent.ImplementationTypes.Add(typeof(System.ComponentModel.INotifyPropertyChanged));
return propertyChangedEvent;
}
}
}
}
|