public void SetUp()
 {
     _repo     = MockRepository.GenerateMock <IInventoryRepository>();
     _settings = MockRepository.GenerateStub <ISettings>();
     _identity = MockRepository.GenerateStub <IIdentity>();
     DomainModelMapper.Initialize();
 }
        public void TestGetPropertiesForCreate()
        {
            var company = new Company
            {
                DenariAccountId = "12345",
                DenariIntroDate = DateTime.Parse("1980-10-02", DateTimeFormatInfo.InvariantInfo),
                BigGiftAmount   = 12345m,
            };

            string properties = DomainModelMapper.GetPropertiesForCreate(company);

            Assert.NotNull(properties);

            // strings should be quoted
            Assert.True(properties.Contains($"\"account_id\": \"{company.DenariAccountId}\"", StringComparison.InvariantCulture));

            // dates should be milliseconds since unix epoch
            string dateAsUnixOffset = new DateTimeOffset((DateTime)company.DenariIntroDate).ToUnixTimeMilliseconds().ToString(DateTimeFormatInfo.InvariantInfo);

            Assert.True(properties.Contains($"\"denari_intro_date\": \"{dateAsUnixOffset}\"", StringComparison.InvariantCulture));

            // numbers should be quoted
            string stringGiftAmount = $"{company.BigGiftAmount:N}".Replace(",", string.Empty, StringComparison.InvariantCulture);

            Assert.True(properties.Contains($"\"big_gift_amount\": \"{stringGiftAmount}\"", StringComparison.InvariantCulture));
        }
Example #3
0
        private async Task <CrmObject> CreateCompanyAsync(Company company, CancellationToken cancellationToken)
        {
            using var content = new StringContent(DomainModelMapper.GetPropertiesForCreate(company), Encoding.UTF8, "application/json");
            var response = await RequestWithRetriesAsync(
                async cancellationToken => await m_client.PostAsync("/crm/v3/objects/companies", content, cancellationToken),
                cancellationToken);

            await response.EnsureSuccessStatusCodeWithResponseBodyInException();

            return(JsonConvert.DeserializeObject <CrmObject>(await response.Content.ReadAsStringAsync()));
        }
Example #4
0
        public async Task <Contact?> GetContactByEmailAsync(string email, CancellationToken cancellationToken = default)
        {
            return(await m_cache.GetOrCreateAsync(email, async entry =>
            {
                entry.SetSlidingExpiration(TimeSpan.FromMinutes(120));

                var filter = new CrmSearchOptions
                {
                    FilterGroups =
                    {
                        new CrmSearchFilterGroups
                        {
                            Filters =
                            {
                                new CrmSearchFilter
                                {
                                    PropertyName = "email",
                                    Operator = "EQ",
                                    Value = email,
                                },
                            },
                        },
                    },
                    Properties = DomainModelMapper.GetPropertyNames(new Contact()),
                    Limit = 1,
                };

                var json = JsonConvert.SerializeObject(filter, Formatting.Indented, new JsonSerializerSettings
                {
                    ContractResolver = new DefaultContractResolver
                    {
                        NamingStrategy = new CamelCaseNamingStrategy(),
                    },
                    NullValueHandling = NullValueHandling.Ignore,
                });

                using var content = new StringContent(json, Encoding.UTF8, "application/json");
                var response = await RequestWithRetriesAsync(
                    async cancellationToken => await m_client.PostAsync("/crm/v3/objects/contacts/search", content, cancellationToken),
                    cancellationToken);

                if (response.StatusCode == HttpStatusCode.NotFound)
                {
                    return null;
                }

                await response.EnsureSuccessStatusCodeWithResponseBodyInException();

                var searchResults = JsonConvert.DeserializeObject <GetCrmObjectsResult>(await response.Content.ReadAsStringAsync());
                return DomainModelMapper.MapDomainModel <Contact>(searchResults.Results.FirstOrDefault());
            }));
        }
Example #5
0
        public IEnumerable <CStore> GetAllStores()
        {
            using var context = new Project0databaseContext(_contextOptions);
            var dbStores = context.Stores.ToList();

            if (dbStores == null)
            {
                return(null);
            }
            var domainStores = DomainModelMapper.MapStore(dbStores);

            return(domainStores);
        }
Example #6
0
        public CCustomer GetOneCustomerByEmail(string email)
        {
            using var context = new Project0databaseContext(_contextOptions);
            var dbCustomer = context.Customers.FirstOrDefault(x => x.Email == email);

            if (dbCustomer == null)
            {
                return(null);
            }
            var domainCustomer = DomainModelMapper.MapSingleCustomer(dbCustomer);

            return(domainCustomer);
        }
Example #7
0
        public IEnumerable <CStore> GetAllStoresByZipcode(string zipCode)
        {
            using var context = new Project0databaseContext(_contextOptions);
            IEnumerable <Store> dbStores;

            try
            {
                dbStores = context.Stores.Where(x => x.Zipcode == zipCode).ToList();
            }
            catch (Exception e)
            {
                return(null);
            }
            var stores = DomainModelMapper.MapStore(dbStores);

            return(stores);
        }
Example #8
0
        private async Task <CrmObject> UpdateCompanyAsync(Company updatedCompany, Company existingCompany, CancellationToken cancellationToken)
        {
            if (DomainModelMapper.GetPropertiesForUpdate(updatedCompany, existingCompany, out string propertiesJson))
            {
                using var content = new StringContent(propertiesJson, Encoding.UTF8, "application/json");
                var response = await RequestWithRetriesAsync(
                    async cancellationToken => await m_client.PatchAsync($"/crm/v3/objects/companies/{existingCompany.Id}", content, cancellationToken),
                    cancellationToken);

                await response.EnsureSuccessStatusCodeWithResponseBodyInException();

                return(JsonConvert.DeserializeObject <CrmObject>(await response.Content.ReadAsStringAsync()));
            }
            else
            {
                return(existingCompany);
            }
        }
        public void TestGetPropertiesForUpdate()
        {
            var existing = new Company
            {
                DenariAccountId = "12345",
            };

            var updated = new Company
            {
                DenariAccountId = "54321",
            };

            DomainModelMapper.TryGetPropertiesForUpdate(updated, existing, out string?properties);
            Assert.NotNull(properties);

            // new property should be present, not old one
            Assert.True(properties.Contains($"\"account_id\": \"{updated.DenariAccountId}\"", StringComparison.InvariantCulture));
            Assert.False(properties.Contains($"\"account_id\": \"{existing.DenariAccountId}\"", StringComparison.InvariantCulture));
        }
Example #10
0
        public async Task HydrateCompaniesCacheAsync(CancellationToken cancellationToken = default)
        {
            var cacheOptions = new MemoryCacheEntryOptions
            {
                SlidingExpiration = TimeSpan.FromMinutes(120),
            };

            var parameters = new Dictionary <string, string>
            {
                { "limit", "100" },
                { "properties", string.Join(",", DomainModelMapper.GetPropertyNames(new Company())) },
            };

            var uri = new Uri(QueryHelpers.AddQueryString($"{m_client.BaseAddress}crm/v3/objects/companies", parameters));

            while (true)
            {
                var response = await RequestWithRetriesAsync(
                    async cancellationToken => await m_client.GetAsync(uri, cancellationToken),
                    cancellationToken);

                await response.EnsureSuccessStatusCodeWithResponseBodyInException();

                var companies = JsonConvert.DeserializeObject <GetCrmObjectsResult>(await response.Content.ReadAsStringAsync());

                foreach (var company in companies.Results)
                {
                    if (company.Properties != null && company.Properties.ContainsKey("account_id") && !company.Properties.Value <string>("account_id").IsNullOrEmpty())
                    {
                        m_cache.Set(company.Properties.Value <string>("account_id"), DomainModelMapper.MapDomainModel <Company>(company), cacheOptions);
                    }
                }

                if (companies.Paging == null)
                {
                    break;
                }

                uri = new Uri(companies.Paging.Next.Link);
            }
        }
Example #11
0
        public PortfolioVM GetPortfolio()
        {
            try
            {
                //Get the data of postions static object
                var portfolio = this.mandateService.GetPortfolio();

                var filePath = _configuration["FilePath"];
                //Get funds of Mandate data from file
                string fileName       = Path.GetFullPath(filePath);
                var    fundOfMandates = this.mandateService.GetFundOfMandatesFromXML(fileName);

                _logger.LogInformation("Received funds of Mandate data from XML.", fileName.Count());

                //Map response and get calculated mandates
                var position           = DomainModelMapper.MapPosition(portfolio);
                var calculatedPosition = this.mandateService.CalculateMandates(position, fundOfMandates);

                _logger.LogInformation("Mandate Calculations completed.", position);

                //Map Response from API
                var response = ResponseBuilder.MapPortfolio(calculatedPosition);

                return(response);
            }
            catch (FileNotFoundException ex)
            {
                _logger.LogError("File does not exist", ex.FileName);
                throw ex;
            }
            catch (ArgumentNullException ex)
            {
                _logger.LogError("Null", ex.ParamName);
                throw ex;
            }
            catch (Exception ex)
            {
                _logger.LogError("There is some error.", ex.Message);
                throw ex;
            }
        }
 protected void Application_Start(object sender, EventArgs e)
 {
     ObjectFactory.Initialize(x => x.AddRegistry <IoCRegistry>());
     DomainModelMapper.Initialize();
     _log = ObjectFactory.GetInstance <ILogger>();
 }