Example #1
0
        private static void DumpSerializerErrors(YAXSerializer serializer)
        {
            for (int i = 0; i < serializer.ParsingErrors.Count; i++)
            {
                var error = serializer.ParsingErrors[i];
                YAXExceptionTypes errorLevel = error.Value;

                if (error.Key is YAXAttributeMissingException ||
                    error.Key is YAXElementMissingException ||
                    error.Key is YAXElementValueMissingException)
                {
                    errorLevel = YAXExceptionTypes.Warning;
                }

                switch (errorLevel)
                {
                case YAXExceptionTypes.Error:
                    MyLog.ERROR.WriteLine(error.Key.Message);
                    break;

                case YAXExceptionTypes.Warning:
                    MyLog.WARNING.WriteLine(error.Key.Message);
                    break;

                default:
                    break;
                }
            }
        }
Example #2
0
        private void OnSerialize(bool saveToFile)
        {
            object selItem = lstSampleClasses.SelectedItem;

            if (selItem == null || !(selItem is ClassInfoListItem))
            {
                return;
            }

            string fileName = null;

            if (saveToFile)
            {
                if (DialogResult.OK != saveFileDialog1.ShowDialog())
                {
                    return;
                }
                fileName = saveFileDialog1.FileName;
            }

            ClassInfoListItem            info          = selItem as ClassInfoListItem;
            YAXExceptionTypes            defaultExType = GetSelectedDefaultExceptionType();
            YAXExceptionHandlingPolicies exPolicy      = GetSelectedExceptionHandlingPolicy();
            YAXSerializationOptions      serOption     = GetSelectedSerializationOption();

            try
            {
                YAXSerializer serializer = new YAXSerializer(info.ClassType, exPolicy, defaultExType, serOption);
                serializer.MaxRecursion = Convert.ToInt32(numMaxRecursion.Value);

                if (saveToFile)
                {
                    serializer.SerializeToFile(info.SampleObject, fileName);
                }
                else
                {
                    rtbXMLOutput.Text = serializer.Serialize(info.SampleObject);
                }
                rtbParsingErrors.Text = serializer.ParsingErrors.ToString();
            }
            catch (YAXException ex)
            {
                MessageBox.Show("YAXException handled:\r\n\r\n" + ex.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show("Other Exception handled:\r\n\r\n" + ex.ToString());
            }
        }
Example #3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="YAXErrorIfMissedAttribute"/> class.
 /// </summary>
 /// <param name="treatAs">The value indicating this situation is going to be treated as Error or Warning.</param>
 public YAXErrorIfMissedAttribute(YAXExceptionTypes treatAs)
 {
     this.TreatAs      = treatAs;
     this.DefaultValue = null;
 }
 /// <summary>
 /// Adds an exception with the corresponding type.
 /// </summary>
 /// <param name="exception">The exception to add.</param>
 /// <param name="exceptionType">Type of the exception added.</param>
 public void AddException(YAXException exception, YAXExceptionTypes exceptionType)
 {
     this.listExceptions.Add(new KeyValuePair<YAXException, YAXExceptionTypes>(exception, exceptionType));
 }
Example #5
0
        /// <summary>
        /// Called when an exception occurs inside the library. It applies the exception handling policies.
        /// </summary>
        /// <param name="ex">The exception that has occurred.</param>
        /// <param name="exceptionType">Type of the exception.</param>
        private void OnExceptionOccurred(YAXException ex, YAXExceptionTypes exceptionType)
        {
            m_exceptionOccurredDuringMemberDeserialization = true;
            if (exceptionType == YAXExceptionTypes.Ignore)
            {
                return;
            }

            this.m_parsingErrors.AddException(ex, exceptionType);
            if ((this.m_exceptionPolicy == YAXExceptionHandlingPolicies.ThrowWarningsAndErrors) ||
                (this.m_exceptionPolicy == YAXExceptionHandlingPolicies.ThrowErrorsOnly && exceptionType == YAXExceptionTypes.Error))
            {
                throw ex;
            }
        }
Example #6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="YAXSerializer"/> class.
 /// </summary>
 /// <param name="t">The type of the object being serialized/deserialized.</param>
 /// <param name="exceptionPolicy">The exception handling policy.</param>
 /// <param name="defaultExType">The exceptions are treated as the value specified, unless otherwise specified.</param>
 /// <param name="option">The serialization option.</param>
 public YAXSerializer(Type t, YAXExceptionHandlingPolicies exceptionPolicy, YAXExceptionTypes defaultExType, YAXSerializationOptions option)
 {
     m_type = t;
     m_exceptionPolicy = exceptionPolicy;
     m_defaultExceptionType = defaultExType;
     m_serializationOption = option;
     // this must be the last call
     m_udtWrapper = TypeWrappersPool.Pool.GetTypeWrapper(m_type, this);
     if (m_udtWrapper.HasNamespace)
         TypeNamespace = m_udtWrapper.Namespace;
 }
Example #7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="YAXSerializer"/> class.
 /// </summary>
 /// <param name="type">The type of the object being serialized/deserialized.</param>
 /// <param name="exceptionPolicy">The exception handling policy.</param>
 /// <param name="defaultExType">The exceptions are treated as the value specified, unless otherwise specified.</param>
 public YAXSerializer(Type type, YAXExceptionHandlingPolicies exceptionPolicy, YAXExceptionTypes defaultExType)
     : this(type, exceptionPolicy, defaultExType, YAXSerializationOptions.SerializeNullObjects)
 {
 }
Example #8
0
        /// <summary>
        /// Processes the specified attribute which is an instance of <c>YAXAttribute</c>.
        /// </summary>
        /// <param name="attr">The attribute to process.</param>
        private void ProcessYaxAttribute(object attr)
        {
            if (attr is YAXCommentAttribute)
            {
                string comment = (attr as YAXCommentAttribute).Comment;
                if (!String.IsNullOrEmpty(comment))
                {
                    string[] comments = comment.Split(new [] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                    for (int i = 0; i < comments.Length; i++)
                    {
                        comments[i] = String.Format(" {0} ", comments[i].Trim());
                    }

                    this.Comment = comments;
                }
            }
            else if (attr is YAXSerializableFieldAttribute)
            {
                IsAttributedAsSerializable = true;
            }
            else if (attr is YAXAttributeForClassAttribute)
            {
                // it is required that YAXCustomSerializerAttribute is processed earlier
                if (ReflectionUtils.IsBasicType(MemberType) || CustomSerializerType != null ||
                    (m_collectionAttributeInstance != null && m_collectionAttributeInstance.SerializationType == YAXCollectionSerializationTypes.Serially))
                {
                    IsSerializedAsAttribute = true;
                    SerializationLocation = ".";
                }
            }
            else if (attr is YAXValueForClassAttribute)
            {
                // it is required that YAXCustomSerializerAttribute is processed earlier
                if (ReflectionUtils.IsBasicType(MemberType) || CustomSerializerType != null ||
                    (m_collectionAttributeInstance != null && m_collectionAttributeInstance.SerializationType == YAXCollectionSerializationTypes.Serially))
                {
                    IsSerializedAsValue = true;
                    SerializationLocation = ".";
                }
            }
            else if (attr is YAXAttributeForAttribute)
            {
                // it is required that YAXCustomSerializerAttribute is processed earlier
                if (ReflectionUtils.IsBasicType(MemberType) || CustomSerializerType != null ||
                    (m_collectionAttributeInstance != null && m_collectionAttributeInstance.SerializationType == YAXCollectionSerializationTypes.Serially))
                {
                    IsSerializedAsAttribute = true;
                    string path, alias;
                    StringUtils.ExttractPathAndAliasFromLocationString((attr as YAXAttributeForAttribute).Parent, out path, out alias);

                    SerializationLocation = path;
                    if (!String.IsNullOrEmpty(alias))
                        Alias = StringUtils.RefineSingleElement(alias);
                }
            }
            else if (attr is YAXElementForAttribute)
            {
                IsSerializedAsElement = true;

                string path, alias;
                StringUtils.ExttractPathAndAliasFromLocationString((attr as YAXElementForAttribute).Parent, out path, out alias);

                SerializationLocation = path;
                if (!String.IsNullOrEmpty(alias))
                    Alias = StringUtils.RefineSingleElement(alias);
            }
            else if (attr is YAXValueForAttribute)
            {
                // it is required that YAXCustomSerializerAttribute is processed earlier
                if (ReflectionUtils.IsBasicType(this.MemberType) || CustomSerializerType != null ||
                    (m_collectionAttributeInstance != null && m_collectionAttributeInstance.SerializationType == YAXCollectionSerializationTypes.Serially))
                {
                    IsSerializedAsValue = true;

                    string path, alias;
                    StringUtils.ExttractPathAndAliasFromLocationString((attr as YAXValueForAttribute).Parent, out path, out alias);

                    SerializationLocation = path;
                    if (!String.IsNullOrEmpty(alias))
                        Alias = StringUtils.RefineSingleElement(alias);
                }
            }
            else if (attr is YAXDontSerializeAttribute)
            {
                IsAttributedAsDontSerialize = true;
            }
            else if (attr is YAXSerializeAsAttribute)
            {
                Alias = StringUtils.RefineSingleElement((attr as YAXSerializeAsAttribute).SerializeAs);
            }
            else if (attr is YAXCollectionAttribute)
            {
                m_collectionAttributeInstance = attr as YAXCollectionAttribute;
            }
            else if (attr is YAXDictionaryAttribute)
            {
                m_dictionaryAttributeInstance = attr as YAXDictionaryAttribute;
            }
            else if (attr is YAXErrorIfMissedAttribute)
            {
                var temp = attr as YAXErrorIfMissedAttribute;
                DefaultValue = temp.DefaultValue;
                TreatErrorsAs = temp.TreatAs;
            }
            else if (attr is YAXFormatAttribute)
            {
                Format = (attr as YAXFormatAttribute).Format;
            }
            else if (attr is YAXNotCollectionAttribute)
            {
                // arrays are always treated as collections
                if (!ReflectionUtils.IsArray(MemberType))
                    IsAttributedAsNotCollection = true;
            }
            else if (attr is YAXCustomSerializerAttribute)
            {
                Type serType = (attr as YAXCustomSerializerAttribute).CustomSerializerType;

                Type genTypeArg;
                bool isDesiredInterface = ReflectionUtils.IsDerivedFromGenericInterfaceType(serType, typeof(ICustomSerializer<>), out genTypeArg);

                if (!isDesiredInterface)
                {
                    throw new YAXException("The provided custom serialization type is not derived from the proper interface");
                }
                else if (genTypeArg != this.MemberType)
                {
                    throw new YAXException("The generic argument of the class and the member type do not match");
                }
                else
                {
                    CustomSerializerType = serType;
                }
            }
            else if(attr is YAXPreserveWhitespaceAttribute)
            {
                PreservesWhitespace = true;
            }
            else if (attr is YAXSerializableTypeAttribute)
            {
                // this should not happen
                throw new Exception("This attribute is not applicable to fields and properties!");
            }
            else if (attr is YAXNamespaceAttribute)
            {
                var nsAttrib = (attr as YAXNamespaceAttribute);
                Namespace = nsAttrib.Namespace;
                NamespacePrefix = nsAttrib.Prefix;
            }
            else if (attr is YAXTypeAttribute)
            {
                var yaxTypeAttr = attr as YAXTypeAttribute;
                string alias = yaxTypeAttr.Alias;
                if (alias != null)
                {
                    alias = alias.Trim();
                    if (alias.Length == 0)
                        alias = null;
                }

                if(m_possibleRealTypes.Any(x => x.Type == yaxTypeAttr.Type))
                    throw new YAXPolymorphicException(String.Format("The type \"{0}\" for field/property \"{1}\" has already been defined through another attribute.", yaxTypeAttr.Type.Name, m_memberInfo));

                if (alias != null && m_possibleRealTypes.Any(x => alias.Equals(x.Alias, StringComparison.Ordinal)))
                    throw new YAXPolymorphicException(String.Format("The alias \"{0}\" given to type \"{1}\" for field/property \"{2}\" has already been given to another type through another attribute.",
                        alias, yaxTypeAttr.Type.Name, m_memberInfo));

                m_possibleRealTypes.Add(yaxTypeAttr);
            }
            else if (attr is YAXCollectionItemTypeAttribute)
            {
                var yaxColletionItemTypeAttr = attr as YAXCollectionItemTypeAttribute;
                string alias = yaxColletionItemTypeAttr.Alias;
                if (alias != null)
                {
                    alias = alias.Trim();
                    if (alias.Length == 0)
                        alias = null;
                }

                if (m_possibleCollectionItemRealTypes.Any(x => x.Type == yaxColletionItemTypeAttr.Type))
                    throw new YAXPolymorphicException(String.Format("The collection-item type \"{0}\" for collection \"{1}\" has already been defined through another attribute.", yaxColletionItemTypeAttr.Type.Name, m_memberInfo));

                if (alias != null && m_possibleCollectionItemRealTypes.Any(x => alias.Equals(x.Alias, StringComparison.Ordinal)))
                    throw new YAXPolymorphicException(String.Format("The alias \"{0}\" given to collection-item type \"{1}\" for field/property \"{2}\" has already been given to another type through another attribute.",
                        alias, yaxColletionItemTypeAttr.Type.Name, m_memberInfo));

                m_possibleCollectionItemRealTypes.Add(yaxColletionItemTypeAttr);
            }
            else if (attr is YAXDontSerializeIfNullAttribute)
            {
                IsAttributedAsDontSerializeIfNull = true;
            }
            else if (attr is YAXElementOrder)
            {
                Order = (attr as YAXElementOrder).Order;
            }
            else
            {
                throw new Exception("Added new attribute type to the library but not yet processed!");
            }
        }
Example #9
0
        /// <summary>
        /// Processes the specified attribute which is an instance of <c>YAXAttribute</c>.
        /// </summary>
        /// <param name="attr">The attribute to process.</param>
        private void ProcessYaxAttribute(object attr)
        {
            if (attr is YAXCommentAttribute)
            {
                string comment = (attr as YAXCommentAttribute).Comment;
                if (!String.IsNullOrEmpty(comment))
                {
                    string[] comments = comment.Split(new [] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                    for (int i = 0; i < comments.Length; i++)
                    {
                        comments[i] = String.Format(" {0} ", comments[i].Trim());
                    }

                    this.Comment = comments;
                }
            }
            else if (attr is YAXSerializableFieldAttribute)
            {
                IsAttributedAsSerializable = true;
            }
            else if (attr is YAXAttributeForClassAttribute)
            {
                // it is required that YAXCustomSerializerAttribute is processed earlier
                if (ReflectionUtils.IsBasicType(MemberType) || CustomSerializerType != null ||
                    (m_collectionAttributeInstance != null && m_collectionAttributeInstance.SerializationType == YAXCollectionSerializationTypes.Serially))
                {
                    IsSerializedAsAttribute = true;
                    SerializationLocation = ".";
                }
            }
            else if (attr is YAXValueForClassAttribute)
            {
                // it is required that YAXCustomSerializerAttribute is processed earlier
                if (ReflectionUtils.IsBasicType(MemberType) || CustomSerializerType != null ||
                    (m_collectionAttributeInstance != null && m_collectionAttributeInstance.SerializationType == YAXCollectionSerializationTypes.Serially))
                {
                    IsSerializedAsValue = true;
                    SerializationLocation = ".";
                }
            }
            else if (attr is YAXAttributeForAttribute)
            {
                // it is required that YAXCustomSerializerAttribute is processed earlier
                if (ReflectionUtils.IsBasicType(MemberType) || CustomSerializerType != null ||
                    (m_collectionAttributeInstance != null && m_collectionAttributeInstance.SerializationType == YAXCollectionSerializationTypes.Serially))
                {
                    IsSerializedAsAttribute = true;
                    string path, alias;
                    StringUtils.ExttractPathAndAliasFromLocationString((attr as YAXAttributeForAttribute).Parent, out path, out alias);

                    SerializationLocation = path;
                    if (!String.IsNullOrEmpty(alias))
                        Alias = alias;
                }
            }
            else if (attr is YAXElementForAttribute)
            {
                IsSerializedAsElement = true;

                string path, alias;
                StringUtils.ExttractPathAndAliasFromLocationString((attr as YAXElementForAttribute).Parent, out path, out alias);

                SerializationLocation = path;
                if (!String.IsNullOrEmpty(alias))
                    Alias = alias;
            }
            else if (attr is YAXValueForAttribute)
            {
                // it is required that YAXCustomSerializerAttribute is processed earlier
                if (ReflectionUtils.IsBasicType(this.MemberType) || CustomSerializerType != null ||
                    (m_collectionAttributeInstance != null && m_collectionAttributeInstance.SerializationType == YAXCollectionSerializationTypes.Serially))
                {
                    IsSerializedAsValue = true;

                    string path, alias;
                    StringUtils.ExttractPathAndAliasFromLocationString((attr as YAXValueForAttribute).Parent, out path, out alias);

                    SerializationLocation = path;
                    if (!String.IsNullOrEmpty(alias))
                        Alias = alias;
                }
            }
            else if (attr is YAXDontSerializeAttribute)
            {
                IsAttributedAsDontSerialize = true;
            }
            else if (attr is YAXSerializeAsAttribute)
            {
                Alias = (attr as YAXSerializeAsAttribute).SerializeAs;
            }
            else if (attr is YAXCollectionAttribute)
            {
                m_collectionAttributeInstance = attr as YAXCollectionAttribute;
            }
            else if (attr is YAXDictionaryAttribute)
            {
                m_dictionaryAttributeInstance = attr as YAXDictionaryAttribute;
            }
            else if (attr is YAXErrorIfMissedAttribute)
            {
                var temp = attr as YAXErrorIfMissedAttribute;
                DefaultValue = temp.DefaultValue;
                TreatErrorsAs = temp.TreatAs;
            }
            else if (attr is YAXFormatAttribute)
            {
                Format = (attr as YAXFormatAttribute).Format;
            }
            else if (attr is YAXNotCollectionAttribute)
            {
                // arrays are always treated as collections
                if (!ReflectionUtils.IsArray(MemberType))
                    IsAttributedAsNotCollection = true;
            }
            else if (attr is YAXCustomSerializerAttribute)
            {
                Type serType = (attr as YAXCustomSerializerAttribute).CustomSerializerType;

                Type genTypeArg;
                bool isDesiredInterface = ReflectionUtils.IsDerivedFromGenericInterfaceType(serType, typeof(ICustomSerializer<>), out genTypeArg);

                if (!isDesiredInterface)
                {
                    throw new YAXException("The provided custom serialization type is not derived from the proper interface");
                }
                else if (genTypeArg != this.MemberType)
                {
                    throw new YAXException("The generic argument of the class and the member type do not match");
                }
                else
                {
                    CustomSerializerType = serType;
                }
            }
            //else if (attr is YAXCustomDeserializerAttribute)
            //{
            //    Type deserType = (attr as YAXCustomDeserializerAttribute).CustomDeserializerType;

            //    Type genTypeArg;
            //    bool isDesiredInterface = ReflectionUtils.IsDerivedFromGenericInterfaceType(deserType, typeof(ICustomSerializer<>), out genTypeArg);

            //    if (!isDesiredInterface)
            //    {
            //        throw new YAXException("The provided custom deserialization type is not derived from the proper interface");
            //    }
            //    else if (genTypeArg != this.MemberType)
            //    {
            //        throw new YAXException("The generic argument of the class and the member type do not match");
            //    }
            //    else
            //    {
            //        this.CustomDeserializerType = deserType;
            //    }
            //}
            else if (attr is YAXSerializableTypeAttribute)
            {
                // this should not happen
                throw new Exception("This attribute is not applicable to fields and properties!");
            }
            else
            {
                throw new Exception("Added new attribute type to the library but not yet processed!");
            }
        }
Example #10
0
        private void OnDeserialize(bool openFromFile)
        {
            rtbParsingErrors.Text = "";
            object selItem = lstSampleClasses.SelectedItem;

            if (selItem == null || !(selItem is ClassInfoListItem))
            {
                return;
            }

            string fileName = null;

            if (openFromFile)
            {
                if (DialogResult.OK != openFileDialog1.ShowDialog())
                {
                    return;
                }
                fileName = openFileDialog1.FileName;
            }

            var info = selItem as ClassInfoListItem;
            YAXExceptionTypes            defaultExType = GetSelectedDefaultExceptionType();
            YAXExceptionHandlingPolicies exPolicy      = GetSelectedExceptionHandlingPolicy();
            YAXSerializationOptions      serOption     = GetSelectedSerializationOption();

            try
            {
                object        deserializedObject = null;
                YAXSerializer serializer         = new YAXSerializer(info.ClassType, exPolicy, defaultExType, serOption);
                serializer.MaxRecursion = Convert.ToInt32(numMaxRecursion.Value);

                if (openFromFile)
                {
                    deserializedObject = serializer.DeserializeFromFile(fileName);
                }
                else
                {
                    deserializedObject = serializer.Deserialize(rtbXMLOutput.Text);
                }

                rtbParsingErrors.Text = serializer.ParsingErrors.ToString();

                if (deserializedObject != null)
                {
                    rtbDeserializeOutput.Text = deserializedObject.ToString();

                    if (deserializedObject is List <string> )
                    {
                        StringBuilder sb = new StringBuilder();
                        foreach (var item in deserializedObject as List <string> )
                        {
                            sb.AppendLine(item.ToString());
                        }
                        MessageBox.Show(sb.ToString());
                    }
                }
                else
                {
                    rtbDeserializeOutput.Text = "The deserialized object is null";
                }
            }
            catch (YAXException ex)
            {
                rtbDeserializeOutput.Text = "";
                MessageBox.Show("YAXException handled:\r\n\r\n" + ex.ToString());
            }
            catch (Exception ex)
            {
                rtbDeserializeOutput.Text = "";
                MessageBox.Show("Other Exception handled:\r\n\r\n" + ex.ToString());
            }
        }
Example #11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="YAXErrorIfMissedAttribute"/> class.
 /// </summary>
 /// <param name="treatAs">The value indicating this situation is going to be treated as Error or Warning.</param>
 public YAXErrorIfMissedAttribute(YAXExceptionTypes treatAs)
 {
     this.TreatAs = treatAs;
     this.DefaultValue = null;
 }
Example #12
0
 /// <summary>
 ///     Adds an exception with the corresponding type.
 /// </summary>
 /// <param name="exception">The exception to add.</param>
 /// <param name="exceptionType">Type of the exception added.</param>
 public void AddException(YAXException exception, YAXExceptionTypes exceptionType)
 {
     listExceptions.Add(new KeyValuePair <YAXException, YAXExceptionTypes>(exception, exceptionType));
 }