예제 #1
0
        internal XmlStatistic(XmlDictionary dictionary, int id, bool createNew)
        {
            m_oDictionary = dictionary;
            m_dictionary = dictionary.Dictionary;

            if (createNew)
            {
                XmlElement xeStat = m_dictionary.CreateElement(m_XPathStatsElement);
                XmlHelper.CreateAndAppendAttribute(xeStat, m_XPathIdAttribute, Convert.ToString(0));
                XmlHelper.CreateAndAppendElement(xeStat, m_XPathStartElement, XmlConvert.ToString(DateTime.Now, XmlDateTimeSerializationMode.RoundtripKind));
                XmlHelper.CreateAndAppendElement(xeStat, m_XPathEndElement, XmlConvert.ToString(DateTime.Now, XmlDateTimeSerializationMode.RoundtripKind));
                XmlHelper.CreateAndAppendElement(xeStat, m_XPathRightElement, Convert.ToString(0));
                XmlHelper.CreateAndAppendElement(xeStat, m_XPathWrongElement, Convert.ToString(0));
                for (int i = 0; i < m_oDictionary.NumberOfBoxes; i++)
                {
                    XmlHelper.CreateElementWithAttribute(xeStat, m_XPathBoxesElement, XmlConvert.ToString(0), m_XPathIdAttribute, XmlConvert.ToString(i));
                }
                m_statistic = xeStat;
                Id = id;

                m_dictionary.DocumentElement.AppendChild(Statistic);
            }
            else
            {
                string baseXPath = String.Format(m_XPathStatsFilter, id);
                m_statistic = (XmlElement)m_dictionary.SelectSingleNode(baseXPath);
            }

            InitializeBoxList();
        }
예제 #2
0
 internal XmlChapters(XmlDictionary dictionary, ParentClass parent)
 {
     this.parent = parent;
     m_oDictionary = dictionary;
     m_dictionary = dictionary.Dictionary;
     Initialize();
     PrepareIdNavigator();
 }
예제 #3
0
 internal XmlAnswerDistractors(XmlDictionary dic, XmlCard card, ParentClass parent)
     : base(parent)
 {
     base.m_oDictionary = dic;
     base.m_XPathBasePath = m_XPathBasePath;
     this.m_Culture = card.Dictionary.AnswerCulture;
     Initialize(card);
 }
예제 #4
0
        internal XmlQueryOptions(XmlDictionary dictionary, ParentClass parentClass)
        {
            parent = parentClass;

            m_dictionary = dictionary.Dictionary;
            m_userSettings = (XmlElement)m_dictionary.SelectSingleNode(m_basePath);
            m_MultipleChoiceOptions = new XmlQueryMultipleChoiceOptions(dictionary, Parent.GetChildParentClass(this));
        }
예제 #5
0
        internal XmlCards(XmlDictionary dictionary, ParentClass parentClass)
        {
            parent = parentClass;

            m_oDictionary = dictionary;
            m_dictionary = dictionary.Dictionary;
            PrepareIdNavigator();
            Initialize();
        }
예제 #6
0
        internal XmlStatistics(XmlDictionary dictionary)
        {
            m_oDictionary = dictionary;
            m_dictionary = dictionary.Dictionary;
            PrepareIdNavigator();

            XmlNodeList xmlStats = m_dictionary.SelectNodes(m_basePath);
            foreach (XmlNode node in xmlStats)
                stats.Add(new XmlStatistic(dictionary, node as XmlElement));
        }
예제 #7
0
        public void WriteValueInt16()
        {
            MemoryStream  ms  = new MemoryStream();
            XmlDictionary dic = new XmlDictionary();
            var           w   = XmlDictionaryWriter.CreateBinaryWriter(ms, dic, null);

            w.WriteStartElement("a");
            w.WriteValue((short)0);
            w.WriteValue((short)2);
            w.Close();
            Assert.AreEqual(value_int16, ms.ToArray());
        }
 internal XmlAllowedQueryDirections(XmlDictionary dictionary, ParentClass parent)
 {
     m_QueryDirections = (XmlElement)dictionary.Dictionary.SelectSingleNode(m_XPathBasePath);
     if (m_QueryDirections == null)
     {
         m_QueryDirections = XmlHelper.CreateAndAppendElement((XmlElement)dictionary.Dictionary.SelectSingleNode(m_XPathGeneral), m_XPathAllowedQueryDirections);
         AppendMode(EQueryDirection.Question2Answer, true);
         AppendMode(EQueryDirection.Answer2Question, true);
         AppendMode(EQueryDirection.Mixed, true);
     }
     this.parent = parent;
 }
예제 #9
0
 public void UseNOPSession ()
 {
     MemoryStream ms = new MemoryStream ();
     MyWriterSession2 session = new MyWriterSession2 ();
     XmlDictionary dic = new XmlDictionary ();
     XmlDictionaryWriter w = XmlDictionaryWriter.CreateBinaryWriter (ms, dic, session);
     w.WriteStartElement (dic.Add ("FOO"), XmlDictionaryString.Empty);
     w.WriteStartElement (dic.Add ("blah"), XmlDictionaryString.Empty);
     w.WriteStartElement (dic.Add ("blabla"), XmlDictionaryString.Empty);
     w.Close ();
     Assert.AreEqual (new byte [] {0x42, 0, 0x42, 2, 0x42, 4, 1, 1, 1}, ms.ToArray ());
 }
        public virtual XmlObjectSerializer CreateSerializer(Type type, string name, string ns, IList <Type> knownTypes)
        {
            XmlDictionary dictionary = new XmlDictionary(2);
            DataContractSerializerSettings settings = new DataContractSerializerSettings();

            settings.RootName              = dictionary.Add(name);
            settings.RootNamespace         = dictionary.Add(ns);
            settings.KnownTypes            = knownTypes;
            settings.MaxItemsInObjectGraph = MaxItemsInObjectGraph;
            settings.DataContractResolver  = DataContractResolver;
            return(new DataContractSerializer(type, settings));
        }
예제 #11
0
        /// <summary>
        /// 反序列化一个datacontract属性的对象
        /// </summary>
        /// <param name="type">要反序列化的对象的类型</param>
        /// <param name="rootName">xml字典的根名称,如:MyObject</param>
        /// <param name="rootNameSpace">xml的根命名空间,如:http://www.lhbis.com</param>
        /// <param name="knownTypes">其中包含可在对象图中呈现的类型</param>
        /// <param name="buffer">要反序列化为对象的数据</param>
        /// <returns>object对象</returns>
        /// <remarks>只有在程序集里同一个命名空间下的对象才能互相序列化/反序列化. 否则反序列化可能不成功</remarks>
        public static object DeserializeDataContract(Type type, string rootName, string rootNameSpace, IEnumerable <Type> knownTypes, byte[] buffer)
        {
            var dictionary      = new XmlDictionary();
            var rootString      = dictionary.Add(rootName);
            var namesapceString = dictionary.Add(rootNameSpace);

            using (var br = XmlDictionaryReader.CreateBinaryReader(buffer, 0, buffer.Length, dictionary, XmlDictionaryReaderQuotas.Max))
            {
                var ser = new DataContractSerializer(type, rootString, namesapceString, knownTypes);
                return(ser.ReadObject(br));
            }
        }
예제 #12
0
        public DataContractSerializer(Type type, string rootName, string rootNamespace,
                                      IEnumerable <Type> knownTypes,
                                      int maxItemsInObjectGraph,
                                      bool ignoreExtensionDataObject,
                                      bool preserveObjectReferences,
                                      IDataContractSurrogate dataContractSurrogate,
                                      DataContractResolver dataContractResolver)
        {
            XmlDictionary dictionary = new XmlDictionary(2);

            Initialize(type, dictionary.Add(rootName), dictionary.Add(DataContract.GetNamespace(rootNamespace)), knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, preserveObjectReferences, dataContractSurrogate, dataContractResolver, false);
        }
        public override bool TryResolveType(Type dataContractType, Type declaredType, DataContractResolver knownTypeResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace)
        {
            if (dataContractType == typeof(ServiceRequestWithData <Guid, ConversationService.UpdateConversationParameters>))
            {
                XmlDictionary dictionary = new XmlDictionary();
                typeName      = dictionary.Add("ConversationServiceUpdateConversationParameters");
                typeNamespace = dictionary.Add(ServiceNamespace);
                return(true);
            }

            return(base.TryResolveType(dataContractType, declaredType, knownTypeResolver, out typeName, out typeNamespace));
        }
예제 #14
0
        public override bool TryResolveType(
            Type type,
            Type declaredType,
            DataContractResolver knownTypeResolver,
            out XmlDictionaryString typeName,
            out XmlDictionaryString typeNamespace)
        {
            var dict = new XmlDictionary();

            typeName      = dict.Add(Uri.EscapeDataString(type.FullName).Replace("%", ".."));
            typeNamespace = dict.Add(type.Namespace);
            return(true);
        }
예제 #15
0
        public override bool TryResolveType(Type dataContractType, Type declaredType, DataContractResolver knownTypeResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace)
        {
            if (Identity.ContainsKey(dataContractType))
            {
                var dictionary = new XmlDictionary();
                typeName      = dictionary.Add(Identity[dataContractType]);
                typeNamespace = dictionary.Add(dataContractType.FullName);
                return(true);
            }

            // Defer to the known type resolver
            return(knownTypeResolver.TryResolveType(dataContractType, declaredType, null, out typeName, out typeNamespace));
        }
예제 #16
0
        static DataContract DecodeDataContract(int index, XmlDictionary xmlDict, TodoList knownContractsTodoList)
        {
            DataContract contract = AllocateSimpleDataContract(DataContracts[index].Kind);

            DecodeCommon(xmlDict, contract, ref DataContracts[index].Common, knownContractsTodoList);

            if (contract is InvalidDataContract)
            {
                ((InvalidDataContract)contract).ErrorMessage = GetString(DataContracts[index].ErrorMessageIndex);
            }

            return(contract);
        }
예제 #17
0
 internal XmlQueryMultipleChoiceOptions(XmlDictionary dictionary, ParentClass parent)
 {
     m_MultipleChoiceOptions = (XmlElement)dictionary.Dictionary.SelectSingleNode(m_XPathBasePath);
     if (m_MultipleChoiceOptions == null)
     {
         m_MultipleChoiceOptions = XmlHelper.CreateAndAppendElement((XmlElement)dictionary.Dictionary.SelectSingleNode(m_XPathGeneral), m_XPathMultipleChoiceOptions);
         XmlHelper.CreateAndAppendAttribute(m_MultipleChoiceOptions, m_XPathAllowRandomDistractorsName, XmlConvert.ToString(m_DefValAllowRandomDistractors));
         XmlHelper.CreateAndAppendAttribute(m_MultipleChoiceOptions, m_XPathNumberOfChoicesName, XmlConvert.ToString(m_DefValNumberOfChoices));
         XmlHelper.CreateAndAppendAttribute(m_MultipleChoiceOptions, m_XPathMultipleCorrectAnswersName, XmlConvert.ToString(m_DefValMultipleCorrectAnswers));
         XmlHelper.CreateAndAppendAttribute(m_MultipleChoiceOptions, m_XPathMaximumCorrectAnswersName, XmlConvert.ToString(m_DefValMaximumCorrectAnswers));
     }
     this.parent = parent;
 }
예제 #18
0
 private void useCustomStaticDictionaryToolStripMenuItem_Click(object sender, EventArgs e)
 {
     string[] allLines = this.ReadAllLinesFromDialog();
     if (allLines != null)
     {
         XmlDictionary temp = new XmlDictionary();
         this.staticDictionary = temp;
         foreach (string line in allLines)
         {
             temp.Add(line);
         }
     }
 }
예제 #19
0
    public override bool TryResolveType(Type dataContractType, Type declaredType, DataContractResolver knownTypeResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace)
    {
        if (!knownTypeResolver.TryResolveType(dataContractType, declaredType, null, out typeName, out typeNamespace))
        {
            XmlDictionary dictionary = new XmlDictionary();

            typeName = dictionary.Add(dataContractType.FullName);

            typeNamespace = dictionary.Add(dataContractType.Assembly.FullName);
        }

        return(true);
    }
 internal XmlQueryMultipleChoiceOptions(XmlDictionary dictionary, ParentClass parent)
 {
     m_MultipleChoiceOptions = (XmlElement)dictionary.Dictionary.SelectSingleNode(m_XPathBasePath);
     if (m_MultipleChoiceOptions == null)
     {
         m_MultipleChoiceOptions = XmlHelper.CreateAndAppendElement((XmlElement)dictionary.Dictionary.SelectSingleNode(m_XPathGeneral), m_XPathMultipleChoiceOptions);
         XmlHelper.CreateAndAppendAttribute(m_MultipleChoiceOptions, m_XPathAllowRandomDistractorsName, XmlConvert.ToString(m_DefValAllowRandomDistractors));
         XmlHelper.CreateAndAppendAttribute(m_MultipleChoiceOptions, m_XPathNumberOfChoicesName, XmlConvert.ToString(m_DefValNumberOfChoices));
         XmlHelper.CreateAndAppendAttribute(m_MultipleChoiceOptions, m_XPathMultipleCorrectAnswersName, XmlConvert.ToString(m_DefValMultipleCorrectAnswers));
         XmlHelper.CreateAndAppendAttribute(m_MultipleChoiceOptions, m_XPathMaximumCorrectAnswersName, XmlConvert.ToString(m_DefValMaximumCorrectAnswers));
     }
     this.parent = parent;
 }
        public override bool TryResolveType(Type type, Type declaredType, DataContractResolver knownTypeResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace)
        {
            var a = AttributeUtils.GetAttribute <T>(type);

            if (a != null)
            {
                var dictionary = new XmlDictionary();
                typeName      = dictionary.Add(_contractNamePrefix + a.ContractId);
                typeNamespace = dictionary.Add(_contractNamespace);
                return(true);
            }
            return(knownTypeResolver.TryResolveType(type, declaredType, knownTypeResolver, out typeName, out typeNamespace));
        }
예제 #22
0
        internal XmlStatistics(XmlDictionary dictionary)
        {
            m_oDictionary = dictionary;
            m_dictionary  = dictionary.Dictionary;
            PrepareIdNavigator();

            XmlNodeList xmlStats = m_dictionary.SelectNodes(m_basePath);

            foreach (XmlNode node in xmlStats)
            {
                stats.Add(new XmlStatistic(dictionary, node as XmlElement));
            }
        }
예제 #23
0
        internal XmlBoxes(XmlDictionary dictionary, ParentClass parent)
        {
            Parent       = parent;
            m_Dictionary = dictionary;

            m_Box = new List <IBox>(dictionary.NumberOfBoxes + 1);
            for (int i = 0; i < dictionary.NumberOfBoxes + 1; i++)             //including pool and box 10
            {
                m_Box.Add(new XmlBox(m_Dictionary, i, Parent.GetChildParentClass(this)));
            }
            m_Box[0].MaximalSize = Int32.MaxValue;
            m_Box[dictionary.NumberOfBoxes].MaximalSize = Int32.MaxValue;
        }
예제 #24
0
            internal XmlDataContractCriticalHelper(
                [DynamicallyAccessedMembers(ClassDataContract.DataContractPreserveMemberTypes)]
                Type type) : base(type)
            {
                if (type.IsDefined(Globals.TypeOfDataContractAttribute, false))
                {
                    throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.IXmlSerializableCannotHaveDataContract, DataContract.GetClrTypeFullName(type))));
                }
                if (type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false))
                {
                    throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.IXmlSerializableCannotHaveCollectionDataContract, DataContract.GetClrTypeFullName(type))));
                }
                bool             hasRoot;
                XmlSchemaType?   xsdType;
                XmlQualifiedName xmlName;

                SchemaExporter.GetXmlTypeInfo(type, out xmlName, out xsdType, out hasRoot);
                XmlName = xmlName;
                XsdType = xsdType;
                HasRoot = hasRoot;
                XmlDictionary dictionary = new XmlDictionary();

                Name      = dictionary.Add(XmlName.Name);
                Namespace = dictionary.Add(XmlName.Namespace);
                object[]? xmlRootAttributes = UnderlyingType?.GetCustomAttributes(Globals.TypeOfXmlRootAttribute, false).ToArray();
                if (xmlRootAttributes == null || xmlRootAttributes.Length == 0)
                {
                    if (hasRoot)
                    {
                        _topLevelElementName       = Name;
                        _topLevelElementNamespace  = (this.XmlName.Namespace == Globals.SchemaNamespace) ? DictionaryGlobals.EmptyString : Namespace;
                        _isTopLevelElementNullable = true;
                    }
                }
                else
                {
                    if (hasRoot)
                    {
                        XmlRootAttribute xmlRootAttribute = (XmlRootAttribute)xmlRootAttributes[0];
                        _isTopLevelElementNullable = xmlRootAttribute.IsNullable;
                        string elementName = xmlRootAttribute.ElementName;
                        _topLevelElementName = (elementName == null || elementName.Length == 0) ? Name : dictionary.Add(DataContract.EncodeLocalName(elementName));
                        string?elementNs = xmlRootAttribute.Namespace;
                        _topLevelElementNamespace = (elementNs == null || elementNs.Length == 0) ? DictionaryGlobals.EmptyString : dictionary.Add(elementNs);
                    }
                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.IsAnyCannotHaveXmlRoot, DataContract.GetClrTypeFullName(UnderlyingType !))));
                    }
                }
            }
예제 #25
0
        public void UseCase2()
        {
            XmlDictionary       dic   = new XmlDictionary();
            MemoryStream        ms    = new MemoryStream();
            XmlDictionaryWriter w     = XmlDictionaryWriter.CreateBinaryWriter(ms, dic, null);
            XmlDictionaryString empty = dic.Add(String.Empty);

            // empty ns
            w.WriteStartElement(dic.Add("FOO"), empty);
            // non-dic string
            w.WriteStartElement("BAR");
            // second time ns
            w.WriteStartElement(dic.Add("FOO"), empty);
            // first time dic string but prior non-dic name existed
            w.WriteStartElement(dic.Add("BAR"), empty);
            w.WriteEndElement();
            w.WriteEndElement();
            w.WriteEndElement();
            // dicstr w/ ns with empty prefix
            w.WriteStartElement(dic.Add("BAR"), dic.Add("urn:bar"));
            // with prefix
            w.WriteStartElement("ppp", dic.Add("BAR"), dic.Add("urn:bar"));
            w.WriteChars(new char [] { 'x', 'y', 'z' }, 0, 3);
//			w.WriteString ("xyz"); // the same as WriteChars()
            w.WriteEndElement();
            w.WriteString("bbbb");
            w.WriteCData("ccc");
            w.WriteValue(new Guid("11112222333344445555666677778888"));
            w.WriteEndElement();
            w.WriteStartElement("FOO");
            w.WriteStartAttribute("AAA");
            w.WriteValue(new Guid("11112222333344445555666677778888"));
            w.WriteEndAttribute();
            w.WriteStartAttribute("BBB");
            w.WriteValue(TimeSpan.Zero);
            w.WriteEndAttribute();
            w.WriteStartAttribute("CC");
            w.WriteValue(new UniqueId("uuid-00000000-0000-0000-0000-000000000000-1"));
            w.WriteEndAttribute();
            w.WriteStartElement("XX");
            w.WriteValue(true);
            w.WriteValue(false);
            w.WriteEndElement();
            w.WriteStartElement("xx", "aaa", "urn:zzz");
            w.WriteEndElement();
            w.WriteEndElement();

            w.Close();

            Assert.AreEqual(usecase2_result, ms.ToArray());
        }
 public override bool TryResolveType(Type type, Type declaredType, DataContractResolver knownTypeResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace)
 {
     if (type == typeof(IMyEntity))  //|| type == typeof(...)
     {
         XmlDictionary dictionary = new XmlDictionary();
         typeName      = dictionary.Add(type.Name);
         typeNamespace = dictionary.Add(MyEntityNamespace);
         return(true);
     }
     else
     {
         return(knownTypeResolver.TryResolveType(type, declaredType, null, out typeName, out typeNamespace));
     }
 }
예제 #27
0
            internal XmlDataContractCriticalHelper(Type type)
                : base(type)
            {
                if (type.IsDefined(Globals.TypeOfDataContractAttribute, false))
                {
                    throw Fx.Exception.AsError(new InvalidDataContractException(SR.IXmlSerializableCannotHaveDataContract(DataContract.GetClrTypeFullName(type))));
                }
                if (type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false))
                {
                    throw Fx.Exception.AsError(new InvalidDataContractException(SR.IXmlSerializableCannotHaveCollectionDataContract(DataContract.GetClrTypeFullName(type))));
                }
                XmlSchemaType    xsdType;
                bool             hasRoot;
                XmlQualifiedName stableName;

                SchemaExporter.GetXmlTypeInfo(type, out stableName, out xsdType, out hasRoot);
                this.StableName = stableName;
                this.XsdType    = xsdType;
                this.HasRoot    = hasRoot;
                XmlDictionary dictionary = new XmlDictionary();

                this.Name      = dictionary.Add(StableName.Name);
                this.Namespace = dictionary.Add(StableName.Namespace);
                object[] xmlRootAttributes = (UnderlyingType == null) ? null : UnderlyingType.GetCustomAttributes(Globals.TypeOfXmlRootAttribute, false);
                if (xmlRootAttributes == null || xmlRootAttributes.Length == 0)
                {
                    if (hasRoot)
                    {
                        topLevelElementName       = Name;
                        topLevelElementNamespace  = (this.StableName.Namespace == Globals.SchemaNamespace) ? DictionaryGlobals.EmptyString : Namespace;
                        isTopLevelElementNullable = true;
                    }
                }
                else
                {
                    if (hasRoot)
                    {
                        XmlRootAttribute xmlRootAttribute = (XmlRootAttribute)xmlRootAttributes[0];
                        isTopLevelElementNullable = xmlRootAttribute.IsNullable;
                        string elementName = xmlRootAttribute.ElementName;
                        topLevelElementName = (elementName == null || elementName.Length == 0) ? Name : dictionary.Add(DataContract.EncodeLocalName(elementName));
                        string elementNs = xmlRootAttribute.Namespace;
                        topLevelElementNamespace = (elementNs == null || elementNs.Length == 0) ? DictionaryGlobals.EmptyString : dictionary.Add(elementNs);
                    }
                    else
                    {
                        throw Fx.Exception.AsError(new InvalidDataContractException(SR.IsAnyCannotHaveXmlRoot(DataContract.GetClrTypeFullName(UnderlyingType))));
                    }
                }
            }
        public void MergeSimpleSampleComponentData()
        {
            var compDataDict1 = new XmlDictionary <string, ComponentData>();
            var compDataDict2 = new XmlDictionary <string, ComponentData>();

            var sampleCompData = new ComponentData();

            compDataDict2["key2"] = sampleCompData;

            VoicepackMerger.MergeComponentData(compDataDict1, compDataDict2);

            Assert.IsTrue(compDataDict1.ContainsKey("key2"));
            Assert.AreEqual(compDataDict1["key2"], sampleCompData);
        }
 public override bool TryResolveType(Type type, Type declaredType, DataContractResolver knownTypeResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace)
 {
     if (type.Assembly.GetName().Name == DynamicTypeBuilder.AssemblyName)
     {
         XmlDictionary dic = new XmlDictionary();
         typeName      = dic.Add(type.Name);
         typeNamespace = dic.Add(ResolverNamespace);
         return(true);
     }
     else
     {
         return(knownTypeResolver.TryResolveType(type, declaredType, null, out typeName, out typeNamespace));
     }
 }
예제 #30
0
 public override bool TryResolveType(Type type, Type declaredType, DataContractResolver knownTypeResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace)
 {
     if (type == typeof(Manager))
     {
         XmlDictionary dic = new XmlDictionary();
         typeName      = dic.Add(this.Name);
         typeNamespace = dic.Add(this.Namespace);
         return(true);
     }
     else
     {
         return(knownTypeResolver.TryResolveType(type, declaredType, null, out typeName, out typeNamespace));
     }
 }
예제 #31
0
        public void TryAddIndex()
        {
            XmlDictionary          dic = new XmlDictionary();
            XmlDictionaryString    d1  = dic.Add("foo");
            XmlDictionaryString    d2  = dic.Add("bar");
            XmlDictionaryString    d3  = dic.Add("baz");
            XmlBinaryWriterSession s   = new XmlBinaryWriterSession();
            int idx;

            s.TryAdd(d1, out idx);
            Assert.AreEqual(0, idx, "#1");
            s.TryAdd(d3, out idx);
            Assert.AreEqual(1, idx, "#2");              // not 2
        }
예제 #32
0
 protected override void LoadDatabase(ref Dictionary <string, string> number_to_alias_db)       //alright so we hijack the database to convert it to be serializeable
 {
     number_to_alias_ref = new XmlDictionary <string, string>();
     try{
         String contacts_file = Utils.GetUserDataPath() + "\\SimpleXmlContacts.xml";
         if (File.Exists(contacts_file))
         {
             using (FileStream ReadFileStream = new FileStream(contacts_file, FileMode.Open, FileAccess.Read, FileShare.Read)){
                 number_to_alias_ref = (XmlDictionary <string, string>)SerializerObj.Deserialize(ReadFileStream);
             }
         }
     }catch {}
     number_to_alias_db = number_to_alias_ref;
 }
예제 #33
0
        public virtual bool TryResolveType(Type dataContractType, Type declaredType, DataContractResolver knownTypeResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace)
        {
            if (dataContractType == typeof(SingleSignOnToken))
            {
                XmlDictionary dictionary = new XmlDictionary();
                typeName      = dictionary.Add("SingleSignOnToken");
                typeNamespace = dictionary.Add("http://cqrs.co.nz");
                return(true);
            }

            typeName      = null;
            typeNamespace = null;
            return(false);
        }
예제 #34
0
파일: XML.cs 프로젝트: mohan682/Projects
        public static T Load <T>() where T : new()
        {
            var classType = typeof(T);

            var className = typeof(T).IsSerializable
                ? $"ListOf{typeof (T).GetGenericArguments().First().Name}"
                : typeof(T).Name;

            var fileName = $@"Database\{className}.xml";

            Debug.WriteLine($"Info: Read from file: {fileName} to instance of: {classType}");

            //verify readibility of xml, if failed reinstate
            if (File.Exists(fileName) == false)
            {
                Debug.WriteLine($"{fileName} does not exist. Saving initial class.");
                Save(new T());
            }

            var instance = default(T);

            var xmlDictionary = new XmlDictionary();
            var settings2     = new DataContractSerializerSettings
            {
                RootName      = xmlDictionary.Add(className),
                RootNamespace = xmlDictionary.Add("Data")
            };

            using (var fs = File.Open(fileName, FileMode.Open))
            {
                var deserializer = new DataContractSerializer(classType, settings2);

                try
                {
                    instance = (T)deserializer.ReadObject(fs);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Error: " + ex.Message);
                    //todo: handle errors while reading from file
                }

                Debug.WriteLine(instance == null
                    ? $" Deserialized object is null (Nothing in VB)"
                    : $" Deserialized type: {instance.GetType()}");
            }

            // ReSharper disable once ConvertConditionalTernaryToNullCoalescing
            return(instance != null ? instance : new T());
        }
예제 #35
0
        static TrustVersion()
        {
            var dic = new XmlDictionary();

            WSTrust13 = new TrustVersionImpl()
            {
                Prefix = dic.Add("wst"), Namespace = dic.Add("http://docs.oasis-open.org/ws-sx/ws-trust/200512")
            };
            WSTrustFeb2005 = new TrustVersionImpl()
            {
                Prefix = dic.Add("wsse"), Namespace = dic.Add("http://schemas.xmlsoap.org/ws/2002/12/secext")
            };
            Default = WSTrust13;
        }
예제 #36
0
        public override bool TryResolveType(Type dcType, Type declaredType, DataContractResolver KTResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace)
        {
            string resolvedTypeName  = string.Empty;
            string resolvedNamespace = string.Empty;

            resolvedNamespace         = s_defaultNS;
            resolvedTypeName          = dcType.Name + "_foo";
            s_types[resolvedTypeName] = dcType;
            XmlDictionary dic = new XmlDictionary();

            typeName      = dic.Add(resolvedTypeName);
            typeNamespace = dic.Add(resolvedNamespace);
            return(true);
        }
예제 #37
0
 /// <summary>
 /// Merges otherComponentData into componentData
 /// </summary>
 /// <param name="componentData">presumed not to be null (Initialize on null is performed when loading voicepacks)</param>
 /// <param name="otherComponentData">presumed not to be null (Initialize on null is performed when loading voicepacks)</param>
 public static void MergeComponentData(XmlDictionary <string, ComponentData> componentData,
                                       XmlDictionary <string, ComponentData> otherComponentData)
 {
     foreach (var otherData in otherComponentData)
     {
         if (componentData.ContainsKey(otherData.Key))
         {
             //throw new InvalidOperationException("Trying to merge with voicepack with identical key for some sound/resource.\n Key: " + otherData.Key);
             //TODO: possible workaround: create new key and update all references (e.g. AchievementOptions.pakSoundPath,
             Debug.WriteLine("Duplicate key detected while merging: " + otherData.Key + Environment.NewLine);
         }
         componentData[otherData.Key] = otherData.Value;
     }
 }
예제 #38
0
 internal XmlAllowedQueryTypes(XmlDictionary dictionary, ParentClass parent)
 {
     m_AllowedQueryTypes = (XmlElement)dictionary.Dictionary.SelectSingleNode(m_XPathBasePath);
     if (m_AllowedQueryTypes == null)
     {
         m_AllowedQueryTypes = XmlHelper.CreateAndAppendElement((XmlElement)dictionary.Dictionary.SelectSingleNode(m_XPathGeneral), m_XPathAllowedQueryTypes);
         AppendMode(EQueryType.Word, true);
         AppendMode(EQueryType.Sentences, true);
         AppendMode(EQueryType.MultipleChoice, true);
         AppendMode(EQueryType.ListeningComprehension, true);
         AppendMode(EQueryType.ImageRecognition, true);
     }
     this.parent = parent;
 }
 internal XmlAllowedQueryTypes(XmlDictionary dictionary, ParentClass parent)
 {
     m_AllowedQueryTypes = (XmlElement)dictionary.Dictionary.SelectSingleNode(m_XPathBasePath);
     if (m_AllowedQueryTypes == null)
     {
         m_AllowedQueryTypes = XmlHelper.CreateAndAppendElement((XmlElement)dictionary.Dictionary.SelectSingleNode(m_XPathGeneral), m_XPathAllowedQueryTypes);
         AppendMode(EQueryType.Word, true);
         AppendMode(EQueryType.Sentences, true);
         AppendMode(EQueryType.MultipleChoice, true);
         AppendMode(EQueryType.ListeningComprehension, true);
         AppendMode(EQueryType.ImageRecognition, true);
     }
     this.parent = parent;
 }
예제 #40
0
        /// <summary>
        /// Initializes a new instance of the <see cref="XmlChapter"/> class.
        /// </summary>
        /// <param name="dictionary">The dictionary.</param>
        /// <param name="parent">The parent.</param>
        /// <remarks>
        /// Documented by AAB, 7.8.2007.
        /// </remarks>
        internal XmlChapter(XmlDictionary dictionary, ParentClass parent)
        {
            this.parent = parent;
            settings = new XmlChapterSettings(this, Parent.GetChildParentClass(this));

            m_oDictionary = dictionary;
            m_dictionary = dictionary.Dictionary;
            XmlElement xeChapter = m_dictionary.CreateElement(m_XPathChapter);
            XmlHelper.CreateAndAppendAttribute(xeChapter, m_XPathId, Convert.ToString(0));
            XmlHelper.CreateAndAppendElement(xeChapter, m_XPathTitle);
            XmlHelper.CreateAndAppendElement(xeChapter, m_XPathDescription);
            m_chapter = xeChapter;

            Initialize();
        }
예제 #41
0
        public void TestSaveLoad()
        {
            var dictionary1 = new XmlDictionary
            {
                {"key1", "value1"},
                {"key2", "value2"}
            };

            // Serialize and deserialize data
            string data = dictionary1.ToXmlString();
            var dictionary2 = XmlStorage.FromXmlString<XmlDictionary>(data);

            // Ensure data stayed the same
            dictionary2.Should().Equal(dictionary1, because: "Serialized objects should be equal.");
            ReferenceEquals(dictionary1, dictionary2).Should().BeFalse(because: "Serialized objects should not return the same reference.");
        }
예제 #42
0
        protected override void ParseAndRegister(string data)
        {
            var xd = XDocument.Parse(data);
            var lang = xd.Root.Attribute("language").Value;
            var dictionary = new XmlDictionary(lang);

            foreach (XElement item in xd.Root.Elements("contexts").Elements("context"))
            {
                var contextDic = new Dictionary<string, string>();
                foreach (XElement tx in item.Elements("entry"))
                {
                    contextDic.Add(tx.Attribute("key").Value, tx.Attribute("translated").Value);
                }
                dictionary.Translations.Add(item.Attribute("id").Value, contextDic);
            }

            RegisterDictionary(dictionary);
        }
예제 #43
0
    public SaveFile(string name)
    {
        this.name = name;
        FileReadWrite.MakeFolders(path);
        boolDictionary = new XmlBoolDictionary("bools.xml", path, false);
        statistics = new XmlStatisticDictionary("stats.xml", path, false);
        general = new XmlDictionary("general.xml", path, false);
        if (general.GetElement(TimeName) != null)
        {
          TimeClock.CurrentTime = float.Parse(general.GetElement(TimeName));
          TimeClock.SyncLastTime();
        }

        if (general.GetElement(schedName) != null)
        {
          schedule = new Schedule(general.GetElement(schedName));
        }
        else {
          schedule = new Schedule(FileReadWrite.GetXmlFile("DefaultSchedule.xml",FileReadWrite.xmlPath));
        }
    }
예제 #44
0
        /// <summary>
        /// Initializes a new instance of the <see cref="XmlCard"/> class.
        /// </summary>
        /// <param name="dictionary">The dictionary.</param>
        /// <param name="parentClass">The parent class.</param>
        /// <remarks>
        /// Documented by AAB, 7.8.2007.
        /// </remarks>
        internal XmlCard(XmlDictionary dictionary, ParentClass parentClass)
            : this(parentClass)
        {
            settings = new XmlCardSettings(this, Parent.GetChildParentClass(this));

            m_oDictionary = dictionary;
            m_dictionary = dictionary.Dictionary;

            XmlElement xeCard = m_dictionary.CreateElement("card");
            XmlHelper.CreateAndAppendAttribute(xeCard, "id", Convert.ToString(-1));
            XmlHelper.CreateAndAppendElement(xeCard, "answer");
            XmlHelper.CreateAndAppendElement(xeCard, "answerexample");
            XmlHelper.CreateAndAppendElement(xeCard, "answerstylesheet");
            XmlHelper.CreateAndAppendElement(xeCard, "box", Convert.ToString(0));
            XmlHelper.CreateAndAppendElement(xeCard, "chapter", Convert.ToString(0));
            XmlHelper.CreateAndAppendElement(xeCard, "question");
            XmlHelper.CreateAndAppendElement(xeCard, "questionexample");
            XmlHelper.CreateAndAppendElement(xeCard, "questionstylesheet");
            XmlHelper.CreateAndAppendElement(xeCard, "timestamp", XmlConvert.ToString(DateTime.Now, XmlDateTimeSerializationMode.RoundtripKind));
            m_card = xeCard;

            Initialize();
        }
예제 #45
0
        /// <summary>
        /// The PopulateMessages method populates the message section
        /// of the supplied VFX dictionary with all message definitions
        /// that are found in the supplied XML dictionary.
        /// </summary>
        /// <param name="source">
        /// The source dictionary for the message elements.
        /// </param>
        /// <param name="target">
        /// The target dictionary for the converted elements.
        /// </param>
        private static void PopulateMessages(XmlDictionary source, FixDictionary target)
        {
            foreach (XmlFixDxMessage src in source.Messages.Entries)
            {
                FixDxMessage dst = new FixDxMessage(src.MsgType, src.Name, src.MsgCategory);
                foreach (IFixDxElement dxElement in TranslateElements(src.Elements))
                {
                    dst.Elements.Add(dxElement);
                }

                target.AddMessage(dst);
            }
        }
예제 #46
0
 public XmlDistractors(ParentClass parent, XmlDictionary dic)
     : this(parent)
 {
     m_oDictionary = dic;
 }
예제 #47
0
        /// <summary>
        /// Initializes a new instance of the <see cref="XmlChapter"/> class.
        /// </summary>
        /// <param name="dictionary">The dictionary.</param>
        /// <param name="chapter_id">The chapter_id.</param>
        /// <param name="parent">The parent.</param>
        /// <remarks>
        /// Documented by AAB, 7.8.2007.
        /// </remarks>
        internal XmlChapter(XmlDictionary dictionary, int chapter_id,ParentClass parent)
        {
            this.parent = parent;
            settings = new XmlChapterSettings(this, Parent.GetChildParentClass(this));

            m_oDictionary = dictionary;
            m_dictionary = dictionary.Dictionary;
            m_chapter = (XmlElement)m_dictionary.SelectSingleNode(m_BaseXPath + String.Format(m_XPathIdFilter, chapter_id.ToString()));
            if (m_chapter == null)
                throw new IdAccessException(chapter_id);

            Initialize();
        }
예제 #48
0
 internal XmlAllowedSettings(XmlDictionary dictionary, ParentClass parent)
 {
     dic = dictionary;
     this.parent = parent;
 }
예제 #49
0
        internal XmlSettings(XmlDictionary dictionary, ParentClass parent)
        {
            this.parent = parent;
            this.dictionary = dictionary;
            m_dictionary = dictionary.Dictionary;
            m_Settings = (XmlElement)m_dictionary.SelectSingleNode(m_basePath);
            m_MultipleChoiceOptions = new XmlQueryMultipleChoiceOptions(dictionary, Parent.GetChildParentClass(this));

            m_generalSettings = (XmlElement)m_dictionary.SelectSingleNode(m_xpathGenSet);
            m_userSettings = (XmlElement)m_dictionary.SelectSingleNode(m_xpathUsrSet);

            XPathNavigator navigator;
            XPathExpression expression;
            XPathNodeIterator nodeIterator;
            //read commentsound
            m_audioComments = new List<string>();
            navigator = m_generalSettings.CreateNavigator();
            expression = navigator.Compile(m_xpathCommentSound);
            expression.AddSort(m_xpathAttributeId, XmlSortOrder.Ascending, XmlCaseOrder.None, String.Empty, XmlDataType.Number);
            nodeIterator = navigator.Select(expression);
            while (nodeIterator.MoveNext())
                m_audioComments.Add(nodeIterator.Current.Value);
        }
예제 #50
0
        /// <summary>
        /// Initializes a new instance of the <see cref="XmlChapter"/> class.
        /// </summary>
        /// <param name="dictionary">The dictionary.</param>
        /// <param name="chapter">The chapter.</param>
        /// <param name="parent">The parent.</param>
        /// <remarks>
        /// Documented by AAB, 7.8.2007.
        /// </remarks>
        internal XmlChapter(XmlDictionary dictionary, XmlElement chapter,ParentClass parent)
        {
            this.parent = parent;
            settings = new XmlChapterSettings(this, Parent.GetChildParentClass(this));

            m_oDictionary = dictionary;
            m_dictionary = dictionary.Dictionary;
            m_chapter = chapter;

            Initialize();
        }
예제 #51
0
 internal XmlBox(XmlDictionary dictionary, int boxId, ParentClass parent)
 {
     m_Dictionary = dictionary;
     m_Id = boxId;
     Parent = parent;
 }
예제 #52
0
 /// <summary>
 /// The PopulateTrailer method populates the trailer section
 /// of the supplied VFX dictionary with all of the trailer 
 /// elements that are found in the supplied XML dictionary.
 /// </summary>
 /// <param name="source">
 /// The source dictionary for the trailer elements.
 /// </param>
 /// <param name="target">
 /// The target dictionary for the converted elements.
 /// </param>
 private static void PopulateTrailer(XmlDictionary source, FixDictionary target)
 {
     foreach (IFixDxElement dxElement in TranslateElements(source.Trailer.Elements))
     {
         target.Trailer.Add(dxElement);
     }
 }
예제 #53
0
 internal XmlStatistic(XmlDictionary dictionary, XmlElement statistic)
 {
     m_oDictionary = dictionary;
     m_dictionary = dictionary.Dictionary;
     m_statistic = statistic;
     InitializeBoxList();
 }
예제 #54
0
 /// <summary>
 /// The PopulateFields method populates the fields section
 /// of the supplied VFX dictionary with all of the fields
 /// that are found in the supplied XML dictionary.
 /// </summary>
 /// <param name="source">
 /// The source dictionary for the field elements.
 /// </param>
 /// <param name="target">
 /// The target dictionary for the converted elements.
 /// </param>
 private static void PopulateFields(XmlDictionary source, FixDictionary target)
 {
     foreach (XmlFixDxField src in source.Fields.Entries)
     {
         if (src.LengthField == null)
         {
             FixDxField dst = new FixDxField(src.Tag, src.Name, src.Type);
             dst.Enumeration = src.Enumeration;
             target.AddField(dst);
         }
         else
         {
             FixDxField dst = new FixDxField(src.Tag, src.Name, src.Type, src.LengthField);
             dst.Enumeration = src.Enumeration;
             target.AddField(dst);
         }
     }
 }
예제 #55
0
 /// <summary>
 /// The PopulateMetadata method populates the metadata properties
 /// of a VersaFix FIX data dictionary with the properties that are
 /// found in an instance of an XML representation of a dictionary.
 /// </summary>
 /// <param name="source">
 /// The source dictionary to read the properties from.
 /// </param>
 /// <param name="target">
 /// The target dictionary to add the properties to. 
 /// </param>
 private static void PopulateMetadata(XmlDictionary source, FixDictionary target)
 {
     foreach (XmlFixDxProperty xmlProperty in source.Properties.Elements)
     {
         target.Properties.Add(xmlProperty.Name, xmlProperty.Value);
     }
 }
예제 #56
0
 internal XmlDataContractCriticalHelper(Type type) : base(type)
 {
     if (type.GetTypeInfo().IsDefined(Globals.TypeOfDataContractAttribute, false))
         throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.IXmlSerializableCannotHaveDataContract, DataContract.GetClrTypeFullName(type))));
     if (type.GetTypeInfo().IsDefined(Globals.TypeOfCollectionDataContractAttribute, false))
         throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.IXmlSerializableCannotHaveCollectionDataContract, DataContract.GetClrTypeFullName(type))));
     XmlSchemaType xsdType;
     bool hasRoot;
     XmlQualifiedName stableName;
     SchemaExporter.GetXmlTypeInfo(type, out stableName, out xsdType, out hasRoot);
     this.StableName = stableName;
     this.HasRoot = hasRoot;
     XmlDictionary dictionary = new XmlDictionary();
     this.Name = dictionary.Add(StableName.Name);
     this.Namespace = dictionary.Add(StableName.Namespace);
     object[] xmlRootAttributes = (UnderlyingType == null) ? null : UnderlyingType.GetTypeInfo().GetCustomAttributes(Globals.TypeOfXmlRootAttribute, false).ToArray();
     if (xmlRootAttributes == null || xmlRootAttributes.Length == 0)
     {
         if (hasRoot)
         {
             _topLevelElementName = Name;
             _topLevelElementNamespace = (this.StableName.Namespace == Globals.SchemaNamespace) ? DictionaryGlobals.EmptyString : Namespace;
         }
     }
     else
     {
         if (hasRoot)
         {
             XmlRootAttribute xmlRootAttribute = (XmlRootAttribute)xmlRootAttributes[0];
             string elementName = xmlRootAttribute.ElementName;
             _topLevelElementName = (elementName == null || elementName.Length == 0) ? Name : dictionary.Add(DataContract.EncodeLocalName(elementName));
             string elementNs = xmlRootAttribute.Namespace;
             _topLevelElementNamespace = (elementNs == null || elementNs.Length == 0) ? DictionaryGlobals.EmptyString : dictionary.Add(elementNs);
         }
         else
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.IsAnyCannotHaveXmlRoot, DataContract.GetClrTypeFullName(UnderlyingType))));
         }
     }
 }
예제 #57
0
        public void ShouldRejectDuplicateKeys()
        {
            var dictionary = new XmlDictionary
            {
                {"key1", "value1"},
                {"key2", "value2"}
            };

            // Check for duplicate keys when adding new entries
            dictionary.Invoking(x => x.Add("key1", "newValue1")).ShouldThrow<ArgumentException>();

            // Check for duplicate keys when modifying existing entries
            var entry = new XmlDictionaryEntry("key3", "value3");
            dictionary.Add(entry);
            entry.Invoking(x => x.Key = "key1").ShouldThrow<InvalidOperationException>();
        }
예제 #58
0
    public override bool TryResolveType(Type dataContractType, Type declaredType, DataContractResolver knownTypeResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace)
    {
        if (!knownTypeResolver.TryResolveType(dataContractType, declaredType, null, out typeName, out typeNamespace))
        {

            XmlDictionary dictionary = new XmlDictionary();

            typeName = dictionary.Add(dataContractType.FullName);

            typeNamespace = dictionary.Add(dataContractType.Assembly.FullName);

        }

        return true;
    }
예제 #59
-1
 public void TestGetValue()
 {
     var dictionary = new XmlDictionary
     {
         {"key1", "value1"},
         {"key2", "value2"}
     };
     dictionary.GetValue("key1").Should().Be("value1");
 }
예제 #60
-1
 public void TestContainsValue()
 {
     var dictionary = new XmlDictionary
     {
         {"key1", "value1"}
     };
     dictionary.ContainsValue("value1").Should().BeTrue();
     dictionary.ContainsValue("value2").Should().BeFalse();
 }