Пример #1
0
        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();
        }
Пример #2
0
            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));
                }
            }
Пример #3
0
 public AzureServiceBus(string connectionString,
                        string endpointName,
                        ISerialization serialization,
                        RouteTable routes)
 {
     _serialization = serialization;
     foreach (var route in routes.InboundCommands)
     {
         var client = new QueueClient(connectionString, route.Name);
         client.RegisterMessageHandler(OnInboundCommand);
         _commands.Add(route.MessageType, client);
     }
     foreach (var route in routes.OutboundCommands.Where(c => !_commands.ContainsKey(c.MessageType)))
     {
         var client = new QueueClient(connectionString, route.Name);
         _commands.Add(route.MessageType, client);
     }
     foreach (var route in routes.OutboundEvents)
     {
         var client = new TopicClient(connectionString, route.Name);
         _outboundEvent.Add(route.MessageType, client);
     }
     foreach (var route in routes.InboundEvents)
     {
         var client = new SubscriptionClient(connectionString, route.Name, endpointName);
         client.RegisterMessageHandler(OnInboundEvent);
         _inboundEvents.Add(route.MessageType, client);
     }
 }
Пример #4
0
        public ICommandResult <TOutput> Execute <TInput, TOutput>(
            IServiceProvider locator,
            ISerialization <TInput> input,
            ISerialization <TOutput> output,
            IPrincipal principal,
            TInput data)
        {
            var either = CommandResult <TOutput> .Check <Argument, TInput>(input, output, data, CreateExampleArgument);

            if (either.Error != null)
            {
                return(either.Error);
            }
            if (either.Argument.Uri == null)
            {
                return(CommandResult <TOutput> .Fail("Uri not provided.", @"Example argument: 
" + CommandResult <TOutput> .ConvertToString(CreateExampleArgument(output))));
            }
            try
            {
                var arg = new GetDomainObject.Argument {
                    Name = either.Argument.Name, Uri = new[] { either.Argument.Uri }
                };
                var result = GetDomainObject.GetData(locator, arg, principal);
                return(CommandResult <TOutput> .Success(output.Serialize(result.Length == 1), result.Length == 1? "Found" : "Not found"));
            }
            catch (ArgumentException ex)
            {
                return(CommandResult <TOutput> .Fail(
                           ex.Message,
                           ex.GetDetailedExplanation() + @"
Example argument: 
" + CommandResult <TOutput> .ConvertToString(CreateExampleArgument(output))));
            }
        }
Пример #5
0
        public ICommandResult <TOutput> Execute <TInput, TOutput>(
            IServiceProvider locator,
            ISerialization <TInput> input,
            ISerialization <TOutput> output,
            IPrincipal principal,
            TInput data)
        {
            var either = CommandResult <TOutput> .Check <Argument, TInput>(input, output, data, CreateExampleArgument);

            if (either.Error != null)
            {
                return(either.Error);
            }
            var argument = either.Argument;

            var rootType = DomainModel.Find(argument.Name);

            if (rootType == null)
            {
                return(CommandResult <TOutput> .Fail(
                           "Couldn't find domain object type {0}.".With(argument.Name),
                           @"Example argument: 
" + CommandResult <TOutput> .ConvertToString(CreateExampleArgument(output))));
            }

            if (!typeof(IObjectHistory).IsAssignableFrom(rootType))
            {
                return(CommandResult <TOutput> .Fail(@"Specified type ({0}) does not support history tracking. 
Please check your arguments.".With(argument.Name), null));
            }

            if (!Permissions.CanAccess(rootType.FullName, principal))
            {
                return(CommandResult <TOutput> .Forbidden(argument.Name));
            }
            if (argument.Uri == null || argument.Uri.Length == 0)
            {
                return(CommandResult <TOutput> .Fail(
                           "Uri not specified.",
                           @"Example argument: 
" + CommandResult <TOutput> .ConvertToString(CreateExampleArgument(output))));
            }

            try
            {
                var commandType = typeof(FindCommand <>).MakeGenericType(rootType);
                var command     = Activator.CreateInstance(commandType) as IFindCommand;
                var result      = command.Find(output, locator, argument.Uri);

                return(CommandResult <TOutput> .Success(result.Result, "Found {0} item(s)", result.Count));
            }
            catch (ArgumentException ex)
            {
                return(CommandResult <TOutput> .Fail(
                           ex.Message,
                           ex.GetDetailedExplanation() + @"
Example argument: 
" + CommandResult <TOutput> .ConvertToString(CreateExampleArgument(output))));
            }
        }
        public PlayersRepository(ISerialization <List <PlayerDetailsDto> > playerSerialiser)
        {
            _playerSerialiser = playerSerialiser;

            _playerSerialiser.FileName = PlayersFileName;
            _playerSerialiser.Folder   = ApplicationData.Current.LocalFolder;
        }
 public ClientOptionsTests()
 {
     _serialization  = Substitute.For <ISerialization>();
     _options        = new FluentHttpClientOptions();
     _testHttpClient = new HttpClientTester();
     _client         = new TestClient("Test", _testHttpClient.Client, _options);
 }
Пример #8
0
        private string SerializeFile(string serializedFileName)
        {
            string         result        = "";
            ISerialization serialization = null;

            try
            {
                if (BinarySerializationSelected())
                {
                    serialization = new BinSerialization();
                }
                else if (TextSerializationSelected())
                {
                    serialization = new myTextSerialization();
                }
                else
                {
                    MessageBox.Show("Select serialization method");
                }

                if (serialization != null)
                {
                    SerializationStrategy strategy = new SerializationStrategy(serialization);
                    result = strategy.OnSave(list.ListOfObjects, serializedFileName);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return(result);
        }
Пример #9
0
        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);
            }

            try
            {
                var table = PopulateTable(input, output, Locator, DomainModel, either.Argument, Permissions);
                if (either.Argument.UseDataTable)
                {
                    return(CommandResult <TOutput> .Return(HttpStatusCode.Created, output.Serialize(table), "Data analyzed"));
                }
                var result = ConvertTable.Convert(output, table);
                return(CommandResult <TOutput> .Return(HttpStatusCode.Created, result, "Data analyzed"));
            }
            catch (SecurityException ex)
            {
                return(CommandResult <TOutput> .Return(HttpStatusCode.Forbidden, default(TOutput), ex.Message));
            }
            catch (ArgumentException ex)
            {
                return(CommandResult <TOutput> .Fail(
                           ex.Message,
                           ex.GetDetailedExplanation() + @"
Example argument: 
" + CommandResult <TOutput> .ConvertToString(CreateExampleArgument(output))));
            }
        }
Пример #10
0
        public MailService(IServiceLocator locator)
        {
            Contract.Requires(locator != null);

            this.Serialization = locator.Resolve<ISerialization<byte[]>>();
            this.Repository = locator.Resolve<Func<string, IMailMessage>>();
        }
Пример #11
0
 public Client()
 {
     address       = "127.0.0.1";
     port          = 13000;
     tcpClient     = new TcpClient();
     serialization = new Serialization();
 }
Пример #12
0
        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 serviceType = TypeResolver.Resolve(argument.Name);

            if (serviceType == null)
            {
                return
                    (CommandResult <TOutput> .Fail(
                         "Couldn't find service: {0}".With(argument.Name),
                         @"Example argument: 
" + CommandResult <TOutput> .ConvertToString(CreateExampleArgument(output))));
            }

            var serviceInterface =
                serviceType.GetInterfaces()
                .FirstOrDefault(it => it.IsGenericType && typeof(IServerService <,>) == it.GetGenericTypeDefinition());

            if (serviceInterface == null)
            {
                return
                    (CommandResult <TOutput> .Fail(
                         "Object: {0} is not a valid service.".With(argument.Name),
                         "{0} must implement {1} to be executed as a service call".With(argument.Name, typeof(IServerService <,>).FullName)));
            }

            if (!Permissions.CanAccess(serviceType))
            {
                return
                    (CommandResult <TOutput> .Return(
                         HttpStatusCode.Forbidden,
                         default(TOutput),
                         "You don't have permission to access: {0}.",
                         argument.Name));
            }

            try
            {
                var commandType = typeof(ExecuteServiceCommand <,>).MakeGenericType(serviceInterface.GetGenericArguments());
                var command     = Activator.CreateInstance(commandType) as IExecuteServiceCommand;
                var result      = command.Execute(input, output, Locator, serviceType, argument.Data);

                return(CommandResult <TOutput> .Return(HttpStatusCode.Created, result, "Service executed"));
            }
            catch (ArgumentException ex)
            {
                return(CommandResult <TOutput> .Fail(
                           ex.Message,
                           ex.GetDetailedExplanation() + @"
Example argument: 
" + CommandResult <TOutput> .ConvertToString(CreateExampleArgument(output))));
            }
        }
Пример #13
0
        public ICommandResult <TOutput> Execute <TInput, TOutput>(
            IServiceProvider locator,
            ISerialization <TInput> input,
            ISerialization <TOutput> output,
            IPrincipal principal,
            TInput data)
        {
            var either = CommandResult <TOutput> .Check <Argument <TInput>, TInput>(input, output, data, CreateExampleArgument);

            if (either.Error != null)
            {
                return(either.Error);
            }

            try
            {
                var command = PrepareCommand(principal, either.Argument.Name, either.Argument.SpecificationName);
                var exists  = command.CheckExists(input, locator, either.Argument.Specification);
                return(CommandResult <TOutput> .Success(output.Serialize(exists), exists.ToString()));
            }
            catch (ArgumentException ex)
            {
                return(CommandResult <TOutput> .Fail(
                           ex.Message,
                           ex.GetDetailedExplanation() + @"
Example argument: 
" + CommandResult <TOutput> .ConvertToString(CreateExampleArgument(output))));
            }
        }
Пример #14
0
        public JaegerThriftTransportTests()
        {
            _mockJaegerThriftSerialization = Substitute.For <ISerialization>();
            _mockSender = Substitute.For <ISender>();

            _testingTransport = Substitute.For <JaegerThriftTransport>(_mockSender, _mockJaegerThriftSerialization);
        }
Пример #15
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="storageProvider"></param>
 /// <param name="serializer"></param>
 internal ConfigProvider(IConfigStorageProvider storageProvider, ISerialization serializer, IEncryption encryption, string key)
 {
     this.storageProvider = storageProvider;
     this.encryption      = encryption;
     this.key             = key;
     this.serializer      = serializer;
 }
Пример #16
0
 protected HttpClientBase(
     [NotNull] HttpClientBuilder builder,
     [NotNull] ISerialization serialization,
     Action <HttpRequestMessage>[] requestModifications = null)
     : this(builder.Build(), serialization, true, requestModifications)
 {
 }
Пример #17
0
 protected HttpClientBase(
     [NotNull] string baseAddress,
     [NotNull] ISerialization serialization,
     Action <HttpRequestMessage>[] requestModifications = null)
     : this(new HttpClientBuilder().BaseAddress(baseAddress), serialization, requestModifications)
 {
 }
Пример #18
0
        public JaegerHttpTransportTests()
        {
            _mockJaegerThriftSerialization = Substitute.For <ISerialization>();
            _mockSender = Substitute.For <ISender>();

            _testingTransport = new JaegerHttpTransport(new Uri("http://localhost:14268"), _batchSize, _mockSender, _mockJaegerThriftSerialization);
        }
Пример #19
0
 public void Init()
 {
     ser  = new SerXML();
     refl = new Reflector();
     refl.Reflect("../../dllForTests/TPA.ApplicationArchitecture.dll");
     dtg = MapperToDTG.AssemblyDtg(refl.AssemblyModel);
 }
Пример #20
0
        public CommandConverter(
            IRestApplication application,
            IObjectFactory objectFactory,
            IProcessingEngine processingEngine,
            IWireSerialization serialization,
            ISerialization <Stream> protobuf,
            ISerialization <XElement> xml,
            ISerialization <StreamReader> json)
        {
            Contract.Requires(application != null);
            Contract.Requires(objectFactory != null);
            Contract.Requires(processingEngine != null);
            Contract.Requires(serialization != null);
            Contract.Requires(protobuf != null);
            Contract.Requires(xml != null);
            Contract.Requires(json != null);

            this.Application      = application;
            this.ObjectFactory    = objectFactory;
            this.ProcessingEngine = processingEngine;
            this.Serialization    = serialization;
            this.Protobuf         = protobuf;
            this.Xml  = xml;
            this.Json = json;
        }
Пример #21
0
        public MailService(IServiceLocator locator)
        {
            Contract.Requires(locator != null);

            this.Serialization = locator.Resolve <ISerialization <byte[]> >();
            this.Repository    = locator.Resolve <Func <string, IMailMessage> >();
        }
Пример #22
0
        public static string FormatEntry(ISerialization serialization, IApplicationSettings applicationSettings, object obj)
        {
            if (obj == null)
                return null;

            return serialization.ToJson(obj, new[] { "Password" }, applicationSettings.LogJsonFormatted);
        }
Пример #23
0
 /// <summary>
 /// 使用指定的序列化器初始化对象
 /// </summary>
 /// <param name="serialization">指定的序列化器,
 /// 它提供了将对象序列化为Json的功能</param>
 public JsonInputFormatter(ISerialization <object> serialization)
 {
     this.Serialization = serialization;
     SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse(MediaTypeName.Json));
     SupportedEncodings.Add(Encoding.UTF8);
     SupportedEncodings.Add(Encoding.Unicode);
 }
Пример #24
0
 public AnimalService(IUnitOfWork unit, IMapper mapper, ITimeService timeService, ISerialization serializer)
 {
     _unit        = unit;
     _mapper      = mapper;
     _timeService = timeService;
     _serializer  = serializer;
 }
Пример #25
0
        public ICommandResult <TOutput> Execute <TInput, TOutput>(
            IServiceProvider locator,
            ISerialization <TInput> input,
            ISerialization <TOutput> output,
            IPrincipal principal,
            TInput data)
        {
            var either = CommandResult <TOutput> .Check <Argument <TInput>, TInput>(input, output, data, CreateExampleArgument);

            if (either.Error != null)
            {
                return(either.Error);
            }

            try
            {
                var result = FindAndReturn(locator, input, output, principal, either.Argument);
                return(CommandResult <TOutput> .Success(result.Result, "Found {0} item(s)", result.Count));
            }
            catch (ArgumentException ex)
            {
                return(CommandResult <TOutput> .Fail(
                           ex.Message,
                           ex.GetDetailedExplanation() + @"
Example argument: 
" + CommandResult <TOutput> .ConvertToString(CreateExampleArgument(output))));
            }
        }
Пример #26
0
        public ConfigurationRepository(ISerialization <GameConfiguration> configSerialiser)
        {
            _configSerialiser = configSerialiser;

            _configSerialiser.FileName = ConfigFileName;
            _configSerialiser.Folder   = ApplicationData.Current.LocalFolder;
        }
Пример #27
0
        public KafkaEventBus(Dictionary <string, object> config, ISerialization serializer, RouteTable routes)
        {
            _serializer = serializer;
            _routes     = routes;
            _encoding   = Encoding.UTF8;
            _config     = config;
            var topics = routes.InboundCommands.Select(c => c.Name).Union(routes.InboundEvents.Select(c => c.Name));

            var seri   = new StringSerializer(_encoding);
            var deseri = new StringDeserializer(_encoding);
            var noop   = new NullDeserializer();

            _outbound = new Producer <Null, string>(_config, new NullSerializer(), seri);

            var cfg = new Dictionary <string, object>(_config);

            cfg.Add("group.id", Environment.MachineName); //TODO: not right.
            _inbound            = new Consumer <Null, string>(cfg, noop, deseri);
            _inbound.OnMessage += (key, val) =>
            {
                OnMessageReceived(val);
            };

            _inbound.Subscribe(topics);
            _thread = new ConsumerPollerThread(_inbound);
            _thread.Start();
        }
Пример #28
0
        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"));
        }
Пример #29
0
        public ICommandResult <TOutput> Execute <TInput, TOutput>(
            IServiceProvider locator,
            ISerialization <TInput> input,
            ISerialization <TOutput> output,
            IPrincipal principal,
            TInput data)
        {
            var either = CommandResult <TOutput> .Check <Argument <TInput>, TInput>(input, output, data, CreateExampleArgument);

            if (either.Error != null)
            {
                return(either.Error);
            }

            try
            {
                var result = Execute <TInput>(locator, principal, input, either.Argument);
                return(CommandResult <TOutput> .Success(Serialize(output, result), "Document created"));
            }
            catch (FileNotFoundException fnf)
            {
                return(CommandResult <TOutput> .Fail(fnf.Message, null));
            }
            catch (ArgumentException ex)
            {
                return(CommandResult <TOutput> .Fail(
                           ex.Message,
                           ex.GetDetailedExplanation() + @"
Example argument: 
" + CommandResult <TOutput> .ConvertToString(CreateExampleArgument(output))));
            }
        }
Пример #30
0
 public Communication(ISerialization serialization, Settings settings, string ip, int port)
 {
     this.Serialization = serialization;
     this.Settings = settings;
     Ip = ip;
     Port = port;
 }
        public StatisticsRepository(ISerialization <StatisticsSummary> statisticsSerialiser, IPlayersRepository playersRepository)
        {
            _statisticsSerialiser = statisticsSerialiser;
            _playersRepository    = playersRepository;

            _statisticsSerialiser.Folder = ApplicationData.Current.LocalFolder;
        }
Пример #32
0
            protected TOutput ExecuteCommand <TOutput>(ISerialization <TOutput> output, IServiceProvider locator, TCommand command)
            {
                var domainStore = locator.Resolve <IEventStore>();

                try
                {
                    domainStore.Submit(command);
                }
                catch (SecurityException) { throw; }
                catch (Exception ex)
                {
                    throw new ArgumentException(
                              ex.Message,
                              new FrameworkException("Error while submitting query: {0}".With(ex.Message), ex));
                }
                try
                {
                    return(output.Serialize(OutMethod.Invoke(null, new object[] { command })));
                }
                catch (Exception ex)
                {
                    throw new ArgumentException(
                              ex.Message,
                              new FrameworkException(@"Error serializing result: " + ex.Message, ex));
                }
            }
Пример #33
0
 /// <summary>
 /// Initialize new instance for TripleDESEncryption
 /// </summary>
 /// <param name="iSerialization">Serialization Instance</param>
 public TripleDESEncryption(ISerialization serializer)
     : base(serializer)
 {
 }
Пример #34
0
 /// <summary>
 /// Initialize new instance for RijndaelEncryption
 /// </summary>
 /// <param name="iSerialization">Serialization Instance</param>
 public RijndaelEncryption(ISerialization serializer)
     : base(serializer)
 {
 }