Exemple #1
0
        private static KeyValuePair <TKey, TValue> DeserializeKeyValuePair <TKey, TValue>(XElement serializedObject, IXmlSerializer xmlSerializer)
        {
            if (serializedObject.Name.LocalName != "KeyValuePair")
            {
                throw new InvalidOperationException();
            }

            XElement keyElement = serializedObject.Element("Key");

            if (keyElement == null)
            {
                throw new InvalidOperationException();
            }
            object keyValue = xmlSerializer.Deserialize(keyElement.Elements().Single());

            XElement valueElement = serializedObject.Element("Value");

            if (valueElement == null)
            {
                throw new InvalidOperationException();
            }
            object valueValue = xmlSerializer.Deserialize(valueElement.Elements().Single());

            KeyValuePair <TKey, TValue> result = new KeyValuePair <TKey, TValue>((TKey)keyValue, (TValue)valueValue);

            return(result);
        }
Exemple #2
0
        private static Dictionary <TKey, TValue> DeserializeDictionary <TKey, TValue>(XElement serializedObject, IXmlSerializer xmlSerializer)
        {
            if (serializedObject.Name.LocalName != "Dictionary")
            {
                return(null);
            }

            Dictionary <TKey, TValue> result = new Dictionary <TKey, TValue>();

            foreach (XElement childElement in serializedObject.Elements("KeyPair"))
            {
                XElement keyElement = childElement.Element("Key");
                if (keyElement == null)
                {
                    return(null);
                }
                object keyValue = xmlSerializer.Deserialize(keyElement.Elements().Single());

                XElement valueElement = childElement.Element("Value");
                if (valueElement == null)
                {
                    return(null);
                }
                object valueValue = xmlSerializer.Deserialize(valueElement.Elements().Single());

                result.Add((TKey)keyValue, (TValue)valueValue);
            }

            return(result);
        }
Exemple #3
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.");
        }
Exemple #4
0
        private IPassiveMessage ProducePassiveMessageCore(XDocument rawXml, HubContext context, IDictionary <string, string> payloads)
        {
            var typeIdentity = _typeDetector.Detecting(rawXml);

            var typePicker = new TypePicker(context.GetMessageTypes());
            var targetType = typePicker.Picking(typeIdentity);

            if (targetType == null)
            {
                Log.Logger.Debug("unrecognized message type. system doesn't register this type: {0}");
                return(new AsyncPassiveMessage());
            }

            var message = (WechatPushingMessage)_xmlSerializer.Deserialize(rawXml, targetType);

            var handlerPicker = new HandlerPicker(context.GetMessageHandlers());
            var handler       = handlerPicker.Picking(message);

            if (handler == null)
            {
                Log.Logger.Debug("cannot find proper message handler.");
                return(new AsyncPassiveMessage());
            }

            var messageContext = BuideMessageContext(context, typeIdentity, rawXml, message);

            var safeHandler = new SafeMessageHandler(handler);

            return(safeHandler.HandleMessage(message, messageContext));
        }
Exemple #5
0
        private void LoadSearchHistory()
        {
            try
            {
                lock (_lock)
                {
                    Log.Debug("Loading search history");

                    if (!File.Exists(_fileName))
                    {
                        Log.Debug("History file does not exist, skipping loading");
                        return;
                    }

                    using (var fileStream = new FileStream(_fileName, FileMode.OpenOrCreate))
                    {
                        _xmlSerializer.Deserialize(_searchHistory, fileStream, null);
                    }

                    Log.Debug("Loaded search history");
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to load search history");
            }
        }
Exemple #6
0
        public async Task <IEnumerable <LogFilterGroup> > LoadAsync()
        {
            var filterGroups = new List <LogFilterGroup>();

            var applicationDataDirectory = Catel.IO.Path.GetApplicationDataDirectory();
            var configFile = Path.Combine(applicationDataDirectory, LogFilterGroupsConfigFile);

            if (_fileService.Exists(configFile))
            {
                try
                {
                    using (var stream = _fileService.OpenRead(configFile))
                    {
                        filterGroups.AddRange((LogFilterGroup[])_xmlSerializer.Deserialize(typeof(LogFilterGroup[]), stream));
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                }
            }

            var runtimeFilterGroups = CreateRuntimeFilterGroups();

            if (runtimeFilterGroups.Count > 0)
            {
                Log.Debug($"Adding '{runtimeFilterGroups.Count}' runtime filter groups");

                filterGroups.AddRange(runtimeFilterGroups);
            }

            return(filterGroups.OrderBy(x => x.Name));
        }
        public ResultSetSchema Deserialize(XmlReader reader)
        {
            reader.ThrowIfNull("reader");

            if (reader.MoveToContent() == XmlNodeType.Element && reader.LocalName == "Schema")
            {
                if (reader.ReadToDescendant("Columns"))
                {
                    var result = new ResultSetSchema
                    {
                        Columns = columnCollectionSerializer.Deserialize(reader)
                    };

                    reader.ReadEndElement();

                    return(result);
                }
                else
                {
                    throw new InvalidOperationException("No element Columns found in Schema");
                    //return new ResultSetSchema();
                }
            }
            else
            {
                throw new InvalidOperationException("Reader not at a Schema element");
            }
        }
Exemple #8
0
        public object Deserialize(Stream stream)
        {
            try
            {
                object message = _serializer.Deserialize(stream);

                if (message == null)
                {
                    throw new SerializationException("Could not deserialize message.");
                }

                if (message is XmlMessageEnvelope)
                {
                    var envelope = message as XmlMessageEnvelope;

                    InboundMessageHeaders.SetCurrent(envelope.GetMessageHeadersSetAction());

                    return(envelope.Message);
                }

                return(message);
            }
            catch (SerializationException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new SerializationException("Failed to serialize message", ex);
            }
        }
Exemple #9
0
        private void OpenFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var fileDialog = new OpenFileDialog
            {
                Filter = "Xml Files|*.xml",
                Title  = "Select an Xml File"
            };

            if (fileDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            var fileName = Path.GetFileNameWithoutExtension(fileDialog.FileName);

            if (!_fileController.IsFileNameCorrect(fileName))
            {
                MessageBox.Show("File name is not correct.");
                return;
            }

            var xmlObject = _serializer.Deserialize(fileDialog.OpenFile());

            if (_fileController.SaveFileToDB(xmlObject))
            {
                xmlObjectTableAdapter.Fill(xmlStorageDataSet.XmlObject);
                _logger.Info($"File {xmlObject} has been added.");
            }
            else
            {
                _logger.Info($"Error occured while adding file {xmlObject}.");
            }
        }
Exemple #10
0
        private bool TryLoad(string fileName = null)
        {
            fileName = GetFileName(fileName);

            Log.Info("Loading filter schemes from '{0}'", fileName);

            FilterSchemes = new FilterSchemes();

            try
            {
                if (File.Exists(fileName))
                {
                    using (var stream = File.Open(fileName, FileMode.Open))
                    {
                        _xmlSerializer.Deserialize(FilterSchemes, stream, null);
                    }
                }

                Log.Debug("Loaded filter schemes from '{0}'", fileName);
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to load filter schemes");
                return(false);
            }

            FilterSchemes.Scope = Scope;
            return(true);
        }
        public async void ProcessMessages(string businessOrganizationNumber)
        {
            //todo: add guards/nullchecks. flow below is mostly "happy-path". various checks must be added
            if (string.IsNullOrWhiteSpace(businessOrganizationNumber))
            {
                return;
            }

            // Fetch imported messages ready for processsing in database
            var messages = GetActiveImportedNavMessages(businessOrganizationNumber);

            foreach (var navMessage in await messages)
            {
                ValidateSupportedMessage(navMessage.Namespace);

                var sm = _serializer.Deserialize <SykmeldingArbeidsgiver>(navMessage.MessageXml);

                var employee = GetEmployee(sm);

                var hrMananger = GetHrManager(employee);
                var hrMessage  = CreateHrManagerMessage(navMessage.Id.ToString(), businessOrganizationNumber, hrMananger, sm);
                await _repository.Save(hrMessage);

                //_absenceService.CreateAbsence(sm, employee);

                navMessage.WorkState = WorkState.CompletedSuccessfully;
                await _repository.Save(navMessage);
            }
        }
Exemple #12
0
        public ColumnCollection Deserialize(XmlReader reader)
        {
            reader.ThrowIfNull("reader");

            if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "Columns")
            {
                var columns = new ColumnCollection();

                if (reader.ReadToDescendant("Column"))
                {
                    do
                    {
                        columns.Add(columnSerializer.Deserialize(reader));
                    }while (reader.ReadToNextSibling("Column"));
                }

                reader.Read(); // read end of node (cannot use readendelement because if there are 0 rows, there might not be an end elememt (/>)

                return(columns);
            }
            else
            {
                throw new InvalidOperationException("Reader not at a Columns element");
            }
        }
        public async virtual Task <FilterSchemes> LoadFiltersAsync(string fileName)
        {
            Argument.IsNotNullOrWhitespace(() => fileName);

            Log.Info($"Loading filter schemes from '{fileName}'");

            var filterSchemes = new FilterSchemes();

            try
            {
                if (_fileService.Exists(fileName))
                {
                    using (var stream = _fileService.OpenRead(fileName))
                    {
                        _xmlSerializer.Deserialize(filterSchemes, stream, null);
                    }
                }

                Log.Debug("Loaded filter schemes from '{0}'", fileName);
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to load filter schemes");
            }

            return(filterSchemes);
        }
        public T Deserialize(string text)
        {
            var xmlDoc       = xmlParser.Deserialize(text);
            var deserializer = new XmlDeserializer(xmlDoc);

            return(serializationFactory.Deserialize(deserializer));
        }
Exemple #15
0
        public void Deserialize(IReceiveContext context)
        {
            try
            {
                object message = _serializer.Deserialize(context.BodyStream);

                if (message == null)
                {
                    throw new SerializationException("Could not deserialize message.");
                }

                context.SetContentType(ContentTypeHeaderValue);

                if (message is XmlMessageEnvelope)
                {
                    var envelope = message as XmlMessageEnvelope;

                    context.SetUsingMessageEnvelope(envelope);
                    context.SetMessageTypeConverter(new StaticMessageTypeConverter(envelope.Message));
                    return;
                }

                context.SetMessageTypeConverter(new StaticMessageTypeConverter(message));
            }
            catch (SerializationException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new SerializationException("Failed to serialize message", ex);
            }
        }
Exemple #16
0
        public SettingsRoot Load()
        {
            SettingsRoot settingsRoot = null;
            var          path         = GetSettingsFilePath();

            if (!_file.Exists(path))
            {
                _log.Warn(string.Format("Settings file \"{0}\" does not exist.", path));
            }
            else
            {
                _log.Info(string.Format("Settings file \"{0}\" used.", path));

                try
                {
                    using (var fileStream = _file.Open(path, FileMode.Open))
                    {
                        settingsRoot = (SettingsRoot)_serializer.Deserialize(fileStream);
                    }
                }
                catch (SerializationException e)
                {
                    _log.Error("Error opening settings file.", e);
                }
            }

            return(settingsRoot);
        }
Exemple #17
0
        private IEnumerable <EventCustomerResult> GetFinalEventCustomers(string tag, IEnumerable <EventCustomerResult> newEventCustomerResult)
        {
            var xmlFilePath = GetResultNotPostedXmlFilePath(tag);

            var resultNotPosted = _resultPdfNotPostedSerializer.Deserialize(xmlFilePath);

            if (resultNotPosted == null || resultNotPosted.EventCustomer.IsNullOrEmpty())
            {
                return(newEventCustomerResult);
            }

            var eventCustomerIds = resultNotPosted.EventCustomer.Select(x => x.EventCustomerId);

            if (!newEventCustomerResult.IsNullOrEmpty())
            {
                var freshCustomerEventCustomerIds = newEventCustomerResult.Select(x => x.Id);
                eventCustomerIds = (from q in eventCustomerIds where !freshCustomerEventCustomerIds.Contains(q) select q).ToList();
            }

            var resultNotPostedEventCustomerResults = _eventCustomerResultRepository.GetEventCustomerResultsByIdsAndResultState(eventCustomerIds, (int)TestResultStateNumber.ResultDelivered, (int)NewTestResultStateNumber.ResultDelivered, false);

            if (resultNotPostedEventCustomerResults.IsNullOrEmpty())
            {
                return(newEventCustomerResult);
            }

            return(newEventCustomerResult.IsNullOrEmpty() ? resultNotPostedEventCustomerResults.ToArray() : newEventCustomerResult.Concat(resultNotPostedEventCustomerResults).ToArray());
        }
Exemple #18
0
 public override CategoriesContainer Deserialize(Stream source)
 {
     using (var reader = XmlReader.Create(source, new XmlReaderSettings
     {
         ConformanceLevel = ConformanceLevel.Fragment,
     }))
         return(xmlSerializer.Deserialize(reader));
 }
        public void Sync()
        {
            if (!_settings.SyncWithHra)
            {
                _logger.Info("Syncing with HRA is off ");
                return;
            }
            var reportGenerationConfigurationFilePath = _settings.MedicareSyncCustomSettingsPath + "EventTestSync.xml";
            var customSettings = _customSettingXmlSerializer.Deserialize(reportGenerationConfigurationFilePath);

            if (customSettings == null || !customSettings.LastTransactionDate.HasValue)
            {
                customSettings = new CustomSettings {
                    LastTransactionDate = DateTime.Today
                };
            }
            var fromTime = customSettings.LastTransactionDate ?? DateTime.Today;
            //get all tags for IsHealthPlan is true
            var orgName = _settings.OrganizationNameForHraQuestioner;
            var tags    = _corporateAccountRepository.GetHealthPlanTags();

            if (tags != null && tags.Any())
            {
                foreach (var tag in tags)
                {
                    _logger.Info("Medicare Event Test Sync for tag : " + tag);

                    // get todays Events For the Tag

                    var eventIds = _eventRepository.GetEventsByTag(fromTime, tag);
                    if (eventIds.Any())
                    {
                        _logger.Info("Medicare Event Count  : " + eventIds.Count + " " + String.Join(",", eventIds));
                        var pairs = _eventTestRepository.GetTestAliasesByEventIds(eventIds).ToList();
                        var model = new MedicareEventTestSyncModel {
                            Tag = tag, EventTestAliases = pairs, OrganizationName = orgName, TimeToken = DateTime.UtcNow.ToLongTimeString().Encrypt()
                        };
                        try
                        {
                            var result = _medicareApiService.PostAnonymous <bool>(_settings.MedicareApiUrl + MedicareApiUrl.SyncEventTest, model);
                            if (!result)
                            {
                                _logger.Info("Medicare Event Test Sync FAILED for tag : " + tag);
                            }
                        }
                        catch (Exception exception)
                        {
                            _logger.Error(" error occur Medicare Event Test Sync for tag: " + tag +
                                          " Message: " + exception.Message + "\n stack Trace: " +
                                          exception.StackTrace);
                        }
                    }
                }
            }
            customSettings.LastTransactionDate = DateTime.Today;
            _customSettingXmlSerializer.SerializeandSave(reportGenerationConfigurationFilePath, customSettings);
        }
Exemple #20
0
        private ResultSetSchema ReadSchema(XmlReader reader)
        {
            if (!reader.ReadToDescendant("Schema"))
            {
                throw new InvalidOperationException("Cannot find Schema in ResultSet");
            }

            return(schemaSerializer.Deserialize(reader)); //ReadSchema(reader);
        }
Exemple #21
0
        public async Task <IEnumerable <NavMessage> > ReadMessages(string externalCompanyId)
        {
            var navMessagesList = new List <NavMessage>();

            try
            {
                var messages = await _altinnClient.GetMessages(externalCompanyId);

                foreach (var message in messages)
                {
                    var messageId   = message.MessageId;
                    var attachments = await _altinnClient.GetAttachments(externalCompanyId, messageId);

                    foreach (var attachment in attachments)
                    {
                        var xmlAttachment = await _altinnClient.GetAttachmentData(externalCompanyId, messageId, attachment.AttachmentId);

                        if (xmlAttachment != null)
                        {
                            var elementNamespace = xmlAttachment?.Root?.Name?.NamespaceName;

                            if (!string.Equals(elementNamespace, Sykmelding_Namespace))
                            {
                                _logger.LogInformation($"Message will be skipped.Namespace: {elementNamespace}");
                            }
                            else
                            {
                                var xmlMessage = _xmlSerializer.Deserialize <SykmeldingArbeidsgiver>(xmlAttachment.ToString());

                                var navMessage = new NavMessage
                                {
                                    Namespace                  = elementNamespace,
                                    MessageXml                 = xmlAttachment.ToString(),
                                    IntegrationType            = IntegrationType.Import,
                                    WorkState                  = WorkState.ReadyForProcessing,
                                    ExternalId                 = xmlMessage.sykmeldingId,
                                    ReporteeId                 = externalCompanyId,
                                    MesssageId                 = messageId,
                                    AttachmentId               = attachment.AttachmentId,
                                    BusinessOrganizationNumber = xmlMessage.virksomhetsnummer,
                                };
                                navMessagesList.Add(navMessage);
                            }
                        }
                        else
                        {
                            Debug.WriteLine("Attachment is not XML file");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error connecting to Altinn", ex);
            }
            return(navMessagesList);
        }
Exemple #22
0
        private void GetResultPostedList(string tag)
        {
            var resultPostedToPlanFileName = Path.Combine(_resultPostedToPlanPath, string.Format("ResultPostedto_{0}.xml", tag));
            var resultPosted = _resultPdfPostedSerializer.Deserialize(resultPostedToPlanFileName);

            _resultPdfPostedXml = resultPosted == null || resultPosted.Customer.IsNullOrEmpty() ? new ResultPdfPostedXml {
                Customer = new List <CustomerInfo>()
            } : resultPosted;
        }
        public void Deserialize(TObject objectToDeserialize, XElement element, TContext context)
        {
            var subElement = element.Element(MappingName);

            if (subElement == null)
            {
                return;
            }
            _propertyMap.SetValue(objectToDeserialize, _serializer.Deserialize(subElement, context));
        }
        // GET: api/Rates
        public async Task <IEnumerable <Row> > Get()
        {
            var currentRates = await _exchangeRatesService.GetCurrentRates();

            var currencyRates = _xmlSerializer.Deserialize <CurrencyRates>(currentRates);

            var interestingCurrencies = new[] { "USD", "EUR" };
            var filteredRates         = currencyRates.Row.Where(r => interestingCurrencies.Any(c => c == r.SwiftCode));

            return(filteredRates);
        }
Exemple #25
0
        protected override void Context()
        {
            base.Context();
            _entitySerializer     = A.Fake <IXmlSerializer <SerializationContext> >();
            _serializationContext = SerializationTransaction.Create(_container);

            _deserializedObject = A.Fake <IEntity>();
            _element            = new XElement("TUTU");
            A.CallTo(() => _entitySerializer.Deserialize <IEntity>(_element, _serializationContext)).Returns(_deserializedObject);
            A.CallTo(() => _serializerRepository.SerializerFor(_element)).Returns(_entitySerializer);
        }
Exemple #26
0
        private static void RunXmlDeserialization()
        {
            Console.WriteLine("Xml Deserialization Test");
            IXmlSerializer serializer = Container.Get <IXmlSerializer>();

            Config settings = serializer.Deserialize <Config>(File.ReadAllText(Environment.CurrentDirectory + "/output/test.xml"));

            Console.WriteLine(settings != null ? "Success" : "Failure");

            Console.WriteLine();
        }
        protected override void Context()
        {
            base.Context();
            _serializer = A.Fake <IXmlSerializer <SerializationContext> >();
            _tmpFile    = FileHelper.GenerateTemporaryFileName();
            using (var fileWrite = new StreamWriter(_tmpFile))
                fileWrite.WriteLine("<Units></Units>");

            A.CallTo(_xmlSerializerRepository).WithReturnType <IXmlSerializer <SerializationContext> >().Returns(_serializer);
            A.CallTo(() => _serializer.Deserialize <CurveChartTemplate>(A <XElement> ._, A <SerializationContext> ._)).Throws <InvalidCastException>();
        }
        public IEnumerable <WorldDocument> LoadDocuments()
        {
            if (!File.Exists(_path))
            {
                return(new Dialogue[] { });
            }

            using var fileStream = File.Open(_path, FileMode.Open);
            Dialogues dialogues = (Dialogues)_xmlSerializer.Deserialize(typeof(Dialogues), fileStream);

            return(dialogues.AllDialogues.ToArray());
        }
Exemple #29
0
        public IEnumerable <Family> LoadFamilies()
        {
            if (!File.Exists(_path))
            {
                return(new Family[] { });
            }

            using (var fileStream = File.Open(_path, FileMode.Open))
            {
                var settings = _xmlSerializer.Deserialize <Settings>(fileStream);
                return(settings.Families);
            }
        }
        public virtual T GetElement(IXmlSerializer serializer)
        {
            //ThrowExceptionIfInvalid();

            //не проверяем, так как каждый раз выдаем копию элемента, иначе изменения,
            //которые неизбежно вносят элементы правила - сохраняются
            //if (_element == null)
            //{
            _element = serializer.Deserialize <T>(Definition);
            //}

            return(_element);
        }
        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 bool TryDeserialize(XElement serializedObject, IXmlSerializer xmlSerializer, out object deserializedObject)
        {
            if (serializedObject == null) throw new ArgumentNullException("serializedObject");
            if (xmlSerializer == null) throw new ArgumentNullException("xmlSerializer");

            deserializedObject = null;

            if (serializedObject.Name.LocalName != "NamedFunctionCall") return false;

            NamedFunctionCall namedFunctionCall = new NamedFunctionCall(null, null);

            XElement nameElement = serializedObject.Element("Name");
            if (nameElement != null)
            {
                if (nameElement.Elements().Count() != 1) return false;

                namedFunctionCall.Name = (string)xmlSerializer.Deserialize(nameElement.Elements().Single());
            }

            XElement valueElement = serializedObject.Element("Value");
            if (valueElement != null)
            {
                if (valueElement.Elements().Count() != 1) return false;

                object result;
                try
                {
                    result = FunctionFacade.BuildTree(valueElement.Elements().Single());
                }
                catch (Exception)
                {
                    return false;
                }
                if ((result is BaseFunctionRuntimeTreeNode) == false) return false;

                namedFunctionCall.FunctionCall = (BaseFunctionRuntimeTreeNode)result;
            }

            deserializedObject = namedFunctionCall;
            return true;
        }
        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 TryDeserialize(XElement serializedObject, IXmlSerializer xmlSerializer, out object deserializedObject)
        {
            if (serializedObject == null) throw new ArgumentNullException("serializedObject");
            if (xmlSerializer == null) throw new ArgumentNullException("xmlSerializer");

            deserializedObject = null;

            if (serializedObject.Name.LocalName != "ConsoleMessageQueueElements") return false;

            List<ConsoleMessageQueueElement> queueElements = new List<ConsoleMessageQueueElement>();

            foreach (XElement queueElement in serializedObject.Elements())
            {
                ConsoleMessageQueueElement result = new ConsoleMessageQueueElement();
                result.EnqueueTime = DateTime.Parse(queueElement.Attribute("time").Value);
                result.QueueItemNumber = Int32.Parse(queueElement.Attribute("number").Value);
                if (queueElement.Attribute("console") != null)
                    result.ReceiverConsoleId = queueElement.Attribute("console").Value;

                try
                {
                    result.QueueItem = (IConsoleMessageQueueItem)xmlSerializer.Deserialize(queueElement.Elements().First());
                }
                catch (Exception ex)
                {
                    string errorInfo = string.Format("Deserialization of message #{0} failed with an '{1}' exception - the message has been dropped. Details: '{2}'", queueElement.Attribute("number").Value, ex.GetType().Name, ex.Message);
                    // pad queue to ensure sequence.
                    LoggingService.LogWarning("ConsoleMessageQueue", errorInfo);
                    result.QueueItem = new LogEntryMessageQueueItem { Level = LogLevel.Error, Message = errorInfo, Sender = this.GetType() }; 
                }

                queueElements.Add(result);
            }

            deserializedObject = queueElements;
            return true;
        }