Code:
/ 4.0 / 4.0 / DEVDIV_TFS / Dev10 / Releases / RTMRel / ndp / fx / src / Services / Messaging / System / Messaging / XmlMessageFormatter.cs / 1305376 / XmlMessageFormatter.cs
//------------------------------------------------------------------------------ //// Copyright (c) Microsoft Corporation. All rights reserved. // //----------------------------------------------------------------------------- namespace System.Messaging { using System; using System.IO; using System.Xml; using System.Collections; using System.Xml.Serialization; using System.ComponentModel; using System.Security.Permissions; ////// /// Formatter class that serializes and deserializes objects into /// and from MessageQueue messages using Xml. /// public class XmlMessageFormatter : IMessageFormatter { private Type[] targetTypes; private string[] targetTypeNames; Hashtable targetSerializerTable = new Hashtable(); private bool typeNamesAdded; private bool typesAdded; ////// /// Creates a new Xml message formatter object. /// public XmlMessageFormatter() { this.TargetTypes = new Type[0]; this.TargetTypeNames = new string[0]; } ////// /// Creates a new Xml message formatter object, /// using the given properties. /// public XmlMessageFormatter(string[] targetTypeNames) { this.TargetTypeNames = targetTypeNames; this.TargetTypes = new Type[0]; } ////// /// Creates a new Xml message formatter object, /// using the given properties. /// public XmlMessageFormatter(Type[] targetTypes) { this.TargetTypes = targetTypes; this.TargetTypeNames = new string[0]; } ////// /// Specifies the set of possible types that will /// be deserialized by the formatter from the /// message provided. /// [MessagingDescription(Res.XmlMsgTargetTypeNames)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public string[] TargetTypeNames { get { return this.targetTypeNames; } set { if (value == null) throw new ArgumentNullException("value"); this.typeNamesAdded = false; this.targetTypeNames = value; } } ////// /// Specifies the set of possible types that will /// be deserialized by the formatter from the /// message provided. /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MessagingDescription(Res.XmlMsgTargetTypes)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public Type[] TargetTypes { get { return this.targetTypes; } set { if (value == null) throw new ArgumentNullException("value"); this.typesAdded = false; this.targetTypes = value; } } ////// /// When this method is called, the formatter will attempt to determine /// if the contents of the message are something the formatter can deal with. /// public bool CanRead(Message message) { if (message == null) throw new ArgumentNullException("message"); this.CreateTargetSerializerTable(); Stream stream = message.BodyStream; XmlTextReader reader = new XmlTextReader(stream); reader.WhitespaceHandling = WhitespaceHandling.Significant; reader.DtdProcessing = DtdProcessing.Prohibit; bool result = false; foreach (XmlSerializer serializer in targetSerializerTable.Values) { if (serializer.CanDeserialize(reader)) { result = true; break; } } message.BodyStream.Position = 0; // reset stream in case CanRead is followed by Deserialize return result; } ////// /// This method is needed to improve scalability on Receive and ReceiveAsync scenarios. Not requiring /// thread safety on read and write. /// public object Clone() { XmlMessageFormatter formatter = new XmlMessageFormatter(); formatter.targetTypes = targetTypes; formatter.targetTypeNames = targetTypeNames; formatter.typesAdded = typesAdded; formatter.typeNamesAdded = typeNamesAdded; foreach (Type targetType in targetSerializerTable.Keys) formatter.targetSerializerTable[targetType] = new XmlSerializer(targetType); return formatter; } ///private void CreateTargetSerializerTable() { if (!this.typeNamesAdded) { for (int index = 0; index < this.targetTypeNames.Length; ++ index) { Type targetType = Type.GetType(this.targetTypeNames[index], true); if (targetType != null) this.targetSerializerTable[targetType] = new XmlSerializer(targetType); } this.typeNamesAdded = true; } if (!this.typesAdded) { for (int index = 0; index < this.targetTypes.Length; ++ index) this.targetSerializerTable[this.targetTypes[index]] = new XmlSerializer(this.targetTypes[index]); this.typesAdded = true; } if (this.targetSerializerTable.Count == 0) throw new InvalidOperationException(Res.GetString(Res.TypeListMissing)); } /// /// /// This method is used to read the contents from the given message /// and create an object. /// public object Read(Message message) { if (message == null) throw new ArgumentNullException("message"); this.CreateTargetSerializerTable(); Stream stream = message.BodyStream; XmlTextReader reader = new XmlTextReader(stream); reader.WhitespaceHandling = WhitespaceHandling.Significant; reader.DtdProcessing = DtdProcessing.Prohibit; foreach (XmlSerializer serializer in targetSerializerTable.Values) { if (serializer.CanDeserialize(reader)) return serializer.Deserialize(reader); } throw new InvalidOperationException(Res.GetString(Res.InvalidTypeDeserialization)); } ////// /// This method is used to write the given object into the given message. /// If the formatter cannot understand the given object, an exception is thrown. /// public void Write(Message message, object obj) { if (message == null) throw new ArgumentNullException("message"); if (obj == null) throw new ArgumentNullException("obj"); Stream stream = new MemoryStream(); Type serializedType = obj.GetType(); XmlSerializer serializer = null; if (this.targetSerializerTable.ContainsKey(serializedType)) serializer = (XmlSerializer)this.targetSerializerTable[serializedType]; else { serializer = new XmlSerializer(serializedType); this.targetSerializerTable[serializedType] = serializer; } serializer.Serialize(stream, obj); message.BodyStream = stream; //Need to reset the body type, in case the same message //is reused by some other formatter. message.BodyType = 0; } } } // File provided for Reference Use Only by Microsoft Corporation (c) 2007. //------------------------------------------------------------------------------ //// Copyright (c) Microsoft Corporation. All rights reserved. // //----------------------------------------------------------------------------- namespace System.Messaging { using System; using System.IO; using System.Xml; using System.Collections; using System.Xml.Serialization; using System.ComponentModel; using System.Security.Permissions; ////// /// Formatter class that serializes and deserializes objects into /// and from MessageQueue messages using Xml. /// public class XmlMessageFormatter : IMessageFormatter { private Type[] targetTypes; private string[] targetTypeNames; Hashtable targetSerializerTable = new Hashtable(); private bool typeNamesAdded; private bool typesAdded; ////// /// Creates a new Xml message formatter object. /// public XmlMessageFormatter() { this.TargetTypes = new Type[0]; this.TargetTypeNames = new string[0]; } ////// /// Creates a new Xml message formatter object, /// using the given properties. /// public XmlMessageFormatter(string[] targetTypeNames) { this.TargetTypeNames = targetTypeNames; this.TargetTypes = new Type[0]; } ////// /// Creates a new Xml message formatter object, /// using the given properties. /// public XmlMessageFormatter(Type[] targetTypes) { this.TargetTypes = targetTypes; this.TargetTypeNames = new string[0]; } ////// /// Specifies the set of possible types that will /// be deserialized by the formatter from the /// message provided. /// [MessagingDescription(Res.XmlMsgTargetTypeNames)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public string[] TargetTypeNames { get { return this.targetTypeNames; } set { if (value == null) throw new ArgumentNullException("value"); this.typeNamesAdded = false; this.targetTypeNames = value; } } ////// /// Specifies the set of possible types that will /// be deserialized by the formatter from the /// message provided. /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MessagingDescription(Res.XmlMsgTargetTypes)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public Type[] TargetTypes { get { return this.targetTypes; } set { if (value == null) throw new ArgumentNullException("value"); this.typesAdded = false; this.targetTypes = value; } } ////// /// When this method is called, the formatter will attempt to determine /// if the contents of the message are something the formatter can deal with. /// public bool CanRead(Message message) { if (message == null) throw new ArgumentNullException("message"); this.CreateTargetSerializerTable(); Stream stream = message.BodyStream; XmlTextReader reader = new XmlTextReader(stream); reader.WhitespaceHandling = WhitespaceHandling.Significant; reader.DtdProcessing = DtdProcessing.Prohibit; bool result = false; foreach (XmlSerializer serializer in targetSerializerTable.Values) { if (serializer.CanDeserialize(reader)) { result = true; break; } } message.BodyStream.Position = 0; // reset stream in case CanRead is followed by Deserialize return result; } ////// /// This method is needed to improve scalability on Receive and ReceiveAsync scenarios. Not requiring /// thread safety on read and write. /// public object Clone() { XmlMessageFormatter formatter = new XmlMessageFormatter(); formatter.targetTypes = targetTypes; formatter.targetTypeNames = targetTypeNames; formatter.typesAdded = typesAdded; formatter.typeNamesAdded = typeNamesAdded; foreach (Type targetType in targetSerializerTable.Keys) formatter.targetSerializerTable[targetType] = new XmlSerializer(targetType); return formatter; } ///private void CreateTargetSerializerTable() { if (!this.typeNamesAdded) { for (int index = 0; index < this.targetTypeNames.Length; ++ index) { Type targetType = Type.GetType(this.targetTypeNames[index], true); if (targetType != null) this.targetSerializerTable[targetType] = new XmlSerializer(targetType); } this.typeNamesAdded = true; } if (!this.typesAdded) { for (int index = 0; index < this.targetTypes.Length; ++ index) this.targetSerializerTable[this.targetTypes[index]] = new XmlSerializer(this.targetTypes[index]); this.typesAdded = true; } if (this.targetSerializerTable.Count == 0) throw new InvalidOperationException(Res.GetString(Res.TypeListMissing)); } /// /// /// This method is used to read the contents from the given message /// and create an object. /// public object Read(Message message) { if (message == null) throw new ArgumentNullException("message"); this.CreateTargetSerializerTable(); Stream stream = message.BodyStream; XmlTextReader reader = new XmlTextReader(stream); reader.WhitespaceHandling = WhitespaceHandling.Significant; reader.DtdProcessing = DtdProcessing.Prohibit; foreach (XmlSerializer serializer in targetSerializerTable.Values) { if (serializer.CanDeserialize(reader)) return serializer.Deserialize(reader); } throw new InvalidOperationException(Res.GetString(Res.InvalidTypeDeserialization)); } ////// /// This method is used to write the given object into the given message. /// If the formatter cannot understand the given object, an exception is thrown. /// public void Write(Message message, object obj) { if (message == null) throw new ArgumentNullException("message"); if (obj == null) throw new ArgumentNullException("obj"); Stream stream = new MemoryStream(); Type serializedType = obj.GetType(); XmlSerializer serializer = null; if (this.targetSerializerTable.ContainsKey(serializedType)) serializer = (XmlSerializer)this.targetSerializerTable[serializedType]; else { serializer = new XmlSerializer(serializedType); this.targetSerializerTable[serializedType] = serializer; } serializer.Serialize(stream, obj); message.BodyStream = stream; //Need to reset the body type, in case the same message //is reused by some other formatter. message.BodyType = 0; } } } // File provided for Reference Use Only by Microsoft Corporation (c) 2007.
Link Menu
This book is available now!
Buy at Amazon US or
Buy at Amazon UK
- PageThemeBuildProvider.cs
- SqlDataSourceStatusEventArgs.cs
- WebSysDisplayNameAttribute.cs
- RelationshipDetailsCollection.cs
- PackagePartCollection.cs
- Emitter.cs
- AudioSignalProblemOccurredEventArgs.cs
- SelectionList.cs
- Int32Collection.cs
- FixedSOMTextRun.cs
- IIS7UserPrincipal.cs
- UserPersonalizationStateInfo.cs
- DataGridViewRowConverter.cs
- AtomMaterializerLog.cs
- X509Certificate.cs
- TreeBuilder.cs
- X509AsymmetricSecurityKey.cs
- RoutedUICommand.cs
- ControlPaint.cs
- TypedDataSourceCodeGenerator.cs
- ExclusiveTcpListener.cs
- SelectorItemAutomationPeer.cs
- ControlAdapter.cs
- filewebrequest.cs
- BinaryWriter.cs
- ResourceExpressionBuilder.cs
- WebControl.cs
- XmlFormatWriterGenerator.cs
- XmlNode.cs
- ToolStripDropDownButton.cs
- TreeNode.cs
- FrameworkElementFactory.cs
- TextServicesLoader.cs
- XmlSchemaAttribute.cs
- PrinterResolution.cs
- WmlCalendarAdapter.cs
- RectangleGeometry.cs
- ScriptResourceHandler.cs
- Intellisense.cs
- SelectionProviderWrapper.cs
- HashMembershipCondition.cs
- HttpCapabilitiesSectionHandler.cs
- CharEntityEncoderFallback.cs
- ObjectManager.cs
- ManagedWndProcTracker.cs
- ClockGroup.cs
- StylesEditorDialog.cs
- XmlBindingWorker.cs
- GridItemPattern.cs
- HMAC.cs
- Geometry.cs
- EncodingTable.cs
- StringValidatorAttribute.cs
- PeerEndPoint.cs
- Model3DGroup.cs
- DbMetaDataColumnNames.cs
- VirtualStackFrame.cs
- HeaderCollection.cs
- WpfGeneratedKnownTypes.cs
- SmiEventStream.cs
- Task.cs
- FileEnumerator.cs
- UserControlAutomationPeer.cs
- DoubleAnimationBase.cs
- PublisherMembershipCondition.cs
- ExceptionValidationRule.cs
- SqlInfoMessageEvent.cs
- NameValueCollection.cs
- ConstraintConverter.cs
- DesignerObjectListAdapter.cs
- X509CertificateTrustedIssuerElement.cs
- SecurityHelper.cs
- HttpPostLocalhostServerProtocol.cs
- CommandDevice.cs
- EventSourceCreationData.cs
- Emitter.cs
- MinimizableAttributeTypeConverter.cs
- Preprocessor.cs
- PickDesigner.xaml.cs
- WsatServiceAddress.cs
- LicenseProviderAttribute.cs
- MissingFieldException.cs
- SqlBulkCopyColumnMapping.cs
- SiteMapHierarchicalDataSourceView.cs
- XmlDataDocument.cs
- Unit.cs
- ProjectionCamera.cs
- AnonymousIdentificationModule.cs
- FeatureSupport.cs
- HTTPNotFoundHandler.cs
- Stroke2.cs
- Encoding.cs
- PageSetupDialog.cs
- HandlerFactoryWrapper.cs
- SplitContainerDesigner.cs
- UmAlQuraCalendar.cs
- DrawingContextDrawingContextWalker.cs
- GridPattern.cs
- ColorConverter.cs
- Triangle.cs