Пример #1
0
        public void Get_ByIsoCode_Returns_FoundItem()
        {
            var data = new List <Country>
            {
                new Country {
                    IsoCode = "BB", Name = "YYY"
                },
                new Country {
                    IsoCode = "AA", Name = "XXX"
                },
                new Country {
                    IsoCode = "CC", Name = "UUU"
                },
            };

            var mockSet     = new Mock <DbSet <Country> >().SetupData(data);
            var mockContext = new Mock <CountryContext>();

            mockContext.Setup(c => c.Countries).Returns(mockSet.Object);

            var service = new CountryRepository(mockContext.Object);

            // Act
            var item = service.Get("BB");

            Assert.IsNotNull(item);
            Assert.AreEqual(item.IsoCode, "BB");
        }
        public ActionResult <Continent> Delete(int id)
        {
            log("Delete");
            ICountryRepository countRepos = new CountryRepository();

            if (!contRepos.ExistsContinent(id))
            {
                return(NotFound());
            }
            if (countRepos.GetAll(id).Count() > 0)
            {
                GeoException ex = new GeoException("Continent still contains countries.");
                return(BadRequest(ex.Message));
            }

            else
            {
                try
                {
                    contRepos.RemoveContinent(id);
                    return(NoContent());
                }
                catch (GeoException ex)
                {
                    return(BadRequest(ex.Message));
                }
            }
        }
Пример #3
0
 public MigrationController(ISession session)
 {
     _session = session;
     _countryRepository = new CountryRepository(_session);
     _settingsRepository = new SettingsRepository(_session);
     _seriesRepository = new SeriesRepository(_session);
 }
Пример #4
0
        // GET: Create A Single MerchantFee
        public ActionResult Create()
        {
            //Check Access Rights to Domain
            if (!hierarchyRepository.AdminHasDomainWriteAccess(groupName))
            {
                ViewData["Message"] = "You do not have access to this item";
                return(View("Error"));
            }

            MerchantFeeVM merchantFeeVM = new MerchantFeeVM();

            MerchantFee merchantFee = new MerchantFee();

            merchantFeeVM.MerchantFee = merchantFee;

            CountryRepository countryRepository = new CountryRepository();

            merchantFeeVM.Countries = new SelectList(countryRepository.GetAllCountries().ToList(), "CountryCode", "CountryName");

            CreditCardVendorRepository creditCardVendorRepository = new CreditCardVendorRepository();

            merchantFeeVM.CreditCardVendors = new SelectList(creditCardVendorRepository.GetAllCreditCardVendors().ToList(), "CreditCardVendorCode", "CreditCardVendorName");

            ProductRepository productRepository = new ProductRepository();

            merchantFeeVM.Products = new SelectList(productRepository.GetAllProducts().ToList(), "ProductId", "ProductName");

            return(View(merchantFeeVM));
        }
        public void CountryRepositoryAddNewItemSaveItem()
        {
            //Arrange
            var unitOfWork = new MainBCUnitOfWork();
            ICountryRepository countryRepository = new CountryRepository(unitOfWork);

            var country = new Country()
            {
                Id = IdentityGenerator.NewSequentialGuid(),
                CountryName = "France",
                CountryISOCode = "fr-FR"
            };

            //Act

            countryRepository.Add(country);
            countryRepository.UnitOfWork.Commit();

            //Assert

            var result = countryRepository.Get(country.Id);

            Assert.IsNotNull(result);
            Assert.IsTrue(result.Id == country.Id);
        }
Пример #6
0
        public void A_ChangedCountry_modifies_Existing_country_in_the_database()
        {
            var bootStrapper = new BootStrapper();
            bootStrapper.StartServices();
            var serviceEvents = bootStrapper.GetService<IServiceEvents>();
            //1.- Create message
            var aggr = GenerateRandomAggregate();

            //2.- Create the tuple in the database
            var repository = new CountryRepository(_configuration.TestServer);
            repository.Insert(aggr);

            //3.- Change the aggregate
            aggr.NameKeyId = StringExtension.RandomString(20);
            aggr.CurrencyId = Guid.NewGuid();

            //4.- Emit message
            var message = GenerateMessage(aggr);
            message.MessageType = typeof(ChangedCountry).Name;
            serviceEvents.AddIncommingEvent(new IncommingEvent { @event = message });

            //5.- Load the saved country
            var country = repository.Get(aggr.Id);
            //6.- Check equality
            Assert.True(ObjectExtension.AreEqual(aggr, country));
            
        }
Пример #7
0
 private Country[] GetAllCountries()
 {
     using (IRepository <Country> repository = new CountryRepository(DatabaseSourceDefinitor.ConnectionString))
     {
         return(repository.GetAllItems().ToArray());
     }
 }
Пример #8
0
 public UnitOfWork(ApplicationContext context)
 {
     _context  = context;
     Addresses = new AddressRepository(_context);
     Customers = new CustomerRepository(_context);
     Countries = new CountryRepository(_context);
 }
 public UnitOfWork(AssetContext context)
 {
     _context  = context;
     Assets    = new AssetRepository(_context);
     Countries = new CountryRepository(_context);
     MimeTypes = new MimeTypeRepository(_context);
 }
Пример #10
0
        static void Main(string[] args)
        {
            var repo      = new CountryRepository();
            var countries = repo._countries;

            //var countryClass = new Country();
            // repo.SaveAllMethod(countryClass);
            foreach (var country in countries)
            {
                Console.WriteLine(country.name);
                Console.WriteLine(country.alpha3Code);
                Console.WriteLine(country.capital);
                Console.WriteLine(country.region);
                Console.WriteLine(country.subregion);
                Console.WriteLine(country.population);
                //Console.WriteLine(country.lat);
                //Conosole.WriteLine(country.lng);
                Console.WriteLine(country.area);
                Console.WriteLine(country.demonym);
                //Console.WriteLine(country.timeZone);
                Console.WriteLine(country.flag);
                Console.WriteLine("\n");
            }
            Console.ReadKey();
        }
Пример #11
0
        public void DeleteCountry()
        {
            Console.Clear();
            Console.WriteLine("Введите страну которую хотите удалить - ");
            var cityName = CheckNullString(Console.ReadLine());

            using (var repository = new CountryRepository())
            {
                try
                {
                    var id = repository.GetCountry(cityName);
                    repository.Delete(id);
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception.Message);
                    Console.WriteLine("Нажмите Enter чтобы продолжить!");
                    Console.ReadKey();
                    return;
                }
            }

            Console.WriteLine("Данные удалены!");
            Console.WriteLine("Нажмите Enter чтобы продолжить!");
            Console.ReadKey();
        }
Пример #12
0
        public void TestCitiesByNameGetter()
        {
            //Arrange
            int    countryId = 1;
            string name      = "aaa";
            var    regions   = new List <City>
            {
                new City {
                    CountryId = countryId, Name = name
                },
                new City {
                    CountryId = countryId + 1, Name = name
                },
                new City {
                    CountryId = countryId, Name = $"ccc{name}"
                },
                new City {
                    CountryId = countryId + 2, Name = $"bbb{name}"
                }
            };
            var dbSet   = regions.AsQueryable().BuildMockDbSet();
            var context = new Mock <hNextDbContext>(new DbContextOptions <hNextDbContext>());

            context.Setup(c => c.Cities).Returns(dbSet.Object);
            ICountryRepository repository = new CountryRepository(context.Object);

            //Act
            var result = repository.GetCitiesByName(countryId, name).Result;

            //Assert
            Assert.IsInstanceOfType(result, typeof(IEnumerable <City>));
            Assert.AreEqual(result.Count(), 1);
            Assert.IsTrue(result.All(c => c.CountryId == countryId));
            Assert.IsTrue(result.All(c => c.Name.ToLower().StartsWith(name.ToLower())));
        }
Пример #13
0
        public string GetCountryName(CountryRequest request)
        {
            var test   = new CountryRepository();
            var drzave = test.GetAll();

            return(drzave[0].Name);
        }
Пример #14
0
        public HttpResponseMessage GetInitials()
        {
            List <WorkingWeekDay> lstWeekDays = new List <WorkingWeekDay>();

            lstWeekDays = new WeekDaysRepository().GetWeekDaysDataList();

            List <FrayteCountryCode> lstCountry = new List <FrayteCountryCode>();

            lstCountry = new CountryRepository().lstCountry();

            List <FrayteCountryPhoneCode> lstCountryPhones = new List <FrayteCountryPhoneCode>();

            lstCountryPhones = new CountryRepository().GetCountryPhoneCodeList();

            List <TimeZoneModal> lstTimeZone = new List <TimeZoneModal>();

            lstTimeZone = new TimeZoneRepository().GetShipmentTimeZones();

            TimeZoneModal operationTimeZone = new TimeZoneRepository().GetOperationTimezone();

            return(this.Request.CreateResponse(
                       HttpStatusCode.OK,
                       new
            {
                WorkingWeekDays = lstWeekDays,
                Countries = lstCountry,
                TimeZones = lstTimeZone,
                CountryPhoneCodes = lstCountryPhones,
                OperationTimeZone = operationTimeZone
            }));
        }
Пример #15
0
        public void TestCitiesGetter()
        {
            //Arrange
            var regions = new List <City>
            {
                new City {
                    CountryId = 1
                },
                new City {
                    CountryId = 2
                },
                new City {
                    CountryId = 1
                },
                new City {
                    CountryId = 3
                }
            };
            var dbSet   = regions.AsQueryable().BuildMockDbSet();
            var context = new Mock <hNextDbContext>(new DbContextOptions <hNextDbContext>());

            context.Setup(c => c.Cities).Returns(dbSet.Object);
            CountryRepository repository = new CountryRepository(context.Object);

            //Act
            var result = repository.GetCities(1).Result;

            //Assert
            Assert.IsInstanceOfType(result, typeof(IEnumerable <City>));
            Assert.AreEqual(result.Count(), 2);
            Assert.IsTrue(result.All(c => c.CountryId == 1));
        }
        public void SetUp()
        {
            _container = new AutoMocker();

            var cacheProvider = _container.GetMock <ICacheProvider>();

            cacheProvider
            .Setup(provider => provider.GetOrAddAsync(
                       It.IsNotNull <CacheKey>(),
                       It.IsNotNull <Func <Task <Overture.ServiceModel.Country> > >(),
                       It.IsAny <Func <Overture.ServiceModel.Country, Task> >(),
                       It.IsAny <CacheKey>()))
            .Returns <CacheKey, Func <Task <Overture.ServiceModel.Country> >, Func <Overture.ServiceModel.Country, Task>, CacheKey>(
                (key, func, arg3, arg4) => func())
            .Verifiable();

            var overtureClient = _container.GetMock <IOvertureClient>();
            var dummyCountry   = new Overture.ServiceModel.Country();

            overtureClient
            .Setup(client => client.SendAsync(
                       It.IsNotNull <GetCountryRequest>()))
            .ReturnsAsync(dummyCountry)
            .Verifiable();

            _repository = _container.CreateInstance <CountryRepository>();
        }
Пример #17
0
        public void TestInitialize()
        {
            _context = new DbTestContext(Settings.Default.MainConnectionString);
            _fixture = new Fixture();

            _country = new CountryRepository(new SqlProcedureExecutor(Settings.Default.MainConnectionString));
        }
Пример #18
0
 public UnitOfWork(ClientsDbContext context)
 {
     _context  = context;
     Clients   = new ClientRepository(_context);
     Countries = new CountryRepository(_context);
     Cities    = new CityRepository(_context);
 }
Пример #19
0
        public async Task GetNonExistingPurchasersForCountryFromDatabaseTest()
        {
            // arrange
            HAVIdatabaseContext dbContext         = CreateDbContext();
            CountryRepository   countryRepository = new CountryRepository(dbContext);
            Country             country           = new Country()
            {
                Id          = 0,
                ProfileId   = 0,
                CountryName = "Name",
                CountryCode = "Code",
                Profile     = new Profile()
                {
                    Id       = 0,
                    Username = "******",
                    Password = "******",
                    Usertype = 0
                }
            };
            PurchaserRepository repository = new PurchaserRepository(dbContext);
            await countryRepository.AddCountry(country);

            // act
            List <Purchaser> result = await repository.GetPurchasersForCountry(1);

            // assert
            Assert.IsTrue(result.Count == 0);

            dbContext.Dispose();
        }
        public void CountryRepositoryFunction_AddCountry_FunctionalityTest()
        {
            GeographyContextTest context       = new GeographyContextTest(true);
            CountryRepository    countryRepo   = new CountryRepository(context);
            ContinentRepository  continentRepo = new ContinentRepository(context);

            Continent continent = new Continent("Continent60");

            context.SaveChanges();

            continentRepo.AddContinent(continent);
            context.SaveChanges();

            countryRepo.AddCountry(4, "Country60", 20, 30.0f);
            context.SaveChanges();

            var countryFromRepo = countryRepo.GetCountry(4, 2);

            continentRepo.HasCountries(4).Should().BeTrue();

            countryFromRepo.Name.Should().Be("Country60");
            countryFromRepo.Population.Should().Be(20);
            countryFromRepo.Surface.Should().Be(30.0f);
            countryFromRepo.Continent.Name.Should().Be("Continent60");
        }
Пример #21
0
        public IBasket ReadBasket(Int32 basketId, String definitionXml, CountryRepository countryRepository)
        {
            IBasket result;

            using (var reader = XmlReader.Create(new StringReader(definitionXml)))
            {
                var document             = new DocumentElement(reader);
                var expectedElementNames = new String[] { RegionBasket };
                var someElement          = document.MultilockOn(expectedElementNames);

                switch (someElement.Name)
                {
                case RegionBasket:
                {
                    result = this.ReadRegionBasket(someElement, basketId, countryRepository);
                    break;
                }

                default:
                {
                    throw new ApplicationException("Anthough \"" + someElement.Name + "\" is an expected XML element of some basket type, there is no handler for reading it.");
                }
                }
            }
            return(result);
        }
Пример #22
0
 public UnitOfWork(ApplicationContext context)
 {
     this.context = context;
     Cities       = new CityRepository(this.context);
     States       = new StateRespository(this.context);
     Countries    = new CountryRepository(this.context);
 }
Пример #23
0
        protected BasketRepository CreateBasketRepository(IDataManager manager, CountryRepository countryRepository, IMonitor monitor)
        {
            var basketInfos        = manager.GetAllBaskets();
            var countryBasketInfos = manager.GetAllCountryBaskets().ToDictionary(x => x.Id);
            var regionBasketInfos  = manager.GetAllRegionBaskets().ToDictionary(x => x.Id);

            var baskets = new List <IBasket>();

            foreach (var basketInfo in basketInfos)
            {
                var basketOpt = monitor.DefaultIfFails <IBasket>("Creating a basket of the \"" + basketInfo.Type + "\" type and \"" + basketInfo.Id + "\" ID.", delegate
                {
                    switch (basketInfo.Type)
                    {
                    case "country":
                        {
                            CountryBasketInfo countryBasketInfo;
                            if (countryBasketInfos.TryGetValue(basketInfo.Id, out countryBasketInfo))
                            {
                                var country = countryRepository.GetCountry(countryBasketInfo.IsoCountryCode);
                                return(new CountryBasket(basketInfo.Id, country));
                            }
                            else
                            {
                                throw new ApplicationException("There is no country basket with the \"" + basketInfo.Id + "\" ID.");
                            }
                        }

                    case "region":
                        {
                            RegionBasketInfo regionBasketInfo;
                            if (regionBasketInfos.TryGetValue(basketInfo.Id, out regionBasketInfo))
                            {
                                var result = this.xmlDeserializer.ReadBasket(basketInfo.Id, regionBasketInfo.DefinitionXml, countryRepository);
                                return(result);
                            }
                            else
                            {
                                throw new ApplicationException("There is no region basket with the \"" + basketInfo.Id + "\" ID.");
                            }
                        }

                    default:
                        {
                            throw new ApplicationException("Unexpected basket type \"" + basketInfo.Type + "\".");
                        }
                    }
                });
                if (basketOpt == null)
                {
                    continue;
                }
                baskets.Add(basketOpt);
            }


            var repository = new BasketRepository(baskets);

            return(repository);
        }
        private EuGatewayService CreateGatewayServiceAndDependencies(IGatewayHttpClient httpClient)
        {
            var translationsRepositoryMock = new Mock <IGenericRepository <Translation> >(MockBehavior.Strict);

            IOriginSpecificSettings originConfig = new AppSettingsConfig()
            {
                OriginCountryCode = _originCountry.Code.ToUpper()
            };
            var countryRepository = new CountryRepository(_dbContext, translationsRepositoryMock.Object, originConfig);
            var keysRepository    = new TemporaryExposureKeyRepository(_dbContext, countryRepository, _logger.Object);

            var signatureServiceMock = new Mock <ISignatureService>(MockBehavior.Strict);

            signatureServiceMock.Setup(sigService => sigService.Sign(It.IsAny <TemporaryExposureKeyGatewayBatchProtoDto>(), Domain.SortOrder.ASC))
            .Returns(new byte[] { 1, 2, 3, 4, 5, 6, 7 });

            var webContextReaderMock = new Mock <IGatewayWebContextReader>(MockBehavior.Strict);

            var loggerMock    = new Mock <ILogger <EuGatewayService> >(MockBehavior.Loose);
            var keyFilterMock = new Mock <IKeyFilter>(MockBehavior.Strict);
            var storeService  = new Mock <IEFGSKeyStoreService>(MockBehavior.Strict);

            var autoMapper = CreateAutoMapperWithDependencies(countryRepository);

            return(CreateGatewayService(keysRepository,
                                        signatureServiceMock.Object,
                                        autoMapper,
                                        httpClient,
                                        keyFilterMock.Object,
                                        webContextReaderMock.Object,
                                        storeService.Object,
                                        loggerMock.Object,
                                        _config
                                        ));
        }
Пример #25
0
        public ActionResult Edit(Guid?id)
        {
            funder_profile funderModel = null;
            var            countries   = new CountryRepository().Get().Select(x =>
                                                                              new SelectListItem {
                Text = x.Name, Value = x.Id + ""
            }).ToList();

            ViewBag.countries = countries;
            var cities = new CityRepository().Get().Distinct().Select(x =>
                                                                      new SelectListItem {
                Text = x.City + " (" + x.City_ar + ")", Value = x.City + "", Selected = x.City == "Jeddah"
            }).ToList();

            ViewBag.citiesdd = cities;
            if (id == null)
            {
                funderModel              = new funder_profile();
                funderModel.IsActive     = true;
                funderModel.Country      = 1192;
                funderModel.PhoneNumber  = "+966";
                funderModel.FunderMobile = "+966";
            }
            else
            {
                var funderRepo = new FunderRepository();
                funderModel          = funderRepo.GetByRowId(id.Value);
                funderModel.Password = EncryptionKeys.Decrypt(funderModel.user.Password);
            }
            return(View(funderModel));
        }
Пример #26
0
        static void Main(string[] args)
        {
            CountryRepository cr = new CountryRepository();

            // var jskl = cr.GetAll();
            //var res = cr.GetById(new Guid("0a0c816a-5e8f-404c-bc43-c3d76c8d8761"));
            Console.WriteLine("erewwe");

            ProductRepository pr = new ProductRepository();

            List <string> products = new List <string>()
            {
                "Мука", "Молоко", "Яйца", "Яблоко", "Сахар"
            };
            //var res = pr.GetNearest(products, 27.46238, 53.90399);
            var res = pr.GetAllProductsInShop(new Guid("b869aea6-a868-4180-b226-6eeac0292525"));

            //Product product = pr.GetCheapestInCity("Молоко", "Минск");
            //pr.GetById(new Guid("14781a9d-80f0-41f5-9a70-c93cd6d6f6dd"));

            //var jklj = pr.GetNearest("Молоко", 27.46238, 53.90399, 0, 5);

            //var sfdjkl = pr.GetCheapestInCity("Молоко", "Гродно", 0, 10);

            ShopRepository sr = new ShopRepository();

            //var rr = pr.GetOpt("Молоко", "Сыр", "Минск");
            //var res32 = sr.GetAllShopsInCity("Минск");

            CityRepository cp = new CityRepository();

            //var jklj = cp.GetAll("Беларусь");

            Console.WriteLine();
        }
Пример #27
0
        public void CreateDataSet()
        {
            var options = new DbContextOptionsBuilder <DigNDB_SmittestopContext>()
                          .UseInMemoryDatabase(nameof(EuGatewayServiceUploadTest))
                          .Options;

            _dbContext = new DigNDB_SmittestopContext(options);
            _dbContext.Database.EnsureDeleted();

            _temporaryExposureKeyRepositoryLogger = new Mock <ILogger <TemporaryExposureKeyRepository> >(MockBehavior.Loose);
            _loggerGatewayWebContextReader        = new Mock <ILogger <GatewayWebContextReader> >();
            var translationsRepositoryMock = new Mock <IGenericRepository <Translation> >(MockBehavior.Strict);

            _countryRepository = new CountryRepository(_dbContext, translationsRepositoryMock.Object, new AppSettingsConfig());
            _autoMapper        = CreateAutoMapperWithDependencies(_countryRepository);

            _config = new EuGatewayConfig()
            {
                AuthenticationCertificateFingerprint = "AuthenticationCertificateFingerprint",
                SigningCertificateFingerprint        = "SigningCertificateFingerprint",
                Url = "http://netcompany.pl",
            };

            _epochConverter = new EpochConverter();

            _denmark = TestCountryBuilder.Denmark.Build();
            _poland  = TestCountryBuilder.Poland.Build();
            _germany = TestCountryBuilder.Germany.Build();
            _latviaDisabledDownload = TestCountryBuilder.Latvia
                                      .SetIsPullingFromGatewayEnabled(false)
                                      .Build();

            _dbContext.AddRange(_denmark, _poland, _germany, _latviaDisabledDownload);
            _dbContext.SaveChanges();
        }
Пример #28
0
        /// <summary>
        /// get selectable customers by country
        /// </summary>
        /// <param name="countryId"></param>
        /// <returns></returns>
        public List <SelectListItem> GetSelectableCustomersByCountry(Guid countryId)
        {
            var customers = new List <SelectListItem>();

            var _countryRepository = new CountryRepository();

            try
            {
                var country = _countryRepository.GetCountry(countryId);

                var customerAddresses = _dynamicsContext.RM00102_CustomerAddress.Where(x => x.COUNTRY.Replace(" ", string.Empty).ToLower() == country.Name.Replace(" ", string.Empty).ToLower()).ToList();

                foreach (var customerAddress in customerAddresses)
                {
                    var customer = GetCustomer(customerAddress.CUSTNMBR);

                    if (customer != null && customer.INACTIVE != 1 && customer.CUSTCLAS.Replace(" ", string.Empty).ToLower().Equals("foundry"))
                    {
                        var selectListItem = new SelectListItem()
                        {
                            Text = customer.SHRTNAME, Value = customer.CUSTNMBR.TrimEnd()
                        };

                        customers.Add(selectListItem);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.ErrorFormat("Error getting customers: {0} ", ex.ToString());
            }

            return(customers.OrderBy(z => z.Text).ToList());
        }
Пример #29
0
        public List <Country> SelectAllCuntries()
        {
            var returnedEntities = new List <Country>();

            try
            {
                using (var repository = new CountryRepository())
                {
                    foreach (var entity in repository.SelectAll())
                    {
                        //entity.NetSalary = GetNetSalary(entity.GrossSalary, entity.Age);
                        returnedEntities.Add(entity);
                    }
                }

                return(returnedEntities);
            }
            catch (Exception ex)
            {
                //Log exception error
                _loggingHandler.LogEntry(ExceptionHandler.GetExceptionMessageFormatted(ex), true);

                throw new Exception("BusinessLogic:CountryBusiness::SelectAllCountry::Error occured.", ex);
            }
        }
Пример #30
0
        public void Get_Returns_Sorted_Items()
        {
            var data = new List <Country>
            {
                new Country {
                    IsoCode = "BB", Name = "YYY"
                },
                new Country {
                    IsoCode = "AA", Name = "XXX"
                },
                new Country {
                    IsoCode = "CC", Name = "UUU"
                },
            };

            var mockSet     = new Mock <DbSet <Country> >().SetupData(data);
            var mockContext = new Mock <CountryContext>();

            mockContext.Setup(c => c.Countries).Returns(mockSet.Object);

            var service = new CountryRepository(mockContext.Object);

            // Act
            var items = service.Get().ToList();

            Assert.IsNotNull(items);
            Assert.AreEqual(items.Count, data.Count);
            Assert.AreEqual(items[0].IsoCode, "AA");
            Assert.AreEqual(items[1].IsoCode, "BB");
            Assert.AreEqual(items[2].IsoCode, "CC");
        }
Пример #31
0
        public async Task FindAsync_Returns_Sorted_FoundByIsoCode()
        {
            var data = new List <Country>
            {
                new Country {
                    IsoCode = "CC", Name = "UUU"
                },
                new Country {
                    IsoCode = "BB", Name = "XXX"
                },
                new Country {
                    IsoCode = "DD", Name = "YYY"
                },
                new Country {
                    IsoCode = "AA", Name = "YYY"
                },
            };

            var mockSet     = new Mock <DbSet <Country> >().SetupData(data);
            var mockContext = new Mock <CountryContext>();

            mockContext.Setup(c => c.Countries).Returns(mockSet.Object);

            var service = new CountryRepository(mockContext.Object);

            // Act
            var items = (await service.FindAsync(new string[] { "BB", "CC" })).ToList();

            Assert.IsNotNull(items);
            Assert.AreEqual(items.Count, 2);
            Assert.AreEqual(items[0].IsoCode, "BB");
            Assert.AreEqual(items[1].IsoCode, "CC");
        }
Пример #32
0
        public void Add_AddsItemToDbSet()
        {
            var newCountry = new Country()
            {
                CountryId = 4,
                IsoCode   = "DD",
                Name      = "TestName"
            };

            var mockSet = new Mock <DbSet <Country> >().SetupData(new List <Country>());

            mockSet.Setup(m => m.Add(It.IsAny <Country>())).Returns(newCountry);

            var mockContext = new Mock <CountryContext>();

            mockContext.Setup(c => c.Set <Country>()).Returns(mockSet.Object);

            var service = new CountryRepository(mockContext.Object);

            // Act
            var item = service.Add(newCountry);

            mockSet.Verify(m => m.Add(newCountry), Times.Once);
            Assert.IsNotNull(item);
            Assert.AreEqual(item.IsoCode, newCountry.IsoCode);
            Assert.AreEqual(item.Name, newCountry.Name);
        }
Пример #33
0
        public async Task GetAsync_ById_Returns_FoundItem()
        {
            var data = new List <Country>
            {
                new Country {
                    CountryId = 2, IsoCode = "BB", Name = "YYY"
                },
                new Country {
                    CountryId = 1, IsoCode = "AA", Name = "XXX"
                },
                new Country {
                    CountryId = 3, IsoCode = "CC", Name = "UUU"
                },
            };

            var mockSet = new Mock <DbSet <Country> >().SetupData(data,
                                                                  objects => data.SingleOrDefault(d => d.CountryId == (long)objects.First()));
            var mockContext = new Mock <CountryContext>();

            mockContext.Setup(c => c.Countries).Returns(mockSet.Object);
            mockContext.Setup(c => c.Set <Country>()).Returns(mockSet.Object);

            var service = new CountryRepository(mockContext.Object);

            // Act
            var item = await service.GetAsync(2);

            Assert.IsNotNull(item);
            Assert.AreEqual(item.IsoCode, "BB");
        }
        public void WhenGettingAllRecords_ThenAllRecordsAreReturned()
        {
            var repository = new CountryRepository(new MileageStatsDbContext());

            var countries = repository.GetAll();

            Assert.NotNull(countries);
            Assert.Equal(238, countries.Count());
        }
Пример #35
0
        public void WhenGettingAllRecords_ThenRecordsIncludeName()
        {
            var repository = new CountryRepository();

            var countries = repository.GetAll().ToList();

            Assert.NotNull(countries);
            Assert.Equal("Afghanistan", countries[0].Name);
        }
Пример #36
0
        public void WhenGettingAllRecords_ThenRecordsIncludeRegionCode()
        {
            var repository = new CountryRepository();

            var countries = repository.GetAll().ToList();

            Assert.NotNull(countries);
            Assert.Equal("AF", countries[0].TwoLetterRegionCode);
        }
Пример #37
0
        public void WhenGettingAllRecords_ThenAllRecordsAreReturned()
        {
            var repository = new CountryRepository();

            var countries = repository.GetAll();

            Assert.NotNull(countries);
            Assert.Equal(127, countries.Count());
        }
        public StyledList()
        {
            this.InitializeComponent();
            this.DataContext = this;
            var countries = new CountryRepository().GetCountries();
            foreach (var country in countries)
            {
                Countries.Add(country);
            }

        }
        public void CountryRepositoryGetMethodReturnNullWhenIdIsEmpty()
        {
            //Arrange
            var unitOfWork = new MainBCUnitOfWork();
            var countryRepository = new CountryRepository(unitOfWork);

            //Act
            var country = countryRepository.Get(Guid.Empty);

            //Assert
            Assert.IsNull(country);
        }
Пример #40
0
        public static CountryResponse AddCountry(CountryRequest request)
        {
            var response = new CountryResponse();
            var countryRepository = new CountryRepository();
            try
            {
                var newCountry = new country
                                  {
                                      country_name = request.CountryName,
                                      created_date = DateTime.Now,
                                      modified_date = DateTime.Now,
                                      modified_by = request.ModifiedBy
                                  };
                countryRepository.Add(newCountry);
                countryRepository.SaveChanges();
            }
            catch (InvalidOperationException exc)
            {
                log.Error(exc);
                response.Message = exc.Message;
                response.Acknowledge = AcknowledgeType.FAILURE;
            }
            catch (ArgumentNullException exc)
            {
                log.Error(exc);
                response.Message = exc.Message;
                response.Acknowledge = AcknowledgeType.FAILURE;
            }
            catch (NullReferenceException exc)
            {
                log.Error(exc);
                response.Message = exc.Message;
                response.Acknowledge = AcknowledgeType.FAILURE;
            }
            catch (OptimisticConcurrencyException exc)
            {
                log.Error(exc);
                response.Message = exc.Message;
                response.Acknowledge = AcknowledgeType.FAILURE;
            }
            catch (UpdateException exc)
            {
                log.Error(exc);
                response.Message = exc.Message;
                response.Acknowledge = AcknowledgeType.FAILURE;
            }
            finally
            {
                countryRepository.Dispose();
            }

            return response;
        }
Пример #41
0
 public UnitOfWork()
 {
     _context = new ApplicationDbContext();
     Projects = new ProjectRepository(_context);
     Practices = new PracticeRepository(_context);
     Users = new UserRepository(_context);
     PracticeUsers = new PracticeUserRepository(_context);
     Features = new FeatureRepository(_context);
     FeatureUsers = new FeatureUserRepository(_context);
     Experiences = new ExperienceRepository(_context);
     Communications = new CommunicationRespository(_context);
     Countries = new CountryRepository(_context);
 }
        public void Initialize()
        {
            try
            {
                EffortProviderConfiguration.RegisterProvider();
                connection = Effort.DbConnectionFactory.CreateTransient();
                databaseContext = new TestContext(connection);
                objRepo = new CountryRepository(databaseContext);
            }
            catch (Exception ex) {

            }
        }
        public void CountryRepositoryFilterMethodReturnEntitisWithSatisfiedFilter()
        {
            //Arrange
            var unitOfWork = new MainBCUnitOfWork();
            ICountryRepository countryRepository = new CountryRepository(unitOfWork);

            //Act
            var result =countryRepository.GetFiltered(c=>c.CountryName.Contains("EU"));

            //Assert
            Assert.IsNotNull(result);
            Assert.IsTrue(result.All(c=>c.CountryName.Contains("EU")));
        }
        public void CountryRepositoryGetAllReturnMaterializedAllItems()
        {
            //Arrange
            var unitOfWork = new MainBCUnitOfWork();
            var countryRepository = new CountryRepository(unitOfWork);

            //Act
            var allItems = countryRepository.GetAll();

            //Assert
            Assert.IsNotNull(allItems);
            Assert.IsTrue(allItems.Any());
        }
        public void CountryRepositoryAddNewItemSaveItem()
        {
            //Arrange
            var unitOfWork = new MainBCUnitOfWork();
            var countryRepository = new CountryRepository(unitOfWork);

            var country = new Country("France", "fr-FR");
            country.GenerateNewIdentity();

            //Act
            countryRepository.Add(country);
            unitOfWork.Commit();
        }
        public void CountryRepositoryGetMethodReturnMaterializedEntityById()
        {
            //Arrange
            var unitOfWork = new MainBCUnitOfWork();
            var countryRepository = new CountryRepository(unitOfWork);
            var countryId = new Guid("32BB805F-40A4-4C37-AA96-B7945C8C385C");

            //Act
            var country = countryRepository.Get(countryId);
            
            //Assert
            Assert.IsNotNull(country);
            Assert.IsTrue(country.Id == countryId);
        }
        public void CountryRepositoryAllMatchingMethodReturnEntitiesWithSatisfiedCriteria()
        {
            //Arrange
            var unitOfWork = new MainBCUnitOfWork();
            ICountryRepository countryRepository = new CountryRepository(unitOfWork);

            string textToFind = "ain";
            var spec = CountrySpecifications.CountryFullText(textToFind);

            //Act
            var result = countryRepository.AllMatching(spec);

            //Assert
            Assert.IsNotNull(result.All(c=>c.CountryISOCode.Contains(textToFind) || c.CountryName.Contains(textToFind)));
        }
Пример #48
0
 public void A_RegisteredCountry_creates_a_new_country_in_the_database()
 {
     var bootStrapper = new BootStrapper();
     bootStrapper.StartServices();
     var serviceEvents = bootStrapper.GetService<IServiceEvents>();
     //1.- Create message
     var aggr = GenerateRandomAggregate();
     var message = GenerateMessage(aggr);
     //2.- Emit message
     serviceEvents.AddIncommingEvent(new IncommingEvent { @event = message });
     //3.- Load the saved country
     var repository = new CountryRepository(_configuration.TestServer);
     var country = repository.Get(aggr.Id);
     //4.- Check equality
     Assert.True(ObjectExtension.AreEqual(aggr, country));
 }
Пример #49
0
        public void CountryArrayTest()
        {
            const int contryId = 10000;
            var country = TestEntities.CreateCountry(contryId, "EnglishName1", "CountryName1");
            var seriesIdList = new List<int> {1, 2, 3, 4, 5, 6};

            country.AddSeriesIdRange(seriesIdList);
            int listCount = seriesIdList.Count;

            var sessionFactory = SessionFactory.CreateSessionFactory(true);
            using (var session = sessionFactory.OpenSession())
            {
                session.SaveOrUpdate(country);
                session.Flush();
            }

            var repository = new CountryRepository(SessionManager.CurrentSession);
            var fromDb = repository.GetCountryByHtId(contryId);
            Assert.True(fromDb.SupportedSeriesId.Count == listCount);
        }
Пример #50
0
        public void A_UnregisteredCountry_modifies_Existing_country_in_the_database()
        {
            var bootStrapper = new BootStrapper();
            bootStrapper.StartServices();
            var serviceEvents = bootStrapper.GetService<IServiceEvents>();
            //1.- Create message
            var aggr = GenerateRandomAggregate();

            //2.- Create the tuple in the database
            var repository = new CountryRepository(_configuration.TestServer);
            repository.Insert(aggr);

            //2.- Emit message
            var message = GenerateMessage(aggr);
            message.MessageType = typeof(UnregisteredCountry).Name;
            serviceEvents.AddIncommingEvent(new IncommingEvent { @event = message });

            var country = repository.Get(aggr.Id);
            Assert.Null(country);
            
        }
        public override void MigrateLeagueDetails(int countryId)
        {
            var countryRepository = new CountryRepository(Session);
            var country = countryRepository.GetCountryByHtId(countryId);

            foreach (var series in country.SupportedSeriesId)
            {
                if (country.Series.FirstOrDefault(s => s.HtSeriesId == series.HtSeriesId) == null)
                {
                    var htseries = ReadSeriesDetails(series.HtSeriesId);
                    country.AddSeries(new Series
                                          {
                                              HtSeriesId = htseries.LeagueLevelUnitID,
                                              LeagueLevel = (short)htseries.LeagueLevel,
                                              LeagueLevelUnitName = htseries.LeagueLevelUnitName
                                          });
                }
            }
            countryRepository.SaveUpdate(country);
            Session.Flush();
        }
Пример #52
0
        public void CountriesCRUDTest()
        {
            var sessionFactory = SessionFactory.CreateSessionFactory(true);

            const string country1 = "CountryName1";
            const string country2 = "CountryName2";

            var countries = new List<Country>
                                          { TestEntities.CreateCountry(10000, "EnglishName1", country1),
                                            TestEntities.CreateCountry(10001, "EnglishName2", country2)
                                          };
            var session = SessionManager.CurrentSession;
            var repository = new CountryRepository(session);
            repository.SaveUpdateCountries(countries);

            var fromDb = repository.GetAll();
            Assert.True(fromDb.ToList().Count(c => c.CountryName == country1 || c.CountryName == country2) == 2 );

            var updateCountry = countries.First();

            const string country3 = "CountryName3";
            const string englishName3 = "EnglishName3";
            updateCountry.EnglishName = englishName3;
            updateCountry.CountryName = country3;

            repository.SaveUpdate(updateCountry);

            var updatedCountry = repository.GetById(updateCountry.CountryId);
            Assert.True(updatedCountry.CountryName == updateCountry.CountryName);
            Assert.True(updatedCountry.EnglishName == updateCountry.EnglishName);

            foreach (var country in countries)
            {
                repository.Delete(country);
            }
            session.Flush();

            fromDb = repository.GetAll();
            Assert.True(fromDb.ToList().Count(c => c.CountryName == country1 || c.CountryName == country2) == 0);
        }
        public void CountryRepositoryRemoveItemDeleteIt()
        {
            //Arrange
            var unitOfWork = new MainBCUnitOfWork();
            var countryRepository = new CountryRepository(unitOfWork);

            var country = new Country("England", "en-EN");
            country.GenerateNewIdentity();
            
            countryRepository.Add(country);
            countryRepository.UnitOfWork.Commit();

            //Act
            countryRepository.Remove(country);
            unitOfWork.Commit();
        }
        public void LoadChart(UserModel currentUser)
        {
            try
            {
                this.DrillChartIds = (this.DrillOverride) ? this.Id.ToString() : this.DrillChartIds;
                List<ChartParameter> chartParams = null;
                ChartDataSet lastDs = null;
                SandlerModels.DataIntegration.DataQueries queries = new SandlerModels.DataIntegration.DataQueries();

                AppointmentSourceRepository appointmentSource;
                ProductTypesRepository productTypesSource;
                IEnumerable<Tbl_ProductType> products;
                string searchForNewCompany,searchCompanies,franchiseeName, regionName, countryName;
                int yearToProcess, monthToProcess;
                switch ((ChartID)Enum.Parse(typeof(ChartID), this.Id.ToString(), true))
                {
                    #region ProductsReports Logic
                    case ChartID.ProductMarginContributionByProductByMonth:
                        productTypesSource = new ProductTypesRepository();

                        if (currentUser.Role == SandlerRoles.FranchiseeOwner || currentUser.Role == SandlerRoles.FranchiseeUser)
                            products = productTypesSource.GetWithFranchiseeId(currentUser.FranchiseeID);
                        else
                            products = productTypesSource.GetAll();

                        foreach (var record in products.Where(r => r.IsActive == true).AsEnumerable())
                        {
                            this.Categories.Add(new Category { Label = record.ProductTypeName });
                        }
                        chartParams = new List<ChartParameter>();
                        chartParams.Add(new ChartParameter { Value = "-2", Color = "3300ff" });
                        chartParams.Add(new ChartParameter { Value = "-1", Color = "ff6600" });
                        chartParams.Add(new ChartParameter { Value = "0", Color = "32df00" });

                        foreach (ChartParameter parameter in chartParams)
                        {
                            try
                            {
                                IEnumerable<SandlerModels.DataIntegration.ProductTypeVM> productSalesCollection = queries.GetProductSalesByMonth(currentUser, DateTime.Now.AddMonths(int.Parse(parameter.Value)).Month);
                                if (productSalesCollection != null)
                                {
                                    var productSales = from record in productSalesCollection
                                                       select new { Category = record.ProductTypeName, Value = record.AvgPrice };

                                    this.DataSetCollection.Add(new ChartDataSet { Color = parameter.Color, SeriesName = DateTime.Now.AddMonths(int.Parse(parameter.Value)).ToString("MMM") });

                                    foreach (Category category in this.Categories)
                                    {
                                        lastDs = this.DataSetCollection.Last();
                                        lastDs.SetsCollection.Add(new SetValue { Label = category.Label, Link = ChartHelper.GeneratePageLink(lastDs.SeriesName, this.DrillChartIds) });
                                    }

                                    foreach (var record in productSales)
                                    {
                                        foreach (SetValue set in lastDs.SetsCollection)
                                        {
                                            if (set.Label == record.Category)
                                                set.Value = record.Value.ToString();
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                throw new Exception("Error in ChartID.ProductMarginContributionByProductByMonth:" + ex.Message);
                            }
                            //}
                        }
                        break;
                    case ChartID.FirstSaleProductValueByProductByMonth:
                        productTypesSource = new ProductTypesRepository();

                        if (currentUser.Role == SandlerRoles.FranchiseeOwner || currentUser.Role == SandlerRoles.FranchiseeUser)
                            products = productTypesSource.GetWithFranchiseeId(currentUser.FranchiseeID);
                        else
                            products = productTypesSource.GetAll();

                        foreach (var record in products.Where(r => r.IsActive == true).AsEnumerable())
                        {
                            this.Categories.Add(new Category { Label = record.ProductTypeName });
                        }
                        chartParams = new List<ChartParameter>();
                        chartParams.Add(new ChartParameter { Value = "-2", Color = "3300ff" });
                        chartParams.Add(new ChartParameter { Value = "-1", Color = "ff6600" });
                        chartParams.Add(new ChartParameter { Value = "0", Color = "32df00" });

                        foreach (ChartParameter parameter in chartParams)
                        {
                            try
                            {
                                IEnumerable<SandlerModels.DataIntegration.ProductTypeVM> productSalesCollection = queries.GetProductFirstSalesByMonth(currentUser, DateTime.Now.AddMonths(int.Parse(parameter.Value)).Month);
                                if (productSalesCollection != null)
                                {
                                    var productSales = from record in productSalesCollection
                                                       select new { Category = record.ProductTypeName, Value = record.AvgPrice };

                                    this.DataSetCollection.Add(new ChartDataSet { Color = parameter.Color, SeriesName = DateTime.Now.AddMonths(int.Parse(parameter.Value)).ToString("MMM") });

                                    foreach (Category category in this.Categories)
                                    {
                                        lastDs = this.DataSetCollection.Last();
                                        lastDs.SetsCollection.Add(new SetValue { Label = category.Label, Link = ChartHelper.GeneratePageLink(lastDs.SeriesName, this.DrillChartIds) });
                                    }

                                    foreach (var record in productSales)
                                    {
                                        foreach (SetValue set in lastDs.SetsCollection)
                                        {
                                            if (set.Label == record.Category)
                                                set.Value = record.Value.ToString();
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                throw new Exception("Error in ChartID.FirstSaleProductValueByProductByMonth:" + ex.Message);
                            }
                            //}
                        }
                        break;
                    case ChartID.ProductSoldToCompanyByProductByMonth:
                        string companyName;
                        try
                        {
                            companyName = new CompaniesRepository().GetById(long.Parse(SearchParameter)).COMPANYNAME;
                            this.Caption = this.Caption.Replace("Company Name", companyName);
                            productTypesSource = new ProductTypesRepository();

                            if (currentUser.Role == SandlerRoles.FranchiseeOwner || currentUser.Role == SandlerRoles.FranchiseeUser)
                                products = productTypesSource.GetWithFranchiseeId(currentUser.FranchiseeID);
                            else
                                products = productTypesSource.GetAll();

                            foreach (var record in products.Where(r => r.IsActive == true).AsEnumerable())
                            {
                                this.Categories.Add(new Category { Label = record.ProductTypeName });
                            }
                            chartParams = new List<ChartParameter>();
                            chartParams.Add(new ChartParameter { Value = "-2", Color = "3300ff" });
                            chartParams.Add(new ChartParameter { Value = "-1", Color = "ff6600" });
                            chartParams.Add(new ChartParameter { Value = "0", Color = "32df00" });

                            foreach (ChartParameter parameter in chartParams)
                            {
                                IEnumerable<SandlerModels.DataIntegration.ProductTypeVM> productSalesCollection = queries.GetProductSoldByCompanyByMonth(currentUser, DateTime.Now.AddMonths(int.Parse(parameter.Value)).Month, int.Parse(this.SearchParameter));
                                if (productSalesCollection != null)
                                {
                                    var productSales = from record in productSalesCollection
                                                       select new { Category = record.ProductTypeName, Qty = record.Count };

                                    this.DataSetCollection.Add(new ChartDataSet { Color = parameter.Color, SeriesName = DateTime.Now.AddMonths(int.Parse(parameter.Value)).ToString("MMM") });

                                    foreach (Category category in this.Categories)
                                    {
                                        lastDs = this.DataSetCollection.Last();
                                        lastDs.SetsCollection.Add(new SetValue { Label = category.Label, Link = ChartHelper.GeneratePageLink(lastDs.SeriesName, this.DrillChartIds, "SoldByCompany.aspx?searchParameter=" + this.SearchParameter + "&") });
                                    }

                                    foreach (var record in productSales)
                                    {
                                        foreach (SetValue set in lastDs.SetsCollection)
                                        {
                                            if (set.Label == record.Category)
                                                set.Value = record.Qty.ToString();
                                        }
                                    }
                                }

                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Error in ChartID.ProductSoldToCompanyByProductByMonth:" + ex.Message);
                        }
                        break;
                    case ChartID.ProductSoldBySalesRepByProductByMonth:
                        this.Caption = this.Caption.Replace("Sales Rep", this.SearchParameter);
                        productTypesSource = new ProductTypesRepository();

                        if (currentUser.Role == SandlerRoles.FranchiseeOwner || currentUser.Role == SandlerRoles.FranchiseeUser)
                            products = productTypesSource.GetWithFranchiseeId(currentUser.FranchiseeID);
                        else
                            products = productTypesSource.GetAll();

                        foreach (var record in products.Where(r => r.IsActive == true).AsEnumerable())
                        {
                            this.Categories.Add(new Category { Label = record.ProductTypeName });
                        }
                        chartParams = new List<ChartParameter>();
                        chartParams.Add(new ChartParameter { Value = "-2", Color = "3300ff" });
                        chartParams.Add(new ChartParameter { Value = "-1", Color = "ff6600" });
                        chartParams.Add(new ChartParameter { Value = "0", Color = "32df00" });

                        foreach (ChartParameter parameter in chartParams)
                        {
                            try
                            {
                                IEnumerable<SandlerModels.DataIntegration.ProductTypeVM> productSalesCollection = queries.GetProductSoldBySalesRepByMonth(currentUser, DateTime.Now.AddMonths(int.Parse(parameter.Value)).Month, this.SearchParameter);
                                if (productSalesCollection != null)
                                {
                                    var productSales = from record in productSalesCollection
                                                       select new { Category = record.ProductTypeName, Qty = record.Count };

                                    this.DataSetCollection.Add(new ChartDataSet { Color = parameter.Color, SeriesName = DateTime.Now.AddMonths(int.Parse(parameter.Value)).ToString("MMM") });

                                    foreach (Category category in this.Categories)
                                    {
                                        lastDs = this.DataSetCollection.Last();
                                        lastDs.SetsCollection.Add(new SetValue { Label = category.Label, Link = ChartHelper.GeneratePageLink(lastDs.SeriesName, this.DrillChartIds, "SoldByCompanySalesRep.aspx?searchParameter=" + this.SearchParameter + "&") });
                                    }

                                    foreach (var record in productSales)
                                    {
                                        foreach (SetValue set in lastDs.SetsCollection)
                                        {
                                            if (set.Label == record.Category)
                                                set.Value = record.Qty.ToString();
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                throw new Exception("Error in ChartID.ProductSoldToCompanyByProductByMonth:" + ex.Message);
                            }
                            //}
                        }
                        break;
                    #endregion

                    #region ClientReports Logic
                    case ChartID.SalesTotalsByMonthQty:
                        string[] monthNames = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.MonthNames;

                        foreach (string monthName in monthNames) // writing out
                        {
                            if (!string.IsNullOrEmpty(monthName))
                                this.Categories.Add(new Category { Label = monthName.Substring(0, 3) });
                        }

                        chartParams = new List<ChartParameter>();
                        chartParams.Add(new ChartParameter { Value = (DateTime.Now.Year - 2).ToString(), Color = "3300ff" });
                        chartParams.Add(new ChartParameter { Value = (DateTime.Now.Year - 1).ToString(), Color = "ff6600" });
                        chartParams.Add(new ChartParameter { Value = DateTime.Now.Year.ToString(), Color = "32df00" });
                        IEnumerable<SandlerModels.DataIntegration.SalesTotalByMonthVM> salesTotalData;
                        foreach (ChartParameter parameter in chartParams)
                        {
                            try
                            {
                                salesTotalData = queries.GetSalesTotalByYear(currentUser, int.Parse(parameter.Value));
                                if (salesTotalData != null)
                                {
                                    var salesDataForAYear = from opportunity in salesTotalData
                                                            group opportunity by new { opportunity.CloseDate.Month }
                                                                into grp
                                                                select new { Count = grp.Count(), MonthName = ChartHelper.GetMonthName(grp.Key.Month) };

                                    this.DataSetCollection.Add(new ChartDataSet { Color = parameter.Color, SeriesName = parameter.Value });

                                    foreach (Category category in this.Categories)
                                    {
                                        lastDs = this.DataSetCollection.Last();
                                        lastDs.SetsCollection.Add(new SetValue { Label = category.Label });
                                    }

                                    foreach (var record in salesDataForAYear)
                                    {
                                        foreach (SetValue set in lastDs.SetsCollection)
                                        {
                                            if (set.Label == record.MonthName)
                                                set.Value = record.Count.ToString();
                                        }
                                    }
                                }
                                salesTotalData = null;
                            }
                            catch (Exception ex)
                            {
                            }
                        }
                        break;
                    case ChartID.CostOfSale:
                        IEnumerable<SandlerModels.DataIntegration.CostOfSaleVM> costofsaleData = queries.GetCostOfSale(currentUser);

                        this.DataSetCollection.Add(new ChartDataSet { Color = "0000FF", SeriesName = "Profit" });//0000FF blue
                        this.DataSetCollection.Add(new ChartDataSet { Color = "FF8C00", SeriesName = "Cost" });//FF8C00 darkorange
                        this.DataSetCollection.Add(new ChartDataSet { Color = "32CD32", SeriesName = "Revenue" });//32CD32 Lime green

                        foreach (SandlerModels.DataIntegration.CostOfSaleVM cosRecord in costofsaleData)
                        {
                            this.Categories.Add(new Category { Label = cosRecord.ProductName });
                            this.DataSetCollection[0].SetsCollection.Add(new SetValue { Value = cosRecord.Profit.ToString() });
                            this.DataSetCollection[1].SetsCollection.Add(new SetValue { Value = cosRecord.Cost.ToString() });
                            this.DataSetCollection[2].SetsCollection.Add(new SetValue { Value = cosRecord.Revenue.ToString() });

                        }

                        break;

                    #endregion

                    #region BenchmarkReports Logic
                    case ChartID.BenchmarkSalesRepFranchisee:
                        try
                        {
                            chartParams = new List<ChartParameter>();
                            chartParams.Add(new ChartParameter { Value = "-2" });
                            chartParams.Add(new ChartParameter { Value = "-1" });
                            chartParams.Add(new ChartParameter { Value = "0" });

                            franchiseeName = new FranchiseeRepository().GetById(currentUser.FranchiseeID).Name;
                            Caption = Caption.Replace("Sales Rep", SearchParameter).Replace("Name", franchiseeName);
                            IEnumerable<SandlerModels.DataIntegration.BenchMarkVM> salesRepToFranchiseeData;

                            this.DataSetCollection.Add(new ChartDataSet { Color = "4F94CD", SeriesName = "Franchisee" });//4F94CD steelblue3
                            this.DataSetCollection.Add(new ChartDataSet { Color = "FF8C00", SeriesName = "Rep" });//FF8C00 darkorange
                            Double totalValue = 0.0;
                            Double otherSalesRepsTotals = 0.0;
                            Double salesRepValue = 0.0;
                            foreach (ChartParameter parameter in chartParams)
                            {
                                salesRepToFranchiseeData = queries.GetBenchMarkSalesRepToFranchiseeByMonth(currentUser, DateTime.Now.AddMonths(int.Parse(parameter.Value)).Month);
                                totalValue = salesRepToFranchiseeData.Sum(r => r.Value);

                                this.Categories.Add(new Category { Label = DateTime.Now.AddMonths(int.Parse(parameter.Value)).ToString("MMM") });
                                otherSalesRepsTotals = (from record in salesRepToFranchiseeData.Where(r => r.KeyGroupId != SearchParameter)
                                              select record).Sum(r => r.Value);
                                this.DataSetCollection[0].SetsCollection.Add(new SetValue { Value = ((otherSalesRepsTotals / totalValue) * 100).ToString("f2"), Link = ChartHelper.GeneratePageLink(DateTime.Now.AddMonths(int.Parse(parameter.Value)).ToString("MMM"), this.DrillChartIds, "SalesRepToFranchisee.aspx?searchParameter=" + this.SearchParameter + "&") });

                                SandlerModels.DataIntegration.BenchMarkVM repRecord = salesRepToFranchiseeData.Where(r => r.KeyGroupId == SearchParameter).SingleOrDefault();
                                salesRepValue = (repRecord == null) ? 0.0 : repRecord.Value;
                                this.DataSetCollection[1].SetsCollection.Add(new SetValue { Value = ((salesRepValue / totalValue) * 100).ToString("f2"), Link = ChartHelper.GeneratePageLink(DateTime.Now.AddMonths(int.Parse(parameter.Value)).ToString("MMM"), this.DrillChartIds, "SalesRepToFranchisee.aspx?searchParameter=" + this.SearchParameter + "&") });
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Exception in ChartID.BenchmarkSalesRepFranchisee:" + ex.Message);
                        }
                        break;
                    case ChartID.BenchmarkFranchiseeRegion:
                        try
                        {
                            chartParams = new List<ChartParameter>();
                            chartParams.Add(new ChartParameter { Value = "-2" });
                            chartParams.Add(new ChartParameter { Value = "-1" });
                            chartParams.Add(new ChartParameter { Value = "0" });

                            franchiseeName = new FranchiseeRepository().GetById(int.Parse(SearchParameter)).Name;
                            regionName = new RegionRepository().GetById(currentUser.RegionID).Name;
                            Caption = Caption.Replace("Region Name", regionName).Replace("Franchisee Name", franchiseeName);
                            IEnumerable<SandlerModels.DataIntegration.BenchMarkVM> salesFranchiseeToRegionsData;

                            this.DataSetCollection.Add(new ChartDataSet { Color = "32df00", SeriesName = "Region" });
                            this.DataSetCollection.Add(new ChartDataSet { Color = "4F94CD", SeriesName = "Franchisee" });

                            Double totalValue = 0.0;
                            Double otherFranchiseesTotals = 0.0;
                            Double franchiseeValue = 0.0;
                            foreach (ChartParameter parameter in chartParams)
                            {
                                salesFranchiseeToRegionsData = queries.GetBenchMarkFranchiseeToRegionsByMonth(currentUser, DateTime.Now.AddMonths(int.Parse(parameter.Value)).Month);
                                totalValue = salesFranchiseeToRegionsData.Sum(r => r.Value);

                                this.Categories.Add(new Category { Label = DateTime.Now.AddMonths(int.Parse(parameter.Value)).ToString("MMM") });
                                otherFranchiseesTotals = (from record in salesFranchiseeToRegionsData.Where(r => r.KeyGroupId != SearchParameter)
                                              select record).Sum(r => r.Value);
                                this.DataSetCollection[0].SetsCollection.Add(new SetValue { Value = ((otherFranchiseesTotals / totalValue) * 100).ToString("f2"), Link = ChartHelper.GeneratePageLink(DateTime.Now.AddMonths(int.Parse(parameter.Value)).ToString("MMM"), this.DrillChartIds, "FranchiseeToRegion.aspx?searchParameter=" + this.SearchParameter + "&") });

                                SandlerModels.DataIntegration.BenchMarkVM franchiseeRecord = salesFranchiseeToRegionsData.Where(r => r.KeyGroupId == SearchParameter).SingleOrDefault();
                                franchiseeValue = (franchiseeRecord == null) ? 0.0 : franchiseeRecord.Value;
                                this.DataSetCollection[1].SetsCollection.Add(new SetValue { Value = ((franchiseeValue / totalValue) * 100).ToString("f2"), Link = ChartHelper.GeneratePageLink(DateTime.Now.AddMonths(int.Parse(parameter.Value)).ToString("MMM"), this.DrillChartIds, "FranchiseeToRegion.aspx?searchParameter=" + this.SearchParameter + "&") });
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Exception in ChartID.BenchmarkFranchiseeRegion:" + ex.Message);
                        }
                        break;
                    case ChartID.BenchmarkRegionCountry:
                        try
                        {
                            chartParams = new List<ChartParameter>();
                            chartParams.Add(new ChartParameter { Value = "-2" });
                            chartParams.Add(new ChartParameter { Value = "-1" });
                            chartParams.Add(new ChartParameter { Value = "0" });

                            regionName = new RegionRepository().GetById(int.Parse(SearchParameter)).Name;
                            countryName = new CountryRepository().GetById(currentUser.CountryID).Name;
                            Caption = Caption.Replace("Region Name", regionName).Replace("Country Name", countryName);
                            IEnumerable<SandlerModels.DataIntegration.BenchMarkVM> salesRegionToCountryData;

                            this.DataSetCollection.Add(new ChartDataSet { Color = "800080", SeriesName = "Country" });//800080 -- Purple
                            this.DataSetCollection.Add(new ChartDataSet { Color = "32df00", SeriesName = "Region" });

                            Double totalValue = 0.0;
                            Double otherRegionsTotal = 0.0;
                            Double regionValue = 0.0;
                            foreach (ChartParameter parameter in chartParams)
                            {
                                salesRegionToCountryData = queries.GetBenchMarkRegionToCountryByMonth(currentUser, DateTime.Now.AddMonths(int.Parse(parameter.Value)).Month);
                                totalValue = salesRegionToCountryData.Sum(r => r.Value);

                                this.Categories.Add(new Category { Label = DateTime.Now.AddMonths(int.Parse(parameter.Value)).ToString("MMM") });
                                otherRegionsTotal = (from record in salesRegionToCountryData.Where(r => r.KeyGroupId != SearchParameter)
                                                          select record).Sum(r => r.Value);
                                this.DataSetCollection[0].SetsCollection.Add(new SetValue { Value = ((otherRegionsTotal / totalValue) * 100).ToString("f2"), Link = ChartHelper.GeneratePageLink(DateTime.Now.AddMonths(int.Parse(parameter.Value)).ToString("MMM"), this.DrillChartIds, "RegionToCountry.aspx?searchParameter=" + this.SearchParameter + "&") });

                                SandlerModels.DataIntegration.BenchMarkVM regionRecord = salesRegionToCountryData.Where(r => r.KeyGroupId == SearchParameter).SingleOrDefault();
                                regionValue = (regionRecord == null) ? 0.0 : regionRecord.Value;
                                this.DataSetCollection[1].SetsCollection.Add(new SetValue { Value = ((regionValue / totalValue) * 100).ToString("f2"), Link = ChartHelper.GeneratePageLink(DateTime.Now.AddMonths(int.Parse(parameter.Value)).ToString("MMM"), this.DrillChartIds, "RegionToCountry.aspx?searchParameter=" + this.SearchParameter + "&") });
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Exception in ChartID.BenchmarkRegionCountry:" + ex.Message);
                        }
                        break;
                    case ChartID.BenchmarkCountryAll:
                        try
                        {
                            chartParams = new List<ChartParameter>();
                            chartParams.Add(new ChartParameter { Value = "-2" });
                            chartParams.Add(new ChartParameter { Value = "-1" });
                            chartParams.Add(new ChartParameter { Value = "0" });

                            countryName = new CountryRepository().GetById(int.Parse(SearchParameter)).Name;
                            Caption = Caption.Replace("Country Name", countryName);
                            IEnumerable<SandlerModels.DataIntegration.BenchMarkVM> salesCountryAllData;

                            this.DataSetCollection.Add(new ChartDataSet { Color = "800080", SeriesName = "All" });//800080 -- Purple
                            this.DataSetCollection.Add(new ChartDataSet { Color = "00CED1", SeriesName = "Country" });//00CED1 -- darkturquoise

                            Double totalValue = 0.0;
                            Double otherCountriesTotal = 0.0;
                            Double countryValue = 0.0;
                            foreach (ChartParameter parameter in chartParams)
                            {
                                salesCountryAllData = queries.GetBenchMarkCountryAllByMonth(DateTime.Now.AddMonths(int.Parse(parameter.Value)).Month);
                                totalValue = salesCountryAllData.Sum(r => r.Value);

                                this.Categories.Add(new Category { Label = DateTime.Now.AddMonths(int.Parse(parameter.Value)).ToString("MMM") });
                                otherCountriesTotal = (from record in salesCountryAllData.Where(r => r.KeyGroupId != SearchParameter)
                                                          select record).Sum(r => r.Value);
                                this.DataSetCollection[0].SetsCollection.Add(new SetValue { Value = ((otherCountriesTotal / totalValue) * 100).ToString("f2"), Link = ChartHelper.GeneratePageLink(DateTime.Now.AddMonths(int.Parse(parameter.Value)).ToString("MMM"), this.DrillChartIds, "CountryToAll.aspx?searchParameter=" + this.SearchParameter + "&") });

                                SandlerModels.DataIntegration.BenchMarkVM franchiseeRecord = salesCountryAllData.Where(r => r.KeyGroupId == SearchParameter).SingleOrDefault();
                                countryValue = (franchiseeRecord == null) ? 0.0 : franchiseeRecord.Value;
                                this.DataSetCollection[1].SetsCollection.Add(new SetValue { Value = ((countryValue / totalValue) * 100).ToString("f2"), Link = ChartHelper.GeneratePageLink(DateTime.Now.AddMonths(int.Parse(parameter.Value)).ToString("MMM"), this.DrillChartIds, "CountryToAll.aspx?searchParameter=" + this.SearchParameter + "&") });
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Exception in ChartID.BenchmarkCountryAll:" + ex.Message);
                        }
                        break;
                    #endregion

                    #region AdHocReports logic
                    case ChartID.ClosedSalesAnalysis:
                        productTypesSource = new ProductTypesRepository();
                        if (currentUser.Role == SandlerRoles.FranchiseeOwner || currentUser.Role == SandlerRoles.FranchiseeUser)
                            products = productTypesSource.GetWithFranchiseeId(currentUser.FranchiseeID);
                        else
                            products = productTypesSource.GetAll();

                        if (this.SubType == ChartSubType.SalesValueOppSource || this.SubType == ChartSubType.SalesQuantityOppSource)
                        {
                            foreach (var record in new OppSourceeRepository().GetAll())
                            {
                                this.Categories.Add(new Category { Label = record.Name });
                            }
                        }
                        else if (this.SubType == ChartSubType.SalesValueOpportunityType || this.SubType == ChartSubType.SalesQuantityOpportunityType)
                        {
                            foreach (var record in new OpprtunityTypesRepository().GetAll())
                            {
                                this.Categories.Add(new Category { Label = record.Name });
                            }
                        }
                        else
                        {
                            foreach (var record in products.Where(r => r.IsActive == true).AsEnumerable())
                            {
                                this.Categories.Add(new Category { Label = record.ProductTypeName });
                            }
                        }
                        chartParams = new List<ChartParameter>();
                        chartParams.Add(new ChartParameter { Value = "-2", Color = "8A4B08" });
                        chartParams.Add(new ChartParameter { Value = "-1", Color = "0000FF" });
                        chartParams.Add(new ChartParameter { Value = "0", Color = "ff9966" });
                        searchForNewCompany = (HttpContext.Current.Session["searchForNewCompany"] == null) ? "" : HttpContext.Current.Session["searchForNewCompany"].ToString();
                        searchCompanies = (HttpContext.Current.Session["searchCompanies"] == null) ? "" : HttpContext.Current.Session["searchCompanies"].ToString();

                        foreach (ChartParameter parameter in chartParams)
                        {
                            try
                            {
                                if (this.SubType == ChartSubType.ProductsSoldBySalesValue)
                                    this.Caption = "Sales Value By Product (By Month)";
                                if (this.SubType == ChartSubType.ProductsSoldBySalesQuantity)
                                    this.Caption = "Sales Quantity By Product (By Month)";

                                if (this.SubType == ChartSubType.SalesValueOppSource)
                                    this.Caption = "Sales Value By Opportunity Source (By Month)";
                                if (this.SubType == ChartSubType.SalesQuantityOppSource)
                                    this.Caption = "Sales Quantity By Opportunity Source (By Month)";

                                if (this.SubType == ChartSubType.SalesValueOpportunityType)
                                    this.Caption = "Sales Value By Opportunity Type (By Month)";
                                if (this.SubType == ChartSubType.SalesQuantityOpportunityType)
                                    this.Caption = "Sales Quantity By Opportunity Type (By Month)";

                                IEnumerable<SandlerModels.DataIntegration.ClosedSalesVM> productTypeVMCollection = queries.GetClosedSalesAnalysis(currentUser, DateTime.Now.AddMonths(int.Parse(parameter.Value)).Month, this.SubType.ToString(), searchForNewCompany, searchCompanies);
                                if (productTypeVMCollection != null)
                                {
                                    var clientsWithProducts = from record in productTypeVMCollection
                                                              select new { Category = record.Name, SalesValue = record.AvgPrice, SalesQuantity = record.Count };

                                    this.DataSetCollection.Add(new ChartDataSet { Color = parameter.Color, SeriesName = DateTime.Now.AddMonths(int.Parse(parameter.Value)).ToString("MMM") });

                                    string link = "";
                                    foreach (Category category in this.Categories)
                                    {
                                        lastDs = this.DataSetCollection.Last();
                                        link = string.Format("{0}?{1}={2}&{3}={4}&SubType={5}", "ClosedSalesAnalysis.aspx", ConfigurationManager.AppSettings["QueryStringParamDrillChartIDs"], this.DrillChartIds, ConfigurationManager.AppSettings["QueryStringParamDrillBy"], lastDs.SeriesName, this.SubType.ToString());
                                        //lastDs.SetsCollection.Add(new SetValue { Label = category.Label, Link = ChartHelper.GeneratePageLink(lastDs.SeriesName, this.DrillChartIds, this.SubType.ToString()) });
                                        lastDs.SetsCollection.Add(new SetValue { Label = category.Label, Link = link });
                                    }

                                    foreach (var record in clientsWithProducts)
                                    {
                                        foreach (SetValue set in lastDs.SetsCollection)
                                        {
                                            if (set.Label == record.Category)
                                            {
                                                if (this.SubType.ToString().Contains("Value"))
                                                {
                                                    set.Value = record.SalesValue.ToString();
                                                }
                                                if (this.SubType.ToString().Contains("Quantity"))
                                                {
                                                    set.Value = record.SalesQuantity.ToString();
                                                }

                                            }
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                throw new Exception("Error in ChartID.NewClientsByProductTypeMonth:" + ex.Message);
                            }
                        }
                        //}

                        break;
                    case ChartID.PipelineOpportunityAnalysis:
                        productTypesSource = new ProductTypesRepository();
                        if (currentUser.Role == SandlerRoles.FranchiseeOwner || currentUser.Role == SandlerRoles.FranchiseeUser)
                            products = productTypesSource.GetWithFranchiseeId(currentUser.FranchiseeID);
                        else
                            products = productTypesSource.GetAll();

                        if (this.SubType == ChartSubType.SalesValueOppSource || this.SubType == ChartSubType.SalesQuantityOppSource)
                        {
                            foreach (var record in new OppSourceeRepository().GetAll())
                            {
                                this.Categories.Add(new Category { Label = record.Name });
                            }
                        }
                        else if (this.SubType == ChartSubType.SalesValueOpportunityType || this.SubType == ChartSubType.SalesQuantityOpportunityType)
                        {
                            foreach (var record in new OpprtunityTypesRepository().GetAll())
                            {
                                this.Categories.Add(new Category { Label = record.Name });
                            }
                        }
                        else
                        {
                            foreach (var record in products.Where(r => r.IsActive == true).AsEnumerable())
                            {
                                this.Categories.Add(new Category { Label = record.ProductTypeName });
                            }
                        }
                        chartParams = new List<ChartParameter>();
                        chartParams.Add(new ChartParameter { Value = "0", Color = "8A4B08" });
                        chartParams.Add(new ChartParameter { Value = "1", Color = "0000FF" });
                        chartParams.Add(new ChartParameter { Value = "2", Color = "ff9966" });
                        searchForNewCompany = (HttpContext.Current.Session["searchForNewCompany"] == null) ? "" : HttpContext.Current.Session["searchForNewCompany"].ToString();
                        searchCompanies = (HttpContext.Current.Session["searchCompanies"] == null) ? "" : HttpContext.Current.Session["searchCompanies"].ToString();

                        foreach (ChartParameter parameter in chartParams)
                        {
                            try
                            {
                                if (this.SubType == ChartSubType.ProductsSoldBySalesValue)
                                    this.Caption = "Sales Value By Product (By Month)";
                                if (this.SubType == ChartSubType.ProductsSoldBySalesQuantity)
                                    this.Caption = "Sales Quantity By Product (By Month)";

                                if (this.SubType == ChartSubType.SalesValueOppSource)
                                    this.Caption = "Sales Value By Opportunity Source (By Month)";
                                if (this.SubType == ChartSubType.SalesQuantityOppSource)
                                    this.Caption = "Sales Quantity By Opportunity Source (By Month)";

                                if (this.SubType == ChartSubType.SalesValueOpportunityType)
                                    this.Caption = "Sales Value By Opportunity Type (By Month)";
                                if (this.SubType == ChartSubType.SalesQuantityOpportunityType)
                                    this.Caption = "Sales Quantity By Opportunity Type (By Month)";

                                IEnumerable<SandlerModels.DataIntegration.PipelineOppAnalysisVM> productTypeVMCollection = queries.GetPipelineOpportunityAnalysis(currentUser, DateTime.Now.AddMonths(int.Parse(parameter.Value)).Month, this.SubType.ToString(), searchForNewCompany, searchCompanies);
                                if (productTypeVMCollection != null)
                                {
                                    var clientsWithProducts = from record in productTypeVMCollection
                                                              select new { Category = record.Name, SalesValue = record.AvgPrice, SalesQuantity = record.Count };

                                    this.DataSetCollection.Add(new ChartDataSet { Color = parameter.Color, SeriesName = DateTime.Now.AddMonths(int.Parse(parameter.Value)).ToString("MMM") });

                                    string link = "";
                                    foreach (Category category in this.Categories)
                                    {
                                        lastDs = this.DataSetCollection.Last();
                                        link = string.Format("{0}?{1}={2}&{3}={4}&SubType={5}", "PipelineOppAnalysis.aspx", ConfigurationManager.AppSettings["QueryStringParamDrillChartIDs"], this.DrillChartIds, ConfigurationManager.AppSettings["QueryStringParamDrillBy"], lastDs.SeriesName, this.SubType.ToString());
                                        lastDs.SetsCollection.Add(new SetValue { Label = category.Label, Link = link });
                                    }

                                    foreach (var record in clientsWithProducts)
                                    {
                                        foreach (SetValue set in lastDs.SetsCollection)
                                        {
                                            if (set.Label == record.Category)
                                            {
                                                if (this.SubType.ToString().Contains("Value"))
                                                {
                                                    set.Value = record.SalesValue.ToString();
                                                }
                                                if (this.SubType.ToString().Contains("Quantity"))
                                                {
                                                    set.Value = record.SalesQuantity.ToString();
                                                }

                                            }
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                throw new Exception("Error in ChartID.PipelineOpportunityAnalysis:" + ex.Message);
                            }
                        }
                        //}

                        break;
                    #endregion

                    #region FranchiseeReports Logic

                    case ChartID.NewAppointmentsBySourceMonth:
                        appointmentSource = new AppointmentSourceRepository();
                        foreach (var record in appointmentSource.GetAll().Where(r => r.IsActive == true).AsEnumerable())
                        {
                            this.Categories.Add(new Category { Label = record.ApptSourceName });
                        }

                        if (MonthYearCombinations == null)
                        {
                            chartParams = new List<ChartParameter>();
                            chartParams.Add(new ChartParameter { Value = "-2", Color = "3300ff" });
                            chartParams.Add(new ChartParameter { Value = "-1", Color = "ff6600" });
                            chartParams.Add(new ChartParameter { Value = "0", Color = "32df00" });
                        }
                        else
                            chartParams = MonthYearCombinations;

                        foreach (ChartParameter parameter in chartParams)
                        {
                            try
                            {
                                yearToProcess = (string.IsNullOrEmpty(parameter.YearVal)) ? ((DateTime.Now.AddMonths(int.Parse(parameter.Value)).Month > DateTime.Now.Month) ? DateTime.Now.AddYears(-1).Year : DateTime.Now.Year) : int.Parse(parameter.YearVal);
                                monthToProcess = (MonthYearCombinations == null) ? DateTime.Now.AddMonths(int.Parse(parameter.Value)).Month : int.Parse(parameter.Value);
                                IEnumerable<SandlerModels.DataIntegration.AppointmentSourceVM> appointmentSourceVMcollection = queries.GetNewAppointmentSource(currentUser, monthToProcess,yearToProcess);
                                if (appointmentSourceVMcollection != null)
                                {
                                    var newAppointments = from record in appointmentSourceVMcollection
                                                          select new { Category = record.SourceName, Count = record.Count };

                                    this.DataSetCollection.Add(new ChartDataSet { Color = parameter.Color, SeriesName = ChartHelper.GetMonthName(monthToProcess) + " (" + yearToProcess.ToString() + ")"});

                                    foreach (Category category in this.Categories)
                                    {
                                        lastDs = this.DataSetCollection.Last();
                                        lastDs.SetsCollection.Add(new SetValue { Label = category.Label, Link = (currentUser.Role == SandlerRoles.Client) ? "" : ChartHelper.GeneratePageLink(ChartHelper.GetMonthName(monthToProcess), this.DrillChartIds) });
                                    }

                                    foreach (var record in newAppointments)
                                    {
                                        foreach (SetValue set in lastDs.SetsCollection)
                                        {
                                            if (set.Label == record.Category)
                                                set.Value = record.Count.ToString();
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                throw new Exception("Error in ChartID.NewAppointmentsBySourceMonth:" + ex.Message);
                            }
                            //}
                        }
                        break;

                    case ChartID.NewClientsByProductTypeMonth:

                        productTypesSource = new ProductTypesRepository();

                        if (currentUser.Role == SandlerRoles.FranchiseeOwner || currentUser.Role == SandlerRoles.FranchiseeUser)
                            products = productTypesSource.GetWithFranchiseeId(currentUser.FranchiseeID);
                        else
                            products = productTypesSource.GetAll();
                        foreach (var record in products.Where(r => r.IsActive == true).AsEnumerable())
                        {
                            this.Categories.Add(new Category { Label = record.ProductTypeName });
                        }

                        if (MonthYearCombinations == null)
                        {
                            chartParams = new List<ChartParameter>();
                            chartParams.Add(new ChartParameter { Value = "-2", Color = "8A4B08" });
                            chartParams.Add(new ChartParameter { Value = "-1", Color = "0000FF" });
                            chartParams.Add(new ChartParameter { Value = "0", Color = "ff9966" });
                        }
                        else
                            chartParams = MonthYearCombinations;

                        foreach (ChartParameter parameter in chartParams)
                        {
                            try
                            {
                                yearToProcess = (string.IsNullOrEmpty(parameter.YearVal)) ? ((DateTime.Now.AddMonths(int.Parse(parameter.Value)).Month > DateTime.Now.Month) ? DateTime.Now.AddYears(-1).Year : DateTime.Now.Year) : int.Parse(parameter.YearVal);
                                monthToProcess = (MonthYearCombinations == null) ? DateTime.Now.AddMonths(int.Parse(parameter.Value)).Month : int.Parse(parameter.Value);

                                IEnumerable<SandlerModels.DataIntegration.ProductTypeVM> productTypeVMCollection = queries.GetNewClientsByProductType(currentUser, monthToProcess,yearToProcess);
                                if (productTypeVMCollection != null)
                                {
                                    var newClientsByProducts = from record in productTypeVMCollection
                                                               select new { Category = record.ProductTypeName, Count = record.Count };

                                    this.DataSetCollection.Add(new ChartDataSet { Color = parameter.Color, SeriesName = ChartHelper.GetMonthName(monthToProcess) + " (" + yearToProcess.ToString() + ")" });

                                    foreach (Category category in this.Categories)
                                    {
                                        lastDs = this.DataSetCollection.Last();
                                        lastDs.SetsCollection.Add(new SetValue { Label = category.Label, Link = (currentUser.Role == SandlerRoles.Client) ? "" : ChartHelper.GeneratePageLink(ChartHelper.GetMonthName(monthToProcess), this.DrillChartIds) });
                                    }

                                    foreach (var record in newClientsByProducts)
                                    {
                                        foreach (SetValue set in lastDs.SetsCollection)
                                        {
                                            if (set.Label == record.Category)
                                                set.Value = record.Count.ToString();
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                throw new Exception("Error in ChartID.NewClientsByProductTypeMonth:" + ex.Message);
                            }
                        }
                        //}

                        break;
                    case ChartID.NewClientQuantityAverageContractPriceByMonth:
                        if (MonthYearCombinations == null)
                        {
                            this.Categories.Add(new Category { Label = DateTime.Now.AddMonths(-2).ToString("MMM") });
                            this.Categories.Add(new Category { Label = DateTime.Now.AddMonths(-1).ToString("MMM") });
                            this.Categories.Add(new Category { Label = DateTime.Now.AddMonths(0).ToString("MMM") });
                        }
                        else
                        {
                            foreach (ChartParameter param in MonthYearCombinations)
                            {
                                this.Categories.Add(new Category { Label = ChartHelper.GetMonthName(int.Parse(param.Value)) });
                            }
                        }

                        this.DataSetCollection.Add(new ChartDataSet { Color = "0000FF", SeriesName = "New Clients" });
                        this.DataSetCollection.Add(new ChartDataSet { Color = "ff6600", SeriesName = "Ave Contract Price" });

                        foreach (Category catagory in this.Categories)
                        {
                            try
                            {
                                yearToProcess = (DateTime.ParseExact(catagory.Label, "MMM", null).Month > DateTime.Now.Month) ? DateTime.Now.AddYears(-1).Year : DateTime.Now.Year;
                                monthToProcess = DateTime.ParseExact(catagory.Label, "MMM", null).Month;

                                int newClients = queries.GetNewClientCount(currentUser, monthToProcess, yearToProcess);
                                long aveContractPrice = queries.GetAveContractPrice(currentUser, monthToProcess, yearToProcess);

                                if (newClients > 0 && aveContractPrice > 0)
                                {
                                    this.DataSetCollection[0].SetsCollection.Add(new SetValue { Value = newClients.ToString(), Link = (currentUser.Role == SandlerRoles.Client) ? "" : ChartHelper.GeneratePageLink(catagory.Label, this.DrillChartIds) });
                                    this.DataSetCollection[1].SetsCollection.Add(new SetValue { Value = (aveContractPrice / 5).ToString(), Link = (currentUser.Role == SandlerRoles.Client) ? "" : ChartHelper.GeneratePageLink(catagory.Label, this.DrillChartIds) });
                                }
                                else
                                {
                                    this.DataSetCollection[0].SetsCollection.Add(new SetValue());
                                    this.DataSetCollection[1].SetsCollection.Add(new SetValue());

                                }
                                if (MonthYearCombinations != null) //Check CustomChart reports request
                                {
                                    //After done process category change its label with month and year combination
                                    catagory.Label = catagory.Label + "(" + yearToProcess.ToString() + ")";
                                }
                            }
                            catch (System.InvalidOperationException)
                            {

                            }

                        }
                        break;
                    case ChartID.ClassHeadcountByCourseIndustryMonth:
                        this.Categories.Add(new Category { Label = DateTime.Now.AddMonths(-2).ToString("MMM") });
                        this.Categories.Add(new Category { Label = DateTime.Now.AddMonths(-1).ToString("MMM") });
                        this.Categories.Add(new Category { Label = DateTime.Now.AddMonths(0).ToString("MMM") });

                        this.DataSetCollection.Add(new ChartDataSet { Color = "ff6600", SeriesName = "Course" });
                        this.DataSetCollection.Add(new ChartDataSet { Color = "32df00", SeriesName = "Industry" });

                        foreach (Category catagory in this.Categories)
                        {
                            try
                            {
                                int classHeadCountsCourse = queries.GetClassHeadCountsCourse(currentUser, DateTime.ParseExact(catagory.Label, "MMM", null).Month);

                                int classHeadCountsIndustry = queries.GetClassHeadCountsIndustry(currentUser, DateTime.ParseExact(catagory.Label, "MMM", null).Month);

                                //if (classHeadCountsCourse > 0 && classHeadCountsIndustry > 0)
                                //{
                                    this.DataSetCollection[0].SetsCollection.Add(new SetValue { Value = (classHeadCountsCourse > 0) ? classHeadCountsCourse.ToString():"", Link = (currentUser.Role == SandlerRoles.Client) ? "" : (classHeadCountsCourse > 0) ? ChartHelper.GeneratePageLink(catagory.Label, this.DrillChartIds):"" });
                                    this.DataSetCollection[1].SetsCollection.Add(new SetValue { Value = (classHeadCountsIndustry > 0) ? classHeadCountsIndustry.ToString():"", Link = (currentUser.Role == SandlerRoles.Client) ? "" : (classHeadCountsIndustry > 0) ? ChartHelper.GeneratePageLink(catagory.Label, this.DrillChartIds):"" });
                                //}
                            }
                            catch (System.InvalidOperationException)
                            {

                            }

                        }
                        //}
                        break;

                    case ChartID.ActualDollarsBookedComparisonGoal:
                        this.Categories.Add(new Category { Label = DateTime.Now.AddMonths(-4).ToString("MMM") });
                        this.Categories.Add(new Category { Label = DateTime.Now.AddMonths(-3).ToString("MMM") });
                        this.Categories.Add(new Category { Label = DateTime.Now.AddMonths(-2).ToString("MMM") });
                        this.Categories.Add(new Category { Label = DateTime.Now.AddMonths(-1).ToString("MMM") });
                        this.Categories.Add(new Category { Label = DateTime.Now.AddMonths(0).ToString("MMM") });
                        this.Categories.Add(new Category { Label = DateTime.Now.AddMonths(1).ToString("MMM") });

                        this.DataSetCollection.Add(new ChartDataSet { Color = "0066ff", SeriesName = "$$Booked" });
                        this.DataSetCollection.Add(new ChartDataSet { Color = "ffff99", SeriesName = "% of Goal" });

                        foreach (Category catagory in this.Categories)
                        {
                            try
                            {
                                long actualDollarsBooked = queries.GetActualDollarsBooked(currentUser, DateTime.ParseExact(catagory.Label, "MMM", null).Month);

                                long goalOfDollarsBooked = queries.GetGoalOfDollarsBooked(currentUser, DateTime.ParseExact(catagory.Label, "MMM", null).Month);

                                //if (actualDollarsBooked > 0 && goalOfDollarsBooked > 0)
                                //{
                                this.DataSetCollection[0].SetsCollection.Add(new SetValue { Label = catagory.Label, Value = actualDollarsBooked.ToString(), Link = (currentUser.Role == SandlerRoles.Client) ? "" : ChartHelper.GeneratePageLink("", this.DrillChartIds) });
                                this.DataSetCollection[1].SetsCollection.Add(new SetValue { Label = catagory.Label, Value = ((Convert.ToDouble(actualDollarsBooked) / Convert.ToDouble(goalOfDollarsBooked)) * 100).ToString("#.##"), Link = (currentUser.Role == SandlerRoles.Client) ? "" : ChartHelper.GeneratePageLink("", this.DrillChartIds) });
                                //}
                            }
                            catch (System.InvalidOperationException)
                            {

                            }

                        }
                        break;
                    #endregion

                    case ChartID.GapAnalysis:
                        this.Categories.Add(new Category { Label = "Sales Cycle Time" });
                        this.Categories.Add(new Category { Label = "Sales Efficiency" });
                        this.Categories.Add(new Category { Label = "Sales Qualification" });
                        this.Categories.Add(new Category { Label = "Sales Rep Retention" });
                        this.Categories.Add(new Category { Label = "Quota Achievement" });
                        this.Categories.Add(new Category { Label = "Sandler Trng Benefits" });

                        GATracker gaRecord = null;
                        GapAnalysisRepository gaData = new GapAnalysisRepository();

                        this.DataSetCollection.Add(new ChartDataSet { Color = "0000FF", SeriesName = "As-Is" });
                        this.DataSetCollection.Add(new ChartDataSet { Color = "8A4B08", SeriesName = "To-Be" });

                        gaRecord = gaData.GetGATrackerById(int.Parse(SearchParameter));
                        if (gaRecord != null)
                        {
                            this.DataSetCollection[0].SetsCollection.Add(new SetValue { Value = gaRecord.AsIsSalesCycleTimePercentVal.Value.ToString(), Link = "GapAnalysisCreate.aspx" });
                            this.DataSetCollection[0].SetsCollection.Add(new SetValue { Value = gaRecord.AsIsSalesEfficiencyPercentVal.Value.ToString(), Link = "GapAnalysisCreate.aspx" });
                            this.DataSetCollection[0].SetsCollection.Add(new SetValue { Value = gaRecord.AsIsSalesQualificationPercentVal.ToString(), Link = "GapAnalysisCreate.aspx" });
                            this.DataSetCollection[0].SetsCollection.Add(new SetValue { Value = gaRecord.AsIsSalesRepRetentionPercentVal.ToString(), Link = "GapAnalysisCreate.aspx" });
                            this.DataSetCollection[0].SetsCollection.Add(new SetValue { Value = gaRecord.AsIsQuotaAchievementPercentVal.ToString(), Link = "GapAnalysisCreate.aspx" });
                            this.DataSetCollection[0].SetsCollection.Add(new SetValue { Value = gaRecord.AsIsTrngBenefitsPercentVal.ToString(), Link = "GapAnalysisCreate.aspx" });

                            this.DataSetCollection[1].SetsCollection.Add(new SetValue { Value = gaRecord.ToBeSalesCycleTimePercentVal.ToString(), Link = "GapAnalysisCreate.aspx" });
                            this.DataSetCollection[1].SetsCollection.Add(new SetValue { Value = gaRecord.ToBeSalesEfficiencyPercentVal.ToString(), Link = "GapAnalysisCreate.aspx" });
                            this.DataSetCollection[1].SetsCollection.Add(new SetValue { Value = gaRecord.ToBeSalesQualificationPercentVal.ToString(), Link = "GapAnalysisCreate.aspx" });
                            this.DataSetCollection[1].SetsCollection.Add(new SetValue { Value = gaRecord.ToBeSalesRepRetentionPercentVal.ToString(), Link = "GapAnalysisCreate.aspx" });
                            this.DataSetCollection[1].SetsCollection.Add(new SetValue { Value = gaRecord.ToBeQuotaAchievementPercentVal.ToString(), Link = "GapAnalysisCreate.aspx" });
                            this.DataSetCollection[1].SetsCollection.Add(new SetValue { Value = gaRecord.ToBeTrngBenefitsPercentVal.ToString(), Link = "GapAnalysisCreate.aspx" });
                        }
                        break;
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 public void Initialize()
 {
     databaseContext = new TestContext();
     objRepo = new CountryRepository(databaseContext);
 }
        public new void LoadChart(UserModel currentUser)
        {
            try
            {
                this.DrillChartIds = (this.DrillOverride) ? this.Id.ToString() : this.DrillChartIds;
                int colorIndex = 0;
                SandlerModels.DataIntegration.DataQueries queries = new SandlerModels.DataIntegration.DataQueries();
                AppointmentSourceRepository appointmentSource = null;
                ProductTypesRepository productTypesSource = null;
                string[] colors = null;
                string searchForNewCompany, searchCompanies;
                var totalPrice = 0.0;
                var totalCounts = 0.0;
                IEnumerable<Tbl_ProductType> products;
                string companyName = "";
                string franchiseeName = "";
                string regionName = "";
                string countryName = "";
                int monthToProcess, yearToProcess;
                double avgValue;
                switch (this.Id)
                {
                    case ChartID.SalesCycleTimeMain:
                        IEnumerable<SandlerModels.DataIntegration.SalesCycleTimePortfolioVM> salesCyclePortfolio = queries.GetSalesCycleTimePortfolio(currentUser);
                        int totalCount = salesCyclePortfolio.Count();
                        if (salesCyclePortfolio != null)
                        {
                            var salesCycleData = from opportunity in salesCyclePortfolio
                                                 group opportunity by new { opportunity.MultipleOfSixVal }
                                                     into grp
                                                     select new { Legend = ChartHelper.GetSCTimeLegend(grp.Key.MultipleOfSixVal), Count = grp.Count() * 100 / totalCount };

                            colors = new string[] { "CC6600", "9900CC", "FF3300", "0099FF", "00CC66", "FFFF00", "CC6600", "9900CC" };

                            foreach (var record in salesCycleData)
                            {
                                this.SetsCollection.Add(new SetValue { Color = colors.GetValue(colorIndex).ToString(), Label = record.Legend, Value = record.Count.ToString() });
                                colorIndex++;
                            }

                        }
                        break;

                    #region AdHocReports logic
                    case ChartID.PipelineOpportunityAnalysisBySource:
                        if (this.SubType == ChartSubType.ProductsSoldBySalesValue)
                            this.Caption = "Sales Value Percentage By Product";
                        if (this.SubType == ChartSubType.ProductsSoldBySalesQuantity)
                            this.Caption = "Sales Quantity Percentage By Product";

                        if (this.SubType == ChartSubType.SalesValueOppSource)
                            this.Caption = "Sales Value Percentage By Opportunity Source";
                        if (this.SubType == ChartSubType.SalesQuantityOppSource)
                            this.Caption = "Sales Quantity Percentage By Opportunity Source";

                        if (this.SubType == ChartSubType.SalesValueOpportunityType)
                            this.Caption = "Sales Value Percentage By Opportunity Source";
                        if (this.SubType == ChartSubType.SalesQuantityOpportunityType)
                            this.Caption = "Sales Quantity Percentage By Opportunity Source";

                        searchForNewCompany = (HttpContext.Current.Session["searchForNewCompany"] == null) ? "" : HttpContext.Current.Session["searchForNewCompany"].ToString();
                        searchCompanies = (HttpContext.Current.Session["searchCompanies"] == null) ? "" : HttpContext.Current.Session["searchCompanies"].ToString();

                        IEnumerable<SandlerModels.DataIntegration.PipelineOppAnalysisVM> pipelineSalesVMCollection = queries.GetPipelineOpportunityAnalysis(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month, this.SubType.ToString(), searchForNewCompany, searchCompanies);
                        colors = new string[] { "CC6600", "9900CC", "FF3300", "0099FF", "00CC66", "FFFF00", "CC6600", "9900CC" };
                        totalPrice = pipelineSalesVMCollection.Sum(r => r.AvgPrice);
                        totalCounts = pipelineSalesVMCollection.Sum(r => r.Count);
                        productTypesSource = new ProductTypesRepository();

                        if (currentUser.Role == SandlerRoles.FranchiseeOwner || currentUser.Role == SandlerRoles.FranchiseeUser)
                            products = productTypesSource.GetWithFranchiseeId(currentUser.FranchiseeID);
                        else
                            products = productTypesSource.GetAll().Where(r => r.IsActive == true);

                        if (this.SubType == ChartSubType.SalesValueOppSource || this.SubType == ChartSubType.SalesQuantityOppSource)
                        {
                            foreach (var record in new OpprtunitySourceRepository().GetAll())
                            {
                                try
                                {
                                    if (pipelineSalesVMCollection.Single(r => r.Name == record.Name) != null)
                                    {
                                        if (this.SubType.ToString().Contains("Value"))
                                            this.SetsCollection.Add(new SetValue { Color = colors.GetValue(colorIndex).ToString(), Label = record.Name, Value = (((pipelineSalesVMCollection.Single(r => r.Name == record.Name).AvgPrice) / totalPrice) * 100).ToString() });
                                        else
                                        {
                                            this.SetsCollection.Add(new SetValue { Color = colors.GetValue(colorIndex).ToString(), Label = record.Name, Value = ((pipelineSalesVMCollection.Single(r => r.Name == record.Name).Count * 100) / totalCounts).ToString() });
                                        }
                                    }
                                }
                                catch (System.InvalidOperationException)
                                {

                                }
                                colorIndex++;
                            }
                        }
                        else if (this.SubType == ChartSubType.SalesValueOpportunityType || this.SubType == ChartSubType.SalesQuantityOpportunityType)
                        {
                            foreach (var record in new OpprtunityTypesRepository().GetAll())
                            {
                                try
                                {
                                    if (pipelineSalesVMCollection.Single(r => r.Name == record.Name) != null)
                                    {
                                        if (this.SubType.ToString().Contains("Value"))
                                            this.SetsCollection.Add(new SetValue { Color = colors.GetValue(colorIndex).ToString(), Label = record.Name, Value = (((pipelineSalesVMCollection.Single(r => r.Name == record.Name).AvgPrice) / totalPrice) * 100).ToString() });
                                        else
                                        {
                                            this.SetsCollection.Add(new SetValue { Color = colors.GetValue(colorIndex).ToString(), Label = record.Name, Value = ((pipelineSalesVMCollection.Single(r => r.Name == record.Name).Count * 100) / totalCounts).ToString() });
                                        }
                                    }
                                }
                                catch (System.InvalidOperationException)
                                {

                                }
                                colorIndex++;
                            }
                        }
                        else
                        {
                            int tmpCount = 0;
                            foreach (var record in products.AsEnumerable())
                            {
                                try
                                {
                                    if (pipelineSalesVMCollection.Single(r => r.Name == record.ProductTypeName) != null)
                                    {
                                        if (this.SubType.ToString().Contains("Value"))
                                            this.SetsCollection.Add(new SetValue { Color = record.ColorCode, Label = record.ProductTypeName, Value = (((pipelineSalesVMCollection.Single(r => r.Name == record.ProductTypeName).AvgPrice) / totalPrice) * 100).ToString() });
                                        else
                                        {
                                            tmpCount = pipelineSalesVMCollection.Single(r => r.Name == record.ProductTypeName).Count;
                                            this.SetsCollection.Add(new SetValue { Color = record.ColorCode, Label = record.ProductTypeName, Value = ((tmpCount * 100) / totalCounts).ToString() });
                                        }
                                    }
                                }
                                catch (System.InvalidOperationException)
                                {

                                }
                            }
                        }
                        //}
                        break;
                    case ChartID.ClosedSalesAnalysisBySource:
                        if (this.SubType == ChartSubType.ProductsSoldBySalesValue)
                            this.Caption = "Sales Value Percentage By Product";
                        if (this.SubType == ChartSubType.ProductsSoldBySalesQuantity)
                            this.Caption = "Sales Quantity Percentage By Product";

                        if (this.SubType == ChartSubType.SalesValueOppSource)
                            this.Caption = "Sales Value Percentage By Opportunity Source";
                        if (this.SubType == ChartSubType.SalesQuantityOppSource)
                            this.Caption = "Sales Quantity Percentage By Opportunity Source";

                        if (this.SubType == ChartSubType.SalesValueOpportunityType)
                            this.Caption = "Sales Value Percentage By Opportunity Source";
                        if (this.SubType == ChartSubType.SalesQuantityOpportunityType)
                            this.Caption = "Sales Quantity Percentage By Opportunity Source";

                        searchForNewCompany = (HttpContext.Current.Session["searchForNewCompany"] == null) ? "" : HttpContext.Current.Session["searchForNewCompany"].ToString();
                        searchCompanies = (HttpContext.Current.Session["searchCompanies"] == null) ? "" : HttpContext.Current.Session["searchCompanies"].ToString();

                        IEnumerable<SandlerModels.DataIntegration.ClosedSalesVM> productTypeVMCollection = queries.GetClosedSalesAnalysis(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month, this.SubType.ToString(), searchForNewCompany, searchCompanies);
                        colors = new string[] { "CC6600", "9900CC", "FF3300", "0099FF", "00CC66", "FFFF00", "CC6600", "9900CC" };
                        totalPrice = productTypeVMCollection.Sum(r => r.AvgPrice);
                        totalCounts = productTypeVMCollection.Sum(r => r.Count);
                        productTypesSource = new ProductTypesRepository();

                        if (currentUser.Role == SandlerRoles.FranchiseeOwner || currentUser.Role == SandlerRoles.FranchiseeUser)
                            products = productTypesSource.GetWithFranchiseeId(currentUser.FranchiseeID);
                        else
                            products = productTypesSource.GetAll().Where(r => r.IsActive == true);

                        if (this.SubType == ChartSubType.SalesValueOppSource || this.SubType == ChartSubType.SalesQuantityOppSource)
                        {
                            foreach (var record in new OpprtunitySourceRepository().GetAll())
                            {
                                try
                                {
                                    if (productTypeVMCollection.Single(r => r.Name == record.Name) != null)
                                    {
                                        if (this.SubType.ToString().Contains("Value"))
                                            this.SetsCollection.Add(new SetValue { Color = colors.GetValue(colorIndex).ToString(), Label = record.Name, Value = (((productTypeVMCollection.Single(r => r.Name == record.Name).AvgPrice) / totalPrice) * 100).ToString() });
                                        else
                                        {
                                            this.SetsCollection.Add(new SetValue { Color = colors.GetValue(colorIndex).ToString(), Label = record.Name, Value = ((productTypeVMCollection.Single(r => r.Name == record.Name).Count * 100) / totalCounts).ToString() });
                                        }
                                    }
                                }
                                catch (System.InvalidOperationException)
                                {

                                }
                                colorIndex++;
                            }
                        }
                        else if (this.SubType == ChartSubType.SalesValueOpportunityType || this.SubType == ChartSubType.SalesQuantityOpportunityType)
                        {
                            foreach (var record in new OpprtunityTypesRepository().GetAll())
                            {
                                try
                                {
                                    if (productTypeVMCollection.Single(r => r.Name == record.Name) != null)
                                    {
                                        if (this.SubType.ToString().Contains("Value"))
                                            this.SetsCollection.Add(new SetValue { Color = colors.GetValue(colorIndex).ToString(), Label = record.Name, Value = (((productTypeVMCollection.Single(r => r.Name == record.Name).AvgPrice) / totalPrice) * 100).ToString() });
                                        else
                                        {
                                            this.SetsCollection.Add(new SetValue { Color = colors.GetValue(colorIndex).ToString(), Label = record.Name, Value = ((productTypeVMCollection.Single(r => r.Name == record.Name).Count * 100) / totalCounts).ToString() });
                                        }
                                    }
                                }
                                catch (System.InvalidOperationException)
                                {

                                }
                                colorIndex++;
                            }
                        }
                        else
                        {
                            int tmpCount = 0;
                            foreach (var record in products.AsEnumerable())
                            {
                                try
                                {
                                    if (productTypeVMCollection.Single(r => r.Name == record.ProductTypeName) != null)
                                    {
                                        if (this.SubType.ToString().Contains("Value"))
                                            this.SetsCollection.Add(new SetValue { Color = record.ColorCode, Label = record.ProductTypeName, Value = (((productTypeVMCollection.Single(r => r.Name == record.ProductTypeName).AvgPrice) / totalPrice) * 100).ToString() });
                                        else
                                        {
                                            tmpCount = productTypeVMCollection.Single(r => r.Name == record.ProductTypeName).Count;
                                            this.SetsCollection.Add(new SetValue { Color = record.ColorCode, Label = record.ProductTypeName, Value = ((tmpCount * 100) / totalCounts).ToString() });
                                        }
                                    }
                                }
                                catch (System.InvalidOperationException)
                                {

                                }
                            }
                        }
                        //}
                        break;
                    #endregion

                    #region FranchiseeReports logic
                    case ChartID.NewAppointmentsBySource:
                        monthToProcess = DateTime.ParseExact(this.DrillBy, "MMM", null).Month;
                        yearToProcess =  (monthToProcess > DateTime.Now.Month) ? DateTime.Now.AddYears(-1).Year : DateTime.Now.Year;

                        //if (queries.GetNewAppointmentSource(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month) != null)
                        //{
                        var NewAppointmentSource = from record in queries.GetNewAppointmentSource(currentUser, monthToProcess, yearToProcess)
                                                   select new { Category = record.SourceName, Count = record.Count };

                        totalCount = NewAppointmentSource.Sum(r => r.Count);

                        appointmentSource = new AppointmentSourceRepository();
                        foreach (var record in appointmentSource.GetAll().Where(r => r.IsActive == true).AsEnumerable())
                        {
                            try
                            {
                                if (NewAppointmentSource.Single(r => r.Category == record.ApptSourceName) != null)
                                {
                                    avgValue = NewAppointmentSource.Single(r => r.Category == record.ApptSourceName).Count * 100;
                                    avgValue = Math.Round(avgValue/totalCount,2);
                                    this.SetsCollection.Add(new SetValue { Color = record.ColorCode, Label = record.ApptSourceName, Value = avgValue.ToString("#.##") });
                                }
                            }
                            catch (System.InvalidOperationException)
                            {

                            }
                            colorIndex++;
                        }
                        //}
                        break;

                    case ChartID.NewClientByProductType:
                        //if (queries.GetNewClientsByProductType(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month) != null)
                        //{
                        monthToProcess = DateTime.ParseExact(this.DrillBy, "MMM", null).Month;
                        yearToProcess =  (monthToProcess > DateTime.Now.Month) ? DateTime.Now.AddYears(-1).Year : DateTime.Now.Year;

                        var NewClientsByProductType = from record in queries.GetNewClientsByProductType(currentUser,monthToProcess, yearToProcess )
                                                      select new { Category = record.ProductTypeName, Count = record.Count };
                        totalCount = NewClientsByProductType.Sum(r => r.Count);
                        productTypesSource = new ProductTypesRepository();

                        if (currentUser.Role == SandlerRoles.FranchiseeOwner || currentUser.Role == SandlerRoles.FranchiseeUser)
                            products = productTypesSource.GetWithFranchiseeId(currentUser.FranchiseeID);
                        else
                            products = productTypesSource.GetAll().Where(r => r.IsActive == true);

                        foreach (var record in products.AsEnumerable())
                        {
                            try
                            {
                                if (NewClientsByProductType.Single(r => r.Category == record.ProductTypeName) != null)
                                {
                                    avgValue = NewClientsByProductType.Single(r => r.Category == record.ProductTypeName).Count * 100;
                                    avgValue = Math.Round(avgValue / totalCount, 2);
                                    this.SetsCollection.Add(new SetValue { Color = record.ColorCode, Label = record.ProductTypeName, Value = avgValue.ToString("#.##")});
                                }
                            }
                            catch (System.InvalidOperationException)
                            {

                            }
                        }
                        //}
                        break;
                    case ChartID.NewClientQuantity:
                        //if (queries.NewClientsWithProductTypes(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month) != null)
                        //{
                        var NewClientsWithProductTypes = from record in queries.NewClientsWithProductTypes(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month)
                                                         select new { Category = record.ProductTypeName, Count = record.Count };

                        productTypesSource = new ProductTypesRepository();
                        totalCount = NewClientsWithProductTypes.Sum(r => r.Count);
                        if (currentUser.Role == SandlerRoles.FranchiseeOwner || currentUser.Role == SandlerRoles.FranchiseeUser)
                            products = productTypesSource.GetWithFranchiseeId(currentUser.FranchiseeID);
                        else
                            products = productTypesSource.GetAll().Where(r => r.IsActive == true);

                        foreach (var record in products.AsEnumerable())
                        {
                            try
                            {
                                if (NewClientsWithProductTypes.Single(r => r.Category == record.ProductTypeName) != null)
                                {
                                    avgValue = NewClientsWithProductTypes.Single(r => r.Category == record.ProductTypeName).Count * 100;
                                    avgValue = Math.Round(avgValue / totalCount, 2);
                                    this.SetsCollection.Add(new SetValue { Color = record.ColorCode, Label = record.ProductTypeName, Value = avgValue.ToString("#.##") });
                                }
                            }
                            catch (System.InvalidOperationException)
                            {

                            }
                        }
                        //}
                        break;

                    case ChartID.ContractPrice:

                        //if (queries.ContractPriceWithProductTypes(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month) != null)
                        //{
                        var ContractPriceWithProductTypes = from record in queries.ContractPriceWithProductTypes(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month)
                                                            select new { Category = record.ProductTypeName, AvgPrice = record.AvgPrice };

                        productTypesSource = new ProductTypesRepository();
                        totalPrice = ContractPriceWithProductTypes.Sum(r => r.AvgPrice);
                        if (currentUser.Role == SandlerRoles.FranchiseeOwner || currentUser.Role == SandlerRoles.FranchiseeUser)
                            products = productTypesSource.GetWithFranchiseeId(currentUser.FranchiseeID);
                        else
                            products = productTypesSource.GetAll().Where(r => r.IsActive == true);

                        foreach (var record in products.AsEnumerable())
                        {
                            try
                            {
                                if (ContractPriceWithProductTypes.Single(r => r.Category == record.ProductTypeName) != null)
                                {
                                    avgValue = ContractPriceWithProductTypes.Single(r => r.Category == record.ProductTypeName).AvgPrice * 100;
                                    avgValue = Math.Round(avgValue / totalPrice, 2);
                                    this.SetsCollection.Add(new SetValue { Color = record.ColorCode, Label = record.ProductTypeName, Value = avgValue.ToString("#.##") });
                                }
                            }
                            catch (System.InvalidOperationException)
                            {

                            }
                        }
                        //}
                        break;
                    case ChartID.HeadcountByCourse:
                        //if (queries.GetHeadcountByCourse(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month) != null)
                        //{
                        var headCountsByCourse = from record in queries.GetHeadcountByCourse(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month)
                                                 select new { Course = record.CourseName, Count = record.Count };
                        totalCount = headCountsByCourse.Sum(r => r.Count);
                        colors = new string[] { "CC6600", "9900CC", "FF3300", "0099FF", "00CC66", "FFFF00" };

                        CourseRepository courseSource = new CourseRepository();
                        foreach (var record in courseSource.GetAll().Where(r => r.IsActive == true).AsEnumerable())
                        {
                            try
                            {
                                if (headCountsByCourse.Single(r => r.Course == record.CourseName) != null)
                                {
                                    avgValue = headCountsByCourse.Single(r => r.Course == record.CourseName).Count * 100;
                                    avgValue = Math.Round(avgValue/totalCount,2);
                                    this.SetsCollection.Add(new SetValue { Color = colors.GetValue(colorIndex).ToString(), Label = record.CourseName, Value = avgValue.ToString("#.##") });
                                }
                            }
                            catch (System.InvalidOperationException)
                            {

                            }
                            colorIndex++;
                        }
                        //}
                        break;
                    case ChartID.HeadcountByIndustry:
                        var data = from record in queries.GetHeadcountByIndustry(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month)
                                   select new { Industry = record.IndustryTypeName, Count = record.Count };
                        totalCount = data.Sum(r => r.Count);
                        colors = new string[] { "9900CC", "FF3300", "0099FF", "00CC66", "FFFF00" };

                        IndustryTypeRepository industrySource = new IndustryTypeRepository();
                        foreach (var record in industrySource.GetAll().Where(r => r.IsActive == true).AsEnumerable())
                        {
                            try
                            {
                                if (data.Single(r => r.Industry == record.IndustryTypeName) != null)
                                {
                                    avgValue = data.Single(r => r.Industry == record.IndustryTypeName).Count * 100;
                                    avgValue = Math.Round(avgValue / totalCount, 2);
                                    this.SetsCollection.Add(new SetValue { Color = record.ColorCode, Label = record.IndustryTypeName, Value =  avgValue.ToString("#.##") });
                                }
                            }
                            catch (System.InvalidOperationException)
                            {

                            }
                            colorIndex++;
                        }
                        //}
                        break;
                    #endregion

                    #region ProductsReports Logic
                    case ChartID.ProductMarginValue:
                        var productSalesValue = from record in queries.GetProductSalesByMonth(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month)
                                                select new { Name = record.ProductTypeName, Value = record.AvgPrice };

                        totalPrice = productSalesValue.Sum(r => r.Value);

                        productTypesSource = new ProductTypesRepository();

                        if (currentUser.Role == SandlerRoles.FranchiseeOwner || currentUser.Role == SandlerRoles.FranchiseeUser)
                            products = productTypesSource.GetWithFranchiseeId(currentUser.FranchiseeID);
                        else
                            products = productTypesSource.GetAll().Where(r => r.IsActive == true);

                        foreach (var record in products.AsEnumerable())
                        {
                            try
                            {
                                if (productSalesValue.Single(r => r.Name == record.ProductTypeName) != null)
                                {
                                    avgValue = productSalesValue.Single(r => r.Name == record.ProductTypeName).Value * 100;
                                    avgValue = Math.Round(avgValue / totalPrice, 2);
                                    this.SetsCollection.Add(new SetValue { Color = record.ColorCode, Label = record.ProductTypeName, Value = avgValue.ToString("#.##") });
                                }
                            }
                            catch (System.InvalidOperationException)
                            {

                            }
                        }
                        break;
                    case ChartID.ProductSalesQty:
                        var productSalesQty = from record in queries.GetProductSalesByMonth(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month)
                                              select new { Name = record.ProductTypeName, Count = record.Count };

                        totalPrice = productSalesQty.Sum(r => r.Count);

                        productTypesSource = new ProductTypesRepository();

                        if (currentUser.Role == SandlerRoles.FranchiseeOwner || currentUser.Role == SandlerRoles.FranchiseeUser)
                            products = productTypesSource.GetWithFranchiseeId(currentUser.FranchiseeID);
                        else
                            products = productTypesSource.GetAll().Where(r => r.IsActive == true);

                        foreach (var record in products.AsEnumerable())
                        {
                            try
                            {
                                if (productSalesQty.Single(r => r.Name == record.ProductTypeName) != null)
                                {
                                    avgValue = productSalesQty.Single(r => r.Name == record.ProductTypeName).Count * 100;
                                    avgValue = Math.Round(avgValue / totalPrice, 2);
                                    this.SetsCollection.Add(new SetValue { Color = record.ColorCode, Label = record.ProductTypeName, Value = avgValue.ToString("#.##") });
                                }
                            }
                            catch (System.InvalidOperationException)
                            {

                            }
                        }
                        break;
                    case ChartID.ProductFirstSalesValue:
                        var productFirstSalesValue = from record in queries.GetProductFirstSalesByMonth(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month)
                                                     select new { Name = record.ProductTypeName, Value = record.AvgPrice };

                        totalPrice = productFirstSalesValue.Sum(r => r.Value);

                        productTypesSource = new ProductTypesRepository();

                        if (currentUser.Role == SandlerRoles.FranchiseeOwner || currentUser.Role == SandlerRoles.FranchiseeUser)
                            products = productTypesSource.GetWithFranchiseeId(currentUser.FranchiseeID);
                        else
                            products = productTypesSource.GetAll().Where(r => r.IsActive == true);

                        foreach (var record in products.AsEnumerable())
                        {
                            try
                            {
                                if (productFirstSalesValue.Single(r => r.Name == record.ProductTypeName) != null)
                                {
                                    avgValue = productFirstSalesValue.Single(r => r.Name == record.ProductTypeName).Value*100;
                                    avgValue = Math.Round(avgValue/totalPrice,2);
                                    this.SetsCollection.Add(new SetValue { Color = record.ColorCode, Label = record.ProductTypeName, Value = avgValue.ToString("#.##") });
                                }
                            }
                            catch (System.InvalidOperationException)
                            {

                            }
                        }
                        break;
                    case ChartID.ProductFirstSalesQty:
                        var productFirstSalesQty = from record in queries.GetProductFirstSalesByMonth(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month)
                                                   select new { Name = record.ProductTypeName, Count = record.Count };

                        totalPrice = productFirstSalesQty.Sum(r => r.Count);

                        productTypesSource = new ProductTypesRepository();

                        if (currentUser.Role == SandlerRoles.FranchiseeOwner || currentUser.Role == SandlerRoles.FranchiseeUser)
                            products = productTypesSource.GetWithFranchiseeId(currentUser.FranchiseeID);
                        else
                            products = productTypesSource.GetAll().Where(r => r.IsActive == true);

                        foreach (var record in products.AsEnumerable())
                        {
                            try
                            {
                                if (productFirstSalesQty.Single(r => r.Name == record.ProductTypeName) != null)
                                    this.SetsCollection.Add(new SetValue { Color = record.ColorCode, Label = record.ProductTypeName, Value = (((productFirstSalesQty.Single(r => r.Name == record.ProductTypeName).Count) / totalPrice) * 100).ToString() });
                            }
                            catch (System.InvalidOperationException)
                            {

                            }
                        }
                        break;
                    case ChartID.ProductSalesByCompanyQuantity:
                        try
                        {
                            companyName = new CompaniesRepository().GetById(long.Parse(SearchParameter)).COMPANYNAME;
                            this.Caption = this.Caption.Replace("Company Name", companyName);
                            var productSalestoCompanyQty = from record in queries.GetProductSoldByCompanyByMonth(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month, int.Parse(this.SearchParameter))
                                                           select new { Name = record.ProductTypeName, Count = record.Count };

                            totalCounts = productSalestoCompanyQty.Sum(r => r.Count);

                            productTypesSource = new ProductTypesRepository();

                            if (currentUser.Role == SandlerRoles.FranchiseeOwner || currentUser.Role == SandlerRoles.FranchiseeUser)
                                products = productTypesSource.GetWithFranchiseeId(currentUser.FranchiseeID);
                            else
                                products = productTypesSource.GetAll().Where(r => r.IsActive == true);

                            //double percentCount = 0.0;
                            foreach (var record in products.AsEnumerable())
                            {
                                try
                                {
                                    if (productSalestoCompanyQty.Single(r => r.Name == record.ProductTypeName) != null)
                                    {
                                        this.SetsCollection.Add(new SetValue { Color = record.ColorCode, Label = record.ProductTypeName, Value = (((productSalestoCompanyQty.Single(r => r.Name == record.ProductTypeName).Count) / totalCounts) * 100).ToString() });
                                    }
                                }
                                catch (System.InvalidOperationException)
                                {

                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Exception in ChartID.ProductSalesByCompanyQuantity:" + ex.Message);
                        }
                        break;
                    case ChartID.ProductSalesByCompanyValue:
                        try
                        {
                            companyName = new CompaniesRepository().GetById(long.Parse(SearchParameter)).COMPANYNAME;
                            this.Caption = this.Caption.Replace("Company Name", companyName);
                            var productSalestoCompanyValue = from record in queries.GetProductSoldByCompanyByMonth(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month, int.Parse(SearchParameter))
                                                             select new { Name = record.ProductTypeName, Value = record.AvgPrice };

                            totalPrice = productSalestoCompanyValue.Sum(r => r.Value);

                            productTypesSource = new ProductTypesRepository();

                            if (currentUser.Role == SandlerRoles.FranchiseeOwner || currentUser.Role == SandlerRoles.FranchiseeUser)
                                products = productTypesSource.GetWithFranchiseeId(currentUser.FranchiseeID);
                            else
                                products = productTypesSource.GetAll().Where(r => r.IsActive == true);

                            foreach (var record in products.AsEnumerable())
                            {
                                try
                                {
                                    if (productSalestoCompanyValue.Single(r => r.Name == record.ProductTypeName) != null)
                                        this.SetsCollection.Add(new SetValue { Color = record.ColorCode, Label = record.ProductTypeName, Value = (((productSalestoCompanyValue.Single(r => r.Name == record.ProductTypeName).Value) / totalPrice) * 100).ToString() });
                                }
                                catch (System.InvalidOperationException)
                                {

                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Exception in ChartID.ProductSalesByCompanyValue:" + ex.Message);
                        }
                        break;
                    case ChartID.ProductSalesBySalesRepQuantity:
                        try
                        {
                            this.Caption = this.Caption.Replace("Sales Rep", SearchParameter);
                            var productSalesBySalesRepQty = from record in queries.GetProductSoldBySalesRepByMonth(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month, this.SearchParameter)
                                                            select new { Name = record.ProductTypeName, Count = record.Count };

                            totalCounts = productSalesBySalesRepQty.Sum(r => r.Count);

                            productTypesSource = new ProductTypesRepository();

                            if (currentUser.Role == SandlerRoles.FranchiseeOwner || currentUser.Role == SandlerRoles.FranchiseeUser)
                                products = productTypesSource.GetWithFranchiseeId(currentUser.FranchiseeID);
                            else
                                products = productTypesSource.GetAll().Where(r => r.IsActive == true);

                            //double percentCount = 0.0;
                            foreach (var record in products.AsEnumerable())
                            {
                                try
                                {
                                    if (productSalesBySalesRepQty.Single(r => r.Name == record.ProductTypeName) != null)
                                    {
                                        this.SetsCollection.Add(new SetValue { Color = record.ColorCode, Label = record.ProductTypeName, Value = (((productSalesBySalesRepQty.Single(r => r.Name == record.ProductTypeName).Count) / totalCounts) * 100).ToString() });
                                    }
                                }
                                catch (System.InvalidOperationException)
                                {

                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Exception in ChartID.ProductSalesBySalesRepQuantity:" + ex.Message);
                        }
                        break;
                    case ChartID.ProductSalesBySalesRepValue:
                        try
                        {
                            this.Caption = this.Caption.Replace("Sales Rep", SearchParameter);
                            var productSalesBtSalesRepValue = from record in queries.GetProductSoldBySalesRepByMonth(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month, SearchParameter)
                                                              select new { Name = record.ProductTypeName, Value = record.AvgPrice };

                            totalPrice = productSalesBtSalesRepValue.Sum(r => r.Value);

                            productTypesSource = new ProductTypesRepository();

                            if (currentUser.Role == SandlerRoles.FranchiseeOwner || currentUser.Role == SandlerRoles.FranchiseeUser)
                                products = productTypesSource.GetWithFranchiseeId(currentUser.FranchiseeID);
                            else
                                products = productTypesSource.GetAll().Where(r => r.IsActive == true);

                            foreach (var record in products.AsEnumerable())
                            {
                                try
                                {
                                    if (productSalesBtSalesRepValue.Single(r => r.Name == record.ProductTypeName) != null)
                                        this.SetsCollection.Add(new SetValue { Color = record.ColorCode, Label = record.ProductTypeName, Value = (((productSalesBtSalesRepValue.Single(r => r.Name == record.ProductTypeName).Value) / totalPrice) * 100).ToString() });
                                }
                                catch (System.InvalidOperationException)
                                {

                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Exception in ChartID.ProductSalesBySalesRepValue:" + ex.Message);
                        }
                        break;
                    #endregion

                    #region BenchMarkReports Logic

                    case ChartID.BenchmarkSalesRepFranchiseeQty:
                        double salesRepQty;
                        try
                        {
                            franchiseeName = new FranchiseeRepository().GetById(currentUser.FranchiseeID).Name;
                            Caption = Caption.Replace("Sales Rep", SearchParameter).Replace("Name", franchiseeName);
                            IEnumerable<SandlerModels.DataIntegration.BenchMarkVM> salesRepToFranchiseeData = queries.GetBenchMarkSalesRepToFranchiseeByMonth(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month); ;

                            totalCounts = salesRepToFranchiseeData.Sum(r => r.Count);

                            this.SetsCollection.Add(new SetValue
                            {
                                Color = "4F94CD",
                                Label = "Franchisee",
                                Value = ((((from record in salesRepToFranchiseeData.Where(r => r.KeyGroupId != SearchParameter)
                                            select record).Sum(r => r.Count)) / totalCounts) * 100).ToString()
                            });

                            SandlerModels.DataIntegration.BenchMarkVM repRecord = salesRepToFranchiseeData.Where(r => r.KeyGroupId == SearchParameter).SingleOrDefault();
                            salesRepQty = (repRecord == null) ? 0.0 : repRecord.Count;

                            this.SetsCollection.Add(new SetValue
                            {
                                Color = "FF8C00",
                                Label = "Rep",
                                Value = (( salesRepQty/ totalCounts) * 100).ToString()

                            });

                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Exception in ChartID.BenchmarkSalesRepFranchiseeQty:" + ex.Message);
                        }
                        break;

                    case ChartID.BenchmarkSalesRepFranchiseeValue:
                        double salesRepValue;
                        try
                        {
                            franchiseeName = new FranchiseeRepository().GetById(currentUser.FranchiseeID).Name;
                            Caption = Caption.Replace("Sales Rep", SearchParameter).Replace("Name", franchiseeName);
                            IEnumerable<SandlerModels.DataIntegration.BenchMarkVM> salesRepToFranchiseeData = queries.GetBenchMarkSalesRepToFranchiseeByMonth(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month); ;

                            totalPrice = salesRepToFranchiseeData.Sum(r => r.Value);

                            this.SetsCollection.Add(new SetValue
                            {
                                Color = "4F94CD",
                                Label = "Franchisee",
                                Value = ((((from record in salesRepToFranchiseeData.Where(r => r.KeyGroupId != SearchParameter)
                                            select record).Sum(r => r.Value)) / totalPrice) * 100).ToString()
                            });

                            SandlerModels.DataIntegration.BenchMarkVM repRecord = salesRepToFranchiseeData.Where(r => r.KeyGroupId == SearchParameter).SingleOrDefault();
                            salesRepValue = (repRecord == null) ? 0.0 : repRecord.Value;

                            this.SetsCollection.Add(new SetValue
                            {
                                Color = "FF8C00",
                                Label = "Rep",
                                Value = ((salesRepValue / totalPrice) * 100).ToString()

                            });

                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Exception in ChartID.BenchmarkSalesRepFranchiseeValue:" + ex.Message);
                        }
                        break;

                    case ChartID.BenchmarkFranchiseeRegionQty:
                        double franchiseeQty;
                        try
                        {
                            franchiseeName = new FranchiseeRepository().GetById(int.Parse(SearchParameter)).Name;
                            regionName = new RegionRepository().GetById(currentUser.RegionID).Name;
                            Caption = Caption.Replace("Region Name", regionName).Replace("Franchisee Name", franchiseeName);
                            IEnumerable<SandlerModels.DataIntegration.BenchMarkVM> salesFranchiseeToRegionsData = queries.GetBenchMarkFranchiseeToRegionsByMonth(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month); ;

                            totalCounts = salesFranchiseeToRegionsData.Sum(r => r.Count);

                            this.SetsCollection.Add(new SetValue
                            {
                                Color = "32df00",
                                Label = "Region",
                                Value = ((((from record in salesFranchiseeToRegionsData.Where(r => r.KeyGroupId != SearchParameter)
                                            select record).Sum(r => r.Count)) / totalCounts) * 100).ToString()
                            });

                            SandlerModels.DataIntegration.BenchMarkVM franchiseeRecord = salesFranchiseeToRegionsData.Where(r => r.KeyGroupId == SearchParameter).SingleOrDefault();
                            franchiseeQty = (franchiseeRecord == null) ? 0.0 : franchiseeRecord.Count;

                            this.SetsCollection.Add(new SetValue
                            {
                                Color = "4F94CD",
                                Label = "Franchisee",
                                Value = ((franchiseeQty / totalCounts) * 100).ToString()

                            });

                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Exception in ChartID.BenchmarkFranchiseeRegionQty:" + ex.Message);
                        }
                        break;

                    case ChartID.BenchmarkFranchiseeRegionValue:
                        double franchiseeValue;
                        try
                        {
                            franchiseeName = new FranchiseeRepository().GetById(int.Parse(SearchParameter)).Name;
                            regionName = new RegionRepository().GetById(currentUser.RegionID).Name;
                            Caption = Caption.Replace("Region Name", regionName).Replace("Franchisee Name", franchiseeName);
                            IEnumerable<SandlerModels.DataIntegration.BenchMarkVM> salesFranchiseeToRegionsData = queries.GetBenchMarkFranchiseeToRegionsByMonth(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month); ;

                            totalPrice = salesFranchiseeToRegionsData.Sum(r => r.Value);

                            this.SetsCollection.Add(new SetValue
                            {
                                Color = "32df00",
                                Label = "Region",
                                Value = ((((from record in salesFranchiseeToRegionsData.Where(r => r.KeyGroupId != SearchParameter)
                                            select record).Sum(r => r.Value)) / totalPrice) * 100).ToString()
                            });

                            SandlerModels.DataIntegration.BenchMarkVM franchiseeRecord = salesFranchiseeToRegionsData.Where(r => r.KeyGroupId == SearchParameter).SingleOrDefault();
                            franchiseeValue = (franchiseeRecord == null) ? 0.0 : franchiseeRecord.Value;

                            this.SetsCollection.Add(new SetValue
                            {
                                Color = "4F94CD",
                                Label = "Franchisee",
                                Value = ((franchiseeValue / totalPrice) * 100).ToString()

                            });

                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Exception in ChartID.BenchmarkFranchiseeRegionValue:" + ex.Message);
                        }
                        break;
                    case ChartID.BenchmarkRegionCountryQty:
                        double regionQty;
                        try
                        {
                            regionName = new RegionRepository().GetById(int.Parse(SearchParameter)).Name;
                            countryName = new CountryRepository().GetById(currentUser.CountryID).Name;
                            Caption = Caption.Replace("Region Name", regionName).Replace("Country Name", countryName);
                            IEnumerable<SandlerModels.DataIntegration.BenchMarkVM> salesRegionToCountryData = queries.GetBenchMarkRegionToCountryByMonth(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month); ;

                            totalCounts = salesRegionToCountryData.Sum(r => r.Count);

                            this.SetsCollection.Add(new SetValue
                            {
                                Color = "800080",
                                Label = "Country",
                                Value = ((((from record in salesRegionToCountryData.Where(r => r.KeyGroupId != SearchParameter)
                                            select record).Sum(r => r.Count)) / totalCounts) * 100).ToString()
                            });

                            SandlerModels.DataIntegration.BenchMarkVM regionRecord = salesRegionToCountryData.Where(r => r.KeyGroupId == SearchParameter).SingleOrDefault();
                            regionQty = (regionRecord == null) ? 0.0 : regionRecord.Count;

                            this.SetsCollection.Add(new SetValue
                            {
                                Color = "32df00",
                                Label = "Region",
                                Value = ((regionQty / totalCounts) * 100).ToString()

                            });

                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Exception in ChartID.BenchmarkRegionCountryQty:" + ex.Message);
                        }
                        break;
                    case ChartID.BenchmarkRegionCountryValue:
                        double regionValue;
                        try
                        {
                            regionName = new RegionRepository().GetById(int.Parse(SearchParameter)).Name;
                            countryName = new CountryRepository().GetById(currentUser.CountryID).Name;
                            Caption = Caption.Replace("Region Name", regionName).Replace("Country Name", countryName);

                            IEnumerable<SandlerModels.DataIntegration.BenchMarkVM> salesRegionToCountryData = queries.GetBenchMarkRegionToCountryByMonth(currentUser, DateTime.ParseExact(this.DrillBy, "MMM", null).Month);

                            totalPrice = salesRegionToCountryData.Sum(r => r.Value);

                            this.SetsCollection.Add(new SetValue
                            {
                                Color = "800080",
                                Label = "Country",
                                Value = ((((from record in salesRegionToCountryData.Where(r => r.KeyGroupId != SearchParameter)
                                            select record).Sum(r => r.Value)) / totalPrice) * 100).ToString()
                            });

                            SandlerModels.DataIntegration.BenchMarkVM regionRecord = salesRegionToCountryData.Where(r => r.KeyGroupId == SearchParameter).SingleOrDefault();
                            regionValue = (regionRecord == null) ? 0.0 : regionRecord.Value;

                            this.SetsCollection.Add(new SetValue
                            {
                                Color = "32df00",
                                Label = "Region",
                                Value = ((regionValue / totalPrice) * 100).ToString()

                            });

                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Exception in ChartID.BenchmarkFranchiseeRegionValue:" + ex.Message);
                        }
                        break;
                    case ChartID.BenchmarkCountryAllQty:
                        double countryQty;
                        try
                        {
                            countryName = new CountryRepository().GetById(int.Parse(SearchParameter)).Name;
                            Caption = Caption.Replace("Country Name", countryName);
                            IEnumerable<SandlerModels.DataIntegration.BenchMarkVM> salesCountryAllData = queries.GetBenchMarkCountryAllByMonth( DateTime.ParseExact(this.DrillBy, "MMM", null).Month); ;

                            totalCounts = salesCountryAllData.Sum(r => r.Count);

                            this.SetsCollection.Add(new SetValue
                            {
                                Color = "800080",
                                Label = "All",
                                Value = ((((from record in salesCountryAllData.Where(r => r.KeyGroupId != SearchParameter)
                                            select record).Sum(r => r.Count)) / totalCounts) * 100).ToString()
                            });

                            SandlerModels.DataIntegration.BenchMarkVM countryRecord = salesCountryAllData.Where(r => r.KeyGroupId == SearchParameter).SingleOrDefault();
                            countryQty = (countryRecord == null) ? 0.0 : countryRecord.Count;

                            this.SetsCollection.Add(new SetValue
                            {
                                Color = "00CED1",
                                Label = "Country",
                                Value = ((countryQty / totalCounts) * 100).ToString()

                            });

                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Exception in ChartID.BenchmarkRegionCountryQty:" + ex.Message);
                        }
                        break;
                    case ChartID.BenchmarkCountryAllValue:
                        double countryValue;
                        try
                        {
                            countryName = new CountryRepository().GetById(int.Parse(SearchParameter)).Name;
                            Caption = Caption.Replace("Country Name", countryName);

                            IEnumerable<SandlerModels.DataIntegration.BenchMarkVM> salesCountryAllData = queries.GetBenchMarkCountryAllByMonth( DateTime.ParseExact(this.DrillBy, "MMM", null).Month);

                            totalPrice = salesCountryAllData.Sum(r => r.Value);

                            this.SetsCollection.Add(new SetValue
                            {
                                Color = "800080",
                                Label = "All",
                                Value = ((((from record in salesCountryAllData.Where(r => r.KeyGroupId != SearchParameter)
                                            select record).Sum(r => r.Value)) / totalPrice) * 100).ToString()
                            });

                            SandlerModels.DataIntegration.BenchMarkVM countryRecord = salesCountryAllData.Where(r => r.KeyGroupId == SearchParameter).SingleOrDefault();
                            countryValue = (countryRecord == null) ? 0.0 : countryRecord.Value;

                            this.SetsCollection.Add(new SetValue
                            {
                                Color = "00CED1",
                                Label = "Country",
                                Value = ((countryValue / totalPrice) * 100).ToString()

                            });

                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Exception in ChartID.BenchmarkCountryAllValue:" + ex.Message);
                        }
                        break;
                    #endregion

                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #57
0
 public void WhenConstructingRepositoryWithNullContext_ThenThrows()
 {
     Assert.Throws<ArgumentNullException>(
         () => { var repository = new CountryRepository(); });
 }
Пример #58
0
 public BCountry()
 {
     countryRepository = new CountryRepository();
 }
        public void CountryRepositoryPagedMethodReturnEntitiesInPageFashion()
        {
            //Arrange
            var unitOfWork = new MainBCUnitOfWork();
            var countryRepository = new CountryRepository(unitOfWork);

            //Act
            var pageI = countryRepository.GetPaged(0, 1, b => b.Id, false);
            var pageII = countryRepository.GetPaged(1, 1, b => b.Id, false);

            //Assert
            Assert.IsNotNull(pageI);
            Assert.IsTrue(pageI.Count() == 1);

            Assert.IsNotNull(pageII);
            Assert.IsTrue(pageII.Count() == 1);

            Assert.IsFalse(pageI.Intersect(pageII).Any());
        }
Пример #60
0
 public SeriesController(ISession session)
 {
     _countryRepository = new CountryRepository(session);
     _settingsRepository = new SettingsRepository(session);
     _seriesRepository = new SeriesRepository(session);
 }