예제 #1
0
        private async Task <string> GetRequestResult(string wpsUri, Request request)
        {
            if (wpsUri == null)
            {
                throw new ArgumentNullException(nameof(wpsUri));
            }
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var requestXml = _serializationService.Serialize(request);
            var response   = await _httpClient.PostAsync(wpsUri,
                                                         new StringContent(requestXml, Encoding.UTF8, RequestMimeType));

            var content = await response.Content.ReadAsStringAsync();

            if (response.IsSuccessStatusCode)
            {
                return(content);
            }

            var exceptionReport = _serializationService.Deserialize <ExceptionReport>(content);
            var exception       = exceptionReport.Exceptions.FirstOrDefault();

            if (exception != null)
            {
                throw exception;
            }

            throw new Exception("Could not get a valid response from the WPS server.");
        }
예제 #2
0
    public async Task SetAsync <TResult>(ISecret <TResult> secret, IErrorsAndInfos errorsAndInfos) where TResult : class, ISecretResult <TResult>, new()
    {
        var valueOrDefault = await ValueOrDefaultAsync(secret, errorsAndInfos);

        var xml       = XmlSerializer.Serialize(valueOrDefault);
        var encrypted = secret is IEncryptedSecret <TResult>;

        await WriteToFileAsync(secret, xml, false, encrypted, errorsAndInfos);

        Values[secret.Guid] = valueOrDefault;
    }
예제 #3
0
        private static XElement SerializeKeyValuePair <TKey, TValue>(KeyValuePair <TKey, TValue> KeyValuePairToSerialize, IXmlSerializer xmlSerializer)
        {
            XElement result = new XElement("KeyValuePair");

            XElement serializedKey   = xmlSerializer.Serialize(typeof(TKey), KeyValuePairToSerialize.Key);
            XElement serializedValue = xmlSerializer.Serialize(typeof(TValue), KeyValuePairToSerialize.Value);

            result.Add(new XElement("Key", serializedKey));
            result.Add(new XElement("Value", serializedValue));

            return(result);
        }
예제 #4
0
        private static XElement SerializePair <TKey, TValue>(Pair <TKey, TValue> pairToSerialize, IXmlSerializer xmlSerializer)
        {
            XElement result = new XElement("Pair");

            XElement serializedKey   = xmlSerializer.Serialize(typeof(TKey), pairToSerialize.First);
            XElement serializedValue = xmlSerializer.Serialize(typeof(TValue), pairToSerialize.Second);

            result.Add(new XElement("First", serializedKey));
            result.Add(new XElement("Second", serializedValue));

            return(result);
        }
        public bool TrySerialize(Type objectToSerializeType, object objectToSerialize, IXmlSerializer xmlSerializer, out XElement serializedObject)
        {
            if (objectToSerializeType == null)
            {
                throw new ArgumentNullException("objectToSerializeType");
            }
            if (xmlSerializer == null)
            {
                throw new ArgumentNullException("xmlSerializer");
            }

            serializedObject = null;
            if (objectToSerializeType != typeof(NamedFunctionCall))
            {
                return(false);
            }

            NamedFunctionCall namedFunctionCall = objectToSerialize as NamedFunctionCall;

            serializedObject = new XElement("NamedFunctionCall");

            if (namedFunctionCall != null)
            {
                serializedObject.Add(new XElement("Name", xmlSerializer.Serialize(typeof(string), namedFunctionCall.Name)));

                if (namedFunctionCall.FunctionCall != null)
                {
                    serializedObject.Add(new XElement("Value", namedFunctionCall.FunctionCall.Serialize()));
                }
            }

            return(true);
        }
예제 #6
0
        public void WriteXml(XmlWriter writer, ActionResult actionResult)
        {
            writer.ThrowIfNull("writer");
            actionResult.ThrowIfNull("actionResult");

            var ex = actionResult.Validate(false);

            if (ex != null)
            {
                throw new InvalidOperationException("ActionResult validation failed", ex);
            }

            /*
             * Reading Action result contains the tag <ActioNResult> while writing, the xml serializer
             * already writes this to the writer.
             * Therefore when reading, Expect the ActionResult node, and when writing, do not write this element
             */

            writer.WriteStartElement("ResultSets");

            for (var t = 0; t < actionResult.ResultSets.Count; t++)
            {
                resultSetSerializer.Serialize(writer, actionResult.ResultSets[t]);
            }

            writer.WriteEndElement();
        }
예제 #7
0
        private static XElement SerializeDictionary <TKey, TValue>(Dictionary <TKey, TValue> dictionaryToSerialize, IXmlSerializer xmlSerializer)
        {
            XElement result = new XElement("Dictionary");

            foreach (KeyValuePair <TKey, TValue> kvp in dictionaryToSerialize)
            {
                XElement serializedKey   = xmlSerializer.Serialize(typeof(TKey), kvp.Key);
                XElement serializedValue = xmlSerializer.Serialize(typeof(TValue), kvp.Value);

                result.Add(new XElement("KeyPair",
                                        new XElement("Key", serializedKey),
                                        new XElement("Value", serializedValue)));
            }

            return(result);
        }
예제 #8
0
        public void Serialize <T>(Stream stream, ISendContext <T> context)
            where T : class
        {
            try
            {
                context.SetContentType(ContentTypeHeaderValue);

                XmlMessageEnvelope envelope = XmlMessageEnvelope.Create(context);

                _serializer.Serialize(stream, envelope, (declaringType, propertyType, value) =>
                {
                    if (declaringType == typeof(XmlMessageEnvelope) && propertyType == typeof(object))
                    {
                        return(typeof(T));
                    }

                    if (propertyType == typeof(object))
                    {
                        return(value.GetType());
                    }

                    return(propertyType);
                });
            }
            catch (SerializationException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new SerializationException("Failed to serialize message", ex);
            }
        }
예제 #9
0
        public void Save()
        {
            Log.Info("Saving keyboard mappings");

            try
            {
                var keyboardMappings = new KeyboardMappings();
                foreach (var command in _commandManager.GetCommands())
                {
                    var keyboardMapping = new KeyboardMapping();
                    keyboardMapping.CommandName  = command;
                    keyboardMapping.InputGesture = _commandManager.GetInputGesture(command);

                    keyboardMappings.Mappings.Add(keyboardMapping);
                }

                using (var fileStream = _fileService.Create(_fileName))
                {
                    _xmlSerializer.Serialize(keyboardMappings, fileStream, null);
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to save the keyboard mappings");
            }
        }
예제 #10
0
        public void Serialize <T>(Stream stream, T message)
        {
            try
            {
                var envelope = XmlMessageEnvelope.Create(message);

                _serializer.Serialize(stream, envelope, (declaringType, propertyType, value) =>
                {
                    if (declaringType == typeof(XmlMessageEnvelope) && propertyType == typeof(object))
                    {
                        return(typeof(T));
                    }

                    if (propertyType == typeof(object))
                    {
                        return(value.GetType());
                    }

                    return(propertyType);
                });
            }
            catch (SerializationException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new SerializationException("Failed to serialize message", ex);
            }
        }
예제 #11
0
        public void Serialize()
        {
            string expected =
                "Start " +
                "MockSource " +
                "IsValid True IsValid " +
                "IntNumber 42 IntNumber " +
                $"DoubleNumber {double.MaxValue.ToString(CultureInfo.InvariantCulture)} DoubleNumber " +
                $"LongNumber {long.MaxValue} LongNumber " +
                "Name Source Name " +
                "Items " +
                "Item Name i1 Name Item " +
                "Item Name i2 Name Item " +
                "Items " +
                "DoubleArray " +
                "Item 1 Item " +
                "Item 2 Item " +
                "DoubleArray " +
                "MockSource " +
                "End";
            var            source     = new MockSource();
            var            writer     = new MockXmlWriter();
            IXmlSerializer serializer = XmlSerializer.GetBuilder(typeof(MockSource)).Build();

            serializer.Serialize(writer, source);
            string actual = writer.ToString();

            Assert.Equal(expected, actual);
        }
        public bool TrySerialize(Type objectToSerializeType, object objectToSerialize, IXmlSerializer xmlSerializer, out XElement serializedList)
        {
            if (objectToSerializeType == null) throw new ArgumentNullException("objectToSerializeType");
            if (xmlSerializer == null) throw new ArgumentNullException("xmlSerializer");

            serializedList = null;
            if (objectToSerializeType != typeof(List<ConsoleMessageQueueElement>)) return false;

            List<ConsoleMessageQueueElement> queueElements = objectToSerialize as List<ConsoleMessageQueueElement>;

            serializedList = new XElement("ConsoleMessageQueueElements");

            if (queueElements != null)
            {
                foreach (ConsoleMessageQueueElement queueElement in queueElements)
                {
                    XElement serializedQueueItem = xmlSerializer.Serialize(queueElement.QueueItem.GetType(), queueElement.QueueItem);

                    XElement serializedElement = new XElement("QueueElement",
                        new XAttribute("time", queueElement.EnqueueTime),
                        new XAttribute("number", queueElement.QueueItemNumber),
                        new XAttribute("itemtype", queueElement.QueueItem.GetType()),
                        serializedQueueItem);

                    if (string.IsNullOrEmpty(queueElement.ReceiverConsoleId) == false)
                    {
                        serializedElement.Add(new XAttribute("console", queueElement.ReceiverConsoleId));
                    }

                    serializedList.Add(serializedElement);
                }
            }

            return true;
        }
 public void Serialize <T>(string filename, T obj)
 {
     using (var stream = _fileSystem.File.Create(filename))
     {
         _xmlSerializer.Serialize(stream, obj);
     }
 }
        public List <string> GetValuesToSign(object value)
        {
            Ensure.ArgumentNotNull(value, nameof(value));

            // Need to serialize plain object to order signing values by their xml names.
            var xml = _serializer.Serialize(value, "anyroot");

            return(GetSignedValuesCore(xml).Values);
        }
예제 #15
0
        //public ContentControl RegionContentControl { get; set; }

        //private bool _IsManageable=true;
        ///// <summary>
        ///// displayed in the management manu
        ///// </summary>
        //public bool IsManageable
        //{
        //    get { return _IsManageable; }
        //    set
        //    {
        //        if (value != _IsManageable)
        //        {
        //            _IsManageable = value;
        //            RaisePropertyChanged(() => this.IsManageable);
        //        }
        //    }
        //}



        public virtual void SaveState(Stream stream)
        {
            IXmlSerializer xmlSerializer = SerializationFactory.GetXmlSerializer();

            xmlSerializer.Serialize(this, stream);
            Log.Debug("Saved object {0}", this.ContentId);
            base.ClearIsDirtyOnAllChilds();
            this.IsDataDirty = false;
        }
예제 #16
0
 public void OnShutDown()
 {
     xmlSerializer.Serialize(SomeUser, userConfigFilePath, userConfigFileName);
     //for the first date
     //if (!Directory.Exists(configFilePath))
     //    Directory.CreateDirectory(configFilePath);
     //if (!File.Exists(configFileName))
     //    xmlSerializer.Serialize(config, configFilePath, configFileName);
 }
예제 #17
0
        public void DoesNotWriteUnwriteableCollection()
        {
            IXmlWriter     writer     = new MockXmlWriter();
            IXmlSerializer serializer = XmlSerializer.GetBuilder(typeof(UnwriteableCollectionSource)).Build();

            serializer.Serialize(writer, new UnwriteableCollectionSource());
            string actual = writer.ToString();

            Assert.DoesNotContain(actual, "Items");
        }
예제 #18
0
        private static void RunXmlSerialization()
        {
            Console.WriteLine("Xml Serialization Test");
            var            settings   = GetSettings();
            IXmlSerializer serializer = Container.Get <IXmlSerializer>();


            File.WriteAllText(Environment.CurrentDirectory + "/output/test.xml", serializer.Serialize(settings));
            Console.WriteLine();
        }
예제 #19
0
 public override void Serialize(CategoriesContainer item, Stream target)
 {
     using (var writer = XmlWriter.Create(target, new XmlWriterSettings
     {
         ConformanceLevel = ConformanceLevel.Fragment,
         WriteEndDocumentOnClose = false,
         OmitXmlDeclaration = true,
         Indent = true,
     }))
         xmlSerializer.Serialize(item, writer);
 }
예제 #20
0
        public void WritesElementStringGivenSimpleCollectionItem()
        {
            IXmlWriter     writer     = new MockXmlWriter();
            IXmlSerializer serializer = XmlSerializer.GetBuilder(typeof(SimpleItemSource)).Build();

            serializer.Serialize(writer, new SimpleItemSource());
            string actual = writer.ToString();

            Assert.Contains("Item s1 Item", actual);
            Assert.Contains("Item s2 Item", actual);
        }
예제 #21
0
 protected override void Context()
 {
     base.Context();
     _element           = new XElement("TOTO");
     _entityToSerialize = A.Fake <IEntity>();
     _entitySerializer  = A.Fake <IXmlSerializer <SerializationContext> >();
     A.CallTo(() => _entitySerializer.ObjectType).Returns(typeof(IEntity));
     _serializationContext = SerializationTransaction.Create();
     A.CallTo(() => _entitySerializer.Serialize(_entityToSerialize, _serializationContext)).Returns(_element);
     A.CallTo(() => _serializerRepository.SerializerFor(_entityToSerialize)).Returns(_entitySerializer);
 }
예제 #22
0
        public void SaveFamilies(IEnumerable <Family> families)
        {
            var settings = new Settings();

            settings.Families.ReplaceRange(families);

            using (var fileStream = File.Open(_path, FileMode.Create))
            {
                _xmlSerializer.Serialize(settings, fileStream);
            }
        }
        public void SaveDocuments(IEnumerable <WorldDocument> documents)
        {
            Dialogues dialogueHolder = new Dialogues();

            foreach (WorldDocument doc in documents)
            {
                Dialogue dialogue = (Dialogue)doc;
                dialogueHolder.AllDialogues.Add(dialogue);
                using var fileStream = File.Open(_path, FileMode.Create);
                _xmlSerializer.Serialize(dialogueHolder, fileStream);
            }
        }
        public void Serialize_SitemapModel()
        {
            SitemapModel sitemap = new SitemapModel(new List <SitemapNode> {
                new SitemapNode("abc"), new SitemapNode("def")
            });

            string result = serializer.Serialize(sitemap);

            result.Should().BeXmlEquivalent("sitemap.xml");
        }
예제 #25
0
 public override void Serialize(Array item, XmlWriter writer)
 {
     writer.WriteStartElement("Array");
     try
     {
         writer.WriteAttributeString("Count", item.Length.ToString(CultureInfo.InvariantCulture));
         foreach (var element in item)
         {
             elementSerializer.Serialize(element, writer);
         }
     }
     finally { writer.WriteEndElement(); }
 }
예제 #26
0
        public void WithExcludedProperty()
        {
            var            source           = new MockSource();
            var            writer           = new MockXmlWriter();
            var            excludedProperty = nameof(MockSource.IntNumber);
            IXmlSerializer serializer       = XmlSerializer.GetBuilder(typeof(MockSource))
                                              .WithExcludedProperty(excludedProperty)
                                              .Build();

            serializer.Serialize(writer, source);
            string actual = writer.ToString();

            Assert.DoesNotContain(excludedProperty, actual);
        }
예제 #27
0
        public void WithRootName()
        {
            var            source     = new MockSource();
            var            writer     = new MockXmlWriter();
            string         rootName   = "CustomRoot";
            IXmlSerializer serializer = XmlSerializer.GetBuilder(typeof(MockSource))
                                        .WithRootName(rootName)
                                        .Build();

            serializer.Serialize(writer, source);
            string actual = writer.ToString();

            Assert.Contains(rootName, actual);
            Assert.DoesNotContain(nameof(MockSource), actual);
        }
예제 #28
0
        public void WithCollectionItemName()
        {
            var            source     = new MockSource();
            var            writer     = new MockXmlWriter();
            var            itemName   = "CustomItem";
            IXmlSerializer serializer = XmlSerializer.GetBuilder(typeof(MockSource))
                                        .WithCollectionItemName(nameof(MockSource.Items), itemName)
                                        .Build();

            serializer.Serialize(writer, source);
            string actual = writer.ToString();

            Assert.Contains(itemName, actual);
            Assert.DoesNotContain(nameof(XmlSerializer.DefaultItemName), actual);
        }
예제 #29
0
        public Service()
        {
            var kernel = new StandardKernel();

            kernel.Load(Assembly.GetExecutingAssembly());
            serializer = kernel.Get <IXmlSerializer>();
            provider   = kernel.Get <IDataProvider>();
            config     = serializer.Deserialize <Config>(configFilePath);
            serializer.Serialize(config, configPath, configFilePath);
            provider.Configure(config.ConnectionTimeOut);
            provider.Configure(config.ConnectionString);
            provider.Initialize();
            stores = new List <Store>();
            OnTimerEvent(null, null);
            StartTimer();
        }
예제 #30
0
        public override void Serialize(LinearGradientPalette item, XmlWriter writer)
        {
            var map = item.GetMap();

            writer.WriteStartElement("Palette");
            try
            {
                writer.WriteAttributeString("Count", map.Length.ToString(CultureInfo.InvariantCulture));
                foreach (var element in map)
                {
                    doubleSerializer.Serialize(element.Item1, writer);
                    colourSerializer.Serialize(element.Item2, writer);
                }
            }
            finally { writer.WriteEndElement(); }
        }
예제 #31
0
        private void Save()
        {
            Log.Info("Saving recently used items to '{0}'", _fileName);

            try
            {
                using (var fileStream = _fileService.Create(_fileName))
                {
                    _xmlSerializer.Serialize(_items, fileStream, null);
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to save recently used items");
            }
        }
        public EditFilterViewModel(FilterSchemeEditInfo filterSchemeEditInfo, IReflectionService reflectionService, 
            IXmlSerializer xmlSerializer, IMessageService messageService)
        {
            Argument.IsNotNull(() => filterSchemeEditInfo);
            Argument.IsNotNull(() => reflectionService);
            Argument.IsNotNull(() => xmlSerializer);
            Argument.IsNotNull(() => messageService);

            PreviewItems = new FastObservableCollection<object>();
            RawCollection = filterSchemeEditInfo.RawCollection;
            EnableAutoCompletion = filterSchemeEditInfo.EnableAutoCompletion;
            AllowLivePreview = filterSchemeEditInfo.AllowLivePreview;
            EnableLivePreview = filterSchemeEditInfo.AllowLivePreview;
            
            var filterScheme = filterSchemeEditInfo.FilterScheme;

            _originalFilterScheme = filterScheme;
            _reflectionService = reflectionService;
            _xmlSerializer = xmlSerializer;
            _messageService = messageService;

            DeferValidationUntilFirstSaveCall = true;

            InstanceProperties = _reflectionService.GetInstanceProperties(filterScheme.TargetType).Properties;

            // Serializing gives us a *real* deep clone, there was a bug in Copy()
            //FilterScheme = _originalFilterScheme.Copy();

            using (var memoryStream = new MemoryStream())
            {
                xmlSerializer.Serialize(_originalFilterScheme, memoryStream);
                memoryStream.Position = 0L;
                FilterScheme = (FilterScheme) xmlSerializer.Deserialize(typeof (FilterScheme), memoryStream);
            }

            FilterSchemeTitle = FilterScheme.Title;

            AddGroupCommand = new Command<ConditionGroup>(OnAddGroup);
            AddExpressionCommand = new Command<ConditionGroup>(OnAddExpression);
            DeleteConditionItem = new Command<ConditionTreeItem>(OnDeleteCondition);
        }
        public EditFilterViewModel(FilterSchemeEditInfo filterSchemeEditInfo, IXmlSerializer xmlSerializer, 
            IMessageService messageService, IServiceLocator serviceLocator)
        {
            Argument.IsNotNull(() => filterSchemeEditInfo);
            Argument.IsNotNull(() => xmlSerializer);
            Argument.IsNotNull(() => messageService);
            Argument.IsNotNull(() => serviceLocator);

            PreviewItems = new FastObservableCollection<object>();
            RawCollection = filterSchemeEditInfo.RawCollection;
            EnableAutoCompletion = filterSchemeEditInfo.EnableAutoCompletion;
            AllowLivePreview = filterSchemeEditInfo.AllowLivePreview;
            EnableLivePreview = filterSchemeEditInfo.AllowLivePreview;

            var filterScheme = filterSchemeEditInfo.FilterScheme;

            _originalFilterScheme = filterScheme;
            _xmlSerializer = xmlSerializer;
            _messageService = messageService;
            _serviceLocator = serviceLocator;

            _reflectionService = _serviceLocator.ResolveType<IReflectionService>(filterScheme.Tag);

            DeferValidationUntilFirstSaveCall = true;

            using (var memoryStream = new MemoryStream())
            {
                xmlSerializer.Serialize(_originalFilterScheme, memoryStream);
                memoryStream.Position = 0L;
                FilterScheme = (FilterScheme)xmlSerializer.Deserialize(typeof(FilterScheme), memoryStream);
                FilterScheme.Tag = filterScheme.Tag;
            }

            FilterSchemeTitle = FilterScheme.Title;

            AddGroupCommand = new Command<ConditionGroup>(OnAddGroup);
            AddExpressionCommand = new Command<ConditionGroup>(OnAddExpression);
            DeleteConditionItem = new Command<ConditionTreeItem>(OnDeleteCondition, OnDeleteConditionCanExecute);
        }
        public bool TrySerialize(Type objectToSerializeType, object objectToSerialize, IXmlSerializer xmlSerializer, out XElement serializedObject)
        {
            if (objectToSerializeType == null) throw new ArgumentNullException("objectToSerializeType");
            if (xmlSerializer == null) throw new ArgumentNullException("xmlSerializer");

            serializedObject = null;
            if (objectToSerializeType != typeof(NamedFunctionCall)) return false;

            NamedFunctionCall namedFunctionCall = objectToSerialize as NamedFunctionCall;

            serializedObject = new XElement("NamedFunctionCall");

            if (namedFunctionCall != null)
            {
                serializedObject.Add(new XElement("Name", xmlSerializer.Serialize(typeof(string), namedFunctionCall.Name)));

                if (namedFunctionCall.FunctionCall != null)
                {
                    serializedObject.Add(new XElement("Value", namedFunctionCall.FunctionCall.Serialize()));
                }
            }

            return true;
        }