コード例 #1
0
        public async Task <IHttpActionResult> UpdateAsync(int id, CurrencyDto currency)
        {
            var currencyInDb = await _repository.GetAsync(id);

            if (currencyInDb == null)
            {
                return(NotFound());
            }

            _repository.Add(currency.Map <Currency>());
            await _unitOfWork.CompleteAsync();

            return(Ok());
        }
コード例 #2
0
 public IActionResult Save(Currency_VM currency_VM)
 {
     if (currency_VM != null)
     {
         currency_VM.ClientId = clientId;
         if (currency_VM.Id > 0)
         {
             if (_currencyRepository.Update(currency_VM, this.loginUserId) > 0)
             {
                 TempData["Status"]  = Helper.success_code;
                 TempData["Message"] = Message.currencyUpdated;
             }
             else
             {
                 TempData["Message"] = Message.currencyUpdateError;
             }
         }
         else
         {
             if (_currencyRepository.Add(currency_VM, this.loginUserId) > 0)
             {
                 TempData["Status"]  = Helper.success_code;
                 TempData["Message"] = Message.currencyAdded;
             }
             else
             {
                 TempData["Message"] = Message.currencyAddedError;
             }
         }
     }
     return(RedirectToAction("List", "Currency"));
 }
コード例 #3
0
        public Task Handle(CreateCurrencyCommand message, CancellationToken cancellationToken)
        {
            if (!message.IsValid())
            {
                NotifyValidationErrors(message);
                return(Task.CompletedTask);
            }

            var Currency = new Currency(Guid.NewGuid(), message.Code, message.Name, message.Address, message.Quantity, message.IsActive);

            if (_CurrencyRepository.GetByCode(Currency.Code) != null)
            {
                Bus.RaiseEvent(new DomainNotification(message.MessageType, "The Currency Code has already been taken."));
                return(Task.CompletedTask);
            }

            _CurrencyRepository.Add(Currency);

            if (Commit())
            {
                Bus.RaiseEvent(new CurrencyCreatedEvent(Currency.Id, Currency.Code, Currency.Name, Currency.Address, Currency.Quantity, Currency.IsActive));
            }

            return(Task.CompletedTask);
        }
コード例 #4
0
        public void CurrencyRepository_AddCurrencyRecord_ValidCall()
        {
            //Arrange
            List <Currency> currencyList = CreateTestData.GetListOfCurrency();
            var             mockSet      = new Mock <DbSet <Currency> >()
                                           .SetupData(currencyList, o =>
            {
                return(currencyList.Single(x => x.Character_id.CompareTo(o.First()) == 0));
            });

            using (var mockContext = AutoMock.GetLoose())
            {
                var expected = CreateTestData.GetSampleCurrency();
                var id       = Guid.Parse("b346eee6-eba7-4ea7-be2e-911bb9034233");
                expected.Character_id = id;

                mockContext.Mock <CharacterContext>()
                .Setup(x => x.Set <Currency>()).Returns(mockSet.Object);

                //Act
                ICurrencyRepository toTest = mockContext.Create <CurrencyRepository>();
                toTest.Add(expected);
                var actual = toTest.Get(id);

                //Assert
                actual.Should().NotBeNull();
                expected.Should().NotBeNull();
                actual.Should().BeOfType <Currency>();
                expected.Should().BeOfType <Currency>();
                actual.Should().BeEquivalentTo(expected);
            }
        }
コード例 #5
0
        public async Task <Currency> Add(Currency contract)
        {
            var entity = ContractToEntity(contract);

            entity = await _currencyRepo.Add(entity);

            return(EntityToContract(entity));
        }
コード例 #6
0
 public IResult CreateCurrency(CreateCurrencyRequest request, Guid principal)
 {
     return(_currencyRepository.Add(request, principal).Success(() =>
     {
         _session.SaveChanges();
         return Result.Success();
     }));
 }
コード例 #7
0
        public void Add_Test()
        {
            var entity = datas[0];

            var addedEntity = _repo.Add(entity).Result;

            Assert.NotNull(addedEntity);
            Assert.True(addedEntity.Id > 0);
        }
コード例 #8
0
ファイル: CurrencyService.cs プロジェクト: newdevin/Valuation
        public async Task Add(Currency currency)
        {
            var curr = await currencyRepositiory.Get(currency.Symbol);

            if (curr != null)
            {
                throw new InvalidOperationException($"{currency.Symbol} already exists");
            }
            await currencyRepositiory.Add(currency);
        }
コード例 #9
0
ファイル: CurrencyServices.cs プロジェクト: A-Soltani/portal
        public bool AddCurrency(CurrencyDTO currencyDTO)
        {
            //DefinationCurrencyCommandValidator currencyValidator = new DefinationCurrencyCommandValidator();
            //var validationResult = currencyValidator.Validate(currencyDTO);
            //if (!validationResult.IsValid)
            //    throw new ValidationException("Validation exception", validationResult.Errors);

            Currency currency = Currency.CurrencyDefinition(currencyDTO.CurrencyNumericCode, currencyDTO.Country, currencyDTO.CurrencyType, currencyDTO.AlphabeticCode, currencyDTO.ExchangeRate, currencyDTO.UserID);

            _currencyRepository.Add(currency);
            return(true);
        }
コード例 #10
0
        public ViewResult List()
        {
            CurrentCurrency result = _currencyRepository.CurrentCurrency.FirstOrDefault(x => x.Date == DateTime.Now.Date.AddDays(-1));;

            if (result == null)
            {
                result = _courseService.GetCurrentCourse();
                _currencyRepository.Add(result);
            }

            return(View(result));
        }
コード例 #11
0
        public ActionResult Add(CurrencyDTO currency)
        {
            Currency c = new Currency();

            c.CurrencyName   = currency.CurrencyName;
            c.CurrencySymbol = currency.CurrencySymbol;
            c.Date           = Convert.ToDateTime(currency.Date);
            c.Value          = currency.Value;

            currencyRepository.Add(c);
            currencyRepository.Save();

            return(Json(currency, JsonRequestBehavior.DenyGet));
        }
コード例 #12
0
        // MediatR commands
        // This method handels message. It is responsible for getting inpput message and returning proper output.
        public async Task <bool> Handle(DefinationCurrencyCommand message, CancellationToken cancellationToken)
        {
            Currency currency = Currency.CurrencyDefinition(message.CurrencyNumericCode,
                                                            message.Country,
                                                            message.CurrencyType,
                                                            message.AlphabeticCode,
                                                            message.ExchangeRate,
                                                            message.UserID);

            await _currencyRepository.Add(currency);

            // This is an inappropriate way to return true in every situation,
            // but as far as I can see, there isn't any information to be awared if the currency object has been stored correctly or not.
            // So return true should be superseded by a propper value
            return(true);
        }
コード例 #13
0
        public async Task <CommandResult <Currency> > Handle(CreateCurrencyCommand request, CancellationToken cancellationToken)
        {
            var currency = await currencyRepository.FindOneAsync(p => p.IsoCode.Equals(request.CurrencyIso.ToLower()));

            if (currency != null)
            {
                return(CommandResult <Currency> .Fail(currency, "IsoCode already exists"));
            }

            currency = new Currency(request.Name, request.CurrencyIso);

            await currencyRepository.Add(currency);

            PublishEvents(currency);
            return(CommandResult <Currency> .Success(currency));
        }
コード例 #14
0
        public async Task <IActionResult> Add([FromBody] CurrencyDto currencyDto)
        {
            if (await currencyRepository.GetCurrencyByCode(currencyDto.Code) != null)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, $"Currency with this PublicId == {currencyDto.Code} already exists"));
            }
            if (await currencyRepository.GetCurrency(currencyDto.Name) != null)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, $"Currency with this Name == {currencyDto.Name} already exists"));
            }
            Currency currency = new Currency(currencyDto.Code, currencyDto.Name);
            await currencyRepository.Add(currency);

            await unitOfWork.SaveEntitiesAsync();

            return(Ok());
        }
コード例 #15
0
        public async Task <IEnumerable <CurrencySymbol> > GetCurrencySombols()
        {
            var currenciesStoredLocally = await _currencyRepo.GetAll();

            if (currenciesStoredLocally.Any())
            {
                return(currenciesStoredLocally.Select(ToSymbols));
            }
            else
            {
                var curencySymbols = await _currencyClient.GetCurrencies();

                var currencyDtos = curencySymbols.Select(symbol => ToCurrencyDto(symbol));
                await _currencyRepo.Add(currencyDtos);

                return(curencySymbols);
            }
        }
コード例 #16
0
ファイル: AppSeeder.cs プロジェクト: anndreiAbabei/Kubera
        private async ValueTask CreateCurrencyIfNotExists(string code, string name, string symbol, int index, CancellationToken cancellationToken = default)
        {
            var exCur = await _currencyRepository.GetByCode(code, cancellationToken)
                        .ConfigureAwait(false);

            if (exCur == null)
            {
                exCur = new Currency
                {
                    Code   = code,
                    Name   = name,
                    Symbol = symbol,
                    Order  = index
                };

                await _currencyRepository.Add(exCur, cancellationToken);
            }
        }
コード例 #17
0
 public IActionResult Add(Currency currency)
 {
     if (ModelState.IsValid)
     {
         Currency curr = _currencyRepository.GetCurrencyByCode(currency.CurrencyCode);
         if (curr == null)
         {
             _currencyRepository.Add(currency);
             return(RedirectToAction("Index", "Currency"));
         }
         else
         {
             ViewData["CurrencyAddAlert"] = "Such currency already exists";
             Currency newCurr = new Currency();
             return(View(newCurr));
         }
     }
     return(View());
 }
コード例 #18
0
        public async Task <IActionResult> ExecuteAsync(SaveCurrency saveCurrency, CancellationToken cancellationToken)
        {
            var listCurrency = await _currencyRepository.GetAll(cancellationToken);

            var selectCurrency = listCurrency.SingleOrDefault(x => x.Title == saveCurrency.Title || x.Code == saveCurrency.Code);

            if (selectCurrency != null)
            {
                return(new NoContentResult());
            }
            var currency = _saveCurrencyToCurrencyMapper.Map(saveCurrency);

            //// add created by
            //var user = _httpContextAccessor.HttpContext.User;
            //if (user == null)
            //    return new NotFoundResult();

            //var claims = user.Claims.ToList();
            //if (claims.Count < 1)
            //    return new NotFoundResult();

            //var userId = claims.FirstOrDefault(claimRecord => claimRecord.Type == "sub").Value;

            //if (currency.CreatedBy == null)
            //    currency.CreatedBy = userId;
            //currency.ModifiedBy = userId;
            //// end created by

            await _currencyRepository.Add(currency, cancellationToken);

            if (currency.Default == true)
            {
                await _currencyRepository.Default(currency, cancellationToken);
            }
            var currencyViewModel = _currencyToCurrencyMapper.Map(currency);

            return(new CreatedAtRouteResult(
                       CurrenciesControllerRoute.GetCurrency,
                       new { id = currencyViewModel.Id },
                       currencyViewModel));
        }
コード例 #19
0
        public void AddCurrency(CurrencyViewModel currency)
        {
            var existCurrSpec = new CurrencyByCodeSpec(currency.Code);
            var oldItem       = currRepository.FindOne(existCurrSpec);

            if (oldItem != null)
            {
                throw new ValidationException($"Currency {currency.Code} already exist!");
            }

            var curr = Currency.CreateCurrency(currency.Code, currency.ShortCode, currency.Symbol, currency.Name);

            try
            {
                unitOfWork.BeginTransaction();
                currRepository.Add(curr);
                unitOfWork.Commit();
            }
            catch (Exception)
            {
                unitOfWork.Rollback();
                throw;
            }
        }
コード例 #20
0
        public async Task <IActionResult> SeedPoloniex()
        {
            var coinMarketCapData  = _httpClient.GetStringAsync("https://api.coinmarketcap.com/v2/listings/");
            var poloniexInfo       = _httpClient.GetStringAsync("https://poloniex.com/public?command=returnTicker");
            var poloniexCurrencies = _httpClient.GetStringAsync("https://poloniex.com/public?command=returnCurrencies");


            await Task.WhenAll(poloniexInfo, coinMarketCapData, poloniexCurrencies);

            var pCurrencies  = JObject.Parse(poloniexCurrencies.Result);
            var dbCurrencies = _currencyRepository.List();

            //var poloniex = new Exchange
            //{
            //    Id = "poloniex",
            //    Web = "www.poloniex.com",
            //    Name = "Poloniex",
            //    ProvidesFullHistoryData = true,
            //};

            var pol = _repo.List().FirstOrDefault(o => o.Id == "poloniex");

            //_repo.Add(poloniex);

            var cmcTemplate = new { data = new[] { new { name = "", symbol = "" } } };
            var cmcData     = JsonConvert.DeserializeAnonymousType(coinMarketCapData.Result, cmcTemplate).data;

            foreach (var p in pCurrencies)
            {
                var x = (bool)p.Value["disabled"];


                var propertyName = p.Key;
                if ((bool)p.Value["disabled"] == true || (bool)p.Value["delisted"] == true)
                {
                    continue;
                }
                var originalCurrency = dbCurrencies.FirstOrDefault(o => o.Id == propertyName);
                if (originalCurrency == null)
                {
                    var cmcMatch = cmcData.FirstOrDefault(o => o.symbol == propertyName);

                    _currencyRepository.Add(new Currency
                    {
                        Id   = propertyName,
                        Name = cmcMatch == null ? propertyName : cmcMatch.name,
                    });
                }
                //_exchangeCurrencyRepository.Add(new ExchangeCurrency
                //{
                //    Id = "poloniex_" + propertyName,
                //    CurrencyId = propertyName,
                //    ExchangeId = "poloniex",
                //    CurrencyExchangeId = propertyName,
                //});
            }

            var poloniexData    = JObject.Parse(poloniexInfo.Result);
            var dbSymbols       = _marketRepository.List();
            var errors          = new List <string>();
            var exchangeMarkets = _exchangeMarketRepository.List();
            var asf             = 0;

            foreach (var symbol in poloniexData)
            {
                var marketName     = symbol.Key;
                var coins          = marketName.Split('_');
                var originalMarket = dbSymbols.FirstOrDefault(o => o.Id == marketName);

                if (exchangeMarkets.FirstOrDefault(o => o.Id == "poloniex_" + marketName) == null)
                {
                    try
                    {
                        pol.ExchangeMarkets.Add(new ExchangeMarket
                        {
                            Exchange         = pol,
                            Id               = pol.Id + "_" + marketName,
                            MarketExchangeId = marketName,
                            Market           = originalMarket ?? new Market
                            {
                                Id = marketName,
                                MarketCurrencyId = coins[0].Trim().ToUpper(),
                                CurrencyId       = coins[1].Trim().ToUpper(),
                            }
                        });
                        _repo.Edit(pol);
                    }
                    catch { }
                    errors.Add(marketName);


                    //_exchangeMarketRepository.Add(new ExchangeMarket
                    //{
                    //    Id = pol.Id + "_" + originalMarket.Id,
                    //    MarketExchangeId = originalMarket.Id,
                    //    ExchangeId = pol.Id,
                    //    MarketId = originalMarket.Id
                    //});
                }
            }

            return(Ok(errors));
        }
コード例 #21
0
 public Currency Add(Currency currency)
 {
     return(_currencyRepository.Add(currency));
 }
コード例 #22
0
        public async Task <IActionResult> Init(InitConfigViewModel model)
        {
            // check if it's initialized
            if (_defaultKeysOptions.Value.Initialized)
            {
                return(BadRequest("Already Initialized!"));
            }
            // 1. create company 2. finanital period
            string financialPeriodName = string.Format(Resources.Global.Common.FinancialPeriodName, DateTime.Now.Year, model.CompanyName);
            var    financialPeriod     = new FinancialPeriod(financialPeriodName, model.StartDate, model.EndtDate);

            financialPeriod.Company = new Company(model.CompanyName);
            _financialPeriodRepo.Add(financialPeriod, false);
            // 3. currency
            Currency currency = new Currency();

            if (model.CurrencyId.HasValue)
            {
                var preDefinedCurrency = _predefinedGuideService.GetCurrecny(model.CurrencyId.Value);
                currency = new Currency(preDefinedCurrency.Code, preDefinedCurrency.GetName(_language), 1, preDefinedCurrency.GetPartName(_language), preDefinedCurrency.PartRate, preDefinedCurrency.ISOCode);
            }
            else
            {
                var preDefinedCurrency = _predefinedGuideService.GetCurrecny(1); // USD
                currency = new Currency(preDefinedCurrency.Code, preDefinedCurrency.GetName(_language), 1, preDefinedCurrency.GetPartName(_language), preDefinedCurrency.PartRate, preDefinedCurrency.ISOCode);
            }

            _currencyRepo.Add(currency, false);

            // 4. accounts
            var accounts = _predefinedGuideService.GetGuideAccounts(model.AccoutGuideId);

            foreach (var accountModel in accounts)
            {
                var finalAccountId  = accountModel.FinalAccountId == Guid.Empty ? null : accountModel.FinalAccountId;
                var parentAccountId = accountModel.ParentId == Guid.Empty ? null : accountModel.ParentId;
                var account         =
                    new Account(accountModel.GetName(_language), accountModel.Code, parentAccountId, finalAccountId,
                                (AccountType)accountModel.Type, AccountDirectionType.Both, currency.Id);
                account.Id = accountModel.Id;
                _accountRepo.Add(account, false);
            }

            // 5. billTypes

            // 6. payTypes

            // 7. check and complete defulat items accountId and default cash accountId in predefienedGuides file

            var affectedRows = await _accountRepo.SaveAllAsync();

            if (affectedRows > 0)
            {
                // update appSettings
                //      1. update initialized prop
                _defaultKeysOptions.Update(a => a.Initialized = true);
                //      2. update default currency
                _defaultKeysOptions.Update(a => a.CurrencyId = currency.Id);

                return(Ok());
            }
            return(BadRequest());
        }