public IEnumerable Load(string aggregate, string id) { var list = new List <object>(); _conn.Open(); try { using (var cmd = _conn.CreateCommand()) { cmd.CommandText = "select seqnum,eventtype,event from events where aggregate=@aggregate and aggregateid=@id order by createdonutc asc"; cmd.Parameters.AddWithValue("aggregate", aggregate); cmd.Parameters.AddWithValue("id", id); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { var seq = reader.GetInt64(0); var type = reader.GetString(1); var data = reader.GetString(2); var evt = _serialization.Deserialize(Type.GetType(type), _encoding.GetBytes(data)); list.Add(evt); } } } } finally { _conn.Close(); } return(list); }
public void CheckAssemblyNameAfterDeserialization() { ser.Serialize(dtg); AssemblyDTG tmp = ser.Deserialize(); Assert.AreEqual(tmp.Name, "TPA.ApplicationArchitecture.dll"); }
public void SerTest2() { ser.Serialize(dtg); AssemblyDTG tmp = ser.Deserialize(); Assert.AreEqual(tmp.Name, "TPA.ApplicationArchitecture.dll"); }
public async Task <T> GetDeserializedAsync <T>(Uri requestUri) where T : class { var result = await GetAsync(requestUri); var content = await result.Content.ReadAsStringAsync(); return(serialization.Deserialize <T>(content)); }
public string[] Persist <TFormat>( ISerialization <TFormat> serializer, IServiceProvider locator, TFormat toInsert, TFormat toUpdate, TFormat toDelete) { var repository = locator.Resolve <IPersistableRepository <TRoot> >(); var insertData = toInsert != null?serializer.Deserialize <TFormat, TRoot[]>(toInsert, locator) : null; var updateData = toUpdate != null?serializer.Deserialize <TFormat, KeyValuePair <TRoot, TRoot>[]>(toUpdate, locator) : null; //TODO support old update format if (toUpdate != null && updateData != null && updateData.Length == 0) { var updateValues = serializer.Deserialize <TFormat, TRoot[]>(toUpdate, locator); if (updateValues != null && updateValues.Length > 0) { updateData = updateValues.Select(it => new KeyValuePair <TRoot, TRoot>(default(TRoot), it)).ToArray(); } } var deleteData = toDelete != null?serializer.Deserialize <TFormat, TRoot[]>(toDelete, locator) : null; if ((insertData == null || insertData.Length == 0) && (updateData == null || updateData.Length == 0) && (deleteData == null || deleteData.Length == 0)) { throw new ArgumentException( "Data not sent or deserialized unsuccessfully.", new FrameworkException(@"Example: " + serializer.Serialize( new Argument <TFormat> { RootName = typeof(TRoot).FullName, ToInsert = serializer.Serialize(new TRoot[] { new TRoot() }) }))); } try { return(repository.Persist(insertData, updateData, deleteData)); } catch (FrameworkException ex) { throw new ArgumentException(ex.Message, ex); } catch (Exception ex) { throw new ArgumentException( "Error persisting: {0}.".With(ex.Message), new FrameworkException( @"{0}{1}{2}".With( FormatData(serializer, "Insert", insertData), FormatData(serializer, "Update", updateData), FormatData(serializer, "Delete", deleteData)), ex)); } }
public IEnumerable <TValue> Get(Func <TValue, bool> selector) { EnsureFileExistence(); var result = File.ReadLines(fileName) .Select(line => serialization.Deserialize <TValue>(line)) .Where(selector); //log.Debug($"Got {result.Count()} elements"); return(result); }
public static void Receive(ISerialization serializer, TcpClient Session, Action <TcpClient, Common.DataPackage> MessageReceived) { NetworkStream stream = Session.GetStream(); new Thread(() => { StringBuilder data = new StringBuilder(); while (stream.CanRead) { if (stream.DataAvailable) { byte[] bytes = new byte[100]; int size = stream.Read(bytes, 0, 100); data.Append(Encoding.UTF8.GetString(bytes)); } else { if (data.Length > 0) { string[] packs = data.ToString().Split('\0'); packs = packs.Where(w => w != "").ToArray(); foreach (string s in packs) { Common.DataPackage package = serializer.Deserialize <DataPackage>(Encoding.ASCII.GetBytes(s)); MessageReceived(Session, package); } data.Clear(); } } Thread.Sleep(1); } }).Start(); }
private object Deserialize(Message msg) { var type = msg.UserProperties["ClrType"] as string; var inst = _serialization.Deserialize(Type.GetType(type), msg.Body); return(inst); }
public void Queue <TInput>( ISerialization <TInput> input, IServiceProvider locator, IDataContext context, TInput data) { TEvent domainEvent; try { domainEvent = data != null?input.Deserialize <TInput, TEvent>(data, locator) : Activator.CreateInstance <TEvent>(); } catch (Exception ex) { throw new ArgumentException("Error deserializing domain event.", ex); } try { context.Queue(domainEvent); } catch (SecurityException) { throw; } catch (Exception ex) { throw new ArgumentException( ex.Message, data == null ? new FrameworkException("Error while queuing event: {0}. Data not sent.".With(ex.Message), ex) : new FrameworkException(@"Error while queuing event: {0}. Sent data: {1}".With(ex.Message, input.Serialize(domainEvent)), ex)); } }
public ICommandResult <TOutput> Execute <TInput, TOutput>(ISerialization <TInput> input, ISerialization <TOutput> output, TInput data) { var either = CommandResult <TOutput> .Check <Argument <TInput>, TInput>(input, output, data, CreateExampleArgument); if (either.Error != null) { return(either.Error); } var argument = either.Argument; var commands = Locator.Resolve <IEnumerable <IServerCommandDescription <TInput> > >(); var results = Locator.Resolve <IEnumerable <ICommandResultDescription <TOutput> > >(); var resultCommand = results.FirstOrDefault(it => it.RequestID == argument.ResultID); if (resultCommand == null) { return(CommandResult <TOutput> .Fail("Couldn't find executed command {0}".With(argument.ResultID), null)); } var inputCommand = commands.FirstOrDefault(it => it.RequestID == argument.InputID); if (inputCommand == null) { return(CommandResult <TOutput> .Fail("Couldn't find command description {0}".With(argument.InputID), null)); } var transformation = input.Deserialize <TInput, ITransformation <TOutput, TInput> >(argument.Transformation); inputCommand.Data = transformation.Transform(output, input, resultCommand.Result.Data); return(CommandResult <TOutput> .Success(default(TOutput), "Data propagated")); }
public AssemblyMetadata Load( ) { AssemblyDTG assemblyDTG = serializer.Deserialize(); AssemblyMetadata assemblyModel = new AssemblyMetadata(assemblyDTG); return(assemblyModel); }
private async Task <Response <TResponse> > ExecuteAsync <TResponse>(Func <HttpRequestMessage> reqFn, CancellationToken ct) where TResponse : class { try { var req = reqFn(); if (hasRequestModifications) { foreach (var modify in requestModifications) { modify(req); } } var resp = await http.SendAsync(req, ct).ConfigureAwait(false); if (resp.IsSuccessStatusCode) { if (typeof(TResponse) == typeof(Nothing)) { return(new Response <TResponse>(resp.StatusCode, Nothing.Instance as TResponse)); } else { var responseBytes = await resp.Content.ReadAsByteArrayAsync().ConfigureAwait(false); var response = serialization.Deserialize <TResponse>(responseBytes); return(new Response <TResponse>(resp.StatusCode, response)); } } else { var error = await resp.Content.ReadAsStringAsync().ConfigureAwait(false); return(new Response <TResponse>(resp.StatusCode, error)); } } catch (SerializationException ex) { return(new Response <TResponse>(ex, SerializationErrorMsg)); } catch (HttpRequestException ex) { return(new Response <TResponse>(ex, ServerNotThereErrorMsg)); } catch (TaskCanceledException ex) when(ex.CancellationToken == ct) { return(new Response <TResponse>(ex, CancelledByClientErrorMsg)); } catch (TaskCanceledException ex) { return(new Response <TResponse>(ex, ServerTimeoutErrorMsg)); } catch (Exception ex) { return(new Response <TResponse>(ex, string.Format(FallbackErrorMsg, ex.GetType().Name))); } }
/// <summary> /// Deserialize object without providing context information. /// .NET objects or value objects don't require context so they can be deserialized /// without IServiceProvider in context. /// </summary> /// <typeparam name="TFormat">serialization format</typeparam> /// <typeparam name="T">object type</typeparam> /// <param name="serialization">serialization service</param> /// <param name="data">serialized object in specified format</param> /// <returns>deserialized object</returns> public static T Deserialize <TFormat, T>( this ISerialization <TFormat> serialization, TFormat data) { Contract.Requires(serialization != null); return(serialization.Deserialize <T>(data, default(StreamingContext))); }
public TOutput Transform(ISerialization <TInput> input, ISerialization <TOutput> output, TInput value) { var arg = input.Deserialize <TInput, string[]>(value); return(output.Serialize(new GetDomainObject.Argument { Name = Name, Uri = arg })); }
/// <summary> /// Deserialize object using provided context information. /// Context should usually be IServiceLocator, but in special cases can be something else. /// </summary> /// <typeparam name="TFormat">serialization format</typeparam> /// <typeparam name="T">object type</typeparam> /// <param name="serialization">serialization service</param> /// <param name="data">serialized object in specified format</param> /// <param name="context">context information which will be used during deserialization</param> /// <returns>deserialized object</returns> public static T Deserialize <TFormat, T>( this ISerialization <TFormat> serialization, TFormat data, object context) { Contract.Requires(serialization != null); var sc = new StreamingContext(StreamingContextStates.All, context); return(serialization.Deserialize <T>(data, sc)); }
private void OnMessageReceived(Message <Null, string> val) { if (MessageReceived != null) { var data = _serializer.Deserialize(null, _encoding.GetBytes(val.Value)); Messaging.Message msg = null; if (_routes.InboundCommands.Any(c => c.MessageType == data.GetType())) { msg = new CommandMessage(val.Offset.Value.ToString(), data); } else if (_routes.InboundEvents.Any(c => c.MessageType == data.GetType())) { msg = new EventMessage(val.Offset.Value.ToString(), val.Offset.Value, data); } if (msg != null) { MessageReceived(msg); } } }
public TOutput Submit <TInput, TOutput>( ISerialization <TInput> input, ISerialization <TOutput> output, IServiceProvider locator, bool returnInstance, TInput data) { TEvent domainEvent; try { domainEvent = data != null?input.Deserialize <TInput, TEvent>(data, locator) : Activator.CreateInstance <TEvent>(); } catch (Exception ex) { throw new ArgumentException("Error deserializing domain event.", ex); } var domainStore = locator.Resolve <IEventStore>(); string uri; try { uri = domainStore.Submit(domainEvent); } catch (SecurityException) { throw; } catch (Exception ex) { throw new ArgumentException( ex.Message, data == null ? new FrameworkException("Error while submitting event: {0}. Data not sent.".With(ex.Message), ex) : new FrameworkException(@"Error while submitting event: {0}. Sent data: {1}".With(ex.Message, input.Serialize(domainEvent)), ex)); } try { if (returnInstance) { return(output.Serialize(domainEvent)); } else { return(output.Serialize(uri)); } } catch (Exception ex) { throw new ArgumentException( ex.Message, new FrameworkException(@"Error serializing result: " + ex.Message, ex)); } }
public DataTable Analyze <TFormat>( ISerialization <TFormat> serializer, IServiceProvider locator, IEnumerable <string> dimensions, IEnumerable <string> facts, List <KeyValuePair <string, bool> > order, int?limit, int?offset, TFormat specificationData) { TCube query; try { query = locator.Resolve <TCube>(); } catch (Exception ex) { throw new ArgumentException( "Can't create cube query. Is query {0} registered in system?".With(typeof(TCube).FullName), ex); } TSpecification specification; if (specificationData == null) { try { specification = (TSpecification)Activator.CreateInstance(typeof(TSpecification)); } catch (Exception ex) { throw new ArgumentException("Specification can't be created. It must be sent as argument.", ex); } } else { try { specification = serializer.Deserialize <TFormat, TSpecification>(specificationData, locator); } catch (Exception ex) { throw new ArgumentException("Specification could not be deserialized.", ex); } } if (specification == null) { throw new FrameworkException("Specification could not be deserialized."); } return(query.Analyze(dimensions, facts, order, specification, limit, offset)); }
public override TDomainObject[] FindBy <TFormat>( ISerialization <TFormat> serializer, IDomainModel domainModel, IServiceLocator locator, TFormat data, int?offset, int?limit, IDictionary <string, bool> order) { var repository = GetRepository <TDomainObject>(locator); dynamic specification; if (data == null) { try { specification = Activator.CreateInstance(typeof(TSpecification)); } catch (Exception ex) { throw new ArgumentException("Specification can't be created. It must be sent as argument.", ex); } } else { try { specification = serializer.Deserialize <TFormat, TSpecification>(data, locator); } catch (Exception ex) { throw new ArgumentException("Specification could not be deserialized.", ex); } } if (specification == null) { throw new ArgumentException("Specification could not be deserialized."); } IQueryable <TDomainObject> result; try { result = repository.Query(specification); } catch (Exception ex) { throw new ArgumentException( "Error while executing query: {0}.".With(ex.Message), new FrameworkException(@"Specification deserialized as: {0}".With((TFormat)serializer.Serialize(specification)), ex)); } return(QueryWithConditions(offset, limit, order, result)); }
private void EnsureCache(IEnumerable <StatisticsSummary> statistics) { _statisticsCache = _statisticsCache ?? new Dictionary <Guid, StatisticsSummary>(); foreach (var statistic in statistics) { if (!_statisticsCache.ContainsKey(statistic.PlayerId)) { if (statistic.PlayerId == Guid.Empty) { throw new Exception("INVALID PLAYER NAME"); } _statisticsSerialiser.FileName = statistic.PlayerId + ".XML"; var loadedStatistic = _statisticsSerialiser.Deserialize().Result; _statisticsCache.Add(statistic.PlayerId, loadedStatistic ?? new StatisticsSummary { PlayerId = statistic.PlayerId }); } } }
private bool TryReadResponse <TResponse>(byte[] payload, out TResponse response) where TResponse : class { try { response = serialization.Deserialize <TResponse>(payload); return(true); } catch (SerializationException ex) { response = null; return(false); } }
public Stream Execute <TInput>(ISerialization <TInput> input, Argument <TInput> argument) { var file = Path.Combine(DocumentFolder, argument.File); if (!File.Exists(file)) { throw new FileNotFoundException("Can't locate file: {0}. Check if correct file is specified.".With(argument.File)); } var cms = ChunkedMemoryStream.Create(); using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read)) { fs.CopyTo(cms); } cms.Position = 0; var ext = Path.GetExtension(argument.File); using (var document = TemplaterFactory.Open(cms, ext)) { if (argument.GetSources != null) { foreach (var source in argument.GetSources) { var found = GetDomain.GetData(source); document.Process(found); } } if (argument.SearchSources != null) { foreach (var source in argument.SearchSources) { var found = SearchDomain.FindData <TInput>(input, source); document.Process(found); } } var specification = (from a in (argument.SearchSources ?? new SearchDomainObject.Argument <TInput> [0]) where a.Specification != null select a.Specification) .FirstOrDefault(); if (specification != null) { dynamic filter = input.Deserialize <TInput, dynamic>(specification); document.Process(filter); } } cms.Position = 0; return(argument.ToPdf ? PdfConverter.Convert(cms, ext, true) : cms); }
public TOutput Execute <TInput, TOutput>( ISerialization <TInput> input, ISerialization <TOutput> output, IServiceProvider locator, Type serviceType, TInput data) { TArgument arg; try { arg = data != null?input.Deserialize <TInput, TArgument>(data, locator) : Activator.CreateInstance <TArgument>(); } catch (Exception ex) { throw new ArgumentException("Error deserializing service argument.", ex); } IServerService <TArgument, TResult> service; try { service = locator.Resolve <IServerService <TArgument, TResult> >(serviceType); } catch (Exception ex) { throw new ArgumentException("Can't create service instance.", ex); } try { return(output.Serialize(service.Execute(arg))); } catch (SecurityException) { throw; } catch (Exception ex) { string additionalInfo; try { additionalInfo = @"Sent data: " + input.Serialize(arg); } catch (Exception sex) { additionalInfo = "Error serializing input: " + sex.Message; } throw new ArgumentException( ex.Message, new FrameworkException(@"Error while executing service: {0}. {1}".With(ex.Message, additionalInfo), ex)); } }
public TOutput Update <TInput, TOutput>( ISerialization <TInput> input, ISerialization <TOutput> output, IServiceProvider locator, string uri, bool returnInstance, TInput data) { TRoot root; try { root = input.Deserialize <TInput, TRoot>(data, locator); } catch (Exception ex) { throw new ArgumentException( "Error deserializing: {0}".With(ex.Message), new FrameworkException(@"Sent data: {0}".With(data), ex)); } try { var repository = locator.Resolve <IPersistableRepository <TRoot> >(); var original = repository.Find(uri); if (original == null) { throw new ArgumentException("Can't find {0} with uri: {1}.".With(typeof(TRoot).FullName, uri)); } repository.Persist(null, new[] { new KeyValuePair <TRoot, TRoot>(original, root) }, null); return(returnInstance ? output.Serialize(root) : output.Serialize(root.URI)); } catch (Exception ex) { string additionalInfo; try { additionalInfo = @"Sent data: " + input.Serialize(root); } catch (Exception sex) { additionalInfo = "Error serializing input: " + sex.Message; } throw new ArgumentException( "Error saving: {0}.".With(ex.Message), new FrameworkException(additionalInfo, ex)); } }
public virtual TDomainObject[] FindBy <TFormat>( ISerialization <TFormat> serializer, IDomainModel domainModel, IServiceLocator locator, TFormat data, int?offset, int?limit, IDictionary <string, bool> order) { var repository = GetRepository <TDomainObject>(locator); IQueryable <TDomainObject> result; if (data == null) { result = repository.Query <TDomainObject>(null); } else { dynamic specification; try { specification = serializer.Deserialize <TFormat, dynamic>(data, locator); } catch (Exception ex) { throw new ArgumentException( "Specification could not be deserialized.", new FrameworkException(@"Please provide specification name. Error: {0}.".With(ex.Message), ex)); } if (specification == null) { throw new ArgumentException( "Specification could not be deserialized.", new FrameworkException("Please provide specification name.")); } try { result = repository.Query(specification); } catch (Exception ex) { throw new ArgumentException( "Error while executing query: {0}. ".With(ex.Message), new FrameworkException(@"Specification deserialized as: {0}".With((TFormat)serializer.Serialize(specification)), ex)); } } return(QueryWithConditions <TDomainObject>(offset, limit, order, result)); }
public override bool CheckExists <TFormat>( ISerialization <TFormat> serializer, IServiceProvider locator, TFormat data) { var repository = GetRepository <TDomainObject>(locator); dynamic specification; if (data == null) { try { specification = Activator.CreateInstance(typeof(TSpecification)); } catch { throw new ArgumentException("Specification can't be created. It must be sent as argument."); } } else { try { specification = serializer.Deserialize <TFormat, TSpecification>(data, locator); } catch (Exception ex) { throw new ArgumentException(@"Specification could not be deserialized: " + ex.Message, ex); } } if (specification == null) { throw new FrameworkException("Specification could not be deserialized."); } IQueryable <TDomainObject> result; try { result = repository.Query(specification); } catch (Exception ex) { throw new ArgumentException( "Error while executing query: " + ex.Message, new FrameworkException("Specification deserialized as: {0}".With((TFormat)serializer.Serialize(specification)), ex)); } return(result.Any()); }
public DataTable Analyze <TFormat>( ISerialization <TFormat> serializer, IServiceProvider locator, IEnumerable <string> dimensions, IEnumerable <string> facts, List <KeyValuePair <string, bool> > order, int?limit, int?offset, TFormat specificationData) { TCube query; try { query = locator.Resolve <TCube>(); } catch (Exception ex) { throw new ArgumentException( "Can't create cube query. Is query {0} registered in system?".With(typeof(TCube).FullName), ex); } if (specificationData == null) { return(query.Analyze(dimensions, facts, order, null, limit, offset)); } ISpecification <TSource> specification; try { specification = serializer.Deserialize <TFormat, ISpecification <TSource> >(specificationData, locator); } catch (Exception ex) { throw new ArgumentException( "Specification could not be deserialized.", new FrameworkException(@"Please provide specification name. Error: {0}.".With(ex.Message), ex)); } if (specification == null) { throw new ArgumentException( "Specification could not be deserialized.", new FrameworkException("Please provide specification name.")); } return(query.Analyze(dimensions, facts, order, specification, limit, offset)); }
public TOutput Queue <TInput, TOutput>( ISerialization <TInput> input, ISerialization <TOutput> output, IServiceProvider locator, string uri, TInput data) { TEvent domainEvent; try { domainEvent = data != null?input.Deserialize <TInput, TEvent>(data, locator) : Activator.CreateInstance <TEvent>(); } catch (Exception ex) { throw new ArgumentException("Error deserializing domain event.", ex); } var repository = locator.Resolve <IRepository <TAggregate> >(); var aggregate = repository.Find(uri); if (aggregate == null) { throw new ArgumentException("Can't find aggregate with Uri: {0}".With(uri)); } try { domainEvent.Apply(aggregate); } catch (SecurityException) { throw; } catch (Exception ex) { throw new ArgumentException(ex.Message, ex); } var eventStore = locator.Resolve <IDomainEventStore>(); try { eventStore.Queue(domainEvent); } catch (SecurityException) { throw; } catch (Exception ex) { throw new ArgumentException( ex.Message, data == null ? new FrameworkException("Error while Queuing event: {0}. Data not sent.".With(ex.Message), ex) : new FrameworkException(@"Error while Queuing event: {0}. Sent data: {1}".With(ex.Message, output.Serialize(domainEvent)), ex)); } return(output.Serialize(aggregate)); }
public List <PlayerDetails> GetAll() { var fileObject = _playerSerialiser.Deserialize(); if (fileObject.Result == null) { EnsureCache(); } else { PlayerDetailsCache = fileObject.Result.Select(playerDetails => { var details = new PlayerDetails { Handicap101 = playerDetails.Handicap101, Handicap201 = playerDetails.Handicap201, Handicap301 = playerDetails.Handicap301, Handicap401 = playerDetails.Handicap401, Handicap501 = playerDetails.Handicap501, HandicapCricket = playerDetails.HandicapCricket, Name = playerDetails.Name, NickName = playerDetails.NickName, Id = playerDetails.Id }; var definition = new ImageDefinition { Name = playerDetails.PlayerImageDefinition.Name, SourceBytes = playerDetails.PlayerImageDefinition.SourceBytes }; details.PlayerImageDefinition = definition; details.SelectedFlight = playerDetails.SelectedFlight; return(details); }).ToList(); } // Regenerate seriaizable Images foreach (var playerDetails in PlayerDetailsCache) { playerDetails.RegenerateImage(); } return(PlayerDetailsCache.OrderBy(m => m.NickName).ToList()); }
public TOutput Create <TInput, TOutput>( ISerialization <TInput> input, ISerialization <TOutput> output, IServiceProvider locator, bool returnInstance, TInput data) { TRoot root; try { root = input.Deserialize <TInput, TRoot>(data, locator); } catch (Exception ex) { throw new ArgumentException( "Error deserializing: " + ex.Message, new FrameworkException(@"Sent data: {0}".With(data), ex)); } try { var repository = locator.Resolve <IPersistableRepository <TRoot> >(); repository.Insert(root); return(returnInstance ? output.Serialize(root) : output.Serialize(root.URI)); } catch (Exception ex) { string additionalInfo; try { additionalInfo = @"Sent data: " + input.Serialize(root); } catch (Exception sex) { additionalInfo = "Error serializing input: " + sex.Message; } throw new ArgumentException( "Error saving: " + ex.Message, new FrameworkException(additionalInfo, ex)); } }