protected void Page_Load(object sender, EventArgs e)
        {
            lblErrorMessage.Visible = false;
            lblProcessMessage.Text  = string.Empty;
            if (!IsPostBack)
            {
                hfLoggedOnUser.Value          = ApplicationAuthentication.GetGlobalId();
                ucDgcProgress.CurrentProgress = DemandGapCalculationStep.NotStarted;
                PopulateScenarios();
                PopulateMinAndMaxSpreadDates();
                pnlGapFill.Visible = false;
            }

            if (ucDgcProgress.CurrentProgress == DemandGapCalculationStep.Complete ||
                ucDgcProgress.CurrentProgress == DemandGapCalculationStep.Error)
            {
                hfLoading.Value      = string.Empty;
                btnCaluclate.Enabled = true;
                pnlGapFill.Visible   = true;
                tbSummary.Text       = ucDgcProgress.CurrentProgress == DemandGapCalculationStep.Complete
                    ? SummaryText : string.Empty;
                ucDgcProgress.CurrentProgress = DemandGapCalculationStep.NotStarted;
            }

            ucDemanGapStageOneGrid.GridItemType           = typeof(WeeklyMaxMinValues);
            ucDemanGapStageOneGrid.SessionNameForGridData = DemandGapDisplaySession;
            ucDemanGapStageOneGrid.ColumnHeaders          = WeeklyMaxMinValues.HeaderRows;
            ucDemanGapStageOneGrid.ColumnFormats          = WeeklyMaxMinValues.Formats;

            ucResult.GridItemType           = typeof(AdditionEntity);
            ucResult.SessionNameForGridData = AdditionPlanSessionHolder;
            ucResult.ColumnHeaders          = AdditionEntity.HeaderRows;
            ucResult.ColumnFormats          = AdditionEntity.Formats;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                var comData = CommunicationDataAccess.GetAllActiveNewsItems();

                rptComm.DataSource = comData;
                rptComm.DataBind();

                var documents = CommunicationDataAccess.GetAllDocuments().ToList();
                rptDocs.DataSource = documents;
                rptDocs.DataBind();

                using (var dataAccess = new UsersAndRolesDataAccess())
                {
                    var employeeId    = ApplicationAuthentication.GetEmployeeId();
                    var userType      = dataAccess.GetUserType(employeeId);
                    var countryAdmins = dataAccess.GetCountryAdmin(userType);
                    gvCountryAdmins.DataSource = countryAdmins.OrderBy(d => d.Country).ThenBy(d => d.Name);
                }
                using (var dataAccess = new UserTrainingDataAccess())
                {
                    var trainingEntities = dataAccess.GetActiveEntries();
                    rptTraining.DataSource = trainingEntities;
                }
                gvCountryAdmins.DataBind();
                rptTraining.DataBind();
            }
        }
Exemplo n.º 3
0
        public void UpdateMinCommercialSegments(double newMinCommSegPercent)
        {
            var comSegData  = CommercialSegmentQueryable.GetCommercialCarSemgents(DataContext, Parameters);
            var locations   = LocationQueryable.GetLocations(DataContext, Parameters);
            var carSegments = CarSegmentQueryable.GetCarSegments(DataContext, Parameters);

            var fullComSeg = from ccs in comSegData
                             from l in locations
                             from cs in carSegments
                             select new
            {
                LocationId   = l.dim_Location_id,
                CarSegmentId = cs.car_segment_id,
                ccs.CommercialCarSegmentId
            };

            var minCommIdsToUpdate = from fullCs in fullComSeg
                                     join mcs in DataContext.MinCommercialSegments on
                                     new { fullCs.LocationId, fullCs.CarSegmentId, fullCs.CommercialCarSegmentId }
            equals new { mcs.LocationId, mcs.CarSegmentId, mcs.CommercialCarSegmentId }
            select mcs;

            minCommIdsToUpdate.ForEach(d => d.Percentage = newMinCommSegPercent);
            minCommIdsToUpdate.ForEach(d => d.UpdatedBy  = ApplicationAuthentication.GetGlobalId());
            minCommIdsToUpdate.ForEach(d => d.UpdatedOn  = DateTime.Now);

            var entriesToCreate = from fullCs in fullComSeg
                                  join mcs in DataContext.MinCommercialSegments on
                                  new { fullCs.LocationId, fullCs.CarSegmentId, fullCs.CommercialCarSegmentId }
            equals new { mcs.LocationId, mcs.CarSegmentId, mcs.CommercialCarSegmentId }
            into joinedComSeg
            from comSegFigures in joinedComSeg.DefaultIfEmpty()
            where comSegFigures == null
                select new
            {
                LocationId             = fullCs.LocationId,
                CarSegmentId           = fullCs.CarSegmentId,
                CommercialCarSegmentId = fullCs.CommercialCarSegmentId,
                Percentage             = newMinCommSegPercent,
                LastChangedOn          = DateTime.Now,
                LastChangedBy          = ApplicationAuthentication.GetGlobalId()
            };
            var localEntities = from etc in entriesToCreate.AsEnumerable()
                                select new MinCommercialSegment
            {
                LocationId             = etc.LocationId,
                CarSegmentId           = etc.CarSegmentId,
                CommercialCarSegmentId = etc.CommercialCarSegmentId,
                Percentage             = newMinCommSegPercent,
                UpdatedOn = DateTime.Now,
                UpdatedBy = ApplicationAuthentication.GetGlobalId()
            };

            DataContext.MinCommercialSegments.InsertAllOnSubmit(localEntities);
            DataContext.SubmitChanges();
        }
Exemplo n.º 4
0
        private void InitializeAuthentication()
        {
            var auth = new ApplicationAuthentication();

            var context = new ICIdentityDbContext(ConnectionFactory.Create(ConnectionFactory.GetConnectionString(typeof(ICIdentityDbContext).Name)));

            auth.AddProviders(new AspNetIdentityAuthenticationProvider(DefaultUserManager.Create(new UserStore <IdentityUser>(context))));

            GlobalContainer.AddInstance(auth);
        }
Exemplo n.º 5
0
        public static int GetUserID(System.Security.Principal.IPrincipal userSecurity, HttpContextBase httpContext)
        {
            int userID = GUESTID;

            if (userSecurity.Identity.IsAuthenticated)
            {
                IMyAppAuthentication user = new ApplicationAuthentication(httpContext);
                userID = user.GetAuthenticationUserId();
            }

            return(userID);
        }
Exemplo n.º 6
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                UserActivity.LogPageAccess(ApplicationAuthentication.GetGlobalId(), Request.Url.AbsolutePath, ApplicationAuthentication.GetUserName());
            }
            //Check session timeout
            base.CheckSessionTimeout();

            this.ControlPanelRibbon.UserLoggedIn = @"User Logged In: " + ApplicationAuthentication.GetUserName();
            this.ControlPanelRibbon.ControlTitle = @"Application Home";

            this.ChangeMenuStyles();
        }
Exemplo n.º 7
0
        public List <ListItem> GetFleetTypesList(ModuleType modType)
        {
            var returned = NonRevParameterDataAccess.GetFleetTypes(DataContext);

            switch (modType)
            {
            case ModuleType.Availability:
                returned.ForEach(d => d.Selected =
                                     d.Text.ToLower() != "licensee" &&
                                     d.Text.ToLower() != "inactive" &&
                                     d.Text.ToLower() != "undefined" &&
                                     d.Text.ToLower() != "firefly" &&
                                     d.Text.ToLower() != "hertz on demand" &&
                                     d.Text.ToLower() != "sold");
                break;

            case ModuleType.NonRev:
                returned.ForEach(d => d.Selected =
                                     d.Text.ToLower() != "licensee" &&
                                     d.Text.ToLower() != "inactive" &&
                                     d.Text.ToLower() != "sold");
                break;

            default:
                throw new ArgumentOutOfRangeException("modType");
            }
            var loggedOnEmployee = ApplicationAuthentication.GetEmployeeId();

            if (loggedOnEmployee == string.Empty) //Special case for Itdemo
            {
                loggedOnEmployee = ApplicationAuthentication.GetGlobalId();
            }

            var marsUserEntity = DataContext.MarsUsers.FirstOrDefault(d => d.EmployeeId == loggedOnEmployee);

            if (marsUserEntity != null)
            {
                if (marsUserEntity.CompanyType.CompanyTypeName == CompanyTypeEnum.Licensee.ToString())
                {
                    var item = returned.SingleOrDefault(d => d.Text.ToLower() == "licensee");
                    if (item != null)
                    {
                        item.Selected = true;
                    }
                }
            }

            return(returned);
        }
        public static oauthDetails ToApiModel(this ApplicationAuthentication authentication)
        {
            var result = new oauthDetails
            {
                WellKnownUrl          = authentication.WellKnownUrl,
                AuthorizationEndpoint = authentication.AuthorizationEndpoint,
                TokenEndpoint         = authentication.TokenEndpoint,
                UserInfoEndpoint      = authentication.UserInfoEndpoint,
                EndSessionEndpoint    = authentication.EndSessionEndpoint,
                RevocationEndpoint    = authentication.RevocationEndpoint,
                RegistrationEndpoint  = authentication.RegistrationEndpoint
            };

            return(result);
        }
        public static ApplicationAuthenticationDetails ToModel(this ApplicationAuthentication appAuth)
        {
            var result = new ApplicationAuthenticationDetails();

            result.ID                    = appAuth.ID;
            result.ApplicationID         = appAuth.ApplicationID;
            result.WellKnownUrl          = appAuth.WellKnownUrl;
            result.Issuer                = appAuth.Issuer;
            result.JwksUri               = appAuth.JwksUri;
            result.AuthorizationEndpoint = appAuth.AuthorizationEndpoint;
            result.TokenEndpoint         = appAuth.TokenEndpoint;
            result.RegistrationEndpoint  = appAuth.RegistrationEndpoint;
            result.RevocationEndpoint    = appAuth.RevocationEndpoint;

            return(result);
        }
Exemplo n.º 10
0
        private void CheckPageAuthorized(string urlRequested)
        {
            if (ApplicationAuthentication.GetEmployeeId() == string.Empty)
            {
                Response.Redirect("~/Default.aspx");
            }
            var employeeId = ApplicationAuthentication.GetEmployeeId();


            //var userAllowed  = UserActivity.UserAllowedToAccessUrl(userId, urlRequested);
            var userAllowed = UserActivity.Phase4UserAllowedToAccessUrl(employeeId, urlRequested);

            if (!userAllowed)
            {
                Response.Redirect("~/Default.aspx");
            }
        }
Exemplo n.º 11
0
        public List <PageEntity> GetPagesForRole(int roleId, CompanyTypeEnum companyType)
        {
            var accessData = from ma in DataContext.MarsUserRoleMenuAccesses
                             where ma.MarsUserRoleId == roleId
                             select ma;

            var baseAccess = from ma in DataContext.MarsUserRoleMenuAccesses
                             where ma.MarsUserRole.BaseAccess &&
                             ma.MarsUserRole.CompanyType.CompanyTypeName == companyType.ToString()
                             select ma;


            var loggedOnEmployee = ApplicationAuthentication.GetEmployeeId();

            var userHasSysAdmin = DataContext.MarsUserUserRoles.FirstOrDefault(
                d => d.MarsUser.EmployeeId == loggedOnEmployee &&
                d.MarsUserRole.AdminAccess);



            var roleData = from rm in DataContext.RibbonMenus
                           join ad in accessData on rm.UrlId equals ad.UrlId into joinedData
                           from jd in joinedData.DefaultIfEmpty()
                           join ba in baseAccess on rm.UrlId equals ba.UrlId into joinedBaseData
                           from jbd in joinedBaseData.DefaultIfEmpty()
                           where rm.ParentId != null &&
                           rm.Enabled.HasValue && rm.Enabled.Value
                           select new PageEntity
            {
                UrlId         = rm.UrlId,
                PageName      = rm.Title,
                Url           = rm.Url,
                Assigned      = jd != null,
                IsBranch      = rm.ParentId == 1,
                BaseHasAccess = jbd != null,
                ParentId      = rm.ParentId.HasValue ? rm.ParentId.Value : 0,
                Enabled       = userHasSysAdmin != null,
                MenuId        = rm.MenuId.HasValue ? rm.MenuId.Value : 0
            };


            var localRoleData = roleData.ToList();
            var returned      = GetTreeStructurePages(localRoleData);

            return(returned);
        }
Exemplo n.º 12
0
        public static IQueryable <FleetNow> RestrictVehicleQueryable(MarsDBDataContext dataContext,
                                                                     IQueryable <FleetNow> fleetNow)
        {
            var employeeId    = ApplicationAuthentication.GetEmployeeId();
            var companyEntity = dataContext.MarsUsers.Single(d => d.EmployeeId == employeeId);

            if (companyEntity.CompanyTypeId == VehicleRestriction.GetIdForCompanyType(CompanyTypeEnum.Corporate, dataContext))
            {
                return(fleetNow);
            }
            var locationsWithCompany = dataContext.LOCATIONs.Where(d => d.CompanyId == companyEntity.CompanyId);

            fleetNow = from v in fleetNow
                       join l in locationsWithCompany on v.LocationId equals l.dim_Location_id
                       select v;

            return(fleetNow);
        }
Exemplo n.º 13
0
        public static IQueryable <Reservation> RestrictVehicleQueryable(MarsDBDataContext dataContext
                                                                        , IQueryable <Reservation> reservations)
        {
            var employeeId    = ApplicationAuthentication.GetEmployeeId();
            var companyEntity = dataContext.MarsUsers.Single(d => d.EmployeeId == employeeId);

            if (companyEntity.CompanyTypeId == VehicleRestriction.GetIdForCompanyType(CompanyTypeEnum.Corporate, dataContext))
            {
                return(reservations);
            }
            var locationsWithCompany = dataContext.LOCATIONs.Where(d => d.CompanyId == companyEntity.CompanyId).Select(d => d.dim_Location_id);

            reservations = from v in reservations
                           where locationsWithCompany.Contains(v.PickupLocationId) ||
                           locationsWithCompany.Contains(v.ReturnLocationId)
                           select v;

            return(reservations);
        }
Exemplo n.º 14
0
        public static IQueryable <VehicleHistory> RestrictVehicleHistoryQueryable(MarsDBDataContext dataContext,
                                                                                  IQueryable <VehicleHistory> vehicleHistory)
        {
            var employeeId    = ApplicationAuthentication.GetEmployeeId();
            var companyEntity = dataContext.MarsUsers.Single(d => d.EmployeeId == employeeId);

            if (companyEntity.CompanyTypeId == VehicleRestriction.GetIdForCompanyType(CompanyTypeEnum.Corporate, dataContext))
            {
                return(vehicleHistory);
            }

            var locationsWithCompany = dataContext.LOCATIONs.Where(d => d.CompanyId == companyEntity.CompanyId).Select(d => d.dim_Location_id);

            vehicleHistory = from v in vehicleHistory
                             where locationsWithCompany.Contains(v.ExpectedLocationId.Value) ||
                             locationsWithCompany.Contains(v.LastLocationId.Value)
                             select v;

            return(vehicleHistory);
        }
        public List <RoleEntity> GetRolesForUser(int userId)
        {
            var companyTypeId = DataContext.MarsUsers.Single(d => d.MarsUserId == userId).CompanyTypeId;

            var userData = from re in DataContext.MarsUserUserRoles
                           where re.MarsUserId == userId
                           select new RoleEntity
            {
                UserRoleId = re.MarsUserRoleId,
                Granted    = true
            };

            var roleData = from re in DataContext.MarsUserRoles.Where(d => d.CompanyTypeId == companyTypeId)
                           join ud in userData on re.MarsUserRoleId equals ud.UserRoleId into joinedData
                           from udg in joinedData.DefaultIfEmpty()
                           select new RoleEntity
            {
                RoleName        = re.Name,
                RoleDescription = re.Description,
                UserRoleId      = re.MarsUserRoleId,
                Enabled         = true,
                Granted         = udg != null,
                AdminRole       = re.AdminAccess
            };

            var returned = roleData.ToList();

            var loggedOnEmployee = ApplicationAuthentication.GetEmployeeId();

            var userHasSysAdmin = DataContext.MarsUserUserRoles.FirstOrDefault(
                d => d.MarsUser.EmployeeId == loggedOnEmployee &&
                d.MarsUserRole.AdminAccess
                );

            if (userHasSysAdmin == null)
            {
                returned.Single(d => d.AdminRole).Enabled = false;
            }

            return(returned);
        }
Exemplo n.º 16
0
        public static IQueryable <Vehicle> RestrictVehicleQueryable(MarsDBDataContext dataContext, IQueryable <Vehicle> vehicles)
        {
            var employeeId    = ApplicationAuthentication.GetEmployeeId();
            var companyEntity = dataContext.MarsUsers.Single(d => d.EmployeeId == employeeId);

            if (companyEntity.CompanyTypeId == GetIdForCompanyType(CompanyTypeEnum.Corporate, dataContext))
            {
                return(vehicles);
            }

            var locationsWithCompany      = dataContext.LOCATIONs.Where(d => d.CompanyId == companyEntity.CompanyId).Select(d => d.dim_Location_id);
            var locationsCodesWithCompany = dataContext.LOCATIONs.Where(d => d.CompanyId == companyEntity.CompanyId).Select(d => d.location1);

            vehicles = from v in vehicles
                       join f in dataContext.FleetOwners on v.OwningArea equals f.OwningAreaCode
                       where f.CompanyId == companyEntity.CompanyId ||
                       locationsWithCompany.Contains(v.LastLocationId.Value) ||
                       locationsCodesWithCompany.Contains(v.ExpectedLocationCode)
                       select v;


            return(vehicles);
        }
Exemplo n.º 17
0
        public void CreateAdditionPlan(AdditionPlanEntity ape
                                       , List <AdditionEntity> weeklyAdditions
                                       , List <WeeklyMaxMinValues> minMaxValues
                                       , int countryId)
        {
            var loggedOnEmployee = ApplicationAuthentication.GetEmployeeId();
            var marsUserId       = GetMarsUserId(loggedOnEmployee);
            var entityToCreate   = new AdditionPlan
            {
                Name = ape.Name,
                MinComSegScenarioName         = ape.MinComSegScenarioName,
                MinComSegSccenarioDescription = ape.GetMinComSegScenarioDescription(),
                MaxFleetScenarioName          = ape.MaxFleetScenarioName,
                MaxFleetScenarioDescription   = ape.GetMaxFleetScenarioDescription(),
                StartRevenueDate = ape.GetStartRevenue(),
                EndRevenueDate   = ape.GetEndRevenue(),
                CurrentDate      = ape.GetCurrentDate(),
                DateCreated      = DateTime.Now,
                WeeksCalculated  = ape.GetWeeksCalculated(),
                CountryId        = countryId,
                //AdditionPlanEntries = additionPlanEntries,
                //AdditionPlanMinMaxValues = minMaxValueEntities,
                //CreatedBy = createdBy,
                MarsUserId = marsUserId
            };

            DataContext.AdditionPlans.InsertOnSubmit(entityToCreate);

            DataContext.SubmitChanges();

            var additionPlanId = entityToCreate.AdditionPlanId;

            var maxMinValues = from mmv in minMaxValues
                               select new AdditionPlanMinMaxValue
            {
                AdditionPlanId        = additionPlanId,
                Year                  = (short)mmv.Year,
                Week                  = (byte)mmv.WeekNumber,
                CarGroupId            = mmv.GetCarGroupId(),
                LocationId            = mmv.GetLocationId(),
                Rank                  = mmv.RankFromRevenue,
                TotalFleet            = mmv.TotalFleet,
                AdditionsAndDeletions = mmv.AdditionDeletionSum,
                MinFleet              = mmv.MinFleet,
                MaxFleet              = mmv.MaxFleet,
                Contribution          = mmv.Contribution,
            };

            var minMaxEntriesToBeInserted = maxMinValues.ToList();

            minMaxEntriesToBeInserted.BulkCopyToDatabase("AdditionPlanMinMaxValue", DataContext, "fao");


            var additionPlanEntryEntities = from wa in weeklyAdditions
                                            select new AdditionPlanEntry
            {
                Week                = (byte)wa.IsoWeek,
                Year                = (short)wa.Year,
                CarGroupId          = wa.GetCarGroupId(),
                LocationId          = wa.GetLocationId(),
                Additions           = wa.Amount,
                AdditionPlanId      = additionPlanId,
                ContributionPerUnit = (decimal)wa.Contribution,
            };


            var additionPlanEntriesToBeInserted = additionPlanEntryEntities.ToList();

            additionPlanEntriesToBeInserted.BulkCopyToDatabase("AdditionPlanEntry", DataContext, "fao");
        }
Exemplo n.º 18
0
        protected void ControlPanel_ItemCommand(object sender, CommandEventArgs e)
        {
            if (e != null)
            {
                // Set variables to hold command and argument
                string option = string.Empty;


                // Get the command name
                switch (e.CommandName)
                {
                //Logo Button Event
                case "ImageLogo":
                    option = e.CommandName;


                    break;

                //Information Button Event
                case "InformationLink":

                    option = e.CommandName;
                    break;

                //About Button Event
                case "AboutLink":

                    option = e.CommandName;
                    break;

                //FAQ Button Event
                case "FAQLink":

                    option = e.CommandName;
                    break;

                //Logout Button Event
                case "LogoutLink":
                    //Sign user out
                    ApplicationAuthentication.SignOut();

                    option = e.CommandName;
                    break;

                case "CultureChanged":

                    string culture = e.CommandArgument.ToString();

                    // Change language in PAGE Base

                    break;

                //Application Link - CommandArgument = Navigate URL
                case "ApplicationLink":

                    Response.Redirect(e.CommandArgument.ToString());

                    break;
                }
            }
        }
Exemplo n.º 19
0
        public Application Create(string url, NewApplicationDetails model, LoggedInUserDetails user)
        {
            // Check whether user has access
            if (user.IsSysAdmin)
            {
                throw new BaseException("Admin can not create an application.");
            }

            // Check whether organisation is active
            if (!user.Organization.IsActive)
            {
                throw new BaseException(
                          "Your organization is inactive. Please check if your organization has approved Legal Officer. For more details contact DataLinker administrator.");
            }

            // Check whether application name already used within the organisation
            if (IsApplicationExistsForThisOrganization(model.Name, string.Empty, user))
            {
                throw new BaseException("Application name already in use.");
            }

            // Check whether hosts provided
            if (string.IsNullOrEmpty(model.OriginHosts))
            {
                throw new BaseException("You should define at least one host.");
            }

            // TODO: check whether all required data provided[Failed when auth tab was now shown in create provider app]

            // Setup application model
            var application = new Application
            {
                Name        = model.Name,
                Description = model.Description,
                PublicID    = Guid.NewGuid(),
                IsProvider  = model.IsProvider,
                IsIntroducedAsIndustryGood = model.IsIntroducedAsIndustryGood,
                OrganizationID             = user.Organization.ID,
                CreatedAt = GetDate,
                IsActive  = !model.IsIntroducedAsIndustryGood,
                CreatedBy = user.ID.Value
            };

            // Add application
            _applications.Add(application);

            if (application.IsProvider)
            {
                // Setup application authentication
                var appAuth = new ApplicationAuthentication
                {
                    ApplicationID         = application.ID,
                    WellKnownUrl          = string.IsNullOrEmpty(model.WellKnownUrl) ? string.Empty : model.WellKnownUrl,
                    Issuer                = string.IsNullOrEmpty(model.Issuer) ? string.Empty : model.Issuer,
                    JwksUri               = string.IsNullOrEmpty(model.JwksUri) ? string.Empty : model.JwksUri,
                    AuthorizationEndpoint = model.AuthorizationEndpoint,
                    TokenEndpoint         = model.TokenEndpoint,
                    RegistrationEndpoint  = model.RegistrationEndpoint,
                    UserInfoEndpoint      = string.Empty,
                    EndSessionEndpoint    = string.Empty,
                    CheckSessionIFrame    = string.Empty,
                    RevocationEndpoint    = string.Empty,
                    CreatedAt             = GetDate,
                    CreatedBy             = user.ID.Value
                };

                // Add application authentication
                _authentications.Add(appAuth);
            }

            foreach (var host in model.OriginHosts.Split(','))
            {
                var appToken = new ApplicationToken()
                {
                    ApplicationID = application.ID,
                    OriginHost    = host,
                    Token         = TokensHelper.GenerateToken(),
                    CreatedAt     = GetDate,
                    CreatedBy     = user.ID.Value
                };

                // Add token
                _tokens.Add(appToken);
            }

            // Send verification request to admin for industry good application
            if (application.IsIntroducedAsIndustryGood)
            {
                _notifications.Admin.NewIndustryGoodApplicationInBackground(url, application.OrganizationID);
            }

            return(application);
        }
Exemplo n.º 20
0
        public void UpdateMaxFleetFactors(double?nonRevPercent, double?utilizationPercent, int scenarioId)
        {
            if (!Parameters.ContainsValueAndIsntEmpty(DictionaryParameter.DayOfWeek))
            {
                return;
            }

            var splitDaysOfWeek =
                Parameters[DictionaryParameter.DayOfWeek].Split(VehicleFieldRestrictions.Separator.ToCharArray())
                .Select(int.Parse)
                .ToList();

            var locations = LocationQueryable.GetLocations(DataContext, Parameters);
            var carGroups = CarGroupQueryable.GetCarGroups(DataContext, Parameters);
            var weekDays  = from wd in DataContext.WeekDays
                            where splitDaysOfWeek.Contains(wd.DayOfWeekId)
                            select wd.DayOfWeekId;

            var locationsAndGroups = from l in locations
                                     from cg in carGroups
                                     from wd in weekDays
                                     select new
            {
                LocationId  = l.dim_Location_id,
                CarGroupId  = cg.car_group_id,
                DayOfWeekId = wd
            };

            var employeeId = ApplicationAuthentication.GetEmployeeId();
            var marsUserId = GetMarsUserId(employeeId);

            var updateParam = BuildSprocParameter();

            updateParam.ScenarioId            = scenarioId;
            updateParam.DayOfWeekIds          = Parameters[DictionaryParameter.DayOfWeek];
            updateParam.MarsUserId            = marsUserId;
            updateParam.NonRevPercentage      = (float?)nonRevPercent;
            updateParam.UtilizationPercentage = (float?)utilizationPercent;


            DataContext.UpdateMaxFleetFactors(updateParam.ScenarioId, updateParam.LocationId,
                                              updateParam.LocationGroupId
                                              , updateParam.PoolId, updateParam.LocationCountry, updateParam.CarGroupId,
                                              updateParam.CarClassId, updateParam.CarSegmentId, updateParam.OwningCountry,
                                              updateParam.DayOfWeekIds, updateParam.MarsUserId, updateParam.NonRevPercentage
                                              , updateParam.UtilizationPercentage);


            var entriesToCreate = from fullCs in locationsAndGroups
                                  join mff in DataContext.MaxFleetFactors.Where(d => d.MaxFleetFactorScenarioId == scenarioId) on
                                  new { fullCs.LocationId, fullCs.CarGroupId, fullCs.DayOfWeekId }
            equals new { mff.LocationId, mff.CarGroupId, mff.DayOfWeekId }
            into joinedFleetFactors
            from fleetFactors in joinedFleetFactors.DefaultIfEmpty()
            where fleetFactors == null
                select new
            {
                LocationId    = fullCs.LocationId,
                CarGroupId    = fullCs.CarGroupId,
                DayOfWeekId   = fullCs.DayOfWeekId,
                NonRev        = nonRevPercent,
                Utilization   = utilizationPercent,
                LastChangedOn = DateTime.Now,
                MarsUserId    = marsUserId
            };


            DataContext.SubmitChanges();
            var localEntities = (from etc in entriesToCreate.ToList()
                                 select new MaxFleetFactor
            {
                MaxFleetFactorScenarioId = scenarioId,
                LocationId = etc.LocationId,
                CarGroupId = etc.CarGroupId,
                DayOfWeekId = etc.DayOfWeekId,
                NonRevPercentage = etc.NonRev,
                UtilizationPercentage = etc.Utilization,
                UpdatedOn = DateTime.Now,
                MarsUserId = etc.MarsUserId
            }).ToList();

            localEntities.ToList().BulkCopyToDatabase("MaxFleetFactor", DataContext, "fao");

            //DataContext.MaxFleetFactors.InsertAllOnSubmit(localEntities);
            DataContext.SubmitChanges();
        }
Exemplo n.º 21
0
        public void UpdateMaxFleetFactors(double?nonRevPercent, double?utilizationPercent)
        {
            if (!Parameters.ContainsValueAndIsntEmpty(DictionaryParameter.DayOfWeek))
            {
                return;
            }

            var splitDaysOfWeek =
                Parameters[DictionaryParameter.DayOfWeek].Split(VehicleFieldRestrictions.Separator.ToCharArray())
                .Select(int.Parse)
                .ToList();

            var locations = LocationQueryable.GetLocations(DataContext, Parameters);
            var carGroups = CarGroupQueryable.GetCarGroups(DataContext, Parameters);
            var weekDays  = from wd in DataContext.WeekDays
                            where splitDaysOfWeek.Contains(wd.DayOfWeekId)
                            select wd.DayOfWeekId;

            var locationsAndGroups = from l in locations
                                     from cg in carGroups
                                     from wd in weekDays
                                     select new
            {
                LocationId  = l.dim_Location_id,
                CarGroupId  = cg.car_group_id,
                DayOfWeekId = wd
            };


            var entriesToUpdate = from lag in locationsAndGroups
                                  join mff in DataContext.MaxFleetFactors on
                                  new { lag.CarGroupId, lag.LocationId, lag.DayOfWeekId } equals
            new { mff.CarGroupId, mff.LocationId, mff.DayOfWeekId }
            select mff;



            if (nonRevPercent.HasValue)
            {
                entriesToUpdate.ForEach(d => d.NonRevPercentage = nonRevPercent.Value);
            }

            if (utilizationPercent.HasValue)
            {
                entriesToUpdate.ForEach(d => d.UtilizationPercentage = utilizationPercent.Value);
            }

            entriesToUpdate.ForEach(d => d.UpdatedBy = ApplicationAuthentication.GetGlobalId());
            entriesToUpdate.ForEach(d => d.UpdatedOn = DateTime.Now);


            var entriesToCreate = from fullCs in locationsAndGroups
                                  join mff in DataContext.MaxFleetFactors on
                                  new { fullCs.LocationId, fullCs.CarGroupId, fullCs.DayOfWeekId }
            equals new { mff.LocationId, mff.CarGroupId, mff.DayOfWeekId }
            into joinedFleetFactors
            from fleetFactors in joinedFleetFactors.DefaultIfEmpty()
            where fleetFactors == null
                select new
            {
                LocationId    = fullCs.LocationId,
                CarGroupId    = fullCs.CarGroupId,
                DayOfWeekId   = fullCs.DayOfWeekId,
                NonRev        = nonRevPercent,
                Utilization   = utilizationPercent,
                LastChangedOn = DateTime.Now,
                LastChangedBy = ApplicationAuthentication.GetGlobalId()
            };
            var localEntities = from etc in entriesToCreate.AsEnumerable()
                                select new MaxFleetFactor
            {
                LocationId            = etc.LocationId,
                CarGroupId            = etc.CarGroupId,
                DayOfWeekId           = etc.DayOfWeekId,
                NonRevPercentage      = etc.NonRev,
                UtilizationPercentage = etc.Utilization,
                UpdatedOn             = DateTime.Now,
                UpdatedBy             = ApplicationAuthentication.GetGlobalId()
            };

            DataContext.MaxFleetFactors.InsertAllOnSubmit(localEntities);
            DataContext.SubmitChanges();
        }