private bool CheckToken(string host, LoginWithResponse loginWith) { if (loginWith == null) { return(false); } var path = host + @"/API/REST/Authorization/CheckToken?token=" + loginWith.AuthToken; try { var response = connectionService.SendGet(path, null); if (response.Contains("Запуск сервера ELMA")) { return(false); } loginWith = serializationService.Deserialize <LoginWithResponse>(response); return(true); } catch (Exception ex) { return(false); } }
public byte[] Deserialize(string path) { var deserializedBuffer = serializationService.Deserialize(path); var decompressedData = compressionService.Decompress(deserializedBuffer); return(decompressedData); }
public void SerializationResolvesFromSnakeCase() { // Arrange var value = "{\"ghost_towns_count\":5}"; // Act var deserialized = _service.Deserialize <TestClass>(value); var actual = deserialized.GhostTownsCount; // Assert Assert.Equal(5, actual); }
protected async Task <T> ProvideFileAsync <T>(string fileKey, string container, CancellationToken cancellationToken) { using (var stream = await _fileService.OpenReadStreamAsync(fileKey, container, cancellationToken)) { return(_serializationService.Deserialize <T>(stream)); } }
/// <summary> /// Invoked when the Page is loaded and becomes the current source of a parent Frame. /// </summary> /// <param name="e">Event data that can be examined by overriding code. The event data is representative of the pending navigation that will load the current Page. Usually the most relevant property to examine is Parameter.</param> protected override async void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); if (e.Parameter == null) { return; } if (!new Connection().IsInternetConnected) { AddToFavorites.Visibility = Visibility.Collapsed; ShowToastNotification("No internet", "You need an internet connection to view this movie's details."); return; } try { LoadingIndicator.IsActive = true; AddToFavorites.Visibility = Visibility.Collapsed; _movieId = _serializationService.Deserialize(e.Parameter?.ToString()).ToString(); var res = await _mdvm.Lookup(_movieId); MainGrid.ItemsSource = res; CheckIfMovieIsFavorite(_movieId); } finally { LoadingIndicator.IsActive = false; AddToFavorites.Visibility = Visibility.Visible; } }
protected override void InitFromBundle(IMvxBundle parameters) { base.InitFromBundle(parameters); var jsonString = parameters.Data["JsonString"]; var mainPojo = _serializationService.Deserialize <MainPojo>(jsonString); Location = "Weather in " + mainPojo.Name + ", " + mainPojo.Sys.Country; Temperature = mainPojo.Main.Temp.Convert(ConversionType.Degrees); Date = "get at " + mainPojo.Dt.Convert(ConversionType.Date); foreach (var weather in mainPojo.Weather) { PicUrl = "http://openweathermap.org/img/w/" + weather.Icon + ".png"; Description = weather.Description; } ListOfData.Add(new WeatherData(Strings.Temperature, Temperature)); ListOfData.Add(new WeatherData(Strings.Humidity, mainPojo.Main.Humidity.Convert(ConversionType.Percentage))); ListOfData.Add(new WeatherData(Strings.Pressure, mainPojo.Main.Pressure.Convert(ConversionType.Degrees))); ListOfData.Add(new WeatherData(Strings.Clouds, mainPojo.Clouds.All)); ListOfData.Add(new WeatherData(Strings.Sunrise, mainPojo.Sys.Sunrise.Convert(ConversionType.TimeOfDay))); ListOfData.Add(new WeatherData(Strings.Sunset, mainPojo.Sys.Sunset.Convert(ConversionType.TimeOfDay))); ListOfData.Add(new WeatherData(Strings.Coords, "[" + mainPojo.Coord.Lon + ", " + mainPojo.Coord.Lat + "]")); }
private void Receive() { while (_serialPort.BytesToRead > 0) { byte received = (byte)_serialPort.ReadByte(); _buffer.Add(received); if (received == _serializationService.Delimiter) { try { var message = _serializationService.Deserialize(_buffer.ToArray()); if (message != null) { RaiseMessageReceived(message); } } catch (ArgumentException) { RaiseError("Deserialization error."); } _buffer.Clear(); } } }
public async Task <SubmissionSummary> GetSubmissionSummary(CloudBlobContainer container, string fileName, CancellationToken cancellationToken) { if (container == null) { throw new ArgumentNullException(nameof(container)); } try { var blobReference = container.GetBlockBlobReference(fileName); if (await blobReference.ExistsAsync(cancellationToken)) { using (var stream = await blobReference .OpenReadAsync(null, _requestOptions, null, cancellationToken)) { return(_serializationService.Deserialize <SubmissionSummary>(stream)); } } return(null); } catch (Exception e) { _logger.LogError($"Unable to read blob: {fileName} Container:{container.Name} ContainerUri:{container.Uri}", e); throw; } }
public void TestCollection() { Base a = new Base(); Base b = new Base(); Base c = new Base(); Base d = new Base(); CollectionDerived e = new CollectionDerived() { Child = a, Parents = new List <Base>() { a, b, c, d } }; TypeConfiguration.TrustedTypes = TypeMatch.Assembly(typeof(SerializerTests).Assembly); ISerializationService serializer = Container.Resolve <ISerializationService>(); string json = serializer.Serialize(e); Console.WriteLine(json); Base newE = serializer.Deserialize <Base>(json); Assert.IsInstanceOfType(newE, typeof(CollectionDerived)); var listE = (CollectionDerived)newE; Assert.IsNotNull(listE.Parents); Assert.AreEqual(4, listE.Parents.Count()); Assert.AreEqual(listE.Child, listE.Parents.ElementAt(0)); }
private bool Receive(SerialPort serialPort) { var startTime = DateTime.Now; var buffer = new List <byte>(); IMessage message = null; while ((DateTime.Now - startTime).TotalMilliseconds < _handShakeTimeout) { if (serialPort.BytesToRead > 0) { byte received = (byte)serialPort.ReadByte(); buffer.Add(received); if (received == _serializationService.Delimiter) { message = _serializationService.Deserialize(buffer.ToArray()); return(message != null && message.GetType() == typeof(MessageHandShakeResponse)); } } } return(false); }
public async Task ShouldBeAbleToImportOpmlFeeds(string url) { Category category = null; _categoryManager .When(x => x.Insert(Arg.Any <Category>())) .Do(callback => category = callback.Arg <Category>()); var opml = new Opml { Body = new List <OpmlOutline> { new OpmlOutline { XmlUrl = url } } }; _serializationService.Deserialize <Opml>(Arg.Any <Stream>()).Returns(opml); var success = await _opmlService.ImportOpml(new MemoryStream()); success.Should().BeTrue(); category.Channels.Count.Should().Be(1); category.Channels[0].Uri.Should().Be(url); category.Channels[0].Notify.Should().BeTrue(); }
/// <summary> /// Запросить события из ELMA /// </summary> public bool SyncronizeEvents(GlobalSettings settings) { var path = settings.Host + @"/API/REST/Entity/Query?type=" + userTypeUid.ToString(); try { var response = connectionService.SendGet(path, securityService.AuthToken); var users = serializationService.Deserialize <User[]>(response).ToList(); #region Искуственные даты рождения users.ForEach(user => { if (user == users.Last() || user == users.First()) { user.BirthDate = DateTime.Now.AddDays(1); } else { user.BirthDate = DateTime.Now; } }); #endregion todayEvents.Clear(); nextEvents.Clear(); var todayPairs = new List <Tuple <BirthdayEvent, User> >(); var nextPairs = new List <Tuple <BirthdayEvent, User> >(); users.ForEach(user => { if (user.BirthDate.Value.Date == DateTime.Today) { var bEvent = new BirthdayEvent(user); todayEvents.Add(bEvent); todayPairs.Add(new Tuple <BirthdayEvent, User>(bEvent, user)); } else { var bEvent = new BirthdayEvent(user); nextEvents.Add(bEvent); nextPairs.Add(new Tuple <BirthdayEvent, User>(bEvent, user)); } }); //загрузка фотографий SyncronizePhoto(settings, todayPairs); SyncronizePhoto(settings, nextPairs); return(true); } catch (Exception ex) { return(false); } }
public T GetConfigData <X, T>(ConfigFile <X, T> config, string pathOverride = null) where X : class where T : class { var path = pathOverride ?? $@"{_userSettingsService.Get().GameInstallLocation}\{config.GamePath}"; var xml = _fileStorageService.Get(path).Value; var xmlclasses = _serializationService.Deserialize <X>(xml); return(_mapperFactory.GetMapper(config).Convert(xmlclasses.Value)); }
public T Read <T>(string key) { var result = _adapter.ReadString(key); if (EnableCompression) { result = result.Decompress(); } return(_serializationService.Deserialize <T>(result)); }
public async Task <T2> PostDeserializedAsync <T1, T2>(Uri requestUri, T1 payload) where T1 : class where T2 : class { var result = await PostAsync <T1>(requestUri, payload); var content = await result.Content.ReadAsStringAsync(); return(serialization.Deserialize <T2>(content)); }
public async Task <bool> ImportOpmlFeedsAsync(Stream stream) { // Deserialize object from file. var opml = _serializationService.Deserialize <Opml>(stream); if (opml == null) { return(false); } // Process potential categories. var categories = new List <Category>(); opml.Body .Where(i => i.XmlUrl == null && i.HtmlUrl == null) .Select(i => new { Title = i.Title ?? i.Text, Outline = i }) .Where(i => i.Title != null) .Select(i => new Category { Channels = i.Outline.ChildOutlines .Select(o => new Channel { Uri = o.XmlUrl, Notify = true }) .ToList(), Title = i.Title }) .ToList() .ForEach(i => categories.Add(i)); // Process plain feeds. var uncategorized = new Category { Title = "Unknown category", Channels = opml.Body .Where(i => Uri.IsWellFormedUriString(i.XmlUrl, UriKind.Absolute)) .Select(i => new Channel { Uri = i.XmlUrl, Notify = true }) .ToList() }; if (uncategorized.Channels.Any()) { categories.Add(uncategorized); } // Insert into database and notify user. foreach (var category in categories) { await _categoriesRepository.InsertAsync(category); } return(true); }
private void TestValue <T>(T value) { TypeConfiguration.TrustedTypes = TypeMatch.Assembly(typeof(SerializerTests).Assembly); ISerializationService serializer = Container.Resolve <ISerializationService>(); string json = serializer.Serialize(value); Console.WriteLine(json); T newVal = serializer.Deserialize <T>(json); Assert.AreEqual(value, newVal, $"Value type serialization failed on {typeof(T).Name} native serializer."); }
/// <summary> /// Загрузка структуры из файла. /// </summary> private void LoadStruct() { if (_openFileDialog.ShowDialog() != true) { return; } using (var stream = new FileStream(_openFileDialog.FileName, FileMode.Open, FileAccess.Read)) { Root = _serializationService.Deserialize(stream); } }
public T Deserialize <T>(object value) { if (value is string s) { return(_service.Deserialize <T>(s)); } else { // in order to save to settings we require a string throw new ArgumentException($"{nameof(value)} must be string : {value}"); } }
public async Task <IEnumerable <ValidationErrorDto> > GetValidationErrorsAsync(string validationErrorsStorageKey, string validationErrorsLookupStorageKey) { var result = new List <ValidationErrorDto>(); try { var reportExists = await _ioPersistenceService.ContainsAsync(validationErrorsStorageKey); if (reportExists) { _logger.LogInfo($"Error report exists for validationErrorsStorageKey: {validationErrorsStorageKey}, validationErrorsLookupStorageKey : {validationErrorsLookupStorageKey}"); var validationErrorsData = await _ioPersistenceService.GetAsync(validationErrorsStorageKey); var errorsLookupData = await _ioPersistenceService.GetAsync(validationErrorsLookupStorageKey); var validationErrors = _serializationService.Deserialize <IEnumerable <ValidationError> >(validationErrorsData); var errorMessageLookups = _serializationService.Deserialize <IEnumerable <ValidationErrorMessageLookup> >(errorsLookupData); validationErrors.ToList().ForEach(x => result.Add(new ValidationErrorDto() { AimSequenceNumber = x.AimSequenceNumber, LearnerReferenceNumber = x.LearnerReferenceNumber, RuleName = x.RuleName, Severity = x.Severity, ErrorMessage = errorMessageLookups.Single(y => x.RuleName == y.RuleName).Message, FieldValues = x.ValidationErrorParameters == null ? string.Empty : GetValidationErrorParameters(x.ValidationErrorParameters.ToList()), })); } } catch (Exception e) { _logger.LogError($"Error occured trying to get validation errors for validationErrorsStorageKey: {validationErrorsStorageKey}, validationErrorsLookupStorageKey : {validationErrorsLookupStorageKey}", e); throw; } return(result); }
public void ExplicitValueSerialize() { Vector2 vector = new Vector2(10, 40); TypeConfiguration.TrustedTypes = TypeMatch.Type <Vector2>(); ISerializationService serializer = Container.Resolve <ISerializationService>(); string json = serializer.Serialize(vector); Console.WriteLine(json); Vector2 newVector = serializer.Deserialize <Vector2>(json); Assert.AreEqual(vector, newVector); }
private UserSettings GetUserSettingsFromStorage() { var fileData = _localFileService.Get(_userSettingsPath); if (fileData.IsSuccess) { var userSettings = _serializationService.Deserialize <UserSettings>(fileData.Value); if (userSettings.IsSuccess) { return(userSettings.Value); } } return(new UserSettings()); }
public async Task <IEnumerable <Cv> > GetAllCvs() { var result = new List <Cv>(); var cvsInFiles = _fileService.EnumerateFilesInFolder(Cvstoragefolder); foreach (var cvFile in cvsInFiles) { var cvContentPath = _fileService.Combine(Cvstoragefolder, cvFile); var cvContent = _fileService.GetFileContent(cvContentPath); if (cvContent != null) { var cv = await _serializationService.Deserialize <Cv>(cvContent); if (cv != null) { result.Add(cv); } } } return(result); }
public IHttpResult <TResult> SendGetRequest <TResult>(string requestUrl) { try { var webRequest = CreateHttpRequest(requestUrl, HttpMethodType.Get); HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse(); using (var responseStream = webResponse.GetResponseStream()) { string responseStr = string.Empty; if (responseStream != null) { responseStr = new StreamReader(responseStream).ReadToEnd(); } var obj = _serializationService.Deserialize <TResult>(responseStr); return(new HttpResult <TResult>(obj, null)); } } catch (WebException exception) { var error = string.Format("Message:{0}, Url:{1}", exception.Message, requestUrl); return(new HttpResult <TResult>(error)); } }
/// <summary> /// Deserializes the value. /// </summary> public static object Deserialize(object value) { var lastCacheValue = lastCache; if (ReferenceEquals(lastCacheValue.Item2, value)) { return(lastCacheValue.Item1); } else { var result = instance.Deserialize(value?.ToString()); lastCache = new Tuple <object, object>(result, value); return(result); } }
public void TestParameterConstructor() { Base a = new Base(); BaseWithConst b = new BaseWithConst(a, "Fred"); TypeConfiguration.TrustedTypes = TypeMatch.Assembly(typeof(SerializerTests).Assembly); ISerializationService serializer = Container.Resolve <ISerializationService>(); string json = serializer.Serialize(b); Console.WriteLine(json); BaseWithConst newB = serializer.Deserialize <BaseWithConst>(json); Assert.IsInstanceOfType(newB.Child, typeof(Base)); Assert.AreEqual(newB.Name, "Fred"); }
public IObservable <Message> Receive() { return(Observable .FromEventPattern <BasicDeliverEventArgs>( x => _consumer.Received += x, x => _consumer.Received -= x ) .Select(x => { var body = x.EventArgs.Body; var serializedMessage = Encoding.UTF8.GetString(body); return _serializationService.Deserialize <Message>(serializedMessage); })); }
public async Task <List <Cookie> > GetCookieData() { try { var storageFolder = ApplicationData.Current.LocalFolder; IStorageItem cookieFileCheck = await storageFolder.TryGetItemAsync(COOKIEFILE); if (cookieFileCheck == null) { return(new List <Cookie>()); } var cookieFile = (StorageFile)cookieFileCheck; var stream = await cookieFile.OpenAsync(FileAccessMode.Read); ulong size = stream.Size; if (size == 0) { return(new List <Cookie>()); } using (var inputStream = stream.GetInputStreamAt(0)) { using (var dataReader = new DataReader(inputStream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)size); var buff = dataReader.ReadBuffer(numBytesLoaded); var cookieData = await Unprotect(buff); if (!string.IsNullOrWhiteSpace(cookieData)) { return(_serializationService.Deserialize <List <Cookie> >(cookieData)); } } } } catch (Exception e) { // nåt sket sig, vi nollar isf alla cookies Debug.WriteLine("Det sket sig vid hämtning av sparade cookies: " + e.Message); return(new List <Cookie>()); } return(new List <Cookie>()); }
public async Task <bool> ImportOpmlFeedsAsync(Stream stream) { var opml = _serializationService.Deserialize <Opml>(stream); if (opml == null) { return(false); } var categories = opml.Body .Where(i => i.XmlUrl == null && i.HtmlUrl == null) .Select(i => new { Title = i.Title ?? i.Text, Outline = i }) .Where(i => i.Title != null) .Select(i => new Category { Title = i.Title, Channels = i.Outline.ChildOutlines.Select(o => new Channel { Uri = o.XmlUrl, Notify = true }) .ToList() }) .ToList(); var uncategorized = new Category { Title = "Unknown category", Channels = opml.Body .Where(i => Uri.IsWellFormedUriString(i.XmlUrl, UriKind.Absolute)) .Select(i => new Channel { Uri = i.XmlUrl, Notify = true }) .ToList() }; if (uncategorized.Channels.Any()) { categories.Add(uncategorized); } foreach (var category in categories) { await _categoryManager.InsertAsync(category); } return(true); }
public void TestNoConstructor() { Base a = new Base(); DerivedNoConst b = new DerivedNoConst(a, "Fred"); a.Child = b; TypeConfiguration.TrustedTypes = TypeMatch.Assembly(typeof(SerializerTests).Assembly); ISerializationService serializer = Container.Resolve <ISerializationService>(); string json = serializer.Serialize(a); Console.WriteLine(json); Base newA = serializer.Deserialize <Base>(json); Assert.AreEqual(newA.Child.Child, newA); Assert.IsInstanceOfType(newA.Child, typeof(Derived)); Assert.AreEqual(((Derived)newA.Child).Name, "Fred"); }