Exemple #1
0
            public void WhenAdaptManyDoesNotReturnNull_ReturnsEmptyEnumerable()
            {
                A.CallTo(() => _testAdapter.Adapt(A <DateTime> ._)).Returns(true);
                var expected = _sampleInput.Select(str => true);

                _testAdapter.AdaptManyOrEmpty(_sampleInput).Should().BeEquivalentTo(expected);
            }
Exemple #2
0
        public override async Task <long> ReadHighestSequenceNrAsync(string persistenceId, long fromSequenceNr)
        {
            try
            {
                var slice = await _eventStoreConnection.ReadStreamEventsBackwardAsync(persistenceId, StreamPosition.End, 1, false);

                long sequence = 0;

                if (slice.Events.Any())
                {
                    var @event  = slice.Events.First();
                    var adapted = _adapter.Adapt(@event);
                    sequence = adapted.SequenceNr;
                }
                else
                {
                    var metadata = await _eventStoreConnection.GetStreamMetadataAsync(persistenceId);

                    if (metadata.StreamMetadata.TruncateBefore != null)
                    {
                        sequence = metadata.StreamMetadata.TruncateBefore.Value;
                    }
                }

                return(sequence);
            }
            catch (Exception e)
            {
                _log.Error(e, e.Message);
                throw;
            }
        }
Exemple #3
0
            public void WhenAdaptManyDoesNotReturnNull_ReturnsResultFromAdaptMany()
            {
                A.CallTo(() => _testAdapter.Adapt(A <DateTime> ._)).Returns(true);
                var expected = _sampleInput.Select(str => true);

                _testAdapter.AdaptManyOrFallback(_sampleInput, _fallBack).Should().BeEquivalentTo(expected);
            }
        public IObservable <T> Observe(string topic)
        {
            var pipe = _pipeProvider.GetOrCreate(topic, _pipeType);

            return(pipe.Receive()
                   .Select(message => _adapter.Adapt(message))
                   .Finally(pipe.Dispose));
        }
Exemple #5
0
        public void Insert(User model)
        {
            var entity = _adapter.Adapt(model);

            _collection.InsertOne(entity);

            model.SetId(entity.Id.ToString());
        }
Exemple #6
0
        public virtual ActionResult <www.OperationResult> Create([FromBody] WebModel input)
        {
            var id = _service.Create(_adapter.Adapt <DbModel>(input));

            return(Ok(new www.OperationResult
            {
                Message = $"{typeof(DbModel).Name} with the id of '{id}' was successfully created",
                Id = id,
            }));
        }
Exemple #7
0
        public async Task <IActionResult> Create([FromBody] ProductDTO resource)
        {
            var product = _productAdapter.Adapt(resource);
            await _productService.AddAsync(product);

            var unitOfWork = (EntityFrameworkUnitOfWork)this.HttpContext.RequestServices.GetRequiredService <IUnitOfWork>();
            await unitOfWork.Context.SaveChangesAsync();

            var response = new { ResourceId = product.Id, product.Version };

            return(this.CreatedAtRoute(new { id = response.ResourceId }, response));
        }
Exemple #8
0
        public IActionResult ImportContent()
        {
            var    pairs       = new List <Pair <string, bool> >();
            string fs          = "./XML";
            string pattern     = ".xml";
            string currentFile = "";

            string[] files = Directory.GetFiles(fs);

            foreach (string file in files)
            {
                if (file.EndsWith(pattern))
                {
                    try
                    {
                        currentFile = file;
                        Dota       dota1  = _serializer.Deserialize(file);
                        DotaEntity entity = _adapter.Adapt(dota1);
                        _dotaRepository.Persist(entity);
                        var pair = new Pair <string, bool>(file, true);
                        pairs.Add(pair);
                    }
                    catch (Exception e)
                    {
                        var pair = new Pair <string, bool>(currentFile, false);
                        pairs.Add(pair);
                        continue;
                    }
                }
            }

            ViewBag.list = pairs;
            return(View());
        }
Exemple #9
0
        public IAdapter <string, T> Create(string headerString)
        {
            var headers = headerAdapter.Adapt(headerString);
            var stringToDictionaryAdapter = AdapterChain.Create(bodyAdapter, new StringZipAdapter(headers));

            return(AdapterChain.Create(stringToDictionaryAdapter, objectAdapter));
        }
Exemple #10
0
            public void GivenNullAdapter_Throws()
            {
                _testAdapter = null;
                Action act = () => _testAdapter.Adapt(_sampleInput);

                act.Should().Throw <ArgumentNullException>();
            }
Exemple #11
0
        // Violation of CQS, but we are not master of the Google identifiers...
        public async Task <User> ActivateGooglePlusUser(string accessToken)
        {
            if (accessToken == null)
            {
                throw new ArgumentNullException(nameof(accessToken));
            }
            var correlationId = await _googleUserDataService.ActivateGooglePlusUser(accessToken);

            var knownUsers = (await _knownUserDataService.FindKnownUserByCorrelationId((char)UserType.GooglePlus, correlationId)).ToList();

            if (knownUsers.Count > 1)
            {
                throw new SecurityException("Google authentication succeeded, but multiple locally known users were found.");
            }
            if (!knownUsers.Any())
            {
                throw new SecurityException("Google authentication succeeded, but no known user could be found.");
            }
            return(_userAdapter.Adapt(knownUsers.Single()));
        }
        protected override void ProcessRecord()
        {
            //base.ProcessRecord();

            Manager manager = new Manager();

            IAdapter adapter = manager.GetAdapter(this.AdapterName);

            object result = adapter.Adapt(this.AdapterParameters);

            this.WriteObject(result);
        }
        public void Log(ILogEntry entry)
        {
            if (entry == null)
            {
                throw new ArgumentNullException(nameof(entry));
            }

            var eventType      = _traceEventTypeAdapter.Adapt(entry.Severity);
            var formattedEntry = _entryFormatter.Format(entry);

            _traceSource.TraceData(eventType, entry.EventId, formattedEntry);
        }
Exemple #14
0
 public static TOut?Adapt <TIn, TOut>(this IAdapter <TIn, TOut> adapter, TIn?input)
     where TIn : struct
     where TOut : struct
 {
     if (adapter == null)
     {
         throw new ArgumentNullException(nameof(adapter));
     }
     return(input.HasValue
         ? adapter.Adapt(input.Value)
         : new TOut?());
 }
        public void ValidLogEntry_Maps_Formats_DoesNotThrow()
        {
            var input = new LogEntry(new RealSystemClock())
            {
                Severity = Severity.Warning
            };

            Assert.DoesNotThrow(() => _sut.Log(input));

            A.CallTo(() => _traceEventTypeAdapter.Adapt(Severity.Warning)).MustHaveHappened();
            A.CallTo(() => _entryFormatter.Format(input)).MustHaveHappened();
        }
Exemple #16
0
            public void WhenAdaptManyDoesNotReturnNull_ReturnsResultFromAdaptMany()
            {
                A.CallTo(() => _testAdapter.Adapt(A <string> ._))
                .ReturnsLazily(fakeCall => new Foo {
                    Value = fakeCall.Arguments.Get <string>(0)
                });
                var expected = _sampleInput.Select(str => new Foo {
                    Value = str
                });

                _testAdapter.AdaptManyOrEmpty(_sampleInput).Should().BeEquivalentTo(expected);
            }
Exemple #17
0
 public O ReadFromStream()
 {
     if (IsDataAvailable())
     {
         if (adapter == null)
         {
             CreateAdapter();
         }
         return(adapter.Adapt(stream.ReadFromStream()));
     }
     return(default(O));
 }
Exemple #18
0
        public void Mapping_Basic_Poco_Succeeds()
        {
            TypeAdapterConfig <SimplePoco, SimpleDto> .NewConfig();

            IAdapter instance = TypeAdapter.GetInstance();
            var      source   = new SimplePoco {
                Id = new Guid(), Name = "Test"
            };

            var destination = instance.Adapt <SimpleDto>(source);

            destination.Name.ShouldEqual(source.Name);
        }
Exemple #19
0
        public void Passed_Condition_Primitive_Does_Map()
        {
            TypeAdapterConfig <SimplePoco, SimpleDto> .NewConfig()
            .Map(dest => dest.Name, src => src.Name, cond => cond.Name == "TestName");

            var poco = new SimplePoco {
                Id = Guid.NewGuid(), Name = "TestName"
            };

            IAdapter  instance = TypeAdapter.GetInstance();
            SimpleDto dto      = instance.Adapt <SimplePoco, SimpleDto>(poco);

            dto.Id.ShouldEqual(poco.Id);
            dto.Name.ShouldEqual("TestName");
        }
Exemple #20
0
        public void False_Condition_Primitive_Does_Not_Map()
        {
            TypeAdapterConfig <SimplePoco, SimpleDto> .NewConfig()
            .Map(dest => dest.Name, src => src.Name, cond => false)
            .Compile();

            var poco = new SimplePoco {
                Id = Guid.NewGuid(), Name = "TestName"
            };

            IAdapter  instance = TypeAdapter.GetInstance();
            SimpleDto dto      = instance.Adapt <SimplePoco, SimpleDto>(poco);

            dto.Id.ShouldBe(poco.Id);
            dto.Name.ShouldBeNull();
        }
Exemple #21
0
        public IEnumerable <TDestination> Adapt(IEnumerable <TSource> source)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            var result = new List <TDestination>(source.Count());

            foreach (var s in source)
            {
                var destination = _singleAdapter.Adapt(s);

                result.Add(destination);
            }

            return(result);
        }
        public void SourceIsMappedCorrectly()
        {
            //Arrange
            var expectedResult = (TDestination)Substitute.For(new[] { _destinationType }, null);
            var mocks          = CreateMocks();
            var mockedFactory  = GetMockedFactory(mocks);

            RegisterMap(mocks);

            mockedFactory
            .GetType()
            .GetTypeInfo()
            .GetMethod(FactoryMethodName)
            .Invoke(mockedFactory, FactoryParameters)
            .ReturnsForAnyArgs(expectedResult);

            //Act
            var actualResult = _adapter.Adapt(Source, _sourceType, _destinationType);

            //Assert
            GetCallToFactory(mocks)
            .Should()
            .NotBeNull();

            GetCallToFactory(mocks)
            .GetArguments()
            .Should()
            .BeEquivalentTo(FactoryParameters);

            mockedFactory
            .Received(1)
            .GetType()
            .GetTypeInfo()
            .GetMethod(FactoryMethodName)
            .Invoke(mockedFactory, FactoryParameters);

            actualResult
            .Should()
            .BeSameAs(expectedResult);
        }
        public string Adapt(string AdapterName)
        {
            if (this.manager == null)
            {
                this.manager = new DataIntegrator.Manager();
            }

            IAdapter adapter = this.manager.GetAdapter(AdapterName);

            object returnValue = adapter.Adapt(null);

            if (returnValue is object[])
            {
                return(((object[])returnValue)[0].ToString());
            }
            else if (returnValue != null)
            {
                return(returnValue.ToString());
            }

            return("");
        }
Exemple #24
0
        /// <summary>
        ///     Load Characters, this is the Entrypoint for the Client, Wait for 3 Packets.
        /// </summary>
        /// <param name="packet"></param>
        /// <returns></returns>
        public void LoadCharacters(EntryPointPacket packet)
        {
            if (Session.Account == null)
            {
                var servers = WebApiAccess.Instance.Get <List <ChannelInfo> >(WebApiRoute.Channel)
                              ?.Where(c => c.Type == ServerType.WorldServer).ToList();
                var name = packet.Name;
                var alreadyConnnected = false;
                foreach (var server in servers ?? new List <ChannelInfo>())
                {
                    if (WebApiAccess.Instance
                        .Get <List <ConnectedAccount> >(WebApiRoute.ConnectedAccount, server.WebApi)
                        .Any(a => a.Name == name))
                    {
                        alreadyConnnected = true;
                        break;
                    }
                }

                if (alreadyConnnected)
                {
                    Session.Disconnect();
                    return;
                }

                var account = _accountDao.FirstOrDefault(s => s.Name == name);

                if (account != null)
                {
                    if (account.Password.Equals(packet.Password.ToSha512(),
                                                StringComparison.OrdinalIgnoreCase))
                    {
                        var accountobject = new AccountDto
                        {
                            AccountId = account.AccountId,
                            Name      = account.Name,
                            Password  = account.Password.ToLower(),
                            Authority = account.Authority,
                            Language  = account.Language
                        };
                        SessionFactory.Instance.Sessions.FirstOrDefault(s => s.Value.SessionId == Session.SessionId)
                        .Value.RegionType = account.Language;
                        Session.InitializeAccount(accountobject);
                        //Send Account Connected
                    }
                    else
                    {
                        _logger.Error(LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.INVALID_PASSWORD));
                        Session.Disconnect();
                        return;
                    }
                }
                else
                {
                    _logger.Error(LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.INVALID_ACCOUNT));
                    Session.Disconnect();
                    return;
                }
            }

            var characters = _characterDao.Where(s =>
                                                 s.AccountId == Session.Account.AccountId && s.State == CharacterState.Active);

            _logger.Information(LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.ACCOUNT_ARRIVED),
                                Session.Account.Name);

            // load characterlist packet for each character in Character
            Session.SendPacket(new ClistStartPacket {
                Type = 0
            });
            foreach (var character in characters.Select(characterDto => _adapter.Adapt <Character>(characterDto)))
            {
                var equipment = new WearableInstance[16];

                /* IEnumerable<ItemInstanceDTO> inventory = _iteminstanceDAO.Where(s => s.CharacterId == character.CharacterId && s.Type == (byte)InventoryType.Wear);
                 *
                 *
                 * foreach (ItemInstanceDTO equipmentEntry in inventory)
                 * {
                 *   // explicit load of iteminstance
                 *   WearableInstance currentInstance = equipmentEntry as WearableInstance;
                 *   equipment[(short)currentInstance.Item.EquipmentSlot] = currentInstance;
                 *
                 * }
                 */
                var petlist = new List <short?>();
                var mates   = _mateDao.Where(s => s.CharacterId == character.CharacterId)
                              .ToList();
                for (var i = 0; i < 26; i++)
                {
                    if (mates.Count > i)
                    {
                        petlist.Add(mates[i].Skin);
                        petlist.Add(mates[i].VNum);
                    }
                    else
                    {
                        petlist.Add(-1);
                    }
                }

                // 1 1 before long string of -1.-1 = act completion
                Session.SendPacket(new ClistPacket
                {
                    Slot       = character.Slot,
                    Name       = character.Name,
                    Unknown    = 0,
                    Gender     = (byte)character.Gender,
                    HairStyle  = (byte)character.HairStyle,
                    HairColor  = (byte)character.HairColor,
                    Unknown1   = 0,
                    Class      = character.Class,
                    Level      = character.Level,
                    HeroLevel  = character.HeroLevel,
                    Equipments = new List <short?>
                    {
                        equipment[(byte)EquipmentType.Hat]?.ItemVNum ?? -1,
                        equipment[(byte)EquipmentType.Armor]?.ItemVNum ?? -1,
                        equipment[(byte)EquipmentType.WeaponSkin]?.ItemVNum ??
                        (equipment[(byte)EquipmentType.MainWeapon]?.ItemVNum ?? -1),
                        equipment[(byte)EquipmentType.SecondaryWeapon]?.ItemVNum ?? -1,
                        equipment[(byte)EquipmentType.Mask]?.ItemVNum ?? -1,
                        equipment[(byte)EquipmentType.Fairy]?.ItemVNum ?? -1,
                        equipment[(byte)EquipmentType.CostumeSuit]?.ItemVNum ?? -1,
                        equipment[(byte)EquipmentType.CostumeHat]?.ItemVNum ?? -1
                    },
                    JobLevel        = character.JobLevel,
                    QuestCompletion = 1,
                    QuestPart       = 1,
                    Pets            = petlist,
                    Design          = equipment[(byte)EquipmentType.Hat]?.Item.IsColored ?? false
                        ? equipment[(byte)EquipmentType.Hat].Design : 0,
                    Unknown3 = 0
                });
            }

            Session.SendPacket(new ClistEndPacket());
        }
Exemple #25
0
 public void WriteToStream(I item)
 {
     writeStream.WriteToStream(adapter.Adapt(item));
 }
Exemple #26
0
        public override void Execute(SelectPacket packet, ClientSession clientSession)
        {
            try
            {
                if ((clientSession?.Account == null) || clientSession.HasSelectedCharacter)
                {
                    return;
                }

                var characterDto =
                    _characterDao.FirstOrDefault(s =>
                                                 (s.AccountId == clientSession.Account.AccountId) && (s.Slot == packet.Slot) &&
                                                 (s.State == CharacterState.Active));
                if (characterDto == null)
                {
                    return;
                }

                var character = _adapter.Adapt <Character>(characterDto);

                character.MapInstanceId = _mapInstanceProvider.GetBaseMapInstanceIdByMapId(character.MapId);
                character.MapInstance   = _mapInstanceProvider.GetMapInstance(character.MapInstanceId);
                character.PositionX     = character.MapX;
                character.PositionY     = character.MapY;
                character.Direction     = 2;
                character.Account       = clientSession.Account;
                character.Group.JoinGroup(character);

                var inventories = _inventoryItemInstanceDao
                                  .Where(s => s.CharacterId == character.CharacterId)
                                  .ToList();
                var ids   = inventories.Select(o => o.ItemInstanceId).ToArray();
                var items = _itemInstanceDao.Where(s => ids.Contains(s.Id)).ToList();
                inventories.ForEach(k => character.InventoryService[k.ItemInstanceId] =
                                        InventoryItemInstance.Create(_itemProvider.Convert(items.First(s => s.Id == k.ItemInstanceId)),
                                                                     character.CharacterId, k));
                clientSession.SetCharacter(character);

#pragma warning disable CS0618
                clientSession.SendPackets(clientSession.Character.GenerateInv());
#pragma warning restore CS0618
                clientSession.SendPacket(clientSession.Character.GenerateMlobjlst());
                if (clientSession.Character.Hp > clientSession.Character.HpLoad())
                {
                    clientSession.Character.Hp = (int)clientSession.Character.HpLoad();
                }

                if (clientSession.Character.Mp > clientSession.Character.MpLoad())
                {
                    clientSession.Character.Mp = (int)clientSession.Character.MpLoad();
                }

                clientSession.Character.QuicklistEntries = _quickListEntriesDao
                                                           .Where(s => s.CharacterId == clientSession.Character.CharacterId).ToList();
                clientSession.Character.StaticBonusList = _staticBonusDao
                                                          .Where(s => s.CharacterId == clientSession.Character.CharacterId).ToList();
                clientSession.Character.Titles = _titleDao
                                                 .Where(s => s.CharacterId == clientSession.Character.CharacterId).ToList();
                clientSession.SendPacket(new OkPacket());
            }
            catch (Exception ex)
            {
                _logger.Error("Select character failed.", ex);
            }
        }
Exemple #27
0
 public void GivenZeroItems_DoesNotCallAdapter()
 {
     _sampleInput = Array.Empty <string>();
     _testAdapter.AdaptMany(_sampleInput).Should().NotBeNull().And.BeEmpty();
     A.CallTo(() => _testAdapter.Adapt(A <string> ._)).MustNotHaveHappened();
 }
Exemple #28
0
 public O ReadFromStream()
 {
     return(adapter.Adapt(dataStream.ReadFromStream()));
 }
Exemple #29
0
            public void GivenNullInput_ReturnsNull()
            {
                var nullInput = new DateTime?();

                _testAdapter.Adapt(nullInput).Should().NotHaveValue();
            }
        public Task <User> Handle(GetCurrentUserRequest request)
        {
            var authenticatedUser = request.SecurityContext.GetAuthenticatedUser();

            return(Task.FromResult(_userAdapter.Adapt(authenticatedUser)));
        }