public bool Delete(int regionId, out string strResult) { strResult = string.Empty; bool result = false; var region = RegionRepository.GetQueryable().FirstOrDefault(r => r.ID == regionId); if (region != null) { try { RegionRepository.Delete(region); RegionRepository.SaveChanges(); result = true; } catch (Exception) { strResult = "原因:已在使用"; } } else { strResult = "原因:未找到当前需要删除的数据!"; } return(result); }
public bool Add(Region region, out string strResult) { strResult = string.Empty; bool result = false; var reg = new Region(); if (reg != null) { try { reg.RegionName = region.RegionName; reg.Description = region.Description; reg.State = region.State; RegionRepository.Add(reg); RegionRepository.SaveChanges(); result = true; } catch (Exception ex) { strResult = "原因:" + ex.Message; } } else { strResult = "原因:找不到当前登陆用户!请重新登陆!"; } return(result); }
public bool Save(Region region, out string strResult) { strResult = string.Empty; bool result = false; var reg = RegionRepository.GetQueryable().FirstOrDefault(r => r.ID == region.ID); if (reg != null) { try { reg.RegionName = region.RegionName; reg.Description = region.Description; reg.State = region.State; RegionRepository.SaveChanges(); result = true; } catch (Exception ex) { strResult = "原因:" + ex.Message; } } else { strResult = "原因:未找到当前需要修改的数据!"; } return(result); }
public void Detached_UpdateWhenKeyExistsInContext() { Region dettachedRegion; using (var uow = CreateTransientUnitOfWork()) { var regionRepository = new RegionRepository(uow); var originalRegion = regionRepository.Listar().First(); // Simulate Dettached dettachedRegion = new Region(); dettachedRegion.ChangeCurrentIdentity(originalRegion.Id); // Altera dettachedRegion.RegionDescription = Guid.NewGuid().ToString(); regionRepository.Alterar(dettachedRegion); uow.Commit(); } using (var uow = CreateTransientUnitOfWork()) { var regionRepository = new RegionRepository(uow); Assert.IsTrue(regionRepository.Existe(r => r.Id == dettachedRegion.Id && r.RegionDescription == dettachedRegion.RegionDescription)); } }
public void ExcluirTerritoriosDeUmaRegiao() { using (var uow = CreateTransientUnitOfWork()) { var regionRepository = new RegionRepository(uow); var territoriesRepository = new TerritoriesRepository(uow); var region = regionRepository.Listar().FirstOrDefault(); var qtdOriginalDeRegistrosNaTabelaTerritories = territoriesRepository.Contar(); if (region != null) { var qtdTerritoriesRegion = region.Territories.Count; region.Territories.ToList().ForEach(territoriesRepository.Excluir); uow.Commit(); Assert.AreEqual(qtdOriginalDeRegistrosNaTabelaTerritories - qtdTerritoriesRegion , territoriesRepository.Contar()); } else { uow.Rollback(); Assert.IsTrue(false); } } }
public void SeedData() { var territories = new List <Territories> { new Territories { TerritoryDescription = "Territorio Teste" }, new Territories { TerritoryDescription = "Outro Território Teste" } }; territories.ForEach(t => t.GenerateNewIdentity()); var region = new Region { RegionDescription = "Região de Teste", Territories = territories }; region.GenerateNewIdentity(); using (var uow = CreateTransientUnitOfWork()) { var regionRepository = new RegionRepository(uow); regionRepository.Incluir(region); uow.Commit(); } }
public void Dettached_Update() { Region region; // Seleciona using (var uow = CreateTransientUnitOfWork()) { var regionRepository = new RegionRepository(uow); region = regionRepository.Listar().FirstOrDefault(); } // Simulate Dettach // Altera using (var uow = CreateTransientUnitOfWork()) { region.RegionDescription += Guid.NewGuid().ToString(); var regionRepository = new RegionRepository(uow); regionRepository.Alterar(region); uow.Commit(); } // Valida alteração using (var uow = CreateTransientUnitOfWork()) { var regionRepository = new RegionRepository(uow); Assert.IsNotNull(regionRepository.Selecionar(r => r.Id == region.Id && r.RegionDescription == region.RegionDescription)); } }
public void ExcluirUmaRegiaoComSeusTerritorios() { using (var uow = CreateTransientUnitOfWork()) { var regionRepository = new RegionRepository(uow); var territoriesRepository = new TerritoriesRepository(uow); var region = regionRepository.Listar().FirstOrDefault(r => r.Territories.Count >= 2); if (region != null) { var id = region.Territories.First().Id; region.Territories.ToList().ForEach(territoriesRepository.Excluir); regionRepository.Excluir(region); uow.Commit(); Assert.IsNull(territoriesRepository.Selecionar(t => t.Id == id)); } else { uow.Rollback(); Assert.IsTrue(false); } } }
public void TestGetAllRegionsOk() { List <Region> regionsToReturn = new List <Region>() { new Region() { Id = 1, Name = "Region Pajaros Pintados", Spots = null }, new Region() { Id = 2, Name = "Region Metropolitana", Spots = null }, }; regionsToReturn.ForEach(r => _context.Add(r)); _context.SaveChanges(); var repository = new RegionRepository(_context); var result = repository.GetAll(); Assert.IsTrue(regionsToReturn.SequenceEqual(result)); }
public System.Data.DataTable GetRegion(int page, int rows, Region region) { IQueryable <Region> regionQuery = RegionRepository.GetQueryable(); var RegionDetail = regionQuery.Where(r => r.RegionName.Contains(region.RegionName) && r.Description.Contains(region.Description) && r.State.Contains(region.State)).OrderBy(ul => ul.RegionName); //int total = RegionDetail.Count(); //var sRMDetails = RegionDetail.Skip((page - 1) * rows).Take(rows); var sRM_Detail = RegionDetail.ToArray().Select(r => new { r.ID, r.RegionName, r.Description, State = r.State == "01" ? "可用" : "不可用" }); System.Data.DataTable dt = new System.Data.DataTable(); dt.Columns.Add("区域编码", typeof(string)); dt.Columns.Add("区域名称", typeof(string)); dt.Columns.Add("描述", typeof(string)); dt.Columns.Add("是否可用", typeof(string)); foreach (var item in sRM_Detail) { dt.Rows.Add ( item.ID, item.RegionName, item.Description, item.State ); } return(dt); }
public async Task Soft_Deletes() { var repo = new RegionRepository(Context); var region = new Region { Id = Guid.NewGuid(), Name = "My Custom Region", IsMarkedAsDeleted = false }; var deletedRegion = new RegionModel { Id = region.Id, Name = region.Name, IsDeleted = true }; Context.Regions.Add(region); Context.SaveChanges(); var deleted = await repo.UpdateAsync(deletedRegion); Assert.AreEqual(1, Context.Regions.Count()); Assert.IsTrue(deleted.IsDeleted); }
public object GetDetails(int page, int rows, Position positions) { IQueryable <Position> positionQuery = PositionRepository.GetQueryable(); IQueryable <Region> regionQuery = RegionRepository.GetQueryable(); var positionDetail = positionQuery.Join(regionQuery, p => p.RegionID, r => r.ID, (p, r) => new { p.ID, p.PositionName, p.RegionID, r.RegionName, p.SRMName, p.PositionType, p.TravelPos, p.LiftPos, p.Extension, p.Description, p.HasGoods, p.AbleStockOut, p.AbleStockInPallet, p.TagAddress, p.CurrentTaskID, p.CurrentOperateQuantity, p.ChannelCode, p.State }) .Where(p => p.PositionName.Contains(positions.PositionName) && p.SRMName.Contains(positions.SRMName) && p.State.Contains(positions.State) && p.PositionType.Contains(positions.PositionType)) .OrderBy(ul => ul.ID); int total = positionDetail.Count(); var positionDetails = positionDetail.Skip((page - 1) * rows).Take(rows); var position_Detail = positionDetails.ToArray().Select(p => new { p.ID, p.PositionName, PositionType = p.PositionType == "01" ? "正常位置" : (p.PositionType == "02" ? "大品种出库位" : (p.PositionType == "03" ? "小品种出库位" : (p.PositionType == "04" ? "异形烟出库位" : "空托盘出库位"))), p.RegionID, p.RegionName, p.SRMName, p.TravelPos, p.LiftPos, Extension = p.Extension == 0 ? "单右伸" : (p.Extension == 4 ? "双右伸" : (p.Extension == 8 ? "单左伸" : "双左伸")), p.Description, HasGoods = p.HasGoods == true ? "是" : "否", AbleStockOut = p.AbleStockOut == true ? "是" : "否", AbleStockInPallet = p.AbleStockInPallet == true ? "是" : "否", p.TagAddress, p.CurrentTaskID, p.CurrentOperateQuantity, p.ChannelCode, State = p.State == "01" ? "可用" : "不可用", }); return(new { total, rows = position_Detail.ToArray() }); }
public TerritoryRegion GetTerritoryRegion(Guid UserGUID) { TerritoryRegion lTerritoryRegion = new TerritoryRegion(); ITerritoryRepository _ITerritoryRepository = new TerritoryRepository(new WorkersInMotionDB()); IRegionRepository _IRegionRepository = new RegionRepository(new WorkersInMotionDB()); IOrganizationRepository _IOrganizationRepository = new OrganizationRepository(new WorkersInMotionDB()); Guid OrganizationGUID = _IOrganizationRepository.GetOrganizationIDByUserGUID(UserGUID); List <Territory> TerritoryList = _ITerritoryRepository.GetTerritoryByOrganizationGUID(OrganizationGUID).ToList(); if (TerritoryList != null && TerritoryList.Count > 0) { lTerritoryRegion.Territories = new List <MobileTerritory>(); foreach (Territory item in TerritoryList) { MobileTerritory lterritory = new MobileTerritory(); lterritory = convertTerritoryToMobileTerritory(item); lTerritoryRegion.Territories.Add(lterritory); } } List <Region> RegionList = _IRegionRepository.GetRegionByOrganizationGUID(OrganizationGUID).ToList(); if (RegionList != null && RegionList.Count > 0) { lTerritoryRegion.Regions = new List <MobileRegion>(); foreach (Region item in RegionList) { MobileRegion lregion = convertRegionToMobileRegion(item); lTerritoryRegion.Regions.Add(lregion); } } return(lTerritoryRegion); }
public void A_ChangedFreeSessionReason_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 RegionRepository(_configuration.TestServer); repository.Insert(aggr); //3.- Change the aggregate aggr.NameKeyId = StringExtension.RandomString(10); aggr.CountryId = Guid.NewGuid(); aggr.SapCode = StringExtension.RandomString(2); //4.- Emit message var message = GenerateMessage(aggr); message.MessageType = typeof(ChangedRegion).Name; serviceEvents.AddIncommingEvent(new IncommingEvent { @event = message }); //5.- Load the saved country var region = repository.Get(aggr.Id); //6.- Check equality Assert.True(ObjectExtension.AreEqual(aggr, region)); }
public bool Add(Position position) { var post = new Position(); try { var region = RegionRepository.GetQueryable().FirstOrDefault(r => r.ID == position.RegionID); post.ID = position.ID; post.PositionName = position.PositionName; post.PositionType = position.PositionType; post.RegionID = position.RegionID; post.SRMName = position.SRMName; post.TravelPos = position.TravelPos; post.LiftPos = position.LiftPos; post.Extension = position.Extension; post.Description = position.Description; post.HasGoods = position.HasGoods; post.AbleStockOut = position.AbleStockOut; post.AbleStockInPallet = position.AbleStockInPallet; post.TagAddress = position.TagAddress; post.CurrentOperateQuantity = position.CurrentOperateQuantity; post.CurrentTaskID = position.CurrentTaskID; post.ChannelCode = position.ChannelCode; post.State = position.State; PositionRepository.Add(post); PositionRepository.SaveChanges(); } catch (Exception e) { } return(true); }
public void IncluirAtualizarExcluirTerritorioDeUmaRegiao() { using (var uow = CreateTransientUnitOfWork()) { var regionRepository = new RegionRepository(uow); var region = regionRepository.Listar().FirstOrDefault(r => r.Territories.Count >= 2); if (region != null) { var territories = new Territories { TerritoryDescription = "Território de Teste Novo" }; territories.GenerateNewIdentity(); //var Territories = region.Territories.Last(); region.Territories.First().TerritoryDescription = "Território de Teste"; //region.Territories.Remove(Territories); region.Territories.Add(territories); regionRepository.Alterar(region); uow.Commit(); Assert.AreEqual(region.Territories.First().TerritoryDescription , "Território de Teste"); Assert.AreEqual(region.Territories.Last().TerritoryDescription , "Território de Teste Novo"); } else { uow.Rollback(); Assert.IsTrue(false); } } }
public void GetAllRegions_OnNonEmptyTable_ReturnsAllRegions() { // arrange List <Region> data = new List <Region>(); data.Add(new Region { ID = 1, Continent = "North America", Country = "Canada", Name = "Eastern Canada", Provinces = null }); data.Add(new Region { ID = 2, Continent = "North America", Country = "Canada", Name = "Northern Canada", Provinces = null }); data.Add(new Region { ID = 3, Continent = "North America", Country = "Canada", Name = "Western Canada", Provinces = null }); Mock <DbSet <Region> > mockSet = EntityMockFactory.CreateSet(data.AsQueryable()); Mock <LocationDb> mockContext = new Mock <LocationDb>(); mockContext.Setup(c => c.Regions).Returns(mockSet.Object); RegionRepository sut = new RegionRepository(mockContext.Object); // act IEnumerable <Region> actual = sut.GetAllRegions(); // assert Assert.IsTrue(Equality.AreEqual(data, actual)); }
public IList<Region> GetFiltered(Expression<Func<Region, bool>> filter) { using (IRegionRepository regionRepository = new RegionRepository()) { return regionRepository.GetFiltered(filter); } }
public UnitOfWork(ApplicationContext context) { _context = context; Masters = new MasterRepository(_context); Regions = new RegionRepository(_context); MasterRegions = new MasterRegionRepository(_context); }
private void PopulateClubFromControls(Club club) { club.Name = Name.Text; if (club.Address == null) { club.Address = new Address(); } club.Address.Extended = Extended.Text; club.Address.Street = Street.Text; club.Address.Locality = Locality.Text; club.Address.Region = RegionRepository.FindById(DataUtility.ParseInt(Region.SelectedItem.Value)); club.Address.Postcode = Postcode.Text; if (club.GeoPoint == null) { club.GeoPoint = new GeoPoint(); } club.GeoPoint.Latitude = double.Parse(Latitude.Text); club.GeoPoint.Longitude = double.Parse(Longitude.Text); club.Contact = PopulateContactFromControls(club.Contact); club.SiteUrl = SiteUrl.Text; club.Categories.Clear(); foreach (ListItem item in ClubCategories.Items) { if (item.Selected) { club.Categories.Add(CategoryRepository.FindById(DataUtility.ParseInt(item.Value))); } } }
public async Task <Guid> PostDeployTroops(Guid sessionId, Guid regionId, uint numberOfTroops) { IRegionData region = await RegionRepository.GetRegionOrThrow(sessionId, regionId) .IsRegionOwnerOrThrow(User.Identity.GetUserId()); ISession session = await SessionRepository.GetSessionOrThrow(region) .IsUserIdJoinedOrThrow(NationRepository, User.Identity.GetUserId()) .IsPhaseTypeOrThrow(SessionPhase.Reinforcements); INationData nation = await NationRepository.GetNation(sessionId, User.Identity.GetUserId()); if (nation.AvailableReinforcements < numberOfTroops) { throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = "You do not have that many troops available to deploy" }); } else if (numberOfTroops <= 0) { throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = "You can not deploy less than 1 troop" }); } else { return(await CommandQueue.DeployReinforcements(session.GameId, session.PhaseId, region.RegionId, region.CurrentEtag, numberOfTroops)); } }
public ActionResult Index() { if (string.IsNullOrEmpty(User.Identity.Name)) { return(RedirectToAction("Login", "Account")); } using (UserRepository user = new UserRepository()) { ViewBag.IsAdmin = user.IsAdmin(User.Identity.Name); } ViewBag.Title = "Customer List"; CustomerViewModel model = new CustomerViewModel(); using (GenderRepository gender = new GenderRepository()) model.Genders = gender.GetAll(); using (RegionRepository region = new RegionRepository()) model.Regions = region.GetAll(); using (CityRepository city = new CityRepository()) model.Cities = city.GetAll(); using (ClassificationRepository classification = new ClassificationRepository()) model.Classifications = classification.GetAll(); using (UserRepository user = new UserRepository()) model.Sellers = user.GetAll(); return(View(model)); }
public UnitOfWork(ApplicationDbContext db, IMapper mapper) { _db = db; _mapper = mapper; Area = new AreaRepository(_db, _mapper); Attribute = new AttributeRepository(_db, _mapper); Brand = new BrandRepository(_db, _mapper); Customer = new CustomerRepository(_db, _mapper); GeneralSetting = new GeneralSettingRepository(_db, _mapper); Order = new OrderRepository(_db, _mapper); OrderCart = new OrderCartRepository(_db, _mapper); OrderShippingAddress = new OrderShippingAddressRepository(_db, _mapper); Product = new ProductRepository(_db, _mapper); ProductReview = new ProductReviewRepository(_db, _mapper); ProductFaq = new ProductFaqRepository(_db, _mapper); Registration = new RegistrationRepository(_db, _mapper); Region = new RegionRepository(_db, _mapper); Slider = new SliderRepository(_db, _mapper); Specification = new SpecificationRepository(_db, _mapper); Catalog = new CatalogRepository(_db, _mapper); Vendor = new VendorRepository(_db, _mapper); VendorStoreSlider = new VendorStoreSliderRepository(_db, _mapper); VendorProductCategory = new VendorProductCategoryRepository(_db, _mapper); Warehouse = new WarehouseRepository(_db, _mapper); }
private void BindRegions() { Region.DataSource = RegionRepository.CreateQuery( "from Region r where r.Country.Name = 'United Kingdom' order by r.Name" ).List(); Region.DataBind(); }
public IEnumerable <ModelValidationResult> Validate(ModelValidationContext context) { IEnumerable <ModelValidationResult> result = Enumerable.Empty <ModelValidationResult>(); // Dependancy injection does not work with attributes so manually wire up the database context. using (NorthwindContext dbContext = DAL.Startup.NorthwindContext) { IRepository <Region, int> repository = new RegionRepository(dbContext); int?value = context.Model as int?; if (value == null) { result = new List <ModelValidationResult>() { new ModelValidationResult("", "A region id must be provided") }; } else { Region model = repository.Fetch(value.Value); if (model == null) { result = new List <ModelValidationResult>() { new ModelValidationResult("", ErrorMessage) }; } } } return(result); }
public async Task IntegrationTestGetRegions() { // Arrange RegionRepository repository = new RegionRepository(DevelopmentStorageAccountConnectionString, String.Empty); Guid dummySessionId = new Guid("74720766-452A-40AD-8A61-FEF07E8573C9"); Guid dummyRegionId = new Guid("CBDF6EBE-5F91-4ADF-AC30-D149D8E5F8EB"); Guid secondDummyRegionId = new Guid("336312D8-F219-4C9B-B3FE-F4B39602E28D"); Guid dummyContinentId = new Guid("DE167712-0CE6-455C-83EA-CB2A6936F1BE"); TableClient.SetupSessionDataTable(dummySessionId); using (IBatchOperationHandle batchOperation = new BatchOperationHandle(SessionRepository.GetTableForSessionData(TableClient, dummySessionId))) { repository.CreateRegion(batchOperation, dummySessionId, dummyRegionId, dummyContinentId, "DummyRegion", new List <Guid>(), 0); repository.CreateRegion(batchOperation, dummySessionId, secondDummyRegionId, dummyContinentId, "DummyRegion2", new List <Guid>(), 0); } // Act IEnumerable <IRegionData> regionData = await repository.GetRegions(dummySessionId); // Assert Assert.IsNotNull(regionData); Assert.IsTrue(regionData.Count() >= 2, "Expected at least two regions"); Assert.AreEqual(1, regionData.Where(region => region.RegionId == dummyRegionId).Count()); Assert.AreEqual(1, regionData.Where(region => region.RegionId == secondDummyRegionId).Count()); }
public static int CreateUser(List <Beer> pickedBeers, int?regionId, AppDbContext repositoryContext) { UserRepository userRepo = new UserRepository(repositoryContext); User user = new User(); if (regionId != null) { var rr = new RegionRepository(); var region = rr.RetrieveById((int)regionId); userRepo.SetUserRegion(user, region); } try { foreach (var pickedBeer in pickedBeers) { userRepo.AddPickedBeer(user, pickedBeer); } var id = userRepo.Create(user); return(id); } catch (DbEntityValidationException ex) { var errors = ex.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); var message = string.Join("; ", errors); throw new DbEntityValidationException(message, ex.EntityValidationErrors); } }
public JsonResult LoadRegionByCity(string cityId) { if (!string.IsNullOrWhiteSpace(cityId)) { ICityRepository cityRepository = new CityRepository(_connectionString); var cityApp = new CityApplication(cityRepository); var regionList = cityApp.GetAll(); regionList = regionList.Where(c => c.Id == cityId.ToInt32()); var regionData = regionList.Select(r => new SelectListItem() { Text = r.Region.Name, Value = r.Region.Id.ToString(), }); return(Json(regionData, JsonRequestBehavior.AllowGet)); } else { IRegionRepository regionRepository = new RegionRepository(_connectionString); var regionApp = new RegionApplication(regionRepository); var regionData = regionApp.GetAll().Select(g => new SelectListItem() { Text = g.Name, Value = g.Id.ToString() }).ToList(); return(Json(regionData, JsonRequestBehavior.AllowGet)); } }
public List <tbl_Region> GetRegionsByChildID(Int64 childId) { RegionRepository regionRepository = new RegionRepository(); var regions = regionRepository.SV_GetSQLRegionsByChild(childId);; return(regions); }
public List <tbl_Region> GetRegionsByParentID(Int64 parentId) { RegionRepository regionRepository = new RegionRepository(); var regions = regionRepository.SV_GetSQLRegionsByParent(parentId);; return(regions); }
public UnitOfWork(OfflineContext db) { _db = db; District = new DistrictRepository(_db); Region = new RegionRepository(_db); Employee = new EmployeeRepository(_db); }
public void run() { RegionRepository r = new RegionRepository(); Region reg = new Region(); r.Add(reg); }
public LoadService(IpGeoBaseContext dataContext) { DataContext = dataContext; AreaRepository = new AreaRepository(dataContext); RegionRepository = new RegionRepository(dataContext); LocationRepository = new LocationRepository(dataContext); RangeRepository = new RangeRepository(dataContext); }
public TargetService(IpGeoBaseContext dataContext) { DataContext = dataContext; TargetRepository = new TargetRepository(dataContext); CountryRuleRepository = new CountryRuleRepository(dataContext); AreaRuleRepository = new AreaRuleRepository(dataContext); AreaRepository = new AreaRepository(dataContext); RegionRuleRepository = new RegionRuleRepository(dataContext); RegionRepository = new RegionRepository(dataContext); LocationRuleRepository = new LocationRuleRepository(dataContext); LocationRepository = new LocationRepository(dataContext); }
public Coach Get(int id) { TBL_COACH _coach = new CoachRepository().GetById(id); aspnet_Users user = new UsersRepository().GetAll().Where(u => u.UserId == _coach.UserID).SingleOrDefault(); aspnet_Membership member = new MembershipRepository().GetAll().Where(m => m.UserId == _coach.UserID).SingleOrDefault(); TBL_REGION _region = new RegionRepository().GetById(_coach.RegionID); Coach coach = new Coach(); coach.UserName = user.UserName; coach.RegionName = _region.Name; coach.Email = member.Email; CoachMappings.ModelToViewModel(coach, _coach); return coach; }
public void A_RegisteredRegion_creates_a_new_currency_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 RegionRepository(_configuration.TestServer); var region = repository.Get(aggr.Id); //4.- Check equality Assert.True(ObjectExtension.AreEqual(aggr, region)); }
public void A_UnregisteredRegion_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 RegionRepository(_configuration.TestServer); repository.Insert(aggr); //2.- Emit message var message = GenerateMessage(aggr); message.MessageType = typeof(UnregisteredRegion).Name; serviceEvents.AddIncommingEvent(new IncommingEvent { @event = message }); var country = repository.Get(aggr.Id); Assert.Null(country); }
public void AtualizarTerritoriosDeUmaRegiao() { using (var uow = CreateTransientUnitOfWork()) { var regionRepository = new RegionRepository(uow); var region = regionRepository.Listar().FirstOrDefault(); if (region != null) { region.Territories.First().TerritoryDescription = "Território de Teste Novo"; regionRepository.Alterar(region); uow.Commit(); Assert.AreEqual(region.Territories.First().TerritoryDescription , "Território de Teste Novo"); } else { uow.Rollback(); Assert.IsTrue(false); } } }
public void Attached_Update() { Region region; using (var uow = CreateTransientUnitOfWork()) { // Seleciona var regionRepository = new RegionRepository(uow); region = regionRepository.Listar().First(); // Altera region.RegionDescription = Guid.NewGuid().ToString(); regionRepository.Alterar(region); uow.Commit(); } using (var uow = CreateTransientUnitOfWork()) { var regionRepository = new RegionRepository(uow); Assert.IsNotNull(regionRepository.Selecionar(r => r.Id == region.Id && r.RegionDescription == region.RegionDescription)); } }
public void IncluirAtualizarExcluirTerritorioDeUmaRegiao() { using (var uow = CreateTransientUnitOfWork()) { var regionRepository = new RegionRepository(uow); var region = regionRepository.Listar().FirstOrDefault(r => r.Territories.Count >= 2); if (region != null) { var territories = new Territories {TerritoryDescription = "Território de Teste Novo"}; territories.GenerateNewIdentity(); //var Territories = region.Territories.Last(); region.Territories.First().TerritoryDescription = "Território de Teste"; //region.Territories.Remove(Territories); region.Territories.Add(territories); regionRepository.Alterar(region); uow.Commit(); Assert.AreEqual(region.Territories.First().TerritoryDescription , "Território de Teste"); Assert.AreEqual(region.Territories.Last().TerritoryDescription , "Território de Teste Novo"); } else { uow.Rollback(); Assert.IsTrue(false); } } }
public void IncluirTerritorioDeUmaRegiao() { using (var uow = CreateTransientUnitOfWork()) { var region = new Region { RegionDescription = "Região de Teste" }; region.GenerateNewIdentity(); var regionRepository = new RegionRepository(uow); regionRepository.Incluir(region); uow.Commit(); } using (var uow = CreateTransientUnitOfWork()) { var territoriesRepository = new TerritoriesRepository(uow); var regionRepository = new RegionRepository(uow); var region = regionRepository.Listar().FirstOrDefault(r => r.Territories.Count.Equals(0)); var qtdOriginalDeRegistrosNaTabelaTerritories = territoriesRepository.Contar(); if (region != null) { var territories = new Territories { TerritoryDescription = "Território de Teste" }; territories.GenerateNewIdentity(); region.Territories = (new List<Territories> { territories }); regionRepository.Alterar(region); uow.Commit(); Assert.AreEqual(qtdOriginalDeRegistrosNaTabelaTerritories + 1 , territoriesRepository.Contar()); Assert.IsNotNull(region.Territories); } else { uow.Rollback(); Assert.IsTrue(false); } } }
public void SeedData() { var territories = new List<Territories> { new Territories { TerritoryDescription = "Territorio Teste"}, new Territories { TerritoryDescription = "Outro Território Teste"} }; territories.ForEach(t => t.GenerateNewIdentity()); var region = new Region { RegionDescription = "Região de Teste", Territories = territories }; region.GenerateNewIdentity(); using (var uow = CreateTransientUnitOfWork()) { var regionRepository = new RegionRepository(uow); regionRepository.Incluir(region); uow.Commit(); } }
public static RegionRepository GetRegionRepository() { var repository = new RegionRepository(); repository.UnitOfWork = GetUnitOfWork(); return repository; }
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 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; } }
public static RegionRepository GetRegionRepository(IUnitOfWork unitOfWork) { var repository = new RegionRepository(); repository.UnitOfWork = unitOfWork; return repository; }
public void IncluirRegiaoComTerritorios() { var territorieses = new List<Territories> { new Territories { TerritoryDescription = "Territorio Teste"}, new Territories { TerritoryDescription = "Outro Território Teste"} }; territorieses.ForEach(t => t.GenerateNewIdentity()); var region = new Region { RegionDescription = "Região de Teste", Territories = territorieses }; region.GenerateNewIdentity(); using (var uow = CreateTransientUnitOfWork()) { var regionRepository = new RegionRepository(uow); var terrotoriesRepository = new TerritoriesRepository(uow); var qtdOriginalDeRegistrosNaTabelaRegion = regionRepository.Contar(); var qtdOriginalDeRegistrosNaTabelaTerritories = terrotoriesRepository.Contar(); regionRepository.Incluir(region); uow.Commit(); Assert.AreEqual(qtdOriginalDeRegistrosNaTabelaRegion + 1, regionRepository.Contar()); Assert.AreEqual(qtdOriginalDeRegistrosNaTabelaTerritories + territorieses.Count, terrotoriesRepository.Contar()); } }
public void IncluirRegiao() { using (var uow = CreateTransientUnitOfWork()) { var region = new Region { RegionDescription = "Região de Teste" }; region.GenerateNewIdentity(); var regionRepository = new RegionRepository(uow); var qtdOriginalDeRegistrosNaTabelaRegion = regionRepository.Contar(); regionRepository.Incluir(region); uow.Commit(); Assert.AreEqual(qtdOriginalDeRegistrosNaTabelaRegion + 1, regionRepository.Contar()); } }